usbutils.c 37 KB

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