usbutils.c 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310
  1. /*
  2. * Copyright 2012 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. #ifdef USE_ICARUS
  16. #define DRV_ICARUS 1
  17. #endif
  18. #ifdef USE_BITFORCE
  19. #define DRV_BITFORCE 2
  20. #endif
  21. #ifdef USE_MODMINER
  22. #define DRV_MODMINER 3
  23. #endif
  24. #define DRV_LAST -1
  25. #define USB_CONFIG 1
  26. #define EPI(x) (LIBUSB_ENDPOINT_IN | (unsigned char)(x))
  27. #define EPO(x) (LIBUSB_ENDPOINT_OUT | (unsigned char)(x))
  28. #ifdef WIN32
  29. #define BITFORCE_TIMEOUT_MS 500
  30. #define MODMINER_TIMEOUT_MS 200
  31. #else
  32. #define BITFORCE_TIMEOUT_MS 200
  33. #define MODMINER_TIMEOUT_MS 100
  34. #endif
  35. #ifdef USE_BITFORCE
  36. static struct usb_endpoints bfl_eps[] = {
  37. #ifdef WIN32
  38. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  39. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  40. #else
  41. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPI(1), 0 },
  42. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPO(2), 0 }
  43. #endif
  44. };
  45. #endif
  46. #ifdef USE_MODMINER
  47. static struct usb_endpoints mmq_eps[] = {
  48. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  49. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0 }
  50. };
  51. #endif
  52. // TODO: Add support for (at least) Isochronous endpoints
  53. static struct usb_find_devices find_dev[] = {
  54. /*
  55. #ifdef USE_ICARUS
  56. { DRV_ICARUS, "ICA", 0x067b, 0x0230, true, EPI(3), EPO(2), 1 },
  57. { DRV_ICARUS, "LOT", 0x0403, 0x6001, false, EPI(0), EPO(0), 1 },
  58. { DRV_ICARUS, "CM1", 0x067b, 0x0230, false, EPI(0), EPO(0), 1 },
  59. #endif
  60. */
  61. #ifdef USE_BITFORCE
  62. {
  63. .drv = DRV_BITFORCE,
  64. .name = "BFL",
  65. .idVendor = 0x0403,
  66. .idProduct = 0x6014,
  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. .config = 1,
  80. .interface = 1,
  81. .timeout = MODMINER_TIMEOUT_MS,
  82. .epcount = ARRAY_SIZE(mmq_eps),
  83. .eps = mmq_eps },
  84. #endif
  85. { DRV_LAST, NULL, 0, 0, 0, 0, 0, 0, NULL }
  86. };
  87. #ifdef USE_BITFORCE
  88. extern struct device_api bitforce_api;
  89. #endif
  90. #ifdef USE_ICARUS
  91. extern struct device_api icarus_api;
  92. #endif
  93. #ifdef USE_MODMINER
  94. extern struct device_api modminer_api;
  95. #endif
  96. /*
  97. * Our own internal list of used USB devices
  98. * So two drivers or a single driver searching
  99. * can't touch the same device during detection
  100. */
  101. struct usb_list {
  102. uint8_t bus_number;
  103. uint8_t device_address;
  104. uint8_t filler[2];
  105. struct usb_list *prev;
  106. struct usb_list *next;
  107. };
  108. #define STRBUFLEN 256
  109. static const char *BLANK = "";
  110. static pthread_mutex_t *list_lock = NULL;
  111. static struct usb_list *usb_head = NULL;
  112. struct cg_usb_stats_item {
  113. uint64_t count;
  114. double total_delay;
  115. double min_delay;
  116. double max_delay;
  117. struct timeval first;
  118. struct timeval last;
  119. };
  120. #define CMD_CMD 0
  121. #define CMD_TIMEOUT 1
  122. #define CMD_ERROR 2
  123. struct cg_usb_stats_details {
  124. int seq;
  125. struct cg_usb_stats_item item[CMD_ERROR+1];
  126. };
  127. struct cg_usb_stats {
  128. char *name;
  129. int device_id;
  130. struct cg_usb_stats_details *details;
  131. };
  132. #define SEQ0 0
  133. #define SEQ1 1
  134. static struct cg_usb_stats *usb_stats = NULL;
  135. static int next_stat = 0;
  136. static const char **usb_commands;
  137. static const char *C_PING_S = "Ping";
  138. static const char *C_CLEAR_S = "Clear";
  139. static const char *C_REQUESTVERSION_S = "RequestVersion";
  140. static const char *C_GETVERSION_S = "GetVersion";
  141. static const char *C_REQUESTFPGACOUNT_S = "RequestFPGACount";
  142. static const char *C_GETFPGACOUNT_S = "GetFPGACount";
  143. static const char *C_STARTPROGRAM_S = "StartProgram";
  144. static const char *C_STARTPROGRAMSTATUS_S = "StartProgramStatus";
  145. static const char *C_PROGRAM_S = "Program";
  146. static const char *C_PROGRAMSTATUS_S = "ProgramStatus";
  147. static const char *C_PROGRAMSTATUS2_S = "ProgramStatus2";
  148. static const char *C_FINALPROGRAMSTATUS_S = "FinalProgramStatus";
  149. static const char *C_SETCLOCK_S = "SetClock";
  150. static const char *C_REPLYSETCLOCK_S = "ReplySetClock";
  151. static const char *C_REQUESTUSERCODE_S = "RequestUserCode";
  152. static const char *C_GETUSERCODE_S = "GetUserCode";
  153. static const char *C_REQUESTTEMPERATURE_S = "RequestTemperature";
  154. static const char *C_GETTEMPERATURE_S = "GetTemperature";
  155. static const char *C_SENDWORK_S = "SendWork";
  156. static const char *C_SENDWORKSTATUS_S = "SendWorkStatus";
  157. static const char *C_REQUESTWORKSTATUS_S = "RequestWorkStatus";
  158. static const char *C_GETWORKSTATUS_S = "GetWorkStatus";
  159. static const char *C_REQUESTIDENTIFY_S = "RequestIdentify";
  160. static const char *C_GETIDENTIFY_S = "GetIdentify";
  161. static const char *C_REQUESTFLASH_S = "RequestFlash";
  162. static const char *C_REQUESTSENDWORK_S = "RequestSendWork";
  163. static const char *C_REQUESTSENDWORKSTATUS_S = "RequestSendWorkStatus";
  164. static const char *C_RESET_S = "Reset";
  165. static const char *C_SETBAUD_S = "SetBaud";
  166. static const char *C_SETDATA_S = "SetDataCtrl";
  167. static const char *C_SETFLOW_S = "SetFlowCtrl";
  168. static const char *C_SETMODEM_S = "SetModemCtrl";
  169. static const char *C_PURGERX_S = "PurgeRx";
  170. static const char *C_PURGETX_S = "PurgeTx";
  171. #ifdef EOL
  172. #undef EOL
  173. #endif
  174. #define EOL "\n"
  175. static const char *DESDEV = "Device";
  176. static const char *DESCON = "Config";
  177. static const char *DESSTR = "String";
  178. static const char *DESINT = "Interface";
  179. static const char *DESEP = "Endpoint";
  180. static const char *DESHID = "HID";
  181. static const char *DESRPT = "Report";
  182. static const char *DESPHY = "Physical";
  183. static const char *DESHUB = "Hub";
  184. static const char *EPIN = "In: ";
  185. static const char *EPOUT = "Out: ";
  186. static const char *EPX = "?: ";
  187. static const char *CONTROL = "Control";
  188. static const char *ISOCHRONOUS_X = "Isochronous+?";
  189. static const char *ISOCHRONOUS_N_X = "Isochronous+None+?";
  190. static const char *ISOCHRONOUS_N_D = "Isochronous+None+Data";
  191. static const char *ISOCHRONOUS_N_F = "Isochronous+None+Feedback";
  192. static const char *ISOCHRONOUS_N_I = "Isochronous+None+Implicit";
  193. static const char *ISOCHRONOUS_A_X = "Isochronous+Async+?";
  194. static const char *ISOCHRONOUS_A_D = "Isochronous+Async+Data";
  195. static const char *ISOCHRONOUS_A_F = "Isochronous+Async+Feedback";
  196. static const char *ISOCHRONOUS_A_I = "Isochronous+Async+Implicit";
  197. static const char *ISOCHRONOUS_D_X = "Isochronous+Adaptive+?";
  198. static const char *ISOCHRONOUS_D_D = "Isochronous+Adaptive+Data";
  199. static const char *ISOCHRONOUS_D_F = "Isochronous+Adaptive+Feedback";
  200. static const char *ISOCHRONOUS_D_I = "Isochronous+Adaptive+Implicit";
  201. static const char *ISOCHRONOUS_S_X = "Isochronous+Sync+?";
  202. static const char *ISOCHRONOUS_S_D = "Isochronous+Sync+Data";
  203. static const char *ISOCHRONOUS_S_F = "Isochronous+Sync+Feedback";
  204. static const char *ISOCHRONOUS_S_I = "Isochronous+Sync+Implicit";
  205. static const char *BULK = "Bulk";
  206. static const char *INTERRUPT = "Interrupt";
  207. static const char *UNKNOWN = "Unknown";
  208. static const char *destype(uint8_t bDescriptorType)
  209. {
  210. switch (bDescriptorType) {
  211. case LIBUSB_DT_DEVICE:
  212. return DESDEV;
  213. case LIBUSB_DT_CONFIG:
  214. return DESCON;
  215. case LIBUSB_DT_STRING:
  216. return DESSTR;
  217. case LIBUSB_DT_INTERFACE:
  218. return DESINT;
  219. case LIBUSB_DT_ENDPOINT:
  220. return DESEP;
  221. case LIBUSB_DT_HID:
  222. return DESHID;
  223. case LIBUSB_DT_REPORT:
  224. return DESRPT;
  225. case LIBUSB_DT_PHYSICAL:
  226. return DESPHY;
  227. case LIBUSB_DT_HUB:
  228. return DESHUB;
  229. }
  230. return UNKNOWN;
  231. }
  232. static const char *epdir(uint8_t bEndpointAddress)
  233. {
  234. switch (bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) {
  235. case LIBUSB_ENDPOINT_IN:
  236. return EPIN;
  237. case LIBUSB_ENDPOINT_OUT:
  238. return EPOUT;
  239. }
  240. return EPX;
  241. }
  242. static const char *epatt(uint8_t bmAttributes)
  243. {
  244. switch(bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) {
  245. case LIBUSB_TRANSFER_TYPE_CONTROL:
  246. return CONTROL;
  247. case LIBUSB_TRANSFER_TYPE_BULK:
  248. return BULK;
  249. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  250. return INTERRUPT;
  251. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  252. switch(bmAttributes & LIBUSB_ISO_SYNC_TYPE_MASK) {
  253. case LIBUSB_ISO_SYNC_TYPE_NONE:
  254. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  255. case LIBUSB_ISO_USAGE_TYPE_DATA:
  256. return ISOCHRONOUS_N_D;
  257. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  258. return ISOCHRONOUS_N_F;
  259. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  260. return ISOCHRONOUS_N_I;
  261. }
  262. return ISOCHRONOUS_N_X;
  263. case LIBUSB_ISO_SYNC_TYPE_ASYNC:
  264. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  265. case LIBUSB_ISO_USAGE_TYPE_DATA:
  266. return ISOCHRONOUS_A_D;
  267. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  268. return ISOCHRONOUS_A_F;
  269. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  270. return ISOCHRONOUS_A_I;
  271. }
  272. return ISOCHRONOUS_A_X;
  273. case LIBUSB_ISO_SYNC_TYPE_ADAPTIVE:
  274. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  275. case LIBUSB_ISO_USAGE_TYPE_DATA:
  276. return ISOCHRONOUS_D_D;
  277. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  278. return ISOCHRONOUS_D_F;
  279. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  280. return ISOCHRONOUS_D_I;
  281. }
  282. return ISOCHRONOUS_D_X;
  283. case LIBUSB_ISO_SYNC_TYPE_SYNC:
  284. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  285. case LIBUSB_ISO_USAGE_TYPE_DATA:
  286. return ISOCHRONOUS_S_D;
  287. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  288. return ISOCHRONOUS_S_F;
  289. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  290. return ISOCHRONOUS_S_I;
  291. }
  292. return ISOCHRONOUS_S_X;
  293. }
  294. return ISOCHRONOUS_X;
  295. }
  296. return UNKNOWN;
  297. }
  298. static void append(char **buf, char *append, size_t *off, size_t *len)
  299. {
  300. int new = strlen(append);
  301. if ((new + *off) >= *len)
  302. {
  303. *len *= 2;
  304. *buf = realloc(*buf, *len);
  305. }
  306. strcpy(*buf + *off, append);
  307. *off += new;
  308. }
  309. 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)
  310. {
  311. char tmp[512];
  312. int err;
  313. err = libusb_set_configuration(handle, cd);
  314. if (err) {
  315. sprintf(tmp, EOL " ** dev %d: Failed to set config descriptor to %d, err %d",
  316. (int)count, cd, err);
  317. append(buf, tmp, off, len);
  318. return false;
  319. }
  320. err = libusb_get_active_config_descriptor(dev, config);
  321. if (err) {
  322. sprintf(tmp, EOL " ** dev %d: Failed to get active config descriptor set to %d, err %d",
  323. (int)count, cd, err);
  324. append(buf, tmp, off, len);
  325. return false;
  326. }
  327. sprintf(tmp, EOL " ** dev %d: Set & Got active config descriptor to %d, err %d",
  328. (int)count, cd, err);
  329. append(buf, tmp, off, len);
  330. return true;
  331. }
  332. static void usb_full(ssize_t count, libusb_device *dev, char **buf, size_t *off, size_t *len)
  333. {
  334. struct libusb_device_descriptor desc;
  335. struct libusb_device_handle *handle;
  336. struct libusb_config_descriptor *config;
  337. const struct libusb_interface_descriptor *idesc;
  338. const struct libusb_endpoint_descriptor *epdesc;
  339. unsigned char man[STRBUFLEN+1];
  340. unsigned char prod[STRBUFLEN+1];
  341. unsigned char ser[STRBUFLEN+1];
  342. char tmp[512];
  343. int err, i, j, k;
  344. err = libusb_get_device_descriptor(dev, &desc);
  345. if (err) {
  346. sprintf(tmp, EOL ".USB dev %d: Failed to get descriptor, err %d",
  347. (int)count, err);
  348. append(buf, tmp, off, len);
  349. return;
  350. }
  351. sprintf(tmp, EOL ".USB dev %d: Device Descriptor:" EOL "\tLength: %d" EOL
  352. "\tDescriptor Type: %s" EOL "\tUSB: %04x" EOL "\tDeviceClass: %d" EOL
  353. "\tDeviceSubClass: %d" EOL "\tDeviceProtocol: %d" EOL "\tMaxPacketSize0: %d" EOL
  354. "\tidVendor: %04x" EOL "\tidProduct: %04x" EOL "\tDeviceRelease: %x" EOL
  355. "\tNumConfigurations: %d",
  356. (int)count, (int)(desc.bLength), destype(desc.bDescriptorType),
  357. desc.bcdUSB, (int)(desc.bDeviceClass), (int)(desc.bDeviceSubClass),
  358. (int)(desc.bDeviceProtocol), (int)(desc.bMaxPacketSize0),
  359. desc.idVendor, desc.idProduct, desc.bcdDevice,
  360. (int)(desc.bNumConfigurations));
  361. append(buf, tmp, off, len);
  362. err = libusb_open(dev, &handle);
  363. if (err) {
  364. sprintf(tmp, EOL " ** dev %d: Failed to open, err %d", (int)count, err);
  365. append(buf, tmp, off, len);
  366. return;
  367. }
  368. if (libusb_kernel_driver_active(handle, 0) == 1) {
  369. sprintf(tmp, EOL " * dev %d: kernel attached", (int)count);
  370. append(buf, tmp, off, len);
  371. }
  372. err = libusb_get_active_config_descriptor(dev, &config);
  373. if (err) {
  374. if (!setgetdes(count, dev, handle, &config, 1, buf, off, len)
  375. && !setgetdes(count, dev, handle, &config, 0, buf, off, len)) {
  376. libusb_close(handle);
  377. sprintf(tmp, EOL " ** dev %d: Failed to set config descriptor to %d or %d",
  378. (int)count, 1, 0);
  379. append(buf, tmp, off, len);
  380. return;
  381. }
  382. }
  383. sprintf(tmp, EOL " dev %d: Active Config:" EOL "\tDescriptorType: %s" EOL
  384. "\tNumInterfaces: %d" EOL "\tConfigurationValue: %d" EOL
  385. "\tAttributes: %d" EOL "\tMaxPower: %d",
  386. (int)count, destype(config->bDescriptorType),
  387. (int)(config->bNumInterfaces), (int)(config->iConfiguration),
  388. (int)(config->bmAttributes), (int)(config->MaxPower));
  389. append(buf, tmp, off, len);
  390. for (i = 0; i < (int)(config->bNumInterfaces); i++) {
  391. for (j = 0; j < config->interface[i].num_altsetting; j++) {
  392. idesc = &(config->interface[i].altsetting[j]);
  393. sprintf(tmp, EOL " _dev %d: Interface Descriptor %d:" EOL
  394. "\tDescriptorType: %s" EOL "\tInterfaceNumber: %d" EOL
  395. "\tNumEndpoints: %d" EOL "\tInterfaceClass: %d" EOL
  396. "\tInterfaceSubClass: %d" EOL "\tInterfaceProtocol: %d",
  397. (int)count, j, destype(idesc->bDescriptorType),
  398. (int)(idesc->bInterfaceNumber),
  399. (int)(idesc->bNumEndpoints),
  400. (int)(idesc->bInterfaceClass),
  401. (int)(idesc->bInterfaceSubClass),
  402. (int)(idesc->bInterfaceProtocol));
  403. append(buf, tmp, off, len);
  404. for (k = 0; k < (int)(idesc->bNumEndpoints); k++) {
  405. epdesc = &(idesc->endpoint[k]);
  406. sprintf(tmp, EOL " __dev %d: Interface %d Endpoint %d:" EOL
  407. "\tDescriptorType: %s" EOL
  408. "\tEndpointAddress: %s0x%x" EOL
  409. "\tAttributes: %s" EOL "\tMaxPacketSize: %d" EOL
  410. "\tInterval: %d" EOL "\tRefresh: %d",
  411. (int)count, (int)(idesc->bInterfaceNumber), k,
  412. destype(epdesc->bDescriptorType),
  413. epdir(epdesc->bEndpointAddress),
  414. (int)(epdesc->bEndpointAddress),
  415. epatt(epdesc->bmAttributes),
  416. epdesc->wMaxPacketSize,
  417. (int)(epdesc->bInterval),
  418. (int)(epdesc->bRefresh));
  419. append(buf, tmp, off, len);
  420. }
  421. }
  422. }
  423. libusb_free_config_descriptor(config);
  424. config = NULL;
  425. err = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, man, STRBUFLEN);
  426. if (err < 0)
  427. sprintf((char *)man, "** err(%d)", err);
  428. err = libusb_get_string_descriptor_ascii(handle, desc.iProduct, prod, STRBUFLEN);
  429. if (err < 0)
  430. sprintf((char *)prod, "** err(%d)", err);
  431. err = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, ser, STRBUFLEN);
  432. if (err < 0)
  433. sprintf((char *)ser, "** err(%d)", err);
  434. sprintf(tmp, EOL " dev %d: More Info:" EOL "\tManufacturer: '%s'" EOL
  435. "\tProduct: '%s'" EOL "\tSerial '%s'",
  436. (int)count, man, prod, ser);
  437. append(buf, tmp, off, len);
  438. libusb_close(handle);
  439. }
  440. // Function to dump all USB devices
  441. static void usb_all()
  442. {
  443. libusb_device **list;
  444. ssize_t count, i;
  445. char *buf;
  446. size_t len, off;
  447. count = libusb_get_device_list(NULL, &list);
  448. if (count < 0) {
  449. applog(LOG_ERR, "USB all: failed, err %d", (int)count);
  450. return;
  451. }
  452. if (count == 0)
  453. applog(LOG_WARNING, "USB all: found no devices");
  454. else
  455. {
  456. len = 10000;
  457. buf = malloc(len+1);
  458. sprintf(buf, "USB all: found %d devices", (int)count);
  459. off = strlen(buf);
  460. for (i = 0; i < count; i++)
  461. usb_full(i, list[i], &buf, &off, &len);
  462. applog(LOG_WARNING, "%s", buf);
  463. free(buf);
  464. }
  465. libusb_free_device_list(list, 1);
  466. }
  467. static void cgusb_check_init()
  468. {
  469. mutex_lock(&cgusb_lock);
  470. if (list_lock == NULL) {
  471. list_lock = calloc(1, sizeof(*list_lock));
  472. mutex_init(list_lock);
  473. // N.B. environment LIBUSB_DEBUG also sets libusb_set_debug()
  474. if (opt_usbdump >= 0) {
  475. libusb_set_debug(NULL, opt_usbdump);
  476. usb_all();
  477. }
  478. usb_commands = malloc(sizeof(*usb_commands) * C_MAX);
  479. // use constants so the stat generation is very quick
  480. // and the association between number and name can't
  481. // be missalined easily
  482. usb_commands[C_PING] = C_PING_S;
  483. usb_commands[C_CLEAR] = C_CLEAR_S;
  484. usb_commands[C_REQUESTVERSION] = C_REQUESTVERSION_S;
  485. usb_commands[C_GETVERSION] = C_GETVERSION_S;
  486. usb_commands[C_REQUESTFPGACOUNT] = C_REQUESTFPGACOUNT_S;
  487. usb_commands[C_GETFPGACOUNT] = C_GETFPGACOUNT_S;
  488. usb_commands[C_STARTPROGRAM] = C_STARTPROGRAM_S;
  489. usb_commands[C_STARTPROGRAMSTATUS] = C_STARTPROGRAMSTATUS_S;
  490. usb_commands[C_PROGRAM] = C_PROGRAM_S;
  491. usb_commands[C_PROGRAMSTATUS] = C_PROGRAMSTATUS_S;
  492. usb_commands[C_PROGRAMSTATUS2] = C_PROGRAMSTATUS2_S;
  493. usb_commands[C_FINALPROGRAMSTATUS] = C_FINALPROGRAMSTATUS_S;
  494. usb_commands[C_SETCLOCK] = C_SETCLOCK_S;
  495. usb_commands[C_REPLYSETCLOCK] = C_REPLYSETCLOCK_S;
  496. usb_commands[C_REQUESTUSERCODE] = C_REQUESTUSERCODE_S;
  497. usb_commands[C_GETUSERCODE] = C_GETUSERCODE_S;
  498. usb_commands[C_REQUESTTEMPERATURE] = C_REQUESTTEMPERATURE_S;
  499. usb_commands[C_GETTEMPERATURE] = C_GETTEMPERATURE_S;
  500. usb_commands[C_SENDWORK] = C_SENDWORK_S;
  501. usb_commands[C_SENDWORKSTATUS] = C_SENDWORKSTATUS_S;
  502. usb_commands[C_REQUESTWORKSTATUS] = C_REQUESTWORKSTATUS_S;
  503. usb_commands[C_GETWORKSTATUS] = C_GETWORKSTATUS_S;
  504. usb_commands[C_REQUESTIDENTIFY] = C_REQUESTIDENTIFY_S;
  505. usb_commands[C_GETIDENTIFY] = C_GETIDENTIFY_S;
  506. usb_commands[C_REQUESTFLASH] = C_REQUESTFLASH_S;
  507. usb_commands[C_REQUESTSENDWORK] = C_REQUESTSENDWORK_S;
  508. usb_commands[C_REQUESTSENDWORKSTATUS] = C_REQUESTSENDWORKSTATUS_S;
  509. usb_commands[C_RESET] = C_RESET_S;
  510. usb_commands[C_SETBAUD] = C_SETBAUD_S;
  511. usb_commands[C_SETDATA] = C_SETDATA_S;
  512. usb_commands[C_SETFLOW] = C_SETFLOW_S;
  513. usb_commands[C_SETMODEM] = C_SETMODEM_S;
  514. usb_commands[C_PURGERX] = C_PURGERX_S;
  515. usb_commands[C_PURGETX] = C_PURGETX_S;
  516. }
  517. mutex_unlock(&cgusb_lock);
  518. }
  519. static bool in_use(libusb_device *dev, bool lock)
  520. {
  521. struct usb_list *usb_tmp;
  522. bool used = false;
  523. uint8_t bus_number;
  524. uint8_t device_address;
  525. bus_number = libusb_get_bus_number(dev);
  526. device_address = libusb_get_device_address(dev);
  527. if (lock)
  528. mutex_lock(list_lock);
  529. if ((usb_tmp = usb_head))
  530. do {
  531. if (bus_number == usb_tmp->bus_number
  532. && device_address == usb_tmp->device_address) {
  533. used = true;
  534. break;
  535. }
  536. usb_tmp = usb_tmp->next;
  537. } while (usb_tmp != usb_head);
  538. if (lock)
  539. mutex_unlock(list_lock);
  540. return used;
  541. }
  542. static void add_used(libusb_device *dev, bool lock)
  543. {
  544. struct usb_list *usb_tmp;
  545. char buf[128];
  546. uint8_t bus_number;
  547. uint8_t device_address;
  548. bus_number = libusb_get_bus_number(dev);
  549. device_address = libusb_get_device_address(dev);
  550. if (lock)
  551. mutex_lock(list_lock);
  552. if (in_use(dev, false)) {
  553. if (lock)
  554. mutex_unlock(list_lock);
  555. sprintf(buf, "add_used() duplicate bus_number %d device_address %d",
  556. bus_number, device_address);
  557. quit(1, buf);
  558. }
  559. usb_tmp = malloc(sizeof(*usb_tmp));
  560. usb_tmp->bus_number = bus_number;
  561. usb_tmp->device_address = device_address;
  562. if (usb_head) {
  563. // add to end
  564. usb_tmp->prev = usb_head->prev;
  565. usb_tmp->next = usb_head;
  566. usb_head->prev = usb_tmp;
  567. usb_tmp->prev->next = usb_tmp;
  568. } else {
  569. usb_tmp->prev = usb_tmp;
  570. usb_tmp->next = usb_tmp;
  571. usb_head = usb_tmp;
  572. }
  573. if (lock)
  574. mutex_unlock(list_lock);
  575. }
  576. static void release(uint8_t bus_number, uint8_t device_address, bool lock)
  577. {
  578. struct usb_list *usb_tmp;
  579. bool found = false;
  580. char buf[128];
  581. if (lock)
  582. mutex_lock(list_lock);
  583. usb_tmp = usb_head;
  584. if (usb_tmp)
  585. do {
  586. if (bus_number == usb_tmp->bus_number
  587. && device_address == usb_tmp->device_address) {
  588. found = true;
  589. break;
  590. }
  591. usb_tmp = usb_tmp->next;
  592. } while (usb_tmp != usb_head);
  593. if (!found) {
  594. if (lock)
  595. mutex_unlock(list_lock);
  596. sprintf(buf, "release() unknown: bus_number %d device_address %d",
  597. bus_number, device_address);
  598. quit(1, buf);
  599. }
  600. if (usb_tmp->next == usb_tmp) {
  601. usb_head = NULL;
  602. } else {
  603. usb_tmp->next->prev = usb_tmp->prev;
  604. usb_tmp->prev->next = usb_tmp->next;
  605. }
  606. if (lock)
  607. mutex_unlock(list_lock);
  608. free(usb_tmp);
  609. }
  610. static void release_dev(libusb_device *dev, bool lock)
  611. {
  612. uint8_t bus_number;
  613. uint8_t device_address;
  614. bus_number = libusb_get_bus_number(dev);
  615. device_address = libusb_get_device_address(dev);
  616. release(bus_number, device_address, lock);
  617. }
  618. #if 0
  619. static void release_cgusb(struct cg_usb_device *cgusb, bool lock)
  620. {
  621. release(cgusb->bus_number, cgusb->device_address, lock);
  622. }
  623. #endif
  624. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  625. {
  626. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  627. free(cgusb->serial_string);
  628. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  629. free(cgusb->manuf_string);
  630. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  631. free(cgusb->prod_string);
  632. free(cgusb->descriptor);
  633. free(cgusb);
  634. return NULL;
  635. }
  636. void usb_uninit(struct cgpu_info *cgpu)
  637. {
  638. libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface);
  639. libusb_close(cgpu->usbdev->handle);
  640. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  641. }
  642. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  643. {
  644. struct cg_usb_device *cgusb = NULL;
  645. struct libusb_config_descriptor *config = NULL;
  646. const struct libusb_interface_descriptor *idesc;
  647. const struct libusb_endpoint_descriptor *epdesc;
  648. unsigned char strbuf[STRBUFLEN+1];
  649. int err, i, j, k;
  650. cgusb = calloc(1, sizeof(*cgusb));
  651. cgusb->found = found;
  652. cgusb->bus_number = libusb_get_bus_number(dev);
  653. cgusb->device_address = libusb_get_device_address(dev);
  654. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  655. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  656. if (err) {
  657. applog(LOG_ERR, "USB init failed to get descriptor, err %d", err);
  658. goto dame;
  659. }
  660. err = libusb_open(dev, &(cgusb->handle));
  661. if (err) {
  662. switch (err) {
  663. case LIBUSB_ERROR_ACCESS:
  664. applog(LOG_ERR, "USB init open device failed, err %d, you dont have priviledge to access the device", err);
  665. break;
  666. #ifdef WIN32
  667. // Windows specific message
  668. case LIBUSB_ERROR_NOT_SUPPORTED:
  669. applog(LOG_ERR, "USB init, open device failed, err %d, you need to install a Windows USB driver for the device", err);
  670. break;
  671. #endif
  672. default:
  673. applog(LOG_ERR, "USB init, open device failed, err %d", err);
  674. }
  675. goto dame;
  676. }
  677. if (libusb_kernel_driver_active(cgusb->handle, 0) == 1) {
  678. applog(LOG_DEBUG, "USB init, kernel attached ...");
  679. if (libusb_detach_kernel_driver(cgusb->handle, 0) == 0)
  680. applog(LOG_DEBUG, "USB init, kernel detached successfully");
  681. else
  682. applog(LOG_WARNING, "USB init, kernel detach failed :(");
  683. }
  684. err = libusb_set_configuration(cgusb->handle, found->config);
  685. if (err) {
  686. switch(err) {
  687. case LIBUSB_ERROR_BUSY:
  688. applog(LOG_WARNING, "USB init, %s device %d:%d in use",
  689. found->name, cgusb->bus_number, cgusb->device_address);
  690. break;
  691. default:
  692. applog(LOG_DEBUG, "USB init, failed to set config to %d, err %d",
  693. found->config, err);
  694. }
  695. goto cldame;
  696. }
  697. err = libusb_get_active_config_descriptor(dev, &config);
  698. if (err) {
  699. applog(LOG_DEBUG, "USB init, failed to get config descriptor %d, err %d",
  700. found->config, err);
  701. goto cldame;
  702. }
  703. if ((int)(config->bNumInterfaces) <= found->interface)
  704. goto cldame;
  705. for (i = 0; i < found->epcount; i++)
  706. found->eps[i].found = false;
  707. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  708. idesc = &(config->interface[found->interface].altsetting[i]);
  709. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  710. epdesc = &(idesc->endpoint[j]);
  711. for (k = 0; k < found->epcount; k++) {
  712. if (!found->eps[k].found) {
  713. if (epdesc->bmAttributes == found->eps[k].att
  714. && epdesc->wMaxPacketSize >= found->eps[k].size
  715. && epdesc->bEndpointAddress == found->eps[k].ep) {
  716. found->eps[k].found = true;
  717. break;
  718. }
  719. }
  720. }
  721. }
  722. }
  723. for (i = 0; i < found->epcount; i++)
  724. if (found->eps[i].found == false)
  725. goto cldame;
  726. err = libusb_claim_interface(cgusb->handle, found->interface);
  727. if (err) {
  728. applog(LOG_DEBUG, "USB init, claim interface %d failed, err %d",
  729. found->interface, err);
  730. goto cldame;
  731. }
  732. cgusb->usbver = cgusb->descriptor->bcdUSB;
  733. // TODO: allow this with the right version of the libusb include and running library
  734. // cgusb->speed = libusb_get_device_speed(dev);
  735. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  736. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  737. if (err > 0)
  738. cgusb->prod_string = strdup((char *)strbuf);
  739. else
  740. cgusb->prod_string = (char *)BLANK;
  741. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  742. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  743. if (err > 0)
  744. cgusb->manuf_string = strdup((char *)strbuf);
  745. else
  746. cgusb->manuf_string = (char *)BLANK;
  747. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  748. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  749. if (err > 0)
  750. cgusb->serial_string = strdup((char *)strbuf);
  751. else
  752. cgusb->serial_string = (char *)BLANK;
  753. // TODO: ?
  754. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  755. // cgusb->interfaceVersion
  756. applog(LOG_DEBUG, "USB init device bus_number=%d device_address=%d usbver=%04x prod='%s' manuf='%s' serial='%s'", (int)(cgusb->bus_number), (int)(cgusb->device_address), cgusb->usbver, cgusb->prod_string, cgusb->manuf_string, cgusb->serial_string);
  757. cgpu->usbdev = cgusb;
  758. libusb_free_config_descriptor(config);
  759. return true;
  760. cldame:
  761. libusb_close(cgusb->handle);
  762. dame:
  763. if (config)
  764. libusb_free_config_descriptor(config);
  765. cgusb = free_cgusb(cgusb);
  766. return false;
  767. }
  768. static bool usb_check_device(struct device_api *api, struct libusb_device *dev, struct usb_find_devices *look)
  769. {
  770. struct libusb_device_descriptor desc;
  771. int err;
  772. err = libusb_get_device_descriptor(dev, &desc);
  773. if (err) {
  774. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  775. return false;
  776. }
  777. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  778. applog(LOG_DEBUG, "%s looking for %04x:%04x but found %04x:%04x instead",
  779. api->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  780. return false;
  781. }
  782. applog(LOG_DEBUG, "%s looking for and found %04x:%04x",
  783. api->name, look->idVendor, look->idProduct);
  784. return true;
  785. }
  786. static struct usb_find_devices *usb_check_each(int drv, struct device_api *api, struct libusb_device *dev)
  787. {
  788. struct usb_find_devices *found;
  789. int i;
  790. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  791. if (find_dev[i].drv == drv) {
  792. if (usb_check_device(api, dev, &(find_dev[i]))) {
  793. found = malloc(sizeof(*found));
  794. memcpy(found, &(find_dev[i]), sizeof(*found));
  795. return found;
  796. }
  797. }
  798. return NULL;
  799. }
  800. static struct usb_find_devices *usb_check(__maybe_unused struct device_api *api, __maybe_unused struct libusb_device *dev)
  801. {
  802. #ifdef USE_BITFORCE
  803. if (api == &bitforce_api)
  804. return usb_check_each(DRV_BITFORCE, api, dev);
  805. #endif
  806. #ifdef USE_ICARUS
  807. if (api == &icarus_api)
  808. return usb_check_each(DRV_ICARUS, api, dev);
  809. #endif
  810. #ifdef USE_MODMINER
  811. if (api == &modminer_api)
  812. return usb_check_each(DRV_MODMINER, api, dev);
  813. #endif
  814. return NULL;
  815. }
  816. void usb_detect(struct device_api *api, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *))
  817. {
  818. libusb_device **list;
  819. ssize_t count, i;
  820. struct usb_find_devices *found;
  821. cgusb_check_init();
  822. count = libusb_get_device_list(NULL, &list);
  823. if (count < 0) {
  824. applog(LOG_DEBUG, "USB scan devices: failed, err %d", count);
  825. return;
  826. }
  827. if (count == 0)
  828. applog(LOG_DEBUG, "USB scan devices: found no devices");
  829. for (i = 0; i < count; i++) {
  830. mutex_lock(list_lock);
  831. if (in_use(list[i], false))
  832. mutex_unlock(list_lock);
  833. else {
  834. add_used(list[i], false);
  835. mutex_unlock(list_lock);
  836. found = usb_check(api, list[i]);
  837. if (!found)
  838. release_dev(list[i], true);
  839. else
  840. if (!device_detect(list[i], found))
  841. release_dev(list[i], true);
  842. }
  843. }
  844. libusb_free_device_list(list, 1);
  845. }
  846. // Set this to 0 to remove stats processing
  847. #define DO_USB_STATS 1
  848. #if DO_USB_STATS
  849. #define USB_STATS(sgpu, sta, fin, err, cmd, seq) stats(cgpu, sta, fin, err, cmd, seq)
  850. #define STATS_TIMEVAL(tv) gettimeofday(tv, NULL)
  851. #else
  852. #define USB_STATS(sgpu, sta, fin, err, cmd, seq)
  853. #define STATS_TIMEVAL(tv)
  854. #endif
  855. // The stat data can be spurious due to not locking it before copying it -
  856. // however that would require the stat() function to also lock and release
  857. // a mutex every time a usb read or write is called which would slow
  858. // things down more
  859. struct api_data *api_usb_stats(__maybe_unused int *count)
  860. {
  861. #if DO_USB_STATS
  862. struct cg_usb_stats_details *details;
  863. struct cg_usb_stats *sta;
  864. struct api_data *root = NULL;
  865. int device;
  866. int cmdseq;
  867. cgusb_check_init();
  868. if (next_stat == 0)
  869. return NULL;
  870. while (*count < next_stat * C_MAX * 2) {
  871. device = *count / (C_MAX * 2);
  872. cmdseq = *count % (C_MAX * 2);
  873. (*count)++;
  874. sta = &(usb_stats[device]);
  875. details = &(sta->details[cmdseq]);
  876. // Only show stats that have results
  877. if (details->item[CMD_CMD].count == 0 &&
  878. details->item[CMD_TIMEOUT].count == 0 &&
  879. details->item[CMD_ERROR].count == 0)
  880. continue;
  881. root = api_add_string(root, "Name", sta->name, false);
  882. root = api_add_int(root, "ID", &(sta->device_id), false);
  883. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  884. root = api_add_int(root, "Seq", &(details->seq), true);
  885. root = api_add_uint64(root, "Count",
  886. &(details->item[CMD_CMD].count), true);
  887. root = api_add_double(root, "Total Delay",
  888. &(details->item[CMD_CMD].total_delay), true);
  889. root = api_add_double(root, "Min Delay",
  890. &(details->item[CMD_CMD].min_delay), true);
  891. root = api_add_double(root, "Max Delay",
  892. &(details->item[CMD_CMD].max_delay), true);
  893. root = api_add_uint64(root, "Timeout Count",
  894. &(details->item[CMD_TIMEOUT].count), true);
  895. root = api_add_double(root, "Timeout Total Delay",
  896. &(details->item[CMD_TIMEOUT].total_delay), true);
  897. root = api_add_double(root, "Timeout Min Delay",
  898. &(details->item[CMD_TIMEOUT].min_delay), true);
  899. root = api_add_double(root, "Timeout Max Delay",
  900. &(details->item[CMD_TIMEOUT].max_delay), true);
  901. root = api_add_uint64(root, "Error Count",
  902. &(details->item[CMD_ERROR].count), true);
  903. root = api_add_double(root, "Error Total Delay",
  904. &(details->item[CMD_ERROR].total_delay), true);
  905. root = api_add_double(root, "Error Min Delay",
  906. &(details->item[CMD_ERROR].min_delay), true);
  907. root = api_add_double(root, "Error Max Delay",
  908. &(details->item[CMD_ERROR].max_delay), true);
  909. root = api_add_timeval(root, "First Command",
  910. &(details->item[CMD_CMD].first), true);
  911. root = api_add_timeval(root, "Last Command",
  912. &(details->item[CMD_CMD].last), true);
  913. root = api_add_timeval(root, "First Timeout",
  914. &(details->item[CMD_TIMEOUT].first), true);
  915. root = api_add_timeval(root, "Last Timeout",
  916. &(details->item[CMD_TIMEOUT].last), true);
  917. root = api_add_timeval(root, "First Error",
  918. &(details->item[CMD_ERROR].first), true);
  919. root = api_add_timeval(root, "Last Error",
  920. &(details->item[CMD_ERROR].last), true);
  921. return root;
  922. }
  923. #endif
  924. return NULL;
  925. }
  926. #if DO_USB_STATS
  927. static void newstats(struct cgpu_info *cgpu)
  928. {
  929. int i;
  930. cgpu->usbstat = ++next_stat;
  931. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * next_stat);
  932. usb_stats[next_stat-1].name = cgpu->api->name;
  933. usb_stats[next_stat-1].device_id = -1;
  934. usb_stats[next_stat-1].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  935. for (i = 1; i < C_MAX * 2; i += 2)
  936. usb_stats[next_stat-1].details[i].seq = 1;
  937. }
  938. #endif
  939. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  940. {
  941. #if DO_USB_STATS
  942. if (cgpu->usbstat < 1)
  943. newstats(cgpu);
  944. // we don't know the device_id until after add_cgpu()
  945. usb_stats[cgpu->usbstat - 1].device_id = cgpu->device_id;
  946. #endif
  947. }
  948. #if DO_USB_STATS
  949. static void stats(struct cgpu_info *cgpu, struct timeval *tv_start, struct timeval *tv_finish, int err, enum usb_cmds cmd, int seq)
  950. {
  951. struct cg_usb_stats_details *details;
  952. double diff;
  953. int item;
  954. if (cgpu->usbstat < 1)
  955. newstats(cgpu);
  956. details = &(usb_stats[cgpu->usbstat - 1].details[cmd * 2 + seq]);
  957. diff = tdiff(tv_finish, tv_start);
  958. switch (err) {
  959. case LIBUSB_SUCCESS:
  960. item = CMD_CMD;
  961. break;
  962. case LIBUSB_ERROR_TIMEOUT:
  963. item = CMD_TIMEOUT;
  964. break;
  965. default:
  966. item = CMD_ERROR;
  967. break;
  968. }
  969. if (details->item[item].count == 0) {
  970. details->item[item].min_delay = diff;
  971. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  972. } else if (diff < details->item[item].min_delay)
  973. details->item[item].min_delay = diff;
  974. if (diff > details->item[item].max_delay)
  975. details->item[item].max_delay = diff;
  976. details->item[item].total_delay += diff;
  977. memcpy(&(details->item[item].last), tv_start, sizeof(tv_start));
  978. details->item[item].count++;
  979. }
  980. #endif
  981. 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)
  982. {
  983. struct cg_usb_device *usbdev = cgpu->usbdev;
  984. #if DO_USB_STATS
  985. struct timeval tv_start;
  986. #endif
  987. struct timeval read_start, tv_finish;
  988. unsigned int initial_timeout;
  989. double max, done;
  990. int err, got, tot, i;
  991. bool first = true;
  992. if (timeout == DEVTIMEOUT)
  993. timeout = usbdev->found->timeout;
  994. if (eol == -1) {
  995. got = 0;
  996. STATS_TIMEVAL(&tv_start);
  997. err = libusb_bulk_transfer(usbdev->handle,
  998. usbdev->found->eps[ep].ep,
  999. (unsigned char *)buf,
  1000. bufsiz, &got, timeout);
  1001. STATS_TIMEVAL(&tv_finish);
  1002. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1003. if (ftdi) {
  1004. // first 2 bytes returned are an FTDI status
  1005. if (got > 2) {
  1006. got -= 2;
  1007. memmove(buf, buf+2, got+1);
  1008. } else {
  1009. got = 0;
  1010. *buf = '\0';
  1011. }
  1012. }
  1013. *processed = got;
  1014. return err;
  1015. }
  1016. tot = 0;
  1017. err = LIBUSB_SUCCESS;
  1018. initial_timeout = timeout;
  1019. max = ((double)timeout) / 1000.0;
  1020. gettimeofday(&read_start, NULL);
  1021. while (bufsiz) {
  1022. got = 0;
  1023. STATS_TIMEVAL(&tv_start);
  1024. err = libusb_bulk_transfer(usbdev->handle,
  1025. usbdev->found->eps[ep].ep,
  1026. (unsigned char *)buf,
  1027. bufsiz, &got, timeout);
  1028. gettimeofday(&tv_finish, NULL);
  1029. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, first ? SEQ0 : SEQ1);
  1030. if (ftdi) {
  1031. // first 2 bytes returned are an FTDI status
  1032. if (got > 2) {
  1033. got -= 2;
  1034. memmove(buf, buf+2, got+1);
  1035. } else {
  1036. got = 0;
  1037. *buf = '\0';
  1038. }
  1039. }
  1040. tot += got;
  1041. if (err)
  1042. break;
  1043. // WARNING - this will return data past EOL ('if' there is extra data)
  1044. for (i = 0; i < got; i++)
  1045. if (buf[i] == eol)
  1046. goto goteol;
  1047. buf += got;
  1048. bufsiz -= got;
  1049. first = false;
  1050. done = tdiff(&tv_finish, &read_start);
  1051. // N.B. this is return LIBUSB_SUCCESS with whatever size has already been read
  1052. if (unlikely(done >= max))
  1053. break;
  1054. timeout = initial_timeout - (done * 1000);
  1055. }
  1056. goteol:
  1057. *processed = tot;
  1058. return err;
  1059. }
  1060. int _usb_write(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, enum usb_cmds cmd)
  1061. {
  1062. struct cg_usb_device *usbdev = cgpu->usbdev;
  1063. #if DO_USB_STATS
  1064. struct timeval tv_start, tv_finish;
  1065. #endif
  1066. int err, sent;
  1067. sent = 0;
  1068. STATS_TIMEVAL(&tv_start);
  1069. err = libusb_bulk_transfer(usbdev->handle,
  1070. usbdev->found->eps[ep].ep,
  1071. (unsigned char *)buf,
  1072. bufsiz, &sent,
  1073. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1074. STATS_TIMEVAL(&tv_finish);
  1075. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1076. *processed = sent;
  1077. return err;
  1078. }
  1079. 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)
  1080. {
  1081. struct cg_usb_device *usbdev = cgpu->usbdev;
  1082. #if DO_USB_STATS
  1083. struct timeval tv_start, tv_finish;
  1084. #endif
  1085. int err;
  1086. STATS_TIMEVAL(&tv_start);
  1087. err = libusb_control_transfer(usbdev->handle, request_type,
  1088. bRequest, wValue, wIndex, NULL, 0,
  1089. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1090. STATS_TIMEVAL(&tv_finish);
  1091. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1092. return err;
  1093. }
  1094. void usb_cleanup()
  1095. {
  1096. // TODO:
  1097. }