usbutils.c 39 KB

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