usbutils.c 41 KB

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