usbutils.c 42 KB

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