usbutils.c 35 KB

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