usbutils.c 41 KB

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