usbutils.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440
  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. stats_initialised = true;
  503. }
  504. mutex_unlock(&cgusb_lock);
  505. }
  506. #ifdef WIN32
  507. #else
  508. #include <errno.h>
  509. #include <unistd.h>
  510. #include <sys/types.h>
  511. #include <sys/ipc.h>
  512. #include <sys/sem.h>
  513. #include <sys/types.h>
  514. #include <sys/stat.h>
  515. #include <fcntl.h>
  516. union semun {
  517. int sem;
  518. struct semid_ds *seminfo;
  519. ushort *all;
  520. };
  521. #endif
  522. // Any errors should always be printed since they will rarely if ever occur
  523. // and thus it is best to always display them
  524. static bool cgminer_usb_lock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  525. {
  526. #ifdef WIN32
  527. // NOOP for now
  528. drv = 0;
  529. bus_number = device_address = 0;
  530. return true;
  531. #else
  532. struct semid_ds seminfo;
  533. union semun opt;
  534. char name[64];
  535. key_t key;
  536. int fd, sem, count;
  537. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  538. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  539. if (fd == -1) {
  540. applog(LOG_ERR,
  541. "SEM: %s USB open failed '%s' err (%d) %s",
  542. drv->dname, name, errno, strerror(errno));
  543. return false;
  544. }
  545. close(fd);
  546. key = ftok(name, 'K');
  547. sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 438);
  548. if (sem < 0) {
  549. if (errno != EEXIST) {
  550. applog(LOG_ERR,
  551. "SEM: %s USB failed to get '%s' err (%d) %s",
  552. drv->dname, name, errno, strerror(errno));
  553. return false;
  554. }
  555. sem = semget(key, 1, 0);
  556. if (sem < 0) {
  557. applog(LOG_ERR,
  558. "SEM: %s USB failed to access '%s' err (%d) %s",
  559. drv->dname, name, errno, strerror(errno));
  560. return false;
  561. }
  562. opt.seminfo = &seminfo;
  563. count = 0;
  564. while (++count) {
  565. // Should NEVER take 100ms
  566. if (count > 99) {
  567. applog(LOG_ERR,
  568. "SEM: %s USB timeout waiting for (%d) '%s'",
  569. drv->dname, sem, name);
  570. return false;
  571. }
  572. if (semctl(sem, 0, IPC_STAT, opt) == -1) {
  573. applog(LOG_ERR,
  574. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  575. drv->dname, sem, name, count, errno, strerror(errno));
  576. return false;
  577. }
  578. if (opt.seminfo->sem_otime != 0)
  579. break;
  580. nmsleep(1);
  581. }
  582. }
  583. struct sembuf sops[] = {
  584. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  585. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  586. };
  587. if (semop(sem, sops, 2)) {
  588. if (errno == EAGAIN) {
  589. applog(LOG_WARNING,
  590. "SEM: %s USB failed to get (%d) '%s' - device in use",
  591. drv->dname, sem, name);
  592. } else {
  593. applog(LOG_DEBUG,
  594. "SEM: %s USB failed to get (%d) '%s' err(%d) %s",
  595. drv->dname, sem, name, errno, strerror(errno));
  596. }
  597. return false;
  598. }
  599. return true;
  600. #endif
  601. }
  602. static bool cgminer_usb_lock(struct device_drv *drv, libusb_device *dev)
  603. {
  604. return cgminer_usb_lock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  605. }
  606. // Any errors should always be printed since they will rarely if ever occur
  607. // and thus it is best to always display them
  608. static void cgminer_usb_unlock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  609. {
  610. #ifdef WIN32
  611. // NOOP for now
  612. drv = 0;
  613. bus_number = device_address = 0;
  614. #else
  615. char name[64];
  616. key_t key;
  617. int fd, sem;
  618. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  619. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  620. if (fd == -1) {
  621. applog(LOG_ERR,
  622. "SEM: %s USB open failed '%s' for release err (%d) %s",
  623. drv->dname, name, errno, strerror(errno));
  624. return;
  625. }
  626. close(fd);
  627. key = ftok(name, 'K');
  628. sem = semget(key, 1, 0);
  629. if (sem < 0) {
  630. applog(LOG_ERR,
  631. "SEM: %s USB failed to get '%s' for release err (%d) %s",
  632. drv->dname, name, errno, strerror(errno));
  633. return;
  634. }
  635. struct sembuf sops[] = {
  636. { 0, -1, SEM_UNDO }
  637. };
  638. // Allow a 10ms timeout
  639. // exceeding this timeout means it would probably never succeed anyway
  640. struct timespec timeout = { 0, 10000000 };
  641. // Wait forever since we shoud be the one who has it
  642. if (semtimedop(sem, sops, 1, &timeout)) {
  643. applog(LOG_ERR,
  644. "SEM: %d USB failed to release '%s' err (%d) %s",
  645. drv->dname, name, errno, strerror(errno));
  646. }
  647. return;
  648. #endif
  649. }
  650. static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
  651. {
  652. cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  653. }
  654. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  655. {
  656. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  657. free(cgusb->serial_string);
  658. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  659. free(cgusb->manuf_string);
  660. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  661. free(cgusb->prod_string);
  662. free(cgusb->descriptor);
  663. free(cgusb->found);
  664. free(cgusb);
  665. return NULL;
  666. }
  667. void usb_uninit(struct cgpu_info *cgpu)
  668. {
  669. libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface);
  670. libusb_close(cgpu->usbdev->handle);
  671. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  672. }
  673. void release_cgpu(struct cgpu_info *cgpu)
  674. {
  675. struct cg_usb_device *cgusb = cgpu->usbdev;
  676. int i;
  677. cgpu->usbinfo.nodev = true;
  678. cgpu->usbinfo.nodev_count++;
  679. gettimeofday(&(cgpu->usbinfo.last_nodev), NULL);
  680. // Any devices sharing the same USB device should be marked also
  681. // Currently only MMQ shares a USB device
  682. for (i = 0; i < total_devices; i++)
  683. if (devices[i] != cgpu && devices[i]->usbdev == cgusb) {
  684. devices[i]->usbinfo.nodev = true;
  685. devices[i]->usbinfo.nodev_count++;
  686. memcpy(&(devices[i]->usbinfo.last_nodev),
  687. &(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
  688. devices[i]->usbdev = NULL;
  689. }
  690. usb_uninit(cgpu);
  691. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  692. }
  693. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  694. {
  695. struct cg_usb_device *cgusb = NULL;
  696. struct libusb_config_descriptor *config = NULL;
  697. const struct libusb_interface_descriptor *idesc;
  698. const struct libusb_endpoint_descriptor *epdesc;
  699. unsigned char strbuf[STRBUFLEN+1];
  700. char devstr[STRBUFLEN+1];
  701. int err, i, j, k;
  702. cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
  703. cgpu->usbinfo.device_address = libusb_get_device_address(dev);
  704. sprintf(devstr, "- %s device %d:%d", found->name,
  705. cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  706. cgusb = calloc(1, sizeof(*cgusb));
  707. cgusb->found = found;
  708. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  709. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  710. if (err) {
  711. applog(LOG_DEBUG,
  712. "USB init failed to get descriptor, err %d %s",
  713. err, devstr);
  714. goto dame;
  715. }
  716. err = libusb_open(dev, &(cgusb->handle));
  717. if (err) {
  718. switch (err) {
  719. case LIBUSB_ERROR_ACCESS:
  720. applog(LOG_ERR,
  721. "USB init open device failed, err %d, "
  722. "you dont have priviledge to access %s",
  723. err, devstr);
  724. break;
  725. #ifdef WIN32
  726. // Windows specific message
  727. case LIBUSB_ERROR_NOT_SUPPORTED:
  728. applog(LOG_ERR,
  729. "USB init, open device failed, err %d, "
  730. "you need to install a Windows USB driver for %s",
  731. err, devstr);
  732. break;
  733. #endif
  734. default:
  735. applog(LOG_DEBUG,
  736. "USB init, open failed, err %d %s",
  737. err, devstr);
  738. }
  739. goto dame;
  740. }
  741. if (libusb_kernel_driver_active(cgusb->handle, found->config) == 1) {
  742. applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
  743. err = libusb_detach_kernel_driver(cgusb->handle, found->config);
  744. if (err == 0) {
  745. applog(LOG_DEBUG,
  746. "USB init, kernel detached successfully %s",
  747. devstr);
  748. } else {
  749. applog(LOG_WARNING,
  750. "USB init, kernel detach failed, err %d in use? %s",
  751. err, devstr);
  752. goto cldame;
  753. }
  754. }
  755. err = libusb_set_configuration(cgusb->handle, found->config);
  756. if (err) {
  757. switch(err) {
  758. case LIBUSB_ERROR_BUSY:
  759. applog(LOG_WARNING,
  760. "USB init, set config %d in use %s",
  761. found->config, devstr);
  762. break;
  763. default:
  764. applog(LOG_DEBUG,
  765. "USB init, failed to set config to %d, err %d %s",
  766. found->config, err, devstr);
  767. }
  768. goto cldame;
  769. }
  770. err = libusb_get_active_config_descriptor(dev, &config);
  771. if (err) {
  772. applog(LOG_DEBUG,
  773. "USB init, failed to get config descriptor %d, err %d %s",
  774. found->config, err, devstr);
  775. goto cldame;
  776. }
  777. if ((int)(config->bNumInterfaces) <= found->interface)
  778. goto cldame;
  779. for (i = 0; i < found->epcount; i++)
  780. found->eps[i].found = false;
  781. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  782. idesc = &(config->interface[found->interface].altsetting[i]);
  783. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  784. epdesc = &(idesc->endpoint[j]);
  785. for (k = 0; k < found->epcount; k++) {
  786. if (!found->eps[k].found) {
  787. if (epdesc->bmAttributes == found->eps[k].att
  788. && epdesc->wMaxPacketSize >= found->eps[k].size
  789. && epdesc->bEndpointAddress == found->eps[k].ep) {
  790. found->eps[k].found = true;
  791. break;
  792. }
  793. }
  794. }
  795. }
  796. }
  797. for (i = 0; i < found->epcount; i++)
  798. if (found->eps[i].found == false)
  799. goto cldame;
  800. err = libusb_claim_interface(cgusb->handle, found->interface);
  801. if (err) {
  802. switch(err) {
  803. case LIBUSB_ERROR_BUSY:
  804. applog(LOG_WARNING,
  805. "USB init, claim interface %d in use %s",
  806. found->interface, devstr);
  807. break;
  808. default:
  809. applog(LOG_DEBUG,
  810. "USB init, claim interface %d failed, err %d %s",
  811. found->interface, err, devstr);
  812. }
  813. goto cldame;
  814. }
  815. cgusb->usbver = cgusb->descriptor->bcdUSB;
  816. // TODO: allow this with the right version of the libusb include and running library
  817. // cgusb->speed = libusb_get_device_speed(dev);
  818. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  819. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  820. if (err > 0)
  821. cgusb->prod_string = strdup((char *)strbuf);
  822. else
  823. cgusb->prod_string = (char *)BLANK;
  824. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  825. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  826. if (err > 0)
  827. cgusb->manuf_string = strdup((char *)strbuf);
  828. else
  829. cgusb->manuf_string = (char *)BLANK;
  830. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  831. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  832. if (err > 0)
  833. cgusb->serial_string = strdup((char *)strbuf);
  834. else
  835. cgusb->serial_string = (char *)BLANK;
  836. // TODO: ?
  837. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  838. // cgusb->interfaceVersion
  839. applog(LOG_DEBUG,
  840. "USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
  841. devstr, cgusb->usbver, cgusb->prod_string,
  842. cgusb->manuf_string, cgusb->serial_string);
  843. cgpu->usbdev = cgusb;
  844. libusb_free_config_descriptor(config);
  845. // Allow a name change based on the idVendor+idProduct
  846. // N.B. must be done before calling add_cgpu()
  847. if (strcmp(cgpu->drv->name, found->name)) {
  848. if (!cgpu->drv->copy)
  849. cgpu->drv = copy_drv(cgpu->drv);
  850. cgpu->drv->name = (char *)(found->name);
  851. }
  852. return true;
  853. cldame:
  854. libusb_close(cgusb->handle);
  855. dame:
  856. if (config)
  857. libusb_free_config_descriptor(config);
  858. cgusb = free_cgusb(cgusb);
  859. return false;
  860. }
  861. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  862. {
  863. struct libusb_device_descriptor desc;
  864. int err;
  865. err = libusb_get_device_descriptor(dev, &desc);
  866. if (err) {
  867. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  868. return false;
  869. }
  870. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  871. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  872. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  873. return false;
  874. }
  875. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  876. drv->name, look->name, look->idVendor, look->idProduct);
  877. return true;
  878. }
  879. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  880. {
  881. struct usb_find_devices *found;
  882. int i;
  883. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  884. if (find_dev[i].drv == drvnum) {
  885. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  886. found = malloc(sizeof(*found));
  887. memcpy(found, &(find_dev[i]), sizeof(*found));
  888. return found;
  889. }
  890. }
  891. return NULL;
  892. }
  893. static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
  894. {
  895. #ifdef USE_BITFORCE
  896. if (drv->drv == DRIVER_BITFORCE)
  897. return usb_check_each(DRV_BITFORCE, drv, dev);
  898. #endif
  899. #ifdef USE_ICARUS
  900. if (drv->drv == DRIVER_ICARUS)
  901. return usb_check_each(DRV_ICARUS, drv, dev);
  902. #endif
  903. #ifdef USE_MODMINER
  904. if (drv->drv == DRIVER_MODMINER)
  905. return usb_check_each(DRV_MODMINER, drv, dev);
  906. #endif
  907. return NULL;
  908. }
  909. void usb_detect(struct device_drv *drv, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *))
  910. {
  911. libusb_device **list;
  912. ssize_t count, i;
  913. struct usb_find_devices *found;
  914. cgusb_check_init();
  915. count = libusb_get_device_list(NULL, &list);
  916. if (count < 0) {
  917. applog(LOG_DEBUG, "USB scan devices: failed, err %d", count);
  918. return;
  919. }
  920. if (count == 0)
  921. applog(LOG_DEBUG, "USB scan devices: found no devices");
  922. for (i = 0; i < count; i++) {
  923. found = usb_check(drv, list[i]);
  924. if (found != NULL) {
  925. if (cgminer_usb_lock(drv, list[i]) == false)
  926. free(found);
  927. else {
  928. if (!device_detect(list[i], found))
  929. cgminer_usb_unlock(drv, list[i]);
  930. }
  931. }
  932. }
  933. libusb_free_device_list(list, 1);
  934. }
  935. // Set this to 0 to remove stats processing
  936. #define DO_USB_STATS 1
  937. #if DO_USB_STATS
  938. #define USB_STATS(sgpu, sta, fin, err, cmd, seq) stats(cgpu, sta, fin, err, cmd, seq)
  939. #define STATS_TIMEVAL(tv) gettimeofday(tv, NULL)
  940. #else
  941. #define USB_STATS(sgpu, sta, fin, err, cmd, seq)
  942. #define STATS_TIMEVAL(tv)
  943. #endif
  944. // The stat data can be spurious due to not locking it before copying it -
  945. // however that would require the stat() function to also lock and release
  946. // a mutex every time a usb read or write is called which would slow
  947. // things down more
  948. struct api_data *api_usb_stats(__maybe_unused int *count)
  949. {
  950. #if DO_USB_STATS
  951. struct cg_usb_stats_details *details;
  952. struct cg_usb_stats *sta;
  953. struct api_data *root = NULL;
  954. int device;
  955. int cmdseq;
  956. cgusb_check_init();
  957. if (next_stat == 0)
  958. return NULL;
  959. while (*count < next_stat * C_MAX * 2) {
  960. device = *count / (C_MAX * 2);
  961. cmdseq = *count % (C_MAX * 2);
  962. (*count)++;
  963. sta = &(usb_stats[device]);
  964. details = &(sta->details[cmdseq]);
  965. // Only show stats that have results
  966. if (details->item[CMD_CMD].count == 0 &&
  967. details->item[CMD_TIMEOUT].count == 0 &&
  968. details->item[CMD_ERROR].count == 0)
  969. continue;
  970. root = api_add_string(root, "Name", sta->name, false);
  971. root = api_add_int(root, "ID", &(sta->device_id), false);
  972. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  973. root = api_add_int(root, "Seq", &(details->seq), true);
  974. root = api_add_uint64(root, "Count",
  975. &(details->item[CMD_CMD].count), true);
  976. root = api_add_double(root, "Total Delay",
  977. &(details->item[CMD_CMD].total_delay), true);
  978. root = api_add_double(root, "Min Delay",
  979. &(details->item[CMD_CMD].min_delay), true);
  980. root = api_add_double(root, "Max Delay",
  981. &(details->item[CMD_CMD].max_delay), true);
  982. root = api_add_uint64(root, "Timeout Count",
  983. &(details->item[CMD_TIMEOUT].count), true);
  984. root = api_add_double(root, "Timeout Total Delay",
  985. &(details->item[CMD_TIMEOUT].total_delay), true);
  986. root = api_add_double(root, "Timeout Min Delay",
  987. &(details->item[CMD_TIMEOUT].min_delay), true);
  988. root = api_add_double(root, "Timeout Max Delay",
  989. &(details->item[CMD_TIMEOUT].max_delay), true);
  990. root = api_add_uint64(root, "Error Count",
  991. &(details->item[CMD_ERROR].count), true);
  992. root = api_add_double(root, "Error Total Delay",
  993. &(details->item[CMD_ERROR].total_delay), true);
  994. root = api_add_double(root, "Error Min Delay",
  995. &(details->item[CMD_ERROR].min_delay), true);
  996. root = api_add_double(root, "Error Max Delay",
  997. &(details->item[CMD_ERROR].max_delay), true);
  998. root = api_add_timeval(root, "First Command",
  999. &(details->item[CMD_CMD].first), true);
  1000. root = api_add_timeval(root, "Last Command",
  1001. &(details->item[CMD_CMD].last), true);
  1002. root = api_add_timeval(root, "First Timeout",
  1003. &(details->item[CMD_TIMEOUT].first), true);
  1004. root = api_add_timeval(root, "Last Timeout",
  1005. &(details->item[CMD_TIMEOUT].last), true);
  1006. root = api_add_timeval(root, "First Error",
  1007. &(details->item[CMD_ERROR].first), true);
  1008. root = api_add_timeval(root, "Last Error",
  1009. &(details->item[CMD_ERROR].last), true);
  1010. return root;
  1011. }
  1012. #endif
  1013. return NULL;
  1014. }
  1015. #if DO_USB_STATS
  1016. static void newstats(struct cgpu_info *cgpu)
  1017. {
  1018. int i;
  1019. cgpu->usbinfo.usbstat = ++next_stat;
  1020. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * next_stat);
  1021. usb_stats[next_stat-1].name = cgpu->drv->name;
  1022. usb_stats[next_stat-1].device_id = -1;
  1023. usb_stats[next_stat-1].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  1024. for (i = 1; i < C_MAX * 2; i += 2)
  1025. usb_stats[next_stat-1].details[i].seq = 1;
  1026. }
  1027. #endif
  1028. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  1029. {
  1030. #if DO_USB_STATS
  1031. if (cgpu->usbinfo.usbstat < 1)
  1032. newstats(cgpu);
  1033. // we don't know the device_id until after add_cgpu()
  1034. usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
  1035. #endif
  1036. }
  1037. #if DO_USB_STATS
  1038. static void stats(struct cgpu_info *cgpu, struct timeval *tv_start, struct timeval *tv_finish, int err, enum usb_cmds cmd, int seq)
  1039. {
  1040. struct cg_usb_stats_details *details;
  1041. double diff;
  1042. int item;
  1043. if (cgpu->usbinfo.usbstat < 1)
  1044. newstats(cgpu);
  1045. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
  1046. diff = tdiff(tv_finish, tv_start);
  1047. switch (err) {
  1048. case LIBUSB_SUCCESS:
  1049. item = CMD_CMD;
  1050. break;
  1051. case LIBUSB_ERROR_TIMEOUT:
  1052. item = CMD_TIMEOUT;
  1053. break;
  1054. default:
  1055. item = CMD_ERROR;
  1056. break;
  1057. }
  1058. if (details->item[item].count == 0) {
  1059. details->item[item].min_delay = diff;
  1060. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  1061. } else if (diff < details->item[item].min_delay)
  1062. details->item[item].min_delay = diff;
  1063. if (diff > details->item[item].max_delay)
  1064. details->item[item].max_delay = diff;
  1065. details->item[item].total_delay += diff;
  1066. memcpy(&(details->item[item].last), tv_start, sizeof(tv_start));
  1067. details->item[item].count++;
  1068. }
  1069. static void rejected_inc(struct cgpu_info *cgpu)
  1070. {
  1071. struct cg_usb_stats_details *details;
  1072. int item = CMD_ERROR;
  1073. if (cgpu->usbinfo.usbstat < 1)
  1074. newstats(cgpu);
  1075. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  1076. details->item[item].count++;
  1077. }
  1078. #endif
  1079. 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)
  1080. {
  1081. struct cg_usb_device *usbdev = cgpu->usbdev;
  1082. #if DO_USB_STATS
  1083. struct timeval tv_start;
  1084. #endif
  1085. struct timeval read_start, tv_finish;
  1086. unsigned int initial_timeout;
  1087. double max, done;
  1088. int err, got, tot, i;
  1089. bool first = true;
  1090. if (cgpu->usbinfo.nodev) {
  1091. *buf = '\0';
  1092. *processed = 0;
  1093. #if DO_USB_STATS
  1094. rejected_inc(cgpu);
  1095. #endif
  1096. return LIBUSB_ERROR_NO_DEVICE;
  1097. }
  1098. if (timeout == DEVTIMEOUT)
  1099. timeout = usbdev->found->timeout;
  1100. if (eol == -1) {
  1101. got = 0;
  1102. STATS_TIMEVAL(&tv_start);
  1103. err = libusb_bulk_transfer(usbdev->handle,
  1104. usbdev->found->eps[ep].ep,
  1105. (unsigned char *)buf,
  1106. bufsiz, &got, timeout);
  1107. STATS_TIMEVAL(&tv_finish);
  1108. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1109. if (ftdi) {
  1110. // first 2 bytes returned are an FTDI status
  1111. if (got > 2) {
  1112. got -= 2;
  1113. memmove(buf, buf+2, got+1);
  1114. } else {
  1115. got = 0;
  1116. *buf = '\0';
  1117. }
  1118. }
  1119. *processed = got;
  1120. if (NODEV(err))
  1121. release_cgpu(cgpu);
  1122. return err;
  1123. }
  1124. tot = 0;
  1125. err = LIBUSB_SUCCESS;
  1126. initial_timeout = timeout;
  1127. max = ((double)timeout) / 1000.0;
  1128. gettimeofday(&read_start, NULL);
  1129. while (bufsiz) {
  1130. got = 0;
  1131. STATS_TIMEVAL(&tv_start);
  1132. err = libusb_bulk_transfer(usbdev->handle,
  1133. usbdev->found->eps[ep].ep,
  1134. (unsigned char *)buf,
  1135. bufsiz, &got, timeout);
  1136. gettimeofday(&tv_finish, NULL);
  1137. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, first ? SEQ0 : SEQ1);
  1138. if (ftdi) {
  1139. // first 2 bytes returned are an FTDI status
  1140. if (got > 2) {
  1141. got -= 2;
  1142. memmove(buf, buf+2, got+1);
  1143. } else {
  1144. got = 0;
  1145. *buf = '\0';
  1146. }
  1147. }
  1148. tot += got;
  1149. if (err)
  1150. break;
  1151. // WARNING - this will return data past EOL ('if' there is extra data)
  1152. for (i = 0; i < got; i++)
  1153. if (buf[i] == eol)
  1154. goto goteol;
  1155. buf += got;
  1156. bufsiz -= got;
  1157. first = false;
  1158. done = tdiff(&tv_finish, &read_start);
  1159. // N.B. this is return LIBUSB_SUCCESS with whatever size has already been read
  1160. if (unlikely(done >= max))
  1161. break;
  1162. timeout = initial_timeout - (done * 1000);
  1163. }
  1164. goteol:
  1165. *processed = tot;
  1166. if (NODEV(err))
  1167. release_cgpu(cgpu);
  1168. return err;
  1169. }
  1170. int _usb_write(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, enum usb_cmds cmd)
  1171. {
  1172. struct cg_usb_device *usbdev = cgpu->usbdev;
  1173. #if DO_USB_STATS
  1174. struct timeval tv_start, tv_finish;
  1175. #endif
  1176. int err, sent;
  1177. if (cgpu->usbinfo.nodev) {
  1178. *processed = 0;
  1179. #if DO_USB_STATS
  1180. rejected_inc(cgpu);
  1181. #endif
  1182. return LIBUSB_ERROR_NO_DEVICE;
  1183. }
  1184. sent = 0;
  1185. STATS_TIMEVAL(&tv_start);
  1186. err = libusb_bulk_transfer(usbdev->handle,
  1187. usbdev->found->eps[ep].ep,
  1188. (unsigned char *)buf,
  1189. bufsiz, &sent,
  1190. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1191. STATS_TIMEVAL(&tv_finish);
  1192. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1193. *processed = sent;
  1194. if (NODEV(err))
  1195. release_cgpu(cgpu);
  1196. return err;
  1197. }
  1198. 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)
  1199. {
  1200. struct cg_usb_device *usbdev = cgpu->usbdev;
  1201. #if DO_USB_STATS
  1202. struct timeval tv_start, tv_finish;
  1203. #endif
  1204. int err;
  1205. if (cgpu->usbinfo.nodev) {
  1206. #if DO_USB_STATS
  1207. rejected_inc(cgpu);
  1208. #endif
  1209. return LIBUSB_ERROR_NO_DEVICE;
  1210. }
  1211. STATS_TIMEVAL(&tv_start);
  1212. err = libusb_control_transfer(usbdev->handle, request_type,
  1213. bRequest, wValue, wIndex, NULL, 0,
  1214. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1215. STATS_TIMEVAL(&tv_finish);
  1216. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1217. if (NODEV(err))
  1218. release_cgpu(cgpu);
  1219. return err;
  1220. }
  1221. void usb_cleanup()
  1222. {
  1223. // TODO:
  1224. }