usbutils.c 50 KB

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