usbutils.c 41 KB

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