usbutils.c 41 KB

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