usbutils.c 36 KB

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