usbutils.c 41 KB

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