usbutils.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398
  1. /*
  2. * Copyright 2012-2013 Andrew Smith
  3. *
  4. * This program is free software; you can redistribute it and/or modify it
  5. * under the terms of the GNU General Public License as published by the Free
  6. * Software Foundation; either version 3 of the License, or (at your option)
  7. * any later version. See COPYING for more details.
  8. */
  9. #include "config.h"
  10. #include <stdint.h>
  11. #include <stdbool.h>
  12. #include "logging.h"
  13. #include "miner.h"
  14. #include "usbutils.h"
  15. #define NODEV(err) ((err) == LIBUSB_ERROR_NO_DEVICE || \
  16. (err) == LIBUSB_ERROR_PIPE || \
  17. (err) == LIBUSB_ERROR_OTHER)
  18. #ifdef USE_ICARUS
  19. #define DRV_ICARUS 1
  20. #endif
  21. #ifdef USE_BITFORCE
  22. #define DRV_BITFORCE 2
  23. #endif
  24. #ifdef USE_MODMINER
  25. #define DRV_MODMINER 3
  26. #endif
  27. #define DRV_LAST -1
  28. #define USB_CONFIG 1
  29. #define EPI(x) (LIBUSB_ENDPOINT_IN | (unsigned char)(x))
  30. #define EPO(x) (LIBUSB_ENDPOINT_OUT | (unsigned char)(x))
  31. #ifdef WIN32
  32. #define BITFORCE_TIMEOUT_MS 500
  33. #define MODMINER_TIMEOUT_MS 200
  34. #else
  35. #define BITFORCE_TIMEOUT_MS 200
  36. #define MODMINER_TIMEOUT_MS 100
  37. #endif
  38. #ifdef USE_BITFORCE
  39. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  40. static struct usb_endpoints bfl_eps[] = {
  41. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  42. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  43. };
  44. #endif
  45. #ifdef USE_MODMINER
  46. static struct usb_endpoints mmq_eps[] = {
  47. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  48. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0 }
  49. };
  50. #endif
  51. // TODO: Add support for (at least) Isochronous endpoints
  52. static struct usb_find_devices find_dev[] = {
  53. /*
  54. #ifdef USE_ICARUS
  55. { DRV_ICARUS, "ICA", 0x067b, 0x0230, true, EPI(3), EPO(2), 1 },
  56. { DRV_ICARUS, "LOT", 0x0403, 0x6001, false, EPI(0), EPO(0), 1 },
  57. { DRV_ICARUS, "CM1", 0x067b, 0x0230, false, EPI(0), EPO(0), 1 },
  58. #endif
  59. */
  60. #ifdef USE_BITFORCE
  61. {
  62. .drv = DRV_BITFORCE,
  63. .name = "BFL",
  64. .idVendor = 0x0403,
  65. .idProduct = 0x6014,
  66. .config = 1,
  67. .interface = 0,
  68. .timeout = BITFORCE_TIMEOUT_MS,
  69. .epcount = ARRAY_SIZE(bfl_eps),
  70. .eps = bfl_eps },
  71. #endif
  72. #ifdef USE_MODMINER
  73. {
  74. .drv = DRV_MODMINER,
  75. .name = "MMQ",
  76. .idVendor = 0x1fc9,
  77. .idProduct = 0x0003,
  78. .config = 1,
  79. .interface = 1,
  80. .timeout = MODMINER_TIMEOUT_MS,
  81. .epcount = ARRAY_SIZE(mmq_eps),
  82. .eps = mmq_eps },
  83. #endif
  84. { DRV_LAST, NULL, 0, 0, 0, 0, 0, 0, NULL }
  85. };
  86. #ifdef USE_BITFORCE
  87. extern struct device_drv bitforce_drv;
  88. #endif
  89. #ifdef USE_ICARUS
  90. extern struct device_drv icarus_drv;
  91. #endif
  92. #ifdef USE_MODMINER
  93. extern struct device_drv modminer_drv;
  94. #endif
  95. /*
  96. * Our own internal list of used USB devices
  97. * So two drivers or a single driver searching
  98. * can't touch the same device during detection
  99. */
  100. struct usb_list {
  101. uint8_t bus_number;
  102. uint8_t device_address;
  103. uint8_t filler[2];
  104. struct usb_list *prev;
  105. struct usb_list *next;
  106. };
  107. #define STRBUFLEN 256
  108. static const char *BLANK = "";
  109. static pthread_mutex_t *list_lock = NULL;
  110. static struct usb_list *usb_head = NULL;
  111. struct cg_usb_stats_item {
  112. uint64_t count;
  113. double total_delay;
  114. double min_delay;
  115. double max_delay;
  116. struct timeval first;
  117. struct timeval last;
  118. };
  119. #define CMD_CMD 0
  120. #define CMD_TIMEOUT 1
  121. #define CMD_ERROR 2
  122. struct cg_usb_stats_details {
  123. int seq;
  124. struct cg_usb_stats_item item[CMD_ERROR+1];
  125. };
  126. struct cg_usb_stats {
  127. char *name;
  128. int device_id;
  129. struct cg_usb_stats_details *details;
  130. };
  131. #define SEQ0 0
  132. #define SEQ1 1
  133. static struct cg_usb_stats *usb_stats = NULL;
  134. static int next_stat = 0;
  135. static const char **usb_commands;
  136. static const char *C_REJECTED_S = "RejectedNoDevice";
  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_REJECTED] = C_REJECTED_S;
  483. usb_commands[C_PING] = C_PING_S;
  484. usb_commands[C_CLEAR] = C_CLEAR_S;
  485. usb_commands[C_REQUESTVERSION] = C_REQUESTVERSION_S;
  486. usb_commands[C_GETVERSION] = C_GETVERSION_S;
  487. usb_commands[C_REQUESTFPGACOUNT] = C_REQUESTFPGACOUNT_S;
  488. usb_commands[C_GETFPGACOUNT] = C_GETFPGACOUNT_S;
  489. usb_commands[C_STARTPROGRAM] = C_STARTPROGRAM_S;
  490. usb_commands[C_STARTPROGRAMSTATUS] = C_STARTPROGRAMSTATUS_S;
  491. usb_commands[C_PROGRAM] = C_PROGRAM_S;
  492. usb_commands[C_PROGRAMSTATUS] = C_PROGRAMSTATUS_S;
  493. usb_commands[C_PROGRAMSTATUS2] = C_PROGRAMSTATUS2_S;
  494. usb_commands[C_FINALPROGRAMSTATUS] = C_FINALPROGRAMSTATUS_S;
  495. usb_commands[C_SETCLOCK] = C_SETCLOCK_S;
  496. usb_commands[C_REPLYSETCLOCK] = C_REPLYSETCLOCK_S;
  497. usb_commands[C_REQUESTUSERCODE] = C_REQUESTUSERCODE_S;
  498. usb_commands[C_GETUSERCODE] = C_GETUSERCODE_S;
  499. usb_commands[C_REQUESTTEMPERATURE] = C_REQUESTTEMPERATURE_S;
  500. usb_commands[C_GETTEMPERATURE] = C_GETTEMPERATURE_S;
  501. usb_commands[C_SENDWORK] = C_SENDWORK_S;
  502. usb_commands[C_SENDWORKSTATUS] = C_SENDWORKSTATUS_S;
  503. usb_commands[C_REQUESTWORKSTATUS] = C_REQUESTWORKSTATUS_S;
  504. usb_commands[C_GETWORKSTATUS] = C_GETWORKSTATUS_S;
  505. usb_commands[C_REQUESTIDENTIFY] = C_REQUESTIDENTIFY_S;
  506. usb_commands[C_GETIDENTIFY] = C_GETIDENTIFY_S;
  507. usb_commands[C_REQUESTFLASH] = C_REQUESTFLASH_S;
  508. usb_commands[C_REQUESTSENDWORK] = C_REQUESTSENDWORK_S;
  509. usb_commands[C_REQUESTSENDWORKSTATUS] = C_REQUESTSENDWORKSTATUS_S;
  510. usb_commands[C_RESET] = C_RESET_S;
  511. usb_commands[C_SETBAUD] = C_SETBAUD_S;
  512. usb_commands[C_SETDATA] = C_SETDATA_S;
  513. usb_commands[C_SETFLOW] = C_SETFLOW_S;
  514. usb_commands[C_SETMODEM] = C_SETMODEM_S;
  515. usb_commands[C_PURGERX] = C_PURGERX_S;
  516. usb_commands[C_PURGETX] = C_PURGETX_S;
  517. }
  518. mutex_unlock(&cgusb_lock);
  519. }
  520. static bool in_use(libusb_device *dev, bool lock)
  521. {
  522. struct usb_list *usb_tmp;
  523. bool used = false;
  524. uint8_t bus_number;
  525. uint8_t device_address;
  526. bus_number = libusb_get_bus_number(dev);
  527. device_address = libusb_get_device_address(dev);
  528. if (lock)
  529. mutex_lock(list_lock);
  530. if ((usb_tmp = usb_head))
  531. do {
  532. if (bus_number == usb_tmp->bus_number
  533. && device_address == usb_tmp->device_address) {
  534. used = true;
  535. break;
  536. }
  537. usb_tmp = usb_tmp->next;
  538. } while (usb_tmp != usb_head);
  539. if (lock)
  540. mutex_unlock(list_lock);
  541. return used;
  542. }
  543. static void add_used(libusb_device *dev, bool lock)
  544. {
  545. struct usb_list *usb_tmp;
  546. char buf[128];
  547. uint8_t bus_number;
  548. uint8_t device_address;
  549. bus_number = libusb_get_bus_number(dev);
  550. device_address = libusb_get_device_address(dev);
  551. if (lock)
  552. mutex_lock(list_lock);
  553. if (in_use(dev, false)) {
  554. if (lock)
  555. mutex_unlock(list_lock);
  556. sprintf(buf, "add_used() duplicate bus_number %d device_address %d",
  557. bus_number, device_address);
  558. quit(1, buf);
  559. }
  560. usb_tmp = malloc(sizeof(*usb_tmp));
  561. usb_tmp->bus_number = bus_number;
  562. usb_tmp->device_address = device_address;
  563. if (usb_head) {
  564. // add to end
  565. usb_tmp->prev = usb_head->prev;
  566. usb_tmp->next = usb_head;
  567. usb_head->prev = usb_tmp;
  568. usb_tmp->prev->next = usb_tmp;
  569. } else {
  570. usb_tmp->prev = usb_tmp;
  571. usb_tmp->next = usb_tmp;
  572. usb_head = usb_tmp;
  573. }
  574. if (lock)
  575. mutex_unlock(list_lock);
  576. }
  577. static void release(uint8_t bus_number, uint8_t device_address, bool lock)
  578. {
  579. struct usb_list *usb_tmp;
  580. bool found = false;
  581. char buf[128];
  582. if (lock)
  583. mutex_lock(list_lock);
  584. if ((usb_tmp = usb_head))
  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. if (usb_head == usb_tmp)
  604. usb_head = usb_tmp->next;
  605. usb_tmp->next->prev = usb_tmp->prev;
  606. usb_tmp->prev->next = usb_tmp->next;
  607. }
  608. if (lock)
  609. mutex_unlock(list_lock);
  610. free(usb_tmp);
  611. }
  612. static void release_dev(libusb_device *dev, bool lock)
  613. {
  614. uint8_t bus_number;
  615. uint8_t device_address;
  616. bus_number = libusb_get_bus_number(dev);
  617. device_address = libusb_get_device_address(dev);
  618. release(bus_number, device_address, lock);
  619. }
  620. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  621. {
  622. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  623. free(cgusb->serial_string);
  624. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  625. free(cgusb->manuf_string);
  626. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  627. free(cgusb->prod_string);
  628. free(cgusb->descriptor);
  629. free(cgusb->found);
  630. free(cgusb);
  631. return NULL;
  632. }
  633. void usb_uninit(struct cgpu_info *cgpu)
  634. {
  635. libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface);
  636. libusb_close(cgpu->usbdev->handle);
  637. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  638. }
  639. void release_cgpu(struct cgpu_info *cgpu)
  640. {
  641. struct cg_usb_device *cgusb = cgpu->usbdev;
  642. uint8_t bus_number;
  643. uint8_t device_address;
  644. int i;
  645. cgpu->nodev = true;
  646. // Any devices sharing the same USB device should be marked also
  647. // Currently only MMQ shares a USB device
  648. for (i = 0; i < total_devices; i++)
  649. if (devices[i] != cgpu && devices[i]->usbdev == cgusb) {
  650. devices[i]->nodev = true;
  651. devices[i]->usbdev = NULL;
  652. }
  653. bus_number = cgusb->bus_number;
  654. device_address = cgusb->device_address;
  655. usb_uninit(cgpu);
  656. release(bus_number, device_address, true);
  657. }
  658. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  659. {
  660. struct cg_usb_device *cgusb = NULL;
  661. struct libusb_config_descriptor *config = NULL;
  662. const struct libusb_interface_descriptor *idesc;
  663. const struct libusb_endpoint_descriptor *epdesc;
  664. unsigned char strbuf[STRBUFLEN+1];
  665. int err, i, j, k;
  666. cgusb = calloc(1, sizeof(*cgusb));
  667. cgusb->found = found;
  668. cgusb->bus_number = libusb_get_bus_number(dev);
  669. cgusb->device_address = libusb_get_device_address(dev);
  670. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  671. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  672. if (err) {
  673. applog(LOG_ERR, "USB init failed to get descriptor, err %d", err);
  674. goto dame;
  675. }
  676. err = libusb_open(dev, &(cgusb->handle));
  677. if (err) {
  678. switch (err) {
  679. case LIBUSB_ERROR_ACCESS:
  680. applog(LOG_ERR, "USB init open device failed, err %d, you dont have priviledge to access the device", err);
  681. break;
  682. #ifdef WIN32
  683. // Windows specific message
  684. case LIBUSB_ERROR_NOT_SUPPORTED:
  685. applog(LOG_ERR, "USB init, open device failed, err %d, you need to install a Windows USB driver for the device", err);
  686. break;
  687. #endif
  688. default:
  689. applog(LOG_ERR, "USB init, open device failed, err %d", err);
  690. }
  691. goto dame;
  692. }
  693. if (libusb_kernel_driver_active(cgusb->handle, 0) == 1) {
  694. applog(LOG_DEBUG, "USB init, kernel attached ...");
  695. if (libusb_detach_kernel_driver(cgusb->handle, 0) == 0)
  696. applog(LOG_DEBUG, "USB init, kernel detached successfully");
  697. else
  698. applog(LOG_WARNING, "USB init, kernel detach failed :(");
  699. }
  700. err = libusb_set_configuration(cgusb->handle, found->config);
  701. if (err) {
  702. switch(err) {
  703. case LIBUSB_ERROR_BUSY:
  704. applog(LOG_WARNING, "USB init, %s device %d:%d in use",
  705. found->name, cgusb->bus_number, cgusb->device_address);
  706. break;
  707. default:
  708. applog(LOG_DEBUG, "USB init, failed to set config to %d, err %d",
  709. found->config, err);
  710. }
  711. goto cldame;
  712. }
  713. err = libusb_get_active_config_descriptor(dev, &config);
  714. if (err) {
  715. applog(LOG_DEBUG, "USB init, failed to get config descriptor %d, err %d",
  716. found->config, err);
  717. goto cldame;
  718. }
  719. if ((int)(config->bNumInterfaces) <= found->interface)
  720. goto cldame;
  721. for (i = 0; i < found->epcount; i++)
  722. found->eps[i].found = false;
  723. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  724. idesc = &(config->interface[found->interface].altsetting[i]);
  725. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  726. epdesc = &(idesc->endpoint[j]);
  727. for (k = 0; k < found->epcount; k++) {
  728. if (!found->eps[k].found) {
  729. if (epdesc->bmAttributes == found->eps[k].att
  730. && epdesc->wMaxPacketSize >= found->eps[k].size
  731. && epdesc->bEndpointAddress == found->eps[k].ep) {
  732. found->eps[k].found = true;
  733. break;
  734. }
  735. }
  736. }
  737. }
  738. }
  739. for (i = 0; i < found->epcount; i++)
  740. if (found->eps[i].found == false)
  741. goto cldame;
  742. err = libusb_claim_interface(cgusb->handle, found->interface);
  743. if (err) {
  744. applog(LOG_DEBUG, "USB init, claim interface %d failed, err %d",
  745. found->interface, err);
  746. goto cldame;
  747. }
  748. cgusb->usbver = cgusb->descriptor->bcdUSB;
  749. // TODO: allow this with the right version of the libusb include and running library
  750. // cgusb->speed = libusb_get_device_speed(dev);
  751. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  752. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  753. if (err > 0)
  754. cgusb->prod_string = strdup((char *)strbuf);
  755. else
  756. cgusb->prod_string = (char *)BLANK;
  757. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  758. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  759. if (err > 0)
  760. cgusb->manuf_string = strdup((char *)strbuf);
  761. else
  762. cgusb->manuf_string = (char *)BLANK;
  763. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  764. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  765. if (err > 0)
  766. cgusb->serial_string = strdup((char *)strbuf);
  767. else
  768. cgusb->serial_string = (char *)BLANK;
  769. // TODO: ?
  770. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  771. // cgusb->interfaceVersion
  772. 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);
  773. cgpu->usbdev = cgusb;
  774. libusb_free_config_descriptor(config);
  775. // Allow a name change based on the idVendor+idProduct
  776. // N.B. must be done before calling add_cgpu()
  777. if (strcmp(cgpu->drv->name, found->name)) {
  778. if (!cgpu->drv->copy)
  779. cgpu->drv = copy_drv(cgpu->drv);
  780. cgpu->drv->name = (char *)(found->name);
  781. }
  782. return true;
  783. cldame:
  784. libusb_close(cgusb->handle);
  785. dame:
  786. if (config)
  787. libusb_free_config_descriptor(config);
  788. cgusb = free_cgusb(cgusb);
  789. return false;
  790. }
  791. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  792. {
  793. struct libusb_device_descriptor desc;
  794. int err;
  795. err = libusb_get_device_descriptor(dev, &desc);
  796. if (err) {
  797. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  798. return false;
  799. }
  800. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  801. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  802. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  803. return false;
  804. }
  805. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  806. drv->name, look->name, look->idVendor, look->idProduct);
  807. return true;
  808. }
  809. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  810. {
  811. struct usb_find_devices *found;
  812. int i;
  813. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  814. if (find_dev[i].drv == drvnum) {
  815. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  816. found = malloc(sizeof(*found));
  817. memcpy(found, &(find_dev[i]), sizeof(*found));
  818. return found;
  819. }
  820. }
  821. return NULL;
  822. }
  823. static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
  824. {
  825. #ifdef USE_BITFORCE
  826. if (drv->drv == DRIVER_BITFORCE)
  827. return usb_check_each(DRV_BITFORCE, drv, dev);
  828. #endif
  829. #ifdef USE_ICARUS
  830. if (drv->drv == DRIVER_ICARUS)
  831. return usb_check_each(DRV_ICARUS, drv, dev);
  832. #endif
  833. #ifdef USE_MODMINER
  834. if (drv->drv == DRIVER_MODMINER)
  835. return usb_check_each(DRV_MODMINER, drv, dev);
  836. #endif
  837. return NULL;
  838. }
  839. void usb_detect(struct device_drv *drv, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *))
  840. {
  841. libusb_device **list;
  842. ssize_t count, i;
  843. struct usb_find_devices *found;
  844. cgusb_check_init();
  845. count = libusb_get_device_list(NULL, &list);
  846. if (count < 0) {
  847. applog(LOG_DEBUG, "USB scan devices: failed, err %d", count);
  848. return;
  849. }
  850. if (count == 0)
  851. applog(LOG_DEBUG, "USB scan devices: found no devices");
  852. for (i = 0; i < count; i++) {
  853. mutex_lock(list_lock);
  854. if (in_use(list[i], false))
  855. mutex_unlock(list_lock);
  856. else {
  857. add_used(list[i], false);
  858. mutex_unlock(list_lock);
  859. found = usb_check(drv, list[i]);
  860. if (!found)
  861. release_dev(list[i], true);
  862. else
  863. if (!device_detect(list[i], found))
  864. release_dev(list[i], true);
  865. }
  866. }
  867. libusb_free_device_list(list, 1);
  868. }
  869. // Set this to 0 to remove stats processing
  870. #define DO_USB_STATS 1
  871. #if DO_USB_STATS
  872. #define USB_STATS(sgpu, sta, fin, err, cmd, seq) stats(cgpu, sta, fin, err, cmd, seq)
  873. #define STATS_TIMEVAL(tv) gettimeofday(tv, NULL)
  874. #else
  875. #define USB_STATS(sgpu, sta, fin, err, cmd, seq)
  876. #define STATS_TIMEVAL(tv)
  877. #endif
  878. // The stat data can be spurious due to not locking it before copying it -
  879. // however that would require the stat() function to also lock and release
  880. // a mutex every time a usb read or write is called which would slow
  881. // things down more
  882. struct api_data *api_usb_stats(__maybe_unused int *count)
  883. {
  884. #if DO_USB_STATS
  885. struct cg_usb_stats_details *details;
  886. struct cg_usb_stats *sta;
  887. struct api_data *root = NULL;
  888. int device;
  889. int cmdseq;
  890. cgusb_check_init();
  891. if (next_stat == 0)
  892. return NULL;
  893. while (*count < next_stat * C_MAX * 2) {
  894. device = *count / (C_MAX * 2);
  895. cmdseq = *count % (C_MAX * 2);
  896. (*count)++;
  897. sta = &(usb_stats[device]);
  898. details = &(sta->details[cmdseq]);
  899. // Only show stats that have results
  900. if (details->item[CMD_CMD].count == 0 &&
  901. details->item[CMD_TIMEOUT].count == 0 &&
  902. details->item[CMD_ERROR].count == 0)
  903. continue;
  904. root = api_add_string(root, "Name", sta->name, false);
  905. root = api_add_int(root, "ID", &(sta->device_id), false);
  906. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  907. root = api_add_int(root, "Seq", &(details->seq), true);
  908. root = api_add_uint64(root, "Count",
  909. &(details->item[CMD_CMD].count), true);
  910. root = api_add_double(root, "Total Delay",
  911. &(details->item[CMD_CMD].total_delay), true);
  912. root = api_add_double(root, "Min Delay",
  913. &(details->item[CMD_CMD].min_delay), true);
  914. root = api_add_double(root, "Max Delay",
  915. &(details->item[CMD_CMD].max_delay), true);
  916. root = api_add_uint64(root, "Timeout Count",
  917. &(details->item[CMD_TIMEOUT].count), true);
  918. root = api_add_double(root, "Timeout Total Delay",
  919. &(details->item[CMD_TIMEOUT].total_delay), true);
  920. root = api_add_double(root, "Timeout Min Delay",
  921. &(details->item[CMD_TIMEOUT].min_delay), true);
  922. root = api_add_double(root, "Timeout Max Delay",
  923. &(details->item[CMD_TIMEOUT].max_delay), true);
  924. root = api_add_uint64(root, "Error Count",
  925. &(details->item[CMD_ERROR].count), true);
  926. root = api_add_double(root, "Error Total Delay",
  927. &(details->item[CMD_ERROR].total_delay), true);
  928. root = api_add_double(root, "Error Min Delay",
  929. &(details->item[CMD_ERROR].min_delay), true);
  930. root = api_add_double(root, "Error Max Delay",
  931. &(details->item[CMD_ERROR].max_delay), true);
  932. root = api_add_timeval(root, "First Command",
  933. &(details->item[CMD_CMD].first), true);
  934. root = api_add_timeval(root, "Last Command",
  935. &(details->item[CMD_CMD].last), true);
  936. root = api_add_timeval(root, "First Timeout",
  937. &(details->item[CMD_TIMEOUT].first), true);
  938. root = api_add_timeval(root, "Last Timeout",
  939. &(details->item[CMD_TIMEOUT].last), true);
  940. root = api_add_timeval(root, "First Error",
  941. &(details->item[CMD_ERROR].first), true);
  942. root = api_add_timeval(root, "Last Error",
  943. &(details->item[CMD_ERROR].last), true);
  944. return root;
  945. }
  946. #endif
  947. return NULL;
  948. }
  949. #if DO_USB_STATS
  950. static void newstats(struct cgpu_info *cgpu)
  951. {
  952. int i;
  953. cgpu->usbstat = ++next_stat;
  954. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * next_stat);
  955. usb_stats[next_stat-1].name = cgpu->drv->name;
  956. usb_stats[next_stat-1].device_id = -1;
  957. usb_stats[next_stat-1].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  958. for (i = 1; i < C_MAX * 2; i += 2)
  959. usb_stats[next_stat-1].details[i].seq = 1;
  960. }
  961. #endif
  962. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  963. {
  964. #if DO_USB_STATS
  965. if (cgpu->usbstat < 1)
  966. newstats(cgpu);
  967. // we don't know the device_id until after add_cgpu()
  968. usb_stats[cgpu->usbstat - 1].device_id = cgpu->device_id;
  969. #endif
  970. }
  971. #if DO_USB_STATS
  972. static void stats(struct cgpu_info *cgpu, struct timeval *tv_start, struct timeval *tv_finish, int err, enum usb_cmds cmd, int seq)
  973. {
  974. struct cg_usb_stats_details *details;
  975. double diff;
  976. int item;
  977. if (cgpu->usbstat < 1)
  978. newstats(cgpu);
  979. details = &(usb_stats[cgpu->usbstat - 1].details[cmd * 2 + seq]);
  980. diff = tdiff(tv_finish, tv_start);
  981. switch (err) {
  982. case LIBUSB_SUCCESS:
  983. item = CMD_CMD;
  984. break;
  985. case LIBUSB_ERROR_TIMEOUT:
  986. item = CMD_TIMEOUT;
  987. break;
  988. default:
  989. item = CMD_ERROR;
  990. break;
  991. }
  992. if (details->item[item].count == 0) {
  993. details->item[item].min_delay = diff;
  994. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  995. } else if (diff < details->item[item].min_delay)
  996. details->item[item].min_delay = diff;
  997. if (diff > details->item[item].max_delay)
  998. details->item[item].max_delay = diff;
  999. details->item[item].total_delay += diff;
  1000. memcpy(&(details->item[item].last), tv_start, sizeof(tv_start));
  1001. details->item[item].count++;
  1002. }
  1003. static void rejected_inc(struct cgpu_info *cgpu)
  1004. {
  1005. struct cg_usb_stats_details *details;
  1006. int item = CMD_ERROR;
  1007. if (cgpu->usbstat < 1)
  1008. newstats(cgpu);
  1009. details = &(usb_stats[cgpu->usbstat - 1].details[C_REJECTED * 2 + 0]);
  1010. details->item[item].count++;
  1011. }
  1012. #endif
  1013. 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)
  1014. {
  1015. struct cg_usb_device *usbdev = cgpu->usbdev;
  1016. #if DO_USB_STATS
  1017. struct timeval tv_start;
  1018. #endif
  1019. struct timeval read_start, tv_finish;
  1020. unsigned int initial_timeout;
  1021. double max, done;
  1022. int err, got, tot, i;
  1023. bool first = true;
  1024. if (cgpu->nodev) {
  1025. *buf = '\0';
  1026. *processed = 0;
  1027. #if DO_USB_STATS
  1028. rejected_inc(cgpu);
  1029. #endif
  1030. return LIBUSB_ERROR_NO_DEVICE;
  1031. }
  1032. if (timeout == DEVTIMEOUT)
  1033. timeout = usbdev->found->timeout;
  1034. if (eol == -1) {
  1035. got = 0;
  1036. STATS_TIMEVAL(&tv_start);
  1037. err = libusb_bulk_transfer(usbdev->handle,
  1038. usbdev->found->eps[ep].ep,
  1039. (unsigned char *)buf,
  1040. bufsiz, &got, timeout);
  1041. STATS_TIMEVAL(&tv_finish);
  1042. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1043. if (ftdi) {
  1044. // first 2 bytes returned are an FTDI status
  1045. if (got > 2) {
  1046. got -= 2;
  1047. memmove(buf, buf+2, got+1);
  1048. } else {
  1049. got = 0;
  1050. *buf = '\0';
  1051. }
  1052. }
  1053. *processed = got;
  1054. if (NODEV(err)) {
  1055. cgpu->nodev = true;
  1056. release_cgpu(cgpu);
  1057. }
  1058. return err;
  1059. }
  1060. tot = 0;
  1061. err = LIBUSB_SUCCESS;
  1062. initial_timeout = timeout;
  1063. max = ((double)timeout) / 1000.0;
  1064. gettimeofday(&read_start, NULL);
  1065. while (bufsiz) {
  1066. got = 0;
  1067. STATS_TIMEVAL(&tv_start);
  1068. err = libusb_bulk_transfer(usbdev->handle,
  1069. usbdev->found->eps[ep].ep,
  1070. (unsigned char *)buf,
  1071. bufsiz, &got, timeout);
  1072. gettimeofday(&tv_finish, NULL);
  1073. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, first ? SEQ0 : SEQ1);
  1074. if (ftdi) {
  1075. // first 2 bytes returned are an FTDI status
  1076. if (got > 2) {
  1077. got -= 2;
  1078. memmove(buf, buf+2, got+1);
  1079. } else {
  1080. got = 0;
  1081. *buf = '\0';
  1082. }
  1083. }
  1084. tot += got;
  1085. if (err)
  1086. break;
  1087. // WARNING - this will return data past EOL ('if' there is extra data)
  1088. for (i = 0; i < got; i++)
  1089. if (buf[i] == eol)
  1090. goto goteol;
  1091. buf += got;
  1092. bufsiz -= got;
  1093. first = false;
  1094. done = tdiff(&tv_finish, &read_start);
  1095. // N.B. this is return LIBUSB_SUCCESS with whatever size has already been read
  1096. if (unlikely(done >= max))
  1097. break;
  1098. timeout = initial_timeout - (done * 1000);
  1099. }
  1100. goteol:
  1101. *processed = tot;
  1102. if (NODEV(err)) {
  1103. cgpu->nodev = true;
  1104. release_cgpu(cgpu);
  1105. }
  1106. return err;
  1107. }
  1108. int _usb_write(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, enum usb_cmds cmd)
  1109. {
  1110. struct cg_usb_device *usbdev = cgpu->usbdev;
  1111. #if DO_USB_STATS
  1112. struct timeval tv_start, tv_finish;
  1113. #endif
  1114. int err, sent;
  1115. if (cgpu->nodev) {
  1116. *processed = 0;
  1117. #if DO_USB_STATS
  1118. rejected_inc(cgpu);
  1119. #endif
  1120. return LIBUSB_ERROR_NO_DEVICE;
  1121. }
  1122. sent = 0;
  1123. STATS_TIMEVAL(&tv_start);
  1124. err = libusb_bulk_transfer(usbdev->handle,
  1125. usbdev->found->eps[ep].ep,
  1126. (unsigned char *)buf,
  1127. bufsiz, &sent,
  1128. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1129. STATS_TIMEVAL(&tv_finish);
  1130. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1131. *processed = sent;
  1132. if (NODEV(err)) {
  1133. cgpu->nodev = true;
  1134. release_cgpu(cgpu);
  1135. }
  1136. return err;
  1137. }
  1138. 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)
  1139. {
  1140. struct cg_usb_device *usbdev = cgpu->usbdev;
  1141. #if DO_USB_STATS
  1142. struct timeval tv_start, tv_finish;
  1143. #endif
  1144. int err;
  1145. if (cgpu->nodev) {
  1146. #if DO_USB_STATS
  1147. rejected_inc(cgpu);
  1148. #endif
  1149. return LIBUSB_ERROR_NO_DEVICE;
  1150. }
  1151. STATS_TIMEVAL(&tv_start);
  1152. err = libusb_control_transfer(usbdev->handle, request_type,
  1153. bRequest, wValue, wIndex, NULL, 0,
  1154. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1155. STATS_TIMEVAL(&tv_finish);
  1156. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1157. if (NODEV(err)) {
  1158. cgpu->nodev = true;
  1159. release_cgpu(cgpu);
  1160. }
  1161. return err;
  1162. }
  1163. void usb_cleanup()
  1164. {
  1165. // TODO:
  1166. }