usbutils.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  1. /*
  2. * Copyright 2012-2013 Andrew Smith
  3. *
  4. * This program is free software; you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License as published by the Free
  6. * Software Foundation; either version 3 of the License, or (at your option)
  7. * any later version. See COPYING for more details.
  8. */
  9. #include "config.h"
  10. #include <stdint.h>
  11. #include <stdbool.h>
  12. #include "logging.h"
  13. #include "miner.h"
  14. #include "usbutils.h"
  15. #define NODEV(err) ((err) == LIBUSB_ERROR_NO_DEVICE || \
  16. (err) == LIBUSB_ERROR_PIPE || \
  17. (err) == LIBUSB_ERROR_OTHER)
  18. #ifdef USE_ICARUS
  19. #define DRV_ICARUS 1
  20. #endif
  21. #ifdef USE_BITFORCE
  22. #define DRV_BITFORCE 2
  23. #endif
  24. #ifdef USE_MODMINER
  25. #define DRV_MODMINER 3
  26. #endif
  27. #define DRV_LAST -1
  28. #define USB_CONFIG 1
  29. #define EPI(x) (LIBUSB_ENDPOINT_IN | (unsigned char)(x))
  30. #define EPO(x) (LIBUSB_ENDPOINT_OUT | (unsigned char)(x))
  31. #ifdef WIN32
  32. #define BITFORCE_TIMEOUT_MS 500
  33. #define MODMINER_TIMEOUT_MS 200
  34. #else
  35. #define BITFORCE_TIMEOUT_MS 200
  36. #define MODMINER_TIMEOUT_MS 100
  37. #endif
  38. #ifdef USE_BITFORCE
  39. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  40. static struct usb_endpoints bfl_eps[] = {
  41. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  42. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  43. };
  44. #endif
  45. #ifdef USE_MODMINER
  46. static struct usb_endpoints mmq_eps[] = {
  47. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  48. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0 }
  49. };
  50. #endif
  51. // TODO: Add support for (at least) Isochronous endpoints
  52. static struct usb_find_devices find_dev[] = {
  53. /*
  54. #ifdef USE_ICARUS
  55. { DRV_ICARUS, "ICA", 0x067b, 0x0230, true, EPI(3), EPO(2), 1 },
  56. { DRV_ICARUS, "LOT", 0x0403, 0x6001, false, EPI(0), EPO(0), 1 },
  57. { DRV_ICARUS, "CM1", 0x067b, 0x0230, false, EPI(0), EPO(0), 1 },
  58. #endif
  59. */
  60. #ifdef USE_BITFORCE
  61. {
  62. .drv = DRV_BITFORCE,
  63. .name = "BFL",
  64. .idVendor = 0x0403,
  65. .idProduct = 0x6014,
  66. .config = 1,
  67. .interface = 0,
  68. .timeout = BITFORCE_TIMEOUT_MS,
  69. .epcount = ARRAY_SIZE(bfl_eps),
  70. .eps = bfl_eps },
  71. #endif
  72. #ifdef USE_MODMINER
  73. {
  74. .drv = DRV_MODMINER,
  75. .name = "MMQ",
  76. .idVendor = 0x1fc9,
  77. .idProduct = 0x0003,
  78. .config = 1,
  79. .interface = 1,
  80. .timeout = MODMINER_TIMEOUT_MS,
  81. .epcount = ARRAY_SIZE(mmq_eps),
  82. .eps = mmq_eps },
  83. #endif
  84. { DRV_LAST, NULL, 0, 0, 0, 0, 0, 0, NULL }
  85. };
  86. #ifdef USE_BITFORCE
  87. extern struct device_drv bitforce_drv;
  88. #endif
  89. #ifdef USE_ICARUS
  90. extern struct device_drv icarus_drv;
  91. #endif
  92. #ifdef USE_MODMINER
  93. extern struct device_drv modminer_drv;
  94. #endif
  95. #define STRBUFLEN 256
  96. static const char *BLANK = "";
  97. static bool stats_initialised = false;
  98. struct cg_usb_stats_item {
  99. uint64_t count;
  100. double total_delay;
  101. double min_delay;
  102. double max_delay;
  103. struct timeval first;
  104. struct timeval last;
  105. };
  106. #define CMD_CMD 0
  107. #define CMD_TIMEOUT 1
  108. #define CMD_ERROR 2
  109. struct cg_usb_stats_details {
  110. int seq;
  111. struct cg_usb_stats_item item[CMD_ERROR+1];
  112. };
  113. struct cg_usb_stats {
  114. char *name;
  115. int device_id;
  116. struct cg_usb_stats_details *details;
  117. };
  118. #define SEQ0 0
  119. #define SEQ1 1
  120. static struct cg_usb_stats *usb_stats = NULL;
  121. static int next_stat = 0;
  122. static const char **usb_commands;
  123. static const char *C_REJECTED_S = "RejectedNoDevice";
  124. static const char *C_PING_S = "Ping";
  125. static const char *C_CLEAR_S = "Clear";
  126. static const char *C_REQUESTVERSION_S = "RequestVersion";
  127. static const char *C_GETVERSION_S = "GetVersion";
  128. static const char *C_REQUESTFPGACOUNT_S = "RequestFPGACount";
  129. static const char *C_GETFPGACOUNT_S = "GetFPGACount";
  130. static const char *C_STARTPROGRAM_S = "StartProgram";
  131. static const char *C_STARTPROGRAMSTATUS_S = "StartProgramStatus";
  132. static const char *C_PROGRAM_S = "Program";
  133. static const char *C_PROGRAMSTATUS_S = "ProgramStatus";
  134. static const char *C_PROGRAMSTATUS2_S = "ProgramStatus2";
  135. static const char *C_FINALPROGRAMSTATUS_S = "FinalProgramStatus";
  136. static const char *C_SETCLOCK_S = "SetClock";
  137. static const char *C_REPLYSETCLOCK_S = "ReplySetClock";
  138. static const char *C_REQUESTUSERCODE_S = "RequestUserCode";
  139. static const char *C_GETUSERCODE_S = "GetUserCode";
  140. static const char *C_REQUESTTEMPERATURE_S = "RequestTemperature";
  141. static const char *C_GETTEMPERATURE_S = "GetTemperature";
  142. static const char *C_SENDWORK_S = "SendWork";
  143. static const char *C_SENDWORKSTATUS_S = "SendWorkStatus";
  144. static const char *C_REQUESTWORKSTATUS_S = "RequestWorkStatus";
  145. static const char *C_GETWORKSTATUS_S = "GetWorkStatus";
  146. static const char *C_REQUESTIDENTIFY_S = "RequestIdentify";
  147. static const char *C_GETIDENTIFY_S = "GetIdentify";
  148. static const char *C_REQUESTFLASH_S = "RequestFlash";
  149. static const char *C_REQUESTSENDWORK_S = "RequestSendWork";
  150. static const char *C_REQUESTSENDWORKSTATUS_S = "RequestSendWorkStatus";
  151. static const char *C_RESET_S = "Reset";
  152. static const char *C_SETBAUD_S = "SetBaud";
  153. static const char *C_SETDATA_S = "SetDataCtrl";
  154. static const char *C_SETFLOW_S = "SetFlowCtrl";
  155. static const char *C_SETMODEM_S = "SetModemCtrl";
  156. static const char *C_PURGERX_S = "PurgeRx";
  157. static const char *C_PURGETX_S = "PurgeTx";
  158. #ifdef EOL
  159. #undef EOL
  160. #endif
  161. #define EOL "\n"
  162. static const char *DESDEV = "Device";
  163. static const char *DESCON = "Config";
  164. static const char *DESSTR = "String";
  165. static const char *DESINT = "Interface";
  166. static const char *DESEP = "Endpoint";
  167. static const char *DESHID = "HID";
  168. static const char *DESRPT = "Report";
  169. static const char *DESPHY = "Physical";
  170. static const char *DESHUB = "Hub";
  171. static const char *EPIN = "In: ";
  172. static const char *EPOUT = "Out: ";
  173. static const char *EPX = "?: ";
  174. static const char *CONTROL = "Control";
  175. static const char *ISOCHRONOUS_X = "Isochronous+?";
  176. static const char *ISOCHRONOUS_N_X = "Isochronous+None+?";
  177. static const char *ISOCHRONOUS_N_D = "Isochronous+None+Data";
  178. static const char *ISOCHRONOUS_N_F = "Isochronous+None+Feedback";
  179. static const char *ISOCHRONOUS_N_I = "Isochronous+None+Implicit";
  180. static const char *ISOCHRONOUS_A_X = "Isochronous+Async+?";
  181. static const char *ISOCHRONOUS_A_D = "Isochronous+Async+Data";
  182. static const char *ISOCHRONOUS_A_F = "Isochronous+Async+Feedback";
  183. static const char *ISOCHRONOUS_A_I = "Isochronous+Async+Implicit";
  184. static const char *ISOCHRONOUS_D_X = "Isochronous+Adaptive+?";
  185. static const char *ISOCHRONOUS_D_D = "Isochronous+Adaptive+Data";
  186. static const char *ISOCHRONOUS_D_F = "Isochronous+Adaptive+Feedback";
  187. static const char *ISOCHRONOUS_D_I = "Isochronous+Adaptive+Implicit";
  188. static const char *ISOCHRONOUS_S_X = "Isochronous+Sync+?";
  189. static const char *ISOCHRONOUS_S_D = "Isochronous+Sync+Data";
  190. static const char *ISOCHRONOUS_S_F = "Isochronous+Sync+Feedback";
  191. static const char *ISOCHRONOUS_S_I = "Isochronous+Sync+Implicit";
  192. static const char *BULK = "Bulk";
  193. static const char *INTERRUPT = "Interrupt";
  194. static const char *UNKNOWN = "Unknown";
  195. static const char *destype(uint8_t bDescriptorType)
  196. {
  197. switch (bDescriptorType) {
  198. case LIBUSB_DT_DEVICE:
  199. return DESDEV;
  200. case LIBUSB_DT_CONFIG:
  201. return DESCON;
  202. case LIBUSB_DT_STRING:
  203. return DESSTR;
  204. case LIBUSB_DT_INTERFACE:
  205. return DESINT;
  206. case LIBUSB_DT_ENDPOINT:
  207. return DESEP;
  208. case LIBUSB_DT_HID:
  209. return DESHID;
  210. case LIBUSB_DT_REPORT:
  211. return DESRPT;
  212. case LIBUSB_DT_PHYSICAL:
  213. return DESPHY;
  214. case LIBUSB_DT_HUB:
  215. return DESHUB;
  216. }
  217. return UNKNOWN;
  218. }
  219. static const char *epdir(uint8_t bEndpointAddress)
  220. {
  221. switch (bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) {
  222. case LIBUSB_ENDPOINT_IN:
  223. return EPIN;
  224. case LIBUSB_ENDPOINT_OUT:
  225. return EPOUT;
  226. }
  227. return EPX;
  228. }
  229. static const char *epatt(uint8_t bmAttributes)
  230. {
  231. switch(bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) {
  232. case LIBUSB_TRANSFER_TYPE_CONTROL:
  233. return CONTROL;
  234. case LIBUSB_TRANSFER_TYPE_BULK:
  235. return BULK;
  236. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  237. return INTERRUPT;
  238. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  239. switch(bmAttributes & LIBUSB_ISO_SYNC_TYPE_MASK) {
  240. case LIBUSB_ISO_SYNC_TYPE_NONE:
  241. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  242. case LIBUSB_ISO_USAGE_TYPE_DATA:
  243. return ISOCHRONOUS_N_D;
  244. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  245. return ISOCHRONOUS_N_F;
  246. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  247. return ISOCHRONOUS_N_I;
  248. }
  249. return ISOCHRONOUS_N_X;
  250. case LIBUSB_ISO_SYNC_TYPE_ASYNC:
  251. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  252. case LIBUSB_ISO_USAGE_TYPE_DATA:
  253. return ISOCHRONOUS_A_D;
  254. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  255. return ISOCHRONOUS_A_F;
  256. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  257. return ISOCHRONOUS_A_I;
  258. }
  259. return ISOCHRONOUS_A_X;
  260. case LIBUSB_ISO_SYNC_TYPE_ADAPTIVE:
  261. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  262. case LIBUSB_ISO_USAGE_TYPE_DATA:
  263. return ISOCHRONOUS_D_D;
  264. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  265. return ISOCHRONOUS_D_F;
  266. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  267. return ISOCHRONOUS_D_I;
  268. }
  269. return ISOCHRONOUS_D_X;
  270. case LIBUSB_ISO_SYNC_TYPE_SYNC:
  271. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  272. case LIBUSB_ISO_USAGE_TYPE_DATA:
  273. return ISOCHRONOUS_S_D;
  274. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  275. return ISOCHRONOUS_S_F;
  276. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  277. return ISOCHRONOUS_S_I;
  278. }
  279. return ISOCHRONOUS_S_X;
  280. }
  281. return ISOCHRONOUS_X;
  282. }
  283. return UNKNOWN;
  284. }
  285. static void append(char **buf, char *append, size_t *off, size_t *len)
  286. {
  287. int new = strlen(append);
  288. if ((new + *off) >= *len)
  289. {
  290. *len *= 2;
  291. *buf = realloc(*buf, *len);
  292. }
  293. strcpy(*buf + *off, append);
  294. *off += new;
  295. }
  296. static bool setgetdes(ssize_t count, libusb_device *dev, struct libusb_device_handle *handle, struct libusb_config_descriptor **config, int cd, char **buf, size_t *off, size_t *len)
  297. {
  298. char tmp[512];
  299. int err;
  300. err = libusb_set_configuration(handle, cd);
  301. if (err) {
  302. sprintf(tmp, EOL " ** dev %d: Failed to set config descriptor to %d, err %d",
  303. (int)count, cd, err);
  304. append(buf, tmp, off, len);
  305. return false;
  306. }
  307. err = libusb_get_active_config_descriptor(dev, config);
  308. if (err) {
  309. sprintf(tmp, EOL " ** dev %d: Failed to get active config descriptor set to %d, err %d",
  310. (int)count, cd, err);
  311. append(buf, tmp, off, len);
  312. return false;
  313. }
  314. sprintf(tmp, EOL " ** dev %d: Set & Got active config descriptor to %d, err %d",
  315. (int)count, cd, err);
  316. append(buf, tmp, off, len);
  317. return true;
  318. }
  319. static void usb_full(ssize_t count, libusb_device *dev, char **buf, size_t *off, size_t *len)
  320. {
  321. struct libusb_device_descriptor desc;
  322. struct libusb_device_handle *handle;
  323. struct libusb_config_descriptor *config;
  324. const struct libusb_interface_descriptor *idesc;
  325. const struct libusb_endpoint_descriptor *epdesc;
  326. unsigned char man[STRBUFLEN+1];
  327. unsigned char prod[STRBUFLEN+1];
  328. unsigned char ser[STRBUFLEN+1];
  329. char tmp[512];
  330. int err, i, j, k;
  331. err = libusb_get_device_descriptor(dev, &desc);
  332. if (err) {
  333. sprintf(tmp, EOL ".USB dev %d: Failed to get descriptor, err %d",
  334. (int)count, err);
  335. append(buf, tmp, off, len);
  336. return;
  337. }
  338. sprintf(tmp, EOL ".USB dev %d: Device Descriptor:" EOL "\tLength: %d" EOL
  339. "\tDescriptor Type: %s" EOL "\tUSB: %04x" EOL "\tDeviceClass: %d" EOL
  340. "\tDeviceSubClass: %d" EOL "\tDeviceProtocol: %d" EOL "\tMaxPacketSize0: %d" EOL
  341. "\tidVendor: %04x" EOL "\tidProduct: %04x" EOL "\tDeviceRelease: %x" EOL
  342. "\tNumConfigurations: %d",
  343. (int)count, (int)(desc.bLength), destype(desc.bDescriptorType),
  344. desc.bcdUSB, (int)(desc.bDeviceClass), (int)(desc.bDeviceSubClass),
  345. (int)(desc.bDeviceProtocol), (int)(desc.bMaxPacketSize0),
  346. desc.idVendor, desc.idProduct, desc.bcdDevice,
  347. (int)(desc.bNumConfigurations));
  348. append(buf, tmp, off, len);
  349. err = libusb_open(dev, &handle);
  350. if (err) {
  351. sprintf(tmp, EOL " ** dev %d: Failed to open, err %d", (int)count, err);
  352. append(buf, tmp, off, len);
  353. return;
  354. }
  355. if (libusb_kernel_driver_active(handle, 0) == 1) {
  356. sprintf(tmp, EOL " * dev %d: kernel attached", (int)count);
  357. append(buf, tmp, off, len);
  358. }
  359. err = libusb_get_active_config_descriptor(dev, &config);
  360. if (err) {
  361. if (!setgetdes(count, dev, handle, &config, 1, buf, off, len)
  362. && !setgetdes(count, dev, handle, &config, 0, buf, off, len)) {
  363. libusb_close(handle);
  364. sprintf(tmp, EOL " ** dev %d: Failed to set config descriptor to %d or %d",
  365. (int)count, 1, 0);
  366. append(buf, tmp, off, len);
  367. return;
  368. }
  369. }
  370. sprintf(tmp, EOL " dev %d: Active Config:" EOL "\tDescriptorType: %s" EOL
  371. "\tNumInterfaces: %d" EOL "\tConfigurationValue: %d" EOL
  372. "\tAttributes: %d" EOL "\tMaxPower: %d",
  373. (int)count, destype(config->bDescriptorType),
  374. (int)(config->bNumInterfaces), (int)(config->iConfiguration),
  375. (int)(config->bmAttributes), (int)(config->MaxPower));
  376. append(buf, tmp, off, len);
  377. for (i = 0; i < (int)(config->bNumInterfaces); i++) {
  378. for (j = 0; j < config->interface[i].num_altsetting; j++) {
  379. idesc = &(config->interface[i].altsetting[j]);
  380. sprintf(tmp, EOL " _dev %d: Interface Descriptor %d:" EOL
  381. "\tDescriptorType: %s" EOL "\tInterfaceNumber: %d" EOL
  382. "\tNumEndpoints: %d" EOL "\tInterfaceClass: %d" EOL
  383. "\tInterfaceSubClass: %d" EOL "\tInterfaceProtocol: %d",
  384. (int)count, j, destype(idesc->bDescriptorType),
  385. (int)(idesc->bInterfaceNumber),
  386. (int)(idesc->bNumEndpoints),
  387. (int)(idesc->bInterfaceClass),
  388. (int)(idesc->bInterfaceSubClass),
  389. (int)(idesc->bInterfaceProtocol));
  390. append(buf, tmp, off, len);
  391. for (k = 0; k < (int)(idesc->bNumEndpoints); k++) {
  392. epdesc = &(idesc->endpoint[k]);
  393. sprintf(tmp, EOL " __dev %d: Interface %d Endpoint %d:" EOL
  394. "\tDescriptorType: %s" EOL
  395. "\tEndpointAddress: %s0x%x" EOL
  396. "\tAttributes: %s" EOL "\tMaxPacketSize: %d" EOL
  397. "\tInterval: %d" EOL "\tRefresh: %d",
  398. (int)count, (int)(idesc->bInterfaceNumber), k,
  399. destype(epdesc->bDescriptorType),
  400. epdir(epdesc->bEndpointAddress),
  401. (int)(epdesc->bEndpointAddress),
  402. epatt(epdesc->bmAttributes),
  403. epdesc->wMaxPacketSize,
  404. (int)(epdesc->bInterval),
  405. (int)(epdesc->bRefresh));
  406. append(buf, tmp, off, len);
  407. }
  408. }
  409. }
  410. libusb_free_config_descriptor(config);
  411. config = NULL;
  412. err = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, man, STRBUFLEN);
  413. if (err < 0)
  414. sprintf((char *)man, "** err(%d)", err);
  415. err = libusb_get_string_descriptor_ascii(handle, desc.iProduct, prod, STRBUFLEN);
  416. if (err < 0)
  417. sprintf((char *)prod, "** err(%d)", err);
  418. err = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, ser, STRBUFLEN);
  419. if (err < 0)
  420. sprintf((char *)ser, "** err(%d)", err);
  421. sprintf(tmp, EOL " dev %d: More Info:" EOL "\tManufacturer: '%s'" EOL
  422. "\tProduct: '%s'" EOL "\tSerial '%s'",
  423. (int)count, man, prod, ser);
  424. append(buf, tmp, off, len);
  425. libusb_close(handle);
  426. }
  427. // Function to dump all USB devices
  428. static void usb_all()
  429. {
  430. libusb_device **list;
  431. ssize_t count, i;
  432. char *buf;
  433. size_t len, off;
  434. count = libusb_get_device_list(NULL, &list);
  435. if (count < 0) {
  436. applog(LOG_ERR, "USB all: failed, err %d", (int)count);
  437. return;
  438. }
  439. if (count == 0)
  440. applog(LOG_WARNING, "USB all: found no devices");
  441. else
  442. {
  443. len = 10000;
  444. buf = malloc(len+1);
  445. sprintf(buf, "USB all: found %d devices", (int)count);
  446. off = strlen(buf);
  447. for (i = 0; i < count; i++)
  448. usb_full(i, list[i], &buf, &off, &len);
  449. applog(LOG_WARNING, "%s", buf);
  450. free(buf);
  451. }
  452. libusb_free_device_list(list, 1);
  453. }
  454. static void cgusb_check_init()
  455. {
  456. mutex_lock(&cgusb_lock);
  457. if (stats_initialised == false) {
  458. // N.B. environment LIBUSB_DEBUG also sets libusb_set_debug()
  459. if (opt_usbdump >= 0) {
  460. libusb_set_debug(NULL, opt_usbdump);
  461. usb_all();
  462. }
  463. usb_commands = malloc(sizeof(*usb_commands) * C_MAX);
  464. // use constants so the stat generation is very quick
  465. // and the association between number and name can't
  466. // be missalined easily
  467. usb_commands[C_REJECTED] = C_REJECTED_S;
  468. usb_commands[C_PING] = C_PING_S;
  469. usb_commands[C_CLEAR] = C_CLEAR_S;
  470. usb_commands[C_REQUESTVERSION] = C_REQUESTVERSION_S;
  471. usb_commands[C_GETVERSION] = C_GETVERSION_S;
  472. usb_commands[C_REQUESTFPGACOUNT] = C_REQUESTFPGACOUNT_S;
  473. usb_commands[C_GETFPGACOUNT] = C_GETFPGACOUNT_S;
  474. usb_commands[C_STARTPROGRAM] = C_STARTPROGRAM_S;
  475. usb_commands[C_STARTPROGRAMSTATUS] = C_STARTPROGRAMSTATUS_S;
  476. usb_commands[C_PROGRAM] = C_PROGRAM_S;
  477. usb_commands[C_PROGRAMSTATUS] = C_PROGRAMSTATUS_S;
  478. usb_commands[C_PROGRAMSTATUS2] = C_PROGRAMSTATUS2_S;
  479. usb_commands[C_FINALPROGRAMSTATUS] = C_FINALPROGRAMSTATUS_S;
  480. usb_commands[C_SETCLOCK] = C_SETCLOCK_S;
  481. usb_commands[C_REPLYSETCLOCK] = C_REPLYSETCLOCK_S;
  482. usb_commands[C_REQUESTUSERCODE] = C_REQUESTUSERCODE_S;
  483. usb_commands[C_GETUSERCODE] = C_GETUSERCODE_S;
  484. usb_commands[C_REQUESTTEMPERATURE] = C_REQUESTTEMPERATURE_S;
  485. usb_commands[C_GETTEMPERATURE] = C_GETTEMPERATURE_S;
  486. usb_commands[C_SENDWORK] = C_SENDWORK_S;
  487. usb_commands[C_SENDWORKSTATUS] = C_SENDWORKSTATUS_S;
  488. usb_commands[C_REQUESTWORKSTATUS] = C_REQUESTWORKSTATUS_S;
  489. usb_commands[C_GETWORKSTATUS] = C_GETWORKSTATUS_S;
  490. usb_commands[C_REQUESTIDENTIFY] = C_REQUESTIDENTIFY_S;
  491. usb_commands[C_GETIDENTIFY] = C_GETIDENTIFY_S;
  492. usb_commands[C_REQUESTFLASH] = C_REQUESTFLASH_S;
  493. usb_commands[C_REQUESTSENDWORK] = C_REQUESTSENDWORK_S;
  494. usb_commands[C_REQUESTSENDWORKSTATUS] = C_REQUESTSENDWORKSTATUS_S;
  495. usb_commands[C_RESET] = C_RESET_S;
  496. usb_commands[C_SETBAUD] = C_SETBAUD_S;
  497. usb_commands[C_SETDATA] = C_SETDATA_S;
  498. usb_commands[C_SETFLOW] = C_SETFLOW_S;
  499. usb_commands[C_SETMODEM] = C_SETMODEM_S;
  500. usb_commands[C_PURGERX] = C_PURGERX_S;
  501. usb_commands[C_PURGETX] = C_PURGETX_S;
  502. }
  503. mutex_unlock(&cgusb_lock);
  504. }
  505. #ifdef WIN32
  506. #else
  507. #include <errno.h>
  508. #include <unistd.h>
  509. #include <sys/types.h>
  510. #include <sys/ipc.h>
  511. #include <sys/sem.h>
  512. #include <sys/types.h>
  513. #include <sys/stat.h>
  514. #include <fcntl.h>
  515. union semun {
  516. int sem;
  517. struct semid_ds *seminfo;
  518. ushort *all;
  519. };
  520. #endif
  521. // Any errors should always be printed since they will rarely if ever occur
  522. // and thus it is best to always display them
  523. static bool cgminer_usb_lock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  524. {
  525. #ifdef WIN32
  526. // NOOP for now
  527. drv = 0;
  528. bus_number = device_address = 0;
  529. return true;
  530. #else
  531. struct semid_ds seminfo;
  532. union semun opt;
  533. char name[64];
  534. key_t key;
  535. int fd, sem, count;
  536. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  537. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  538. if (fd == -1) {
  539. applog(LOG_ERR,
  540. "SEM: %s USB open failed '%s' err (%d) %s",
  541. drv->dname, name, errno, strerror(errno));
  542. return false;
  543. }
  544. close(fd);
  545. key = ftok(name, 'K');
  546. sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 438);
  547. if (sem < 0) {
  548. if (errno != EEXIST) {
  549. applog(LOG_ERR,
  550. "SEM: %s USB failed to get '%s' err (%d) %s",
  551. drv->dname, name, errno, strerror(errno));
  552. return false;
  553. }
  554. sem = semget(key, 1, 0);
  555. if (sem < 0) {
  556. applog(LOG_ERR,
  557. "SEM: %s USB failed to access '%s' err (%d) %s",
  558. drv->dname, name, errno, strerror(errno));
  559. return false;
  560. }
  561. opt.seminfo = &seminfo;
  562. count = 0;
  563. while (++count) {
  564. // Should NEVER take 100ms
  565. if (count > 99) {
  566. applog(LOG_ERR,
  567. "SEM: %s USB timeout waiting for (%d) '%s'",
  568. drv->dname, sem, name);
  569. return false;
  570. }
  571. if (semctl(sem, 0, IPC_STAT, opt) == -1) {
  572. applog(LOG_ERR,
  573. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  574. drv->dname, sem, name, count, errno, strerror(errno));
  575. return false;
  576. }
  577. if (opt.seminfo->sem_otime != 0)
  578. break;
  579. nmsleep(1);
  580. }
  581. }
  582. struct sembuf sops[] = {
  583. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  584. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  585. };
  586. if (semop(sem, sops, 2)) {
  587. if (errno == EAGAIN) {
  588. applog(LOG_WARNING,
  589. "SEM: %s USB failed to get (%d) '%s' - device in use",
  590. drv->dname, sem, name);
  591. } else {
  592. applog(LOG_DEBUG,
  593. "SEM: %s USB failed to get (%d) '%s' err(%d) %s",
  594. drv->dname, sem, name, errno, strerror(errno));
  595. }
  596. return false;
  597. }
  598. return true;
  599. #endif
  600. }
  601. static bool cgminer_usb_lock(struct device_drv *drv, libusb_device *dev)
  602. {
  603. return cgminer_usb_lock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  604. }
  605. // Any errors should always be printed since they will rarely if ever occur
  606. // and thus it is best to always display them
  607. static void cgminer_usb_unlock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  608. {
  609. #ifdef WIN32
  610. // NOOP for now
  611. drv = 0;
  612. bus_number = device_address = 0;
  613. #else
  614. char name[64];
  615. key_t key;
  616. int fd, sem;
  617. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  618. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  619. if (fd == -1) {
  620. applog(LOG_ERR,
  621. "SEM: %s USB open failed '%s' for release err (%d) %s",
  622. drv->dname, name, errno, strerror(errno));
  623. return;
  624. }
  625. close(fd);
  626. key = ftok(name, 'K');
  627. sem = semget(key, 1, 0);
  628. if (sem < 0) {
  629. applog(LOG_ERR,
  630. "SEM: %s USB failed to get '%s' for release err (%d) %s",
  631. drv->dname, name, errno, strerror(errno));
  632. return;
  633. }
  634. struct sembuf sops[] = {
  635. { 0, -1, SEM_UNDO }
  636. };
  637. // Allow a 10ms timeout
  638. // exceeding this timeout means it would probably never succeed anyway
  639. struct timespec timeout = { 0, 10000000 };
  640. // Wait forever since we shoud be the one who has it
  641. if (semtimedop(sem, sops, 1, &timeout)) {
  642. applog(LOG_ERR,
  643. "SEM: %d USB failed to release '%s' err (%d) %s",
  644. drv->dname, name, errno, strerror(errno));
  645. }
  646. return;
  647. #endif
  648. }
  649. static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
  650. {
  651. cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  652. }
  653. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  654. {
  655. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  656. free(cgusb->serial_string);
  657. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  658. free(cgusb->manuf_string);
  659. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  660. free(cgusb->prod_string);
  661. free(cgusb->descriptor);
  662. free(cgusb->found);
  663. free(cgusb);
  664. return NULL;
  665. }
  666. void usb_uninit(struct cgpu_info *cgpu)
  667. {
  668. libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface);
  669. libusb_close(cgpu->usbdev->handle);
  670. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  671. }
  672. void release_cgpu(struct cgpu_info *cgpu)
  673. {
  674. struct cg_usb_device *cgusb = cgpu->usbdev;
  675. int i;
  676. cgpu->usbinfo.nodev = true;
  677. cgpu->usbinfo.nodev_count++;
  678. gettimeofday(&(cgpu->usbinfo.last_nodev), NULL);
  679. // Any devices sharing the same USB device should be marked also
  680. // Currently only MMQ shares a USB device
  681. for (i = 0; i < total_devices; i++)
  682. if (devices[i] != cgpu && devices[i]->usbdev == cgusb) {
  683. devices[i]->usbinfo.nodev = true;
  684. devices[i]->usbinfo.nodev_count++;
  685. memcpy(&(devices[i]->usbinfo.last_nodev),
  686. &(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
  687. devices[i]->usbdev = NULL;
  688. }
  689. usb_uninit(cgpu);
  690. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  691. }
  692. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  693. {
  694. struct cg_usb_device *cgusb = NULL;
  695. struct libusb_config_descriptor *config = NULL;
  696. const struct libusb_interface_descriptor *idesc;
  697. const struct libusb_endpoint_descriptor *epdesc;
  698. unsigned char strbuf[STRBUFLEN+1];
  699. char devstr[STRBUFLEN+1];
  700. int err, i, j, k;
  701. cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
  702. cgpu->usbinfo.device_address = libusb_get_device_address(dev);
  703. sprintf(devstr, "- %s device %d:%d", found->name,
  704. cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  705. cgusb = calloc(1, sizeof(*cgusb));
  706. cgusb->found = found;
  707. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  708. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  709. if (err) {
  710. applog(LOG_DEBUG,
  711. "USB init failed to get descriptor, err %d %s",
  712. err, devstr);
  713. goto dame;
  714. }
  715. err = libusb_open(dev, &(cgusb->handle));
  716. if (err) {
  717. switch (err) {
  718. case LIBUSB_ERROR_ACCESS:
  719. applog(LOG_ERR,
  720. "USB init open device failed, err %d, "
  721. "you dont have priviledge to access %s",
  722. err, devstr);
  723. break;
  724. #ifdef WIN32
  725. // Windows specific message
  726. case LIBUSB_ERROR_NOT_SUPPORTED:
  727. applog(LOG_ERR,
  728. "USB init, open device failed, err %d, "
  729. "you need to install a Windows USB driver for %s",
  730. err, devstr);
  731. break;
  732. #endif
  733. default:
  734. applog(LOG_DEBUG,
  735. "USB init, open failed, err %d %s",
  736. err, devstr);
  737. }
  738. goto dame;
  739. }
  740. if (libusb_kernel_driver_active(cgusb->handle, found->config) == 1) {
  741. applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
  742. err = libusb_detach_kernel_driver(cgusb->handle, found->config);
  743. if (err == 0) {
  744. applog(LOG_DEBUG,
  745. "USB init, kernel detached successfully %s",
  746. devstr);
  747. } else {
  748. applog(LOG_WARNING,
  749. "USB init, kernel detach failed, err %d in use? %s",
  750. err, devstr);
  751. goto cldame;
  752. }
  753. }
  754. err = libusb_set_configuration(cgusb->handle, found->config);
  755. if (err) {
  756. switch(err) {
  757. case LIBUSB_ERROR_BUSY:
  758. applog(LOG_WARNING,
  759. "USB init, set config %d in use %s",
  760. found->config, devstr);
  761. break;
  762. default:
  763. applog(LOG_DEBUG,
  764. "USB init, failed to set config to %d, err %d %s",
  765. found->config, err, devstr);
  766. }
  767. goto cldame;
  768. }
  769. err = libusb_get_active_config_descriptor(dev, &config);
  770. if (err) {
  771. applog(LOG_DEBUG,
  772. "USB init, failed to get config descriptor %d, err %d %s",
  773. found->config, err, devstr);
  774. goto cldame;
  775. }
  776. if ((int)(config->bNumInterfaces) <= found->interface)
  777. goto cldame;
  778. for (i = 0; i < found->epcount; i++)
  779. found->eps[i].found = false;
  780. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  781. idesc = &(config->interface[found->interface].altsetting[i]);
  782. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  783. epdesc = &(idesc->endpoint[j]);
  784. for (k = 0; k < found->epcount; k++) {
  785. if (!found->eps[k].found) {
  786. if (epdesc->bmAttributes == found->eps[k].att
  787. && epdesc->wMaxPacketSize >= found->eps[k].size
  788. && epdesc->bEndpointAddress == found->eps[k].ep) {
  789. found->eps[k].found = true;
  790. break;
  791. }
  792. }
  793. }
  794. }
  795. }
  796. for (i = 0; i < found->epcount; i++)
  797. if (found->eps[i].found == false)
  798. goto cldame;
  799. err = libusb_claim_interface(cgusb->handle, found->interface);
  800. if (err) {
  801. switch(err) {
  802. case LIBUSB_ERROR_BUSY:
  803. applog(LOG_WARNING,
  804. "USB init, claim interface %d in use %s",
  805. found->interface, devstr);
  806. break;
  807. default:
  808. applog(LOG_DEBUG,
  809. "USB init, claim interface %d failed, err %d %s",
  810. found->interface, err, devstr);
  811. }
  812. goto cldame;
  813. }
  814. cgusb->usbver = cgusb->descriptor->bcdUSB;
  815. // TODO: allow this with the right version of the libusb include and running library
  816. // cgusb->speed = libusb_get_device_speed(dev);
  817. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  818. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  819. if (err > 0)
  820. cgusb->prod_string = strdup((char *)strbuf);
  821. else
  822. cgusb->prod_string = (char *)BLANK;
  823. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  824. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  825. if (err > 0)
  826. cgusb->manuf_string = strdup((char *)strbuf);
  827. else
  828. cgusb->manuf_string = (char *)BLANK;
  829. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  830. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  831. if (err > 0)
  832. cgusb->serial_string = strdup((char *)strbuf);
  833. else
  834. cgusb->serial_string = (char *)BLANK;
  835. // TODO: ?
  836. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  837. // cgusb->interfaceVersion
  838. applog(LOG_DEBUG,
  839. "USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
  840. devstr, cgusb->usbver, cgusb->prod_string,
  841. cgusb->manuf_string, cgusb->serial_string);
  842. cgpu->usbdev = cgusb;
  843. libusb_free_config_descriptor(config);
  844. // Allow a name change based on the idVendor+idProduct
  845. // N.B. must be done before calling add_cgpu()
  846. if (strcmp(cgpu->drv->name, found->name)) {
  847. if (!cgpu->drv->copy)
  848. cgpu->drv = copy_drv(cgpu->drv);
  849. cgpu->drv->name = (char *)(found->name);
  850. }
  851. return true;
  852. cldame:
  853. libusb_close(cgusb->handle);
  854. dame:
  855. if (config)
  856. libusb_free_config_descriptor(config);
  857. cgusb = free_cgusb(cgusb);
  858. return false;
  859. }
  860. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  861. {
  862. struct libusb_device_descriptor desc;
  863. int err;
  864. err = libusb_get_device_descriptor(dev, &desc);
  865. if (err) {
  866. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  867. return false;
  868. }
  869. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  870. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  871. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  872. return false;
  873. }
  874. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  875. drv->name, look->name, look->idVendor, look->idProduct);
  876. return true;
  877. }
  878. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  879. {
  880. struct usb_find_devices *found;
  881. int i;
  882. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  883. if (find_dev[i].drv == drvnum) {
  884. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  885. found = malloc(sizeof(*found));
  886. memcpy(found, &(find_dev[i]), sizeof(*found));
  887. return found;
  888. }
  889. }
  890. return NULL;
  891. }
  892. static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
  893. {
  894. #ifdef USE_BITFORCE
  895. if (drv->drv == DRIVER_BITFORCE)
  896. return usb_check_each(DRV_BITFORCE, drv, dev);
  897. #endif
  898. #ifdef USE_ICARUS
  899. if (drv->drv == DRIVER_ICARUS)
  900. return usb_check_each(DRV_ICARUS, drv, dev);
  901. #endif
  902. #ifdef USE_MODMINER
  903. if (drv->drv == DRIVER_MODMINER)
  904. return usb_check_each(DRV_MODMINER, drv, dev);
  905. #endif
  906. return NULL;
  907. }
  908. void usb_detect(struct device_drv *drv, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *))
  909. {
  910. libusb_device **list;
  911. ssize_t count, i;
  912. struct usb_find_devices *found;
  913. cgusb_check_init();
  914. count = libusb_get_device_list(NULL, &list);
  915. if (count < 0) {
  916. applog(LOG_DEBUG, "USB scan devices: failed, err %d", count);
  917. return;
  918. }
  919. if (count == 0)
  920. applog(LOG_DEBUG, "USB scan devices: found no devices");
  921. for (i = 0; i < count; i++) {
  922. found = usb_check(drv, list[i]);
  923. if (found != NULL) {
  924. if (cgminer_usb_lock(drv, list[i]) == false)
  925. free(found);
  926. else {
  927. if (!device_detect(list[i], found))
  928. cgminer_usb_unlock(drv, list[i]);
  929. }
  930. }
  931. }
  932. libusb_free_device_list(list, 1);
  933. }
  934. // Set this to 0 to remove stats processing
  935. #define DO_USB_STATS 1
  936. #if DO_USB_STATS
  937. #define USB_STATS(sgpu, sta, fin, err, cmd, seq) stats(cgpu, sta, fin, err, cmd, seq)
  938. #define STATS_TIMEVAL(tv) gettimeofday(tv, NULL)
  939. #else
  940. #define USB_STATS(sgpu, sta, fin, err, cmd, seq)
  941. #define STATS_TIMEVAL(tv)
  942. #endif
  943. // The stat data can be spurious due to not locking it before copying it -
  944. // however that would require the stat() function to also lock and release
  945. // a mutex every time a usb read or write is called which would slow
  946. // things down more
  947. struct api_data *api_usb_stats(__maybe_unused int *count)
  948. {
  949. #if DO_USB_STATS
  950. struct cg_usb_stats_details *details;
  951. struct cg_usb_stats *sta;
  952. struct api_data *root = NULL;
  953. int device;
  954. int cmdseq;
  955. cgusb_check_init();
  956. if (next_stat == 0)
  957. return NULL;
  958. while (*count < next_stat * C_MAX * 2) {
  959. device = *count / (C_MAX * 2);
  960. cmdseq = *count % (C_MAX * 2);
  961. (*count)++;
  962. sta = &(usb_stats[device]);
  963. details = &(sta->details[cmdseq]);
  964. // Only show stats that have results
  965. if (details->item[CMD_CMD].count == 0 &&
  966. details->item[CMD_TIMEOUT].count == 0 &&
  967. details->item[CMD_ERROR].count == 0)
  968. continue;
  969. root = api_add_string(root, "Name", sta->name, false);
  970. root = api_add_int(root, "ID", &(sta->device_id), false);
  971. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  972. root = api_add_int(root, "Seq", &(details->seq), true);
  973. root = api_add_uint64(root, "Count",
  974. &(details->item[CMD_CMD].count), true);
  975. root = api_add_double(root, "Total Delay",
  976. &(details->item[CMD_CMD].total_delay), true);
  977. root = api_add_double(root, "Min Delay",
  978. &(details->item[CMD_CMD].min_delay), true);
  979. root = api_add_double(root, "Max Delay",
  980. &(details->item[CMD_CMD].max_delay), true);
  981. root = api_add_uint64(root, "Timeout Count",
  982. &(details->item[CMD_TIMEOUT].count), true);
  983. root = api_add_double(root, "Timeout Total Delay",
  984. &(details->item[CMD_TIMEOUT].total_delay), true);
  985. root = api_add_double(root, "Timeout Min Delay",
  986. &(details->item[CMD_TIMEOUT].min_delay), true);
  987. root = api_add_double(root, "Timeout Max Delay",
  988. &(details->item[CMD_TIMEOUT].max_delay), true);
  989. root = api_add_uint64(root, "Error Count",
  990. &(details->item[CMD_ERROR].count), true);
  991. root = api_add_double(root, "Error Total Delay",
  992. &(details->item[CMD_ERROR].total_delay), true);
  993. root = api_add_double(root, "Error Min Delay",
  994. &(details->item[CMD_ERROR].min_delay), true);
  995. root = api_add_double(root, "Error Max Delay",
  996. &(details->item[CMD_ERROR].max_delay), true);
  997. root = api_add_timeval(root, "First Command",
  998. &(details->item[CMD_CMD].first), true);
  999. root = api_add_timeval(root, "Last Command",
  1000. &(details->item[CMD_CMD].last), true);
  1001. root = api_add_timeval(root, "First Timeout",
  1002. &(details->item[CMD_TIMEOUT].first), true);
  1003. root = api_add_timeval(root, "Last Timeout",
  1004. &(details->item[CMD_TIMEOUT].last), true);
  1005. root = api_add_timeval(root, "First Error",
  1006. &(details->item[CMD_ERROR].first), true);
  1007. root = api_add_timeval(root, "Last Error",
  1008. &(details->item[CMD_ERROR].last), true);
  1009. return root;
  1010. }
  1011. #endif
  1012. return NULL;
  1013. }
  1014. #if DO_USB_STATS
  1015. static void newstats(struct cgpu_info *cgpu)
  1016. {
  1017. int i;
  1018. cgpu->usbinfo.usbstat = ++next_stat;
  1019. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * next_stat);
  1020. usb_stats[next_stat-1].name = cgpu->drv->name;
  1021. usb_stats[next_stat-1].device_id = -1;
  1022. usb_stats[next_stat-1].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  1023. for (i = 1; i < C_MAX * 2; i += 2)
  1024. usb_stats[next_stat-1].details[i].seq = 1;
  1025. }
  1026. #endif
  1027. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  1028. {
  1029. #if DO_USB_STATS
  1030. if (cgpu->usbinfo.usbstat < 1)
  1031. newstats(cgpu);
  1032. // we don't know the device_id until after add_cgpu()
  1033. usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
  1034. #endif
  1035. }
  1036. #if DO_USB_STATS
  1037. static void stats(struct cgpu_info *cgpu, struct timeval *tv_start, struct timeval *tv_finish, int err, enum usb_cmds cmd, int seq)
  1038. {
  1039. struct cg_usb_stats_details *details;
  1040. double diff;
  1041. int item;
  1042. if (cgpu->usbinfo.usbstat < 1)
  1043. newstats(cgpu);
  1044. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
  1045. diff = tdiff(tv_finish, tv_start);
  1046. switch (err) {
  1047. case LIBUSB_SUCCESS:
  1048. item = CMD_CMD;
  1049. break;
  1050. case LIBUSB_ERROR_TIMEOUT:
  1051. item = CMD_TIMEOUT;
  1052. break;
  1053. default:
  1054. item = CMD_ERROR;
  1055. break;
  1056. }
  1057. if (details->item[item].count == 0) {
  1058. details->item[item].min_delay = diff;
  1059. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  1060. } else if (diff < details->item[item].min_delay)
  1061. details->item[item].min_delay = diff;
  1062. if (diff > details->item[item].max_delay)
  1063. details->item[item].max_delay = diff;
  1064. details->item[item].total_delay += diff;
  1065. memcpy(&(details->item[item].last), tv_start, sizeof(tv_start));
  1066. details->item[item].count++;
  1067. }
  1068. static void rejected_inc(struct cgpu_info *cgpu)
  1069. {
  1070. struct cg_usb_stats_details *details;
  1071. int item = CMD_ERROR;
  1072. if (cgpu->usbinfo.usbstat < 1)
  1073. newstats(cgpu);
  1074. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  1075. details->item[item].count++;
  1076. }
  1077. #endif
  1078. int _usb_read(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, int eol, enum usb_cmds cmd, bool ftdi)
  1079. {
  1080. struct cg_usb_device *usbdev = cgpu->usbdev;
  1081. #if DO_USB_STATS
  1082. struct timeval tv_start;
  1083. #endif
  1084. struct timeval read_start, tv_finish;
  1085. unsigned int initial_timeout;
  1086. double max, done;
  1087. int err, got, tot, i;
  1088. bool first = true;
  1089. if (cgpu->usbinfo.nodev) {
  1090. *buf = '\0';
  1091. *processed = 0;
  1092. #if DO_USB_STATS
  1093. rejected_inc(cgpu);
  1094. #endif
  1095. return LIBUSB_ERROR_NO_DEVICE;
  1096. }
  1097. if (timeout == DEVTIMEOUT)
  1098. timeout = usbdev->found->timeout;
  1099. if (eol == -1) {
  1100. got = 0;
  1101. STATS_TIMEVAL(&tv_start);
  1102. err = libusb_bulk_transfer(usbdev->handle,
  1103. usbdev->found->eps[ep].ep,
  1104. (unsigned char *)buf,
  1105. bufsiz, &got, timeout);
  1106. STATS_TIMEVAL(&tv_finish);
  1107. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1108. if (ftdi) {
  1109. // first 2 bytes returned are an FTDI status
  1110. if (got > 2) {
  1111. got -= 2;
  1112. memmove(buf, buf+2, got+1);
  1113. } else {
  1114. got = 0;
  1115. *buf = '\0';
  1116. }
  1117. }
  1118. *processed = got;
  1119. if (NODEV(err))
  1120. release_cgpu(cgpu);
  1121. return err;
  1122. }
  1123. tot = 0;
  1124. err = LIBUSB_SUCCESS;
  1125. initial_timeout = timeout;
  1126. max = ((double)timeout) / 1000.0;
  1127. gettimeofday(&read_start, NULL);
  1128. while (bufsiz) {
  1129. got = 0;
  1130. STATS_TIMEVAL(&tv_start);
  1131. err = libusb_bulk_transfer(usbdev->handle,
  1132. usbdev->found->eps[ep].ep,
  1133. (unsigned char *)buf,
  1134. bufsiz, &got, timeout);
  1135. gettimeofday(&tv_finish, NULL);
  1136. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, first ? SEQ0 : SEQ1);
  1137. if (ftdi) {
  1138. // first 2 bytes returned are an FTDI status
  1139. if (got > 2) {
  1140. got -= 2;
  1141. memmove(buf, buf+2, got+1);
  1142. } else {
  1143. got = 0;
  1144. *buf = '\0';
  1145. }
  1146. }
  1147. tot += got;
  1148. if (err)
  1149. break;
  1150. // WARNING - this will return data past EOL ('if' there is extra data)
  1151. for (i = 0; i < got; i++)
  1152. if (buf[i] == eol)
  1153. goto goteol;
  1154. buf += got;
  1155. bufsiz -= got;
  1156. first = false;
  1157. done = tdiff(&tv_finish, &read_start);
  1158. // N.B. this is return LIBUSB_SUCCESS with whatever size has already been read
  1159. if (unlikely(done >= max))
  1160. break;
  1161. timeout = initial_timeout - (done * 1000);
  1162. }
  1163. goteol:
  1164. *processed = tot;
  1165. if (NODEV(err))
  1166. release_cgpu(cgpu);
  1167. return err;
  1168. }
  1169. int _usb_write(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, enum usb_cmds cmd)
  1170. {
  1171. struct cg_usb_device *usbdev = cgpu->usbdev;
  1172. #if DO_USB_STATS
  1173. struct timeval tv_start, tv_finish;
  1174. #endif
  1175. int err, sent;
  1176. if (cgpu->usbinfo.nodev) {
  1177. *processed = 0;
  1178. #if DO_USB_STATS
  1179. rejected_inc(cgpu);
  1180. #endif
  1181. return LIBUSB_ERROR_NO_DEVICE;
  1182. }
  1183. sent = 0;
  1184. STATS_TIMEVAL(&tv_start);
  1185. err = libusb_bulk_transfer(usbdev->handle,
  1186. usbdev->found->eps[ep].ep,
  1187. (unsigned char *)buf,
  1188. bufsiz, &sent,
  1189. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1190. STATS_TIMEVAL(&tv_finish);
  1191. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1192. *processed = sent;
  1193. if (NODEV(err))
  1194. release_cgpu(cgpu);
  1195. return err;
  1196. }
  1197. int _usb_transfer(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout, enum usb_cmds cmd)
  1198. {
  1199. struct cg_usb_device *usbdev = cgpu->usbdev;
  1200. #if DO_USB_STATS
  1201. struct timeval tv_start, tv_finish;
  1202. #endif
  1203. int err;
  1204. if (cgpu->usbinfo.nodev) {
  1205. #if DO_USB_STATS
  1206. rejected_inc(cgpu);
  1207. #endif
  1208. return LIBUSB_ERROR_NO_DEVICE;
  1209. }
  1210. STATS_TIMEVAL(&tv_start);
  1211. err = libusb_control_transfer(usbdev->handle, request_type,
  1212. bRequest, wValue, wIndex, NULL, 0,
  1213. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1214. STATS_TIMEVAL(&tv_finish);
  1215. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1216. if (NODEV(err))
  1217. release_cgpu(cgpu);
  1218. return err;
  1219. }
  1220. void usb_cleanup()
  1221. {
  1222. // TODO:
  1223. }