usbutils.c 67 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529
  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. #ifdef USE_AVALON
  35. #define DRV_AVALON 6
  36. #endif
  37. #define DRV_LAST -1
  38. #define USB_CONFIG 1
  39. #ifdef WIN32
  40. #define BFLSC_TIMEOUT_MS 999
  41. #define BITFORCE_TIMEOUT_MS 999
  42. #define MODMINER_TIMEOUT_MS 999
  43. #define AVALON_TIMEOUT_MS 999
  44. #define ICARUS_TIMEOUT_MS 999
  45. #else
  46. #define BFLSC_TIMEOUT_MS 200
  47. #define BITFORCE_TIMEOUT_MS 200
  48. #define MODMINER_TIMEOUT_MS 100
  49. #define AVALON_TIMEOUT_MS 200
  50. #define ICARUS_TIMEOUT_MS 200
  51. #endif
  52. #ifdef USE_BFLSC
  53. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  54. static struct usb_endpoints bas_eps[] = {
  55. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  56. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  57. };
  58. #endif
  59. #ifdef USE_BITFORCE
  60. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  61. static struct usb_endpoints bfl_eps[] = {
  62. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  63. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  64. };
  65. #endif
  66. #ifdef USE_MODMINER
  67. static struct usb_endpoints mmq_eps[] = {
  68. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  69. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0 }
  70. };
  71. #endif
  72. #ifdef USE_AVALON
  73. static struct usb_endpoints ava_eps[] = {
  74. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  75. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  76. };
  77. #endif
  78. #ifdef USE_ICARUS
  79. static struct usb_endpoints ica_eps[] = {
  80. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  81. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  82. };
  83. static struct usb_endpoints amu_eps[] = {
  84. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  85. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0 }
  86. };
  87. static struct usb_endpoints llt_eps[] = {
  88. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  89. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  90. };
  91. static struct usb_endpoints cmr_eps[] = {
  92. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  93. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  94. };
  95. #endif
  96. #define IDVENDOR_FTDI 0x0403
  97. // TODO: Add support for (at least) Isochronous endpoints
  98. static struct usb_find_devices find_dev[] = {
  99. #ifdef USE_BFLSC
  100. {
  101. .drv = DRV_BFLSC,
  102. .name = "BAS",
  103. .ident = IDENT_BAS,
  104. .idVendor = IDVENDOR_FTDI,
  105. .idProduct = 0x6014,
  106. .iManufacturer = "Butterfly Labs",
  107. .iProduct = "BitFORCE SHA256 SC",
  108. .kernel = 0,
  109. .config = 1,
  110. .interface = 0,
  111. .timeout = BFLSC_TIMEOUT_MS,
  112. .epcount = ARRAY_SIZE(bas_eps),
  113. .eps = bas_eps },
  114. #endif
  115. #ifdef USE_BITFORCE
  116. {
  117. .drv = DRV_BITFORCE,
  118. .name = "BFL",
  119. .ident = IDENT_BFL,
  120. .idVendor = IDVENDOR_FTDI,
  121. .idProduct = 0x6014,
  122. .iManufacturer = "Butterfly Labs Inc.",
  123. .iProduct = "BitFORCE SHA256",
  124. .kernel = 0,
  125. .config = 1,
  126. .interface = 0,
  127. .timeout = BITFORCE_TIMEOUT_MS,
  128. .epcount = ARRAY_SIZE(bfl_eps),
  129. .eps = bfl_eps },
  130. #endif
  131. #ifdef USE_MODMINER
  132. {
  133. .drv = DRV_MODMINER,
  134. .name = "MMQ",
  135. .ident = IDENT_MMQ,
  136. .idVendor = 0x1fc9,
  137. .idProduct = 0x0003,
  138. .kernel = 0,
  139. .config = 1,
  140. .interface = 1,
  141. .timeout = MODMINER_TIMEOUT_MS,
  142. .epcount = ARRAY_SIZE(mmq_eps),
  143. .eps = mmq_eps },
  144. #endif
  145. #ifdef USE_AVALON
  146. {
  147. .drv = DRV_AVALON,
  148. .name = "AVA",
  149. .ident = IDENT_AVA,
  150. .idVendor = IDVENDOR_FTDI,
  151. .idProduct = 0x6001,
  152. .kernel = 0,
  153. .config = 1,
  154. .interface = 0,
  155. .timeout = AVALON_TIMEOUT_MS,
  156. .epcount = ARRAY_SIZE(ava_eps),
  157. .eps = ava_eps },
  158. #endif
  159. #ifdef USE_ICARUS
  160. {
  161. .drv = DRV_ICARUS,
  162. .name = "ICA",
  163. .ident = IDENT_ICA,
  164. .idVendor = 0x067b,
  165. .idProduct = 0x2303,
  166. .kernel = 0,
  167. .config = 1,
  168. .interface = 0,
  169. .timeout = ICARUS_TIMEOUT_MS,
  170. .epcount = ARRAY_SIZE(ica_eps),
  171. .eps = ica_eps },
  172. {
  173. .drv = DRV_ICARUS,
  174. .name = "AMU",
  175. .ident = IDENT_AMU,
  176. .idVendor = 0x10c4,
  177. .idProduct = 0xea60,
  178. .kernel = 0,
  179. .config = 1,
  180. .interface = 0,
  181. .timeout = ICARUS_TIMEOUT_MS,
  182. .epcount = ARRAY_SIZE(amu_eps),
  183. .eps = amu_eps },
  184. {
  185. .drv = DRV_ICARUS,
  186. .name = "BLT",
  187. .ident = IDENT_BLT,
  188. .idVendor = IDVENDOR_FTDI,
  189. .idProduct = 0x6001,
  190. .iProduct = "FT232R USB UART",
  191. .kernel = 0,
  192. .config = 1,
  193. .interface = 0,
  194. .timeout = ICARUS_TIMEOUT_MS,
  195. .epcount = ARRAY_SIZE(llt_eps),
  196. .eps = llt_eps },
  197. // For any that don't match the above "BLT"
  198. {
  199. .drv = DRV_ICARUS,
  200. .name = "LLT",
  201. .ident = IDENT_LLT,
  202. .idVendor = IDVENDOR_FTDI,
  203. .idProduct = 0x6001,
  204. .kernel = 0,
  205. .config = 1,
  206. .interface = 0,
  207. .timeout = ICARUS_TIMEOUT_MS,
  208. .epcount = ARRAY_SIZE(llt_eps),
  209. .eps = llt_eps },
  210. {
  211. .drv = DRV_ICARUS,
  212. .name = "CMR",
  213. .ident = IDENT_CMR,
  214. .idVendor = IDVENDOR_FTDI,
  215. .idProduct = 0x8350,
  216. .iProduct = "Cairnsmore1",
  217. .kernel = 0,
  218. .config = 1,
  219. .interface = 0,
  220. .timeout = ICARUS_TIMEOUT_MS,
  221. .epcount = ARRAY_SIZE(cmr_eps),
  222. .eps = cmr_eps },
  223. {
  224. .drv = DRV_ICARUS,
  225. .name = "CMR",
  226. .ident = IDENT_CMR,
  227. .idVendor = IDVENDOR_FTDI,
  228. .idProduct = 0x6014,
  229. .iProduct = "Cairnsmore1",
  230. .kernel = 0,
  231. .config = 1,
  232. .interface = 0,
  233. .timeout = ICARUS_TIMEOUT_MS,
  234. .epcount = ARRAY_SIZE(cmr_eps),
  235. .eps = cmr_eps },
  236. #endif
  237. #ifdef USE_ZTEX
  238. // This is here so cgminer -n shows them
  239. // the ztex driver (as at 201303) doesn't use usbutils
  240. {
  241. .drv = DRV_ZTEX,
  242. .name = "ZTX",
  243. .ident = IDENT_ZTX,
  244. .idVendor = 0x221a,
  245. .idProduct = 0x0100,
  246. .kernel = 0,
  247. .config = 1,
  248. .interface = 1,
  249. .timeout = 100,
  250. .epcount = 0,
  251. .eps = NULL },
  252. #endif
  253. { DRV_LAST, NULL, 0, 0, 0, NULL, NULL, 0, 0, 0, 0, 0, NULL }
  254. };
  255. #ifdef USE_BFLSC
  256. extern struct device_drv bflsc_drv;
  257. #endif
  258. #ifdef USE_BITFORCE
  259. extern struct device_drv bitforce_drv;
  260. #endif
  261. #ifdef USE_MODMINER
  262. extern struct device_drv modminer_drv;
  263. #endif
  264. #ifdef USE_ICARUS
  265. extern struct device_drv icarus_drv;
  266. #endif
  267. #ifdef USE_AVALON
  268. extern struct device_drv avalon_drv;
  269. #endif
  270. #define STRBUFLEN 256
  271. static const char *BLANK = "";
  272. static const char *space = " ";
  273. static const char *nodatareturned = "no data returned ";
  274. #if 0 // enable USBDEBUG - only during development testing
  275. static const char *debug_true_str = "true";
  276. static const char *debug_false_str = "false";
  277. static const char *nodevstr = "=NODEV";
  278. #define bool_str(boo) ((boo) ? debug_true_str : debug_false_str)
  279. #define isnodev(err) (NODEV(err) ? nodevstr : BLANK)
  280. #define USBDEBUG(fmt, ...) applog(LOG_WARNING, fmt, ##__VA_ARGS__)
  281. #else
  282. #define USBDEBUG(fmt, ...)
  283. #endif
  284. // For device limits by driver
  285. static struct driver_count {
  286. uint32_t count;
  287. uint32_t limit;
  288. } drv_count[DRIVER_MAX];
  289. // For device limits by list of bus/dev
  290. static struct usb_busdev {
  291. int bus_number;
  292. int device_address;
  293. } *busdev;
  294. static int busdev_count = 0;
  295. // Total device limit
  296. static int total_count = 0;
  297. static int total_limit = 999999;
  298. struct usb_in_use_list {
  299. struct usb_busdev in_use;
  300. struct usb_in_use_list *prev;
  301. struct usb_in_use_list *next;
  302. };
  303. // List of in use devices
  304. static struct usb_in_use_list *in_use_head = NULL;
  305. // Set this to 0 to remove stats processing
  306. #define DO_USB_STATS 1
  307. static bool stats_initialised = false;
  308. #if DO_USB_STATS
  309. // NONE must be 0 - calloced
  310. #define MODE_NONE 0
  311. #define MODE_CTRL_READ (1 << 0)
  312. #define MODE_CTRL_WRITE (1 << 1)
  313. #define MODE_BULK_READ (1 << 2)
  314. #define MODE_BULK_WRITE (1 << 3)
  315. #define MODE_SEP_STR "+"
  316. #define MODE_NONE_STR "X"
  317. #define MODE_CTRL_READ_STR "cr"
  318. #define MODE_CTRL_WRITE_STR "cw"
  319. #define MODE_BULK_READ_STR "br"
  320. #define MODE_BULK_WRITE_STR "bw"
  321. // One for each CMD, TIMEOUT, ERROR
  322. struct cg_usb_stats_item {
  323. uint64_t count;
  324. double total_delay;
  325. double min_delay;
  326. double max_delay;
  327. struct timeval first;
  328. struct timeval last;
  329. };
  330. #define CMD_CMD 0
  331. #define CMD_TIMEOUT 1
  332. #define CMD_ERROR 2
  333. // One for each C_CMD
  334. struct cg_usb_stats_details {
  335. int seq;
  336. uint32_t modes;
  337. struct cg_usb_stats_item item[CMD_ERROR+1];
  338. };
  339. // One for each device
  340. struct cg_usb_stats {
  341. char *name;
  342. int device_id;
  343. struct cg_usb_stats_details *details;
  344. };
  345. #define SEQ0 0
  346. #define SEQ1 1
  347. static struct cg_usb_stats *usb_stats = NULL;
  348. static int next_stat = 0;
  349. #define USB_STATS(sgpu, sta, fin, err, mode, cmd, seq) \
  350. stats(cgpu, sta, fin, err, mode, cmd, seq)
  351. #define STATS_TIMEVAL(tv) cgtime(tv)
  352. #define USB_REJECT(sgpu, mode) rejected_inc(sgpu, mode)
  353. #else
  354. #define USB_STATS(sgpu, sta, fin, err, mode, cmd, seq)
  355. #define STATS_TIMEVAL(tv)
  356. #define USB_REJECT(sgpu, mode)
  357. #endif // DO_USB_STATS
  358. static const char **usb_commands;
  359. static const char *C_REJECTED_S = "RejectedNoDevice";
  360. static const char *C_PING_S = "Ping";
  361. static const char *C_CLEAR_S = "Clear";
  362. static const char *C_REQUESTVERSION_S = "RequestVersion";
  363. static const char *C_GETVERSION_S = "GetVersion";
  364. static const char *C_REQUESTFPGACOUNT_S = "RequestFPGACount";
  365. static const char *C_GETFPGACOUNT_S = "GetFPGACount";
  366. static const char *C_STARTPROGRAM_S = "StartProgram";
  367. static const char *C_STARTPROGRAMSTATUS_S = "StartProgramStatus";
  368. static const char *C_PROGRAM_S = "Program";
  369. static const char *C_PROGRAMSTATUS_S = "ProgramStatus";
  370. static const char *C_PROGRAMSTATUS2_S = "ProgramStatus2";
  371. static const char *C_FINALPROGRAMSTATUS_S = "FinalProgramStatus";
  372. static const char *C_SETCLOCK_S = "SetClock";
  373. static const char *C_REPLYSETCLOCK_S = "ReplySetClock";
  374. static const char *C_REQUESTUSERCODE_S = "RequestUserCode";
  375. static const char *C_GETUSERCODE_S = "GetUserCode";
  376. static const char *C_REQUESTTEMPERATURE_S = "RequestTemperature";
  377. static const char *C_GETTEMPERATURE_S = "GetTemperature";
  378. static const char *C_SENDWORK_S = "SendWork";
  379. static const char *C_SENDWORKSTATUS_S = "SendWorkStatus";
  380. static const char *C_REQUESTWORKSTATUS_S = "RequestWorkStatus";
  381. static const char *C_GETWORKSTATUS_S = "GetWorkStatus";
  382. static const char *C_REQUESTIDENTIFY_S = "RequestIdentify";
  383. static const char *C_GETIDENTIFY_S = "GetIdentify";
  384. static const char *C_REQUESTFLASH_S = "RequestFlash";
  385. static const char *C_REQUESTSENDWORK_S = "RequestSendWork";
  386. static const char *C_REQUESTSENDWORKSTATUS_S = "RequestSendWorkStatus";
  387. static const char *C_RESET_S = "Reset";
  388. static const char *C_SETBAUD_S = "SetBaud";
  389. static const char *C_SETDATA_S = "SetDataCtrl";
  390. static const char *C_SETFLOW_S = "SetFlowCtrl";
  391. static const char *C_SETMODEM_S = "SetModemCtrl";
  392. static const char *C_PURGERX_S = "PurgeRx";
  393. static const char *C_PURGETX_S = "PurgeTx";
  394. static const char *C_FLASHREPLY_S = "FlashReply";
  395. static const char *C_REQUESTDETAILS_S = "RequestDetails";
  396. static const char *C_GETDETAILS_S = "GetDetails";
  397. static const char *C_REQUESTRESULTS_S = "RequestResults";
  398. static const char *C_GETRESULTS_S = "GetResults";
  399. static const char *C_REQUESTQUEJOB_S = "RequestQueJob";
  400. static const char *C_REQUESTQUEJOBSTATUS_S = "RequestQueJobStatus";
  401. static const char *C_QUEJOB_S = "QueJob";
  402. static const char *C_QUEJOBSTATUS_S = "QueJobStatus";
  403. static const char *C_QUEFLUSH_S = "QueFlush";
  404. static const char *C_QUEFLUSHREPLY_S = "QueFlushReply";
  405. static const char *C_REQUESTVOLTS_S = "RequestVolts";
  406. static const char *C_SENDTESTWORK_S = "SendTestWork";
  407. static const char *C_LATENCY_S = "SetLatency";
  408. static const char *C_SETLINE_S = "SetLine";
  409. static const char *C_VENDOR_S = "Vendor";
  410. #ifdef EOL
  411. #undef EOL
  412. #endif
  413. #define EOL "\n"
  414. static const char *DESDEV = "Device";
  415. static const char *DESCON = "Config";
  416. static const char *DESSTR = "String";
  417. static const char *DESINT = "Interface";
  418. static const char *DESEP = "Endpoint";
  419. static const char *DESHID = "HID";
  420. static const char *DESRPT = "Report";
  421. static const char *DESPHY = "Physical";
  422. static const char *DESHUB = "Hub";
  423. static const char *EPIN = "In: ";
  424. static const char *EPOUT = "Out: ";
  425. static const char *EPX = "?: ";
  426. static const char *CONTROL = "Control";
  427. static const char *ISOCHRONOUS_X = "Isochronous+?";
  428. static const char *ISOCHRONOUS_N_X = "Isochronous+None+?";
  429. static const char *ISOCHRONOUS_N_D = "Isochronous+None+Data";
  430. static const char *ISOCHRONOUS_N_F = "Isochronous+None+Feedback";
  431. static const char *ISOCHRONOUS_N_I = "Isochronous+None+Implicit";
  432. static const char *ISOCHRONOUS_A_X = "Isochronous+Async+?";
  433. static const char *ISOCHRONOUS_A_D = "Isochronous+Async+Data";
  434. static const char *ISOCHRONOUS_A_F = "Isochronous+Async+Feedback";
  435. static const char *ISOCHRONOUS_A_I = "Isochronous+Async+Implicit";
  436. static const char *ISOCHRONOUS_D_X = "Isochronous+Adaptive+?";
  437. static const char *ISOCHRONOUS_D_D = "Isochronous+Adaptive+Data";
  438. static const char *ISOCHRONOUS_D_F = "Isochronous+Adaptive+Feedback";
  439. static const char *ISOCHRONOUS_D_I = "Isochronous+Adaptive+Implicit";
  440. static const char *ISOCHRONOUS_S_X = "Isochronous+Sync+?";
  441. static const char *ISOCHRONOUS_S_D = "Isochronous+Sync+Data";
  442. static const char *ISOCHRONOUS_S_F = "Isochronous+Sync+Feedback";
  443. static const char *ISOCHRONOUS_S_I = "Isochronous+Sync+Implicit";
  444. static const char *BULK = "Bulk";
  445. static const char *INTERRUPT = "Interrupt";
  446. static const char *UNKNOWN = "Unknown";
  447. static const char *err_io_str = " IO Error";
  448. static const char *err_access_str = " Access Denied-a";
  449. static const char *err_timeout_str = " Reply Timeout";
  450. static const char *err_pipe_str = " Access denied-p";
  451. static const char *err_other_str = " Access denied-o";
  452. static const char *usberrstr(int err)
  453. {
  454. switch (err) {
  455. case LIBUSB_ERROR_IO:
  456. return err_io_str;
  457. case LIBUSB_ERROR_ACCESS:
  458. return err_access_str;
  459. case LIBUSB_ERROR_TIMEOUT:
  460. return err_timeout_str;
  461. case LIBUSB_ERROR_PIPE:
  462. return err_pipe_str;
  463. case LIBUSB_ERROR_OTHER:
  464. return err_other_str;
  465. }
  466. return BLANK;
  467. }
  468. static const char *destype(uint8_t bDescriptorType)
  469. {
  470. switch (bDescriptorType) {
  471. case LIBUSB_DT_DEVICE:
  472. return DESDEV;
  473. case LIBUSB_DT_CONFIG:
  474. return DESCON;
  475. case LIBUSB_DT_STRING:
  476. return DESSTR;
  477. case LIBUSB_DT_INTERFACE:
  478. return DESINT;
  479. case LIBUSB_DT_ENDPOINT:
  480. return DESEP;
  481. case LIBUSB_DT_HID:
  482. return DESHID;
  483. case LIBUSB_DT_REPORT:
  484. return DESRPT;
  485. case LIBUSB_DT_PHYSICAL:
  486. return DESPHY;
  487. case LIBUSB_DT_HUB:
  488. return DESHUB;
  489. }
  490. return UNKNOWN;
  491. }
  492. static const char *epdir(uint8_t bEndpointAddress)
  493. {
  494. switch (bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) {
  495. case LIBUSB_ENDPOINT_IN:
  496. return EPIN;
  497. case LIBUSB_ENDPOINT_OUT:
  498. return EPOUT;
  499. }
  500. return EPX;
  501. }
  502. static const char *epatt(uint8_t bmAttributes)
  503. {
  504. switch(bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) {
  505. case LIBUSB_TRANSFER_TYPE_CONTROL:
  506. return CONTROL;
  507. case LIBUSB_TRANSFER_TYPE_BULK:
  508. return BULK;
  509. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  510. return INTERRUPT;
  511. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  512. switch(bmAttributes & LIBUSB_ISO_SYNC_TYPE_MASK) {
  513. case LIBUSB_ISO_SYNC_TYPE_NONE:
  514. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  515. case LIBUSB_ISO_USAGE_TYPE_DATA:
  516. return ISOCHRONOUS_N_D;
  517. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  518. return ISOCHRONOUS_N_F;
  519. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  520. return ISOCHRONOUS_N_I;
  521. }
  522. return ISOCHRONOUS_N_X;
  523. case LIBUSB_ISO_SYNC_TYPE_ASYNC:
  524. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  525. case LIBUSB_ISO_USAGE_TYPE_DATA:
  526. return ISOCHRONOUS_A_D;
  527. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  528. return ISOCHRONOUS_A_F;
  529. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  530. return ISOCHRONOUS_A_I;
  531. }
  532. return ISOCHRONOUS_A_X;
  533. case LIBUSB_ISO_SYNC_TYPE_ADAPTIVE:
  534. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  535. case LIBUSB_ISO_USAGE_TYPE_DATA:
  536. return ISOCHRONOUS_D_D;
  537. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  538. return ISOCHRONOUS_D_F;
  539. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  540. return ISOCHRONOUS_D_I;
  541. }
  542. return ISOCHRONOUS_D_X;
  543. case LIBUSB_ISO_SYNC_TYPE_SYNC:
  544. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  545. case LIBUSB_ISO_USAGE_TYPE_DATA:
  546. return ISOCHRONOUS_S_D;
  547. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  548. return ISOCHRONOUS_S_F;
  549. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  550. return ISOCHRONOUS_S_I;
  551. }
  552. return ISOCHRONOUS_S_X;
  553. }
  554. return ISOCHRONOUS_X;
  555. }
  556. return UNKNOWN;
  557. }
  558. static void append(char **buf, char *append, size_t *off, size_t *len)
  559. {
  560. int new = strlen(append);
  561. if ((new + *off) >= *len)
  562. {
  563. *len *= 2;
  564. *buf = realloc(*buf, *len);
  565. }
  566. strcpy(*buf + *off, append);
  567. *off += new;
  568. }
  569. 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)
  570. {
  571. char tmp[512];
  572. int err;
  573. err = libusb_set_configuration(handle, cd);
  574. if (err) {
  575. sprintf(tmp, EOL " ** dev %d: Failed to set config descriptor to %d, err %d",
  576. (int)count, cd, err);
  577. append(buf, tmp, off, len);
  578. return false;
  579. }
  580. err = libusb_get_active_config_descriptor(dev, config);
  581. if (err) {
  582. sprintf(tmp, EOL " ** dev %d: Failed to get active config descriptor set to %d, err %d",
  583. (int)count, cd, err);
  584. append(buf, tmp, off, len);
  585. return false;
  586. }
  587. sprintf(tmp, EOL " ** dev %d: Set & Got active config descriptor to %d, err %d",
  588. (int)count, cd, err);
  589. append(buf, tmp, off, len);
  590. return true;
  591. }
  592. static void usb_full(ssize_t *count, libusb_device *dev, char **buf, size_t *off, size_t *len, int level)
  593. {
  594. struct libusb_device_descriptor desc;
  595. uint8_t bus_number;
  596. uint8_t device_address;
  597. struct libusb_device_handle *handle;
  598. struct libusb_config_descriptor *config;
  599. const struct libusb_interface_descriptor *idesc;
  600. const struct libusb_endpoint_descriptor *epdesc;
  601. unsigned char man[STRBUFLEN+1];
  602. unsigned char prod[STRBUFLEN+1];
  603. unsigned char ser[STRBUFLEN+1];
  604. char tmp[512];
  605. int err, i, j, k;
  606. err = libusb_get_device_descriptor(dev, &desc);
  607. if (opt_usb_list_all && err) {
  608. sprintf(tmp, EOL ".USB dev %d: Failed to get descriptor, err %d",
  609. (int)(++(*count)), err);
  610. append(buf, tmp, off, len);
  611. return;
  612. }
  613. bus_number = libusb_get_bus_number(dev);
  614. device_address = libusb_get_device_address(dev);
  615. if (!opt_usb_list_all) {
  616. bool known = false;
  617. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  618. if ((find_dev[i].idVendor == desc.idVendor) &&
  619. (find_dev[i].idProduct == desc.idProduct)) {
  620. known = true;
  621. break;
  622. }
  623. if (!known)
  624. return;
  625. }
  626. (*count)++;
  627. if (level == 0) {
  628. sprintf(tmp, EOL ".USB dev %d: Bus %d Device %d ID: %04x:%04x",
  629. (int)(*count), (int)bus_number, (int)device_address,
  630. desc.idVendor, desc.idProduct);
  631. } else {
  632. sprintf(tmp, EOL ".USB dev %d: Bus %d Device %d Device Descriptor:" EOL "\tLength: %d" EOL
  633. "\tDescriptor Type: %s" EOL "\tUSB: %04x" EOL "\tDeviceClass: %d" EOL
  634. "\tDeviceSubClass: %d" EOL "\tDeviceProtocol: %d" EOL "\tMaxPacketSize0: %d" EOL
  635. "\tidVendor: %04x" EOL "\tidProduct: %04x" EOL "\tDeviceRelease: %x" EOL
  636. "\tNumConfigurations: %d",
  637. (int)(*count), (int)bus_number, (int)device_address,
  638. (int)(desc.bLength), destype(desc.bDescriptorType),
  639. desc.bcdUSB, (int)(desc.bDeviceClass), (int)(desc.bDeviceSubClass),
  640. (int)(desc.bDeviceProtocol), (int)(desc.bMaxPacketSize0),
  641. desc.idVendor, desc.idProduct, desc.bcdDevice,
  642. (int)(desc.bNumConfigurations));
  643. }
  644. append(buf, tmp, off, len);
  645. err = libusb_open(dev, &handle);
  646. if (err) {
  647. sprintf(tmp, EOL " ** dev %d: Failed to open, err %d", (int)(*count), err);
  648. append(buf, tmp, off, len);
  649. return;
  650. }
  651. err = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, man, STRBUFLEN);
  652. if (err < 0)
  653. sprintf((char *)man, "** err(%d)%s", err, usberrstr(err));
  654. err = libusb_get_string_descriptor_ascii(handle, desc.iProduct, prod, STRBUFLEN);
  655. if (err < 0)
  656. sprintf((char *)prod, "** err(%d)%s", err, usberrstr(err));
  657. if (level == 0) {
  658. libusb_close(handle);
  659. sprintf(tmp, EOL " Manufacturer: '%s'" EOL " Product: '%s'", man, prod);
  660. append(buf, tmp, off, len);
  661. return;
  662. }
  663. if (libusb_kernel_driver_active(handle, 0) == 1) {
  664. sprintf(tmp, EOL " * dev %d: kernel attached", (int)(*count));
  665. append(buf, tmp, off, len);
  666. }
  667. err = libusb_get_active_config_descriptor(dev, &config);
  668. if (err) {
  669. if (!setgetdes(*count, dev, handle, &config, 1, buf, off, len)
  670. && !setgetdes(*count, dev, handle, &config, 0, buf, off, len)) {
  671. libusb_close(handle);
  672. sprintf(tmp, EOL " ** dev %d: Failed to set config descriptor to %d or %d",
  673. (int)(*count), 1, 0);
  674. append(buf, tmp, off, len);
  675. return;
  676. }
  677. }
  678. sprintf(tmp, EOL " dev %d: Active Config:" EOL "\tDescriptorType: %s" EOL
  679. "\tNumInterfaces: %d" EOL "\tConfigurationValue: %d" EOL
  680. "\tAttributes: %d" EOL "\tMaxPower: %d",
  681. (int)(*count), destype(config->bDescriptorType),
  682. (int)(config->bNumInterfaces), (int)(config->iConfiguration),
  683. (int)(config->bmAttributes), (int)(config->MaxPower));
  684. append(buf, tmp, off, len);
  685. for (i = 0; i < (int)(config->bNumInterfaces); i++) {
  686. for (j = 0; j < config->interface[i].num_altsetting; j++) {
  687. idesc = &(config->interface[i].altsetting[j]);
  688. sprintf(tmp, EOL " _dev %d: Interface Descriptor %d:" EOL
  689. "\tDescriptorType: %s" EOL "\tInterfaceNumber: %d" EOL
  690. "\tNumEndpoints: %d" EOL "\tInterfaceClass: %d" EOL
  691. "\tInterfaceSubClass: %d" EOL "\tInterfaceProtocol: %d",
  692. (int)(*count), j, destype(idesc->bDescriptorType),
  693. (int)(idesc->bInterfaceNumber),
  694. (int)(idesc->bNumEndpoints),
  695. (int)(idesc->bInterfaceClass),
  696. (int)(idesc->bInterfaceSubClass),
  697. (int)(idesc->bInterfaceProtocol));
  698. append(buf, tmp, off, len);
  699. for (k = 0; k < (int)(idesc->bNumEndpoints); k++) {
  700. epdesc = &(idesc->endpoint[k]);
  701. sprintf(tmp, EOL " __dev %d: Interface %d Endpoint %d:" EOL
  702. "\tDescriptorType: %s" EOL
  703. "\tEndpointAddress: %s0x%x" EOL
  704. "\tAttributes: %s" EOL "\tMaxPacketSize: %d" EOL
  705. "\tInterval: %d" EOL "\tRefresh: %d",
  706. (int)(*count), (int)(idesc->bInterfaceNumber), k,
  707. destype(epdesc->bDescriptorType),
  708. epdir(epdesc->bEndpointAddress),
  709. (int)(epdesc->bEndpointAddress),
  710. epatt(epdesc->bmAttributes),
  711. epdesc->wMaxPacketSize,
  712. (int)(epdesc->bInterval),
  713. (int)(epdesc->bRefresh));
  714. append(buf, tmp, off, len);
  715. }
  716. }
  717. }
  718. libusb_free_config_descriptor(config);
  719. config = NULL;
  720. err = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, ser, STRBUFLEN);
  721. if (err < 0)
  722. sprintf((char *)ser, "** err(%d)%s", err, usberrstr(err));
  723. sprintf(tmp, EOL " dev %d: More Info:" EOL "\tManufacturer: '%s'" EOL
  724. "\tProduct: '%s'" EOL "\tSerial '%s'",
  725. (int)(*count), man, prod, ser);
  726. append(buf, tmp, off, len);
  727. libusb_close(handle);
  728. }
  729. // Function to dump all USB devices
  730. void usb_all(int level)
  731. {
  732. libusb_device **list;
  733. ssize_t count, i, j;
  734. char *buf;
  735. size_t len, off;
  736. count = libusb_get_device_list(NULL, &list);
  737. if (count < 0) {
  738. applog(LOG_ERR, "USB all: failed, err %d%s", (int)count, usberrstr((int)count));
  739. return;
  740. }
  741. if (count == 0)
  742. applog(LOG_WARNING, "USB all: found no devices");
  743. else
  744. {
  745. len = 10000;
  746. buf = malloc(len+1);
  747. sprintf(buf, "USB all: found %d devices", (int)count);
  748. off = strlen(buf);
  749. if (!opt_usb_list_all)
  750. append(&buf, " - listing known devices", &off, &len);
  751. j = -1;
  752. for (i = 0; i < count; i++)
  753. usb_full(&j, list[i], &buf, &off, &len, level);
  754. applog(LOG_WARNING, "%s", buf);
  755. free(buf);
  756. if (j == -1)
  757. applog(LOG_WARNING, "No known USB devices");
  758. else
  759. applog(LOG_WARNING, "%d %sUSB devices",
  760. (int)(++j), opt_usb_list_all ? BLANK : "known ");
  761. }
  762. libusb_free_device_list(list, 1);
  763. }
  764. static void cgusb_check_init()
  765. {
  766. mutex_lock(&cgusb_lock);
  767. if (stats_initialised == false) {
  768. // N.B. environment LIBUSB_DEBUG also sets libusb_set_debug()
  769. if (opt_usbdump >= 0) {
  770. libusb_set_debug(NULL, opt_usbdump);
  771. usb_all(opt_usbdump);
  772. }
  773. usb_commands = malloc(sizeof(*usb_commands) * C_MAX);
  774. // use constants so the stat generation is very quick
  775. // and the association between number and name can't
  776. // be missalined easily
  777. usb_commands[C_REJECTED] = C_REJECTED_S;
  778. usb_commands[C_PING] = C_PING_S;
  779. usb_commands[C_CLEAR] = C_CLEAR_S;
  780. usb_commands[C_REQUESTVERSION] = C_REQUESTVERSION_S;
  781. usb_commands[C_GETVERSION] = C_GETVERSION_S;
  782. usb_commands[C_REQUESTFPGACOUNT] = C_REQUESTFPGACOUNT_S;
  783. usb_commands[C_GETFPGACOUNT] = C_GETFPGACOUNT_S;
  784. usb_commands[C_STARTPROGRAM] = C_STARTPROGRAM_S;
  785. usb_commands[C_STARTPROGRAMSTATUS] = C_STARTPROGRAMSTATUS_S;
  786. usb_commands[C_PROGRAM] = C_PROGRAM_S;
  787. usb_commands[C_PROGRAMSTATUS] = C_PROGRAMSTATUS_S;
  788. usb_commands[C_PROGRAMSTATUS2] = C_PROGRAMSTATUS2_S;
  789. usb_commands[C_FINALPROGRAMSTATUS] = C_FINALPROGRAMSTATUS_S;
  790. usb_commands[C_SETCLOCK] = C_SETCLOCK_S;
  791. usb_commands[C_REPLYSETCLOCK] = C_REPLYSETCLOCK_S;
  792. usb_commands[C_REQUESTUSERCODE] = C_REQUESTUSERCODE_S;
  793. usb_commands[C_GETUSERCODE] = C_GETUSERCODE_S;
  794. usb_commands[C_REQUESTTEMPERATURE] = C_REQUESTTEMPERATURE_S;
  795. usb_commands[C_GETTEMPERATURE] = C_GETTEMPERATURE_S;
  796. usb_commands[C_SENDWORK] = C_SENDWORK_S;
  797. usb_commands[C_SENDWORKSTATUS] = C_SENDWORKSTATUS_S;
  798. usb_commands[C_REQUESTWORKSTATUS] = C_REQUESTWORKSTATUS_S;
  799. usb_commands[C_GETWORKSTATUS] = C_GETWORKSTATUS_S;
  800. usb_commands[C_REQUESTIDENTIFY] = C_REQUESTIDENTIFY_S;
  801. usb_commands[C_GETIDENTIFY] = C_GETIDENTIFY_S;
  802. usb_commands[C_REQUESTFLASH] = C_REQUESTFLASH_S;
  803. usb_commands[C_REQUESTSENDWORK] = C_REQUESTSENDWORK_S;
  804. usb_commands[C_REQUESTSENDWORKSTATUS] = C_REQUESTSENDWORKSTATUS_S;
  805. usb_commands[C_RESET] = C_RESET_S;
  806. usb_commands[C_SETBAUD] = C_SETBAUD_S;
  807. usb_commands[C_SETDATA] = C_SETDATA_S;
  808. usb_commands[C_SETFLOW] = C_SETFLOW_S;
  809. usb_commands[C_SETMODEM] = C_SETMODEM_S;
  810. usb_commands[C_PURGERX] = C_PURGERX_S;
  811. usb_commands[C_PURGETX] = C_PURGETX_S;
  812. usb_commands[C_FLASHREPLY] = C_FLASHREPLY_S;
  813. usb_commands[C_REQUESTDETAILS] = C_REQUESTDETAILS_S;
  814. usb_commands[C_GETDETAILS] = C_GETDETAILS_S;
  815. usb_commands[C_REQUESTRESULTS] = C_REQUESTRESULTS_S;
  816. usb_commands[C_GETRESULTS] = C_GETRESULTS_S;
  817. usb_commands[C_REQUESTQUEJOB] = C_REQUESTQUEJOB_S;
  818. usb_commands[C_REQUESTQUEJOBSTATUS] = C_REQUESTQUEJOBSTATUS_S;
  819. usb_commands[C_QUEJOB] = C_QUEJOB_S;
  820. usb_commands[C_QUEJOBSTATUS] = C_QUEJOBSTATUS_S;
  821. usb_commands[C_QUEFLUSH] = C_QUEFLUSH_S;
  822. usb_commands[C_QUEFLUSHREPLY] = C_QUEFLUSHREPLY_S;
  823. usb_commands[C_REQUESTVOLTS] = C_REQUESTVOLTS_S;
  824. usb_commands[C_SENDTESTWORK] = C_SENDTESTWORK_S;
  825. usb_commands[C_LATENCY] = C_LATENCY_S;
  826. usb_commands[C_SETLINE] = C_SETLINE_S;
  827. usb_commands[C_VENDOR] = C_VENDOR_S;
  828. stats_initialised = true;
  829. }
  830. mutex_unlock(&cgusb_lock);
  831. }
  832. const char *usb_cmdname(enum usb_cmds cmd)
  833. {
  834. cgusb_check_init();
  835. return usb_commands[cmd];
  836. }
  837. void usb_applog(struct cgpu_info *cgpu, enum usb_cmds cmd, char *msg, int amount, int err)
  838. {
  839. if (msg && !*msg)
  840. msg = NULL;
  841. if (!msg && amount == 0 && err == LIBUSB_SUCCESS)
  842. msg = (char *)nodatareturned;
  843. applog(LOG_ERR, "%s%i: %s failed%s%s (err=%d amt=%d)",
  844. cgpu->drv->name, cgpu->device_id,
  845. usb_cmdname(cmd),
  846. msg ? space : BLANK, msg ? msg : BLANK,
  847. err, amount);
  848. }
  849. static bool __is_in_use(uint8_t bus_number, uint8_t device_address)
  850. {
  851. struct usb_in_use_list *in_use_tmp;
  852. bool ret = false;
  853. in_use_tmp = in_use_head;
  854. while (in_use_tmp) {
  855. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  856. in_use_tmp->in_use.device_address == (int)device_address) {
  857. ret = true;
  858. break;
  859. }
  860. in_use_tmp = in_use_tmp->next;
  861. }
  862. return ret;
  863. }
  864. static bool is_in_use_bd(uint8_t bus_number, uint8_t device_address)
  865. {
  866. bool ret;
  867. mutex_lock(&cgusb_lock);
  868. ret = __is_in_use(bus_number, device_address);
  869. mutex_unlock(&cgusb_lock);
  870. return ret;
  871. }
  872. static bool is_in_use(libusb_device *dev)
  873. {
  874. return is_in_use_bd(libusb_get_bus_number(dev), libusb_get_device_address(dev));
  875. }
  876. static void add_in_use(uint8_t bus_number, uint8_t device_address)
  877. {
  878. struct usb_in_use_list *in_use_tmp;
  879. bool found = false;
  880. mutex_lock(&cgusb_lock);
  881. if (unlikely(__is_in_use(bus_number, device_address))) {
  882. found = true;
  883. goto nofway;
  884. }
  885. in_use_tmp = calloc(1, sizeof(*in_use_tmp));
  886. in_use_tmp->in_use.bus_number = (int)bus_number;
  887. in_use_tmp->in_use.device_address = (int)device_address;
  888. in_use_tmp->next = in_use_head;
  889. if (in_use_head)
  890. in_use_head->prev = in_use_tmp;
  891. in_use_head = in_use_tmp;
  892. nofway:
  893. mutex_unlock(&cgusb_lock);
  894. if (found)
  895. applog(LOG_ERR, "FAIL: USB add already in use (%d:%d)",
  896. (int)bus_number, (int)device_address);
  897. }
  898. static void remove_in_use(uint8_t bus_number, uint8_t device_address)
  899. {
  900. struct usb_in_use_list *in_use_tmp;
  901. bool found = false;
  902. mutex_lock(&cgusb_lock);
  903. in_use_tmp = in_use_head;
  904. while (in_use_tmp) {
  905. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  906. in_use_tmp->in_use.device_address == (int)device_address) {
  907. found = true;
  908. if (in_use_tmp == in_use_head) {
  909. in_use_head = in_use_head->next;
  910. if (in_use_head)
  911. in_use_head->prev = NULL;
  912. } else {
  913. in_use_tmp->prev->next = in_use_tmp->next;
  914. if (in_use_tmp->next)
  915. in_use_tmp->next->prev = in_use_tmp->prev;
  916. }
  917. free(in_use_tmp);
  918. break;
  919. }
  920. in_use_tmp = in_use_tmp->next;
  921. }
  922. mutex_unlock(&cgusb_lock);
  923. if (!found)
  924. applog(LOG_ERR, "FAIL: USB remove not already in use (%d:%d)",
  925. (int)bus_number, (int)device_address);
  926. }
  927. #ifndef WIN32
  928. #include <errno.h>
  929. #include <unistd.h>
  930. #include <sys/types.h>
  931. #include <sys/ipc.h>
  932. #include <sys/sem.h>
  933. #include <sys/types.h>
  934. #include <sys/stat.h>
  935. #include <fcntl.h>
  936. union semun {
  937. int sem;
  938. struct semid_ds *seminfo;
  939. ushort *all;
  940. };
  941. #endif
  942. // Any errors should always be printed since they will rarely if ever occur
  943. // and thus it is best to always display them
  944. static bool cgminer_usb_lock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  945. {
  946. applog(LOG_DEBUG, "USB lock %s %d-%d", drv->name, (int)bus_number, (int)device_address);
  947. #ifdef WIN32
  948. struct cgpu_info *cgpu;
  949. HANDLE usbMutex;
  950. char name[64];
  951. DWORD res;
  952. int i;
  953. if (is_in_use_bd(bus_number, device_address))
  954. return false;
  955. sprintf(name, "cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  956. usbMutex = CreateMutex(NULL, FALSE, name);
  957. if (usbMutex == NULL) {
  958. applog(LOG_ERR,
  959. "MTX: %s USB failed to get '%s' err (%d)",
  960. drv->dname, name, GetLastError());
  961. return false;
  962. }
  963. res = WaitForSingleObject(usbMutex, 0);
  964. switch(res) {
  965. case WAIT_OBJECT_0:
  966. case WAIT_ABANDONED:
  967. // Am I using it already?
  968. for (i = 0; i < total_devices; i++) {
  969. cgpu = get_devices(i);
  970. if (cgpu->usbinfo.bus_number == bus_number &&
  971. cgpu->usbinfo.device_address == device_address &&
  972. cgpu->usbinfo.nodev == false) {
  973. if (ReleaseMutex(usbMutex)) {
  974. applog(LOG_WARNING,
  975. "MTX: %s USB can't get '%s' - device in use",
  976. drv->dname, name);
  977. goto fail;
  978. }
  979. applog(LOG_ERR,
  980. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  981. drv->dname, name, GetLastError());
  982. goto fail;
  983. }
  984. }
  985. add_in_use(bus_number, device_address);
  986. return true;
  987. case WAIT_TIMEOUT:
  988. if (!hotplug_mode)
  989. applog(LOG_WARNING,
  990. "MTX: %s USB failed to get '%s' - device in use",
  991. drv->dname, name);
  992. goto fail;
  993. case WAIT_FAILED:
  994. applog(LOG_ERR,
  995. "MTX: %s USB failed to get '%s' err (%d)",
  996. drv->dname, name, GetLastError());
  997. goto fail;
  998. default:
  999. applog(LOG_ERR,
  1000. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  1001. drv->dname, name, res);
  1002. goto fail;
  1003. }
  1004. CloseHandle(usbMutex);
  1005. add_in_use(bus_number, device_address);
  1006. return true;
  1007. fail:
  1008. CloseHandle(usbMutex);
  1009. return false;
  1010. #else
  1011. struct semid_ds seminfo;
  1012. union semun opt;
  1013. char name[64];
  1014. key_t key;
  1015. int fd, sem, count;
  1016. if (is_in_use_bd(bus_number, device_address))
  1017. return false;
  1018. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  1019. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  1020. if (fd == -1) {
  1021. applog(LOG_ERR,
  1022. "SEM: %s USB open failed '%s' err (%d) %s",
  1023. drv->dname, name, errno, strerror(errno));
  1024. return false;
  1025. }
  1026. close(fd);
  1027. key = ftok(name, 'K');
  1028. sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 438);
  1029. if (sem < 0) {
  1030. if (errno != EEXIST) {
  1031. applog(LOG_ERR,
  1032. "SEM: %s USB failed to get '%s' err (%d) %s",
  1033. drv->dname, name, errno, strerror(errno));
  1034. return false;
  1035. }
  1036. sem = semget(key, 1, 0);
  1037. if (sem < 0) {
  1038. applog(LOG_ERR,
  1039. "SEM: %s USB failed to access '%s' err (%d) %s",
  1040. drv->dname, name, errno, strerror(errno));
  1041. return false;
  1042. }
  1043. opt.seminfo = &seminfo;
  1044. count = 0;
  1045. while (++count) {
  1046. // Should NEVER take 100ms
  1047. if (count > 99) {
  1048. applog(LOG_ERR,
  1049. "SEM: %s USB timeout waiting for (%d) '%s'",
  1050. drv->dname, sem, name);
  1051. return false;
  1052. }
  1053. if (semctl(sem, 0, IPC_STAT, opt) == -1) {
  1054. applog(LOG_ERR,
  1055. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  1056. drv->dname, sem, name, count, errno, strerror(errno));
  1057. return false;
  1058. }
  1059. if (opt.seminfo->sem_otime != 0)
  1060. break;
  1061. nmsleep(1);
  1062. }
  1063. }
  1064. struct sembuf sops[] = {
  1065. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  1066. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  1067. };
  1068. if (semop(sem, sops, 2)) {
  1069. if (errno == EAGAIN) {
  1070. if (!hotplug_mode)
  1071. applog(LOG_WARNING,
  1072. "SEM: %s USB failed to get (%d) '%s' - device in use",
  1073. drv->dname, sem, name);
  1074. } else {
  1075. applog(LOG_DEBUG,
  1076. "SEM: %s USB failed to get (%d) '%s' err (%d) %s",
  1077. drv->dname, sem, name, errno, strerror(errno));
  1078. }
  1079. return false;
  1080. }
  1081. add_in_use(bus_number, device_address);
  1082. return true;
  1083. #endif
  1084. }
  1085. static bool cgminer_usb_lock(struct device_drv *drv, libusb_device *dev)
  1086. {
  1087. return cgminer_usb_lock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1088. }
  1089. // Any errors should always be printed since they will rarely if ever occur
  1090. // and thus it is best to always display them
  1091. static void cgminer_usb_unlock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  1092. {
  1093. applog(LOG_DEBUG, "USB unlock %s %d-%d", drv->name, (int)bus_number, (int)device_address);
  1094. #ifdef WIN32
  1095. HANDLE usbMutex;
  1096. char name[64];
  1097. sprintf(name, "cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  1098. usbMutex = CreateMutex(NULL, FALSE, name);
  1099. if (usbMutex == NULL) {
  1100. applog(LOG_ERR,
  1101. "MTX: %s USB failed to get '%s' for release err (%d)",
  1102. drv->dname, name, GetLastError());
  1103. return;
  1104. }
  1105. if (!ReleaseMutex(usbMutex))
  1106. applog(LOG_ERR,
  1107. "MTX: %s USB failed to release '%s' err (%d)",
  1108. drv->dname, name, GetLastError());
  1109. CloseHandle(usbMutex);
  1110. remove_in_use(bus_number, device_address);
  1111. return;
  1112. #else
  1113. char name[64];
  1114. key_t key;
  1115. int fd, sem;
  1116. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  1117. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  1118. if (fd == -1) {
  1119. applog(LOG_ERR,
  1120. "SEM: %s USB open failed '%s' for release err (%d) %s",
  1121. drv->dname, name, errno, strerror(errno));
  1122. return;
  1123. }
  1124. close(fd);
  1125. key = ftok(name, 'K');
  1126. sem = semget(key, 1, 0);
  1127. if (sem < 0) {
  1128. applog(LOG_ERR,
  1129. "SEM: %s USB failed to get '%s' for release err (%d) %s",
  1130. drv->dname, name, errno, strerror(errno));
  1131. return;
  1132. }
  1133. struct sembuf sops[] = {
  1134. { 0, -1, SEM_UNDO }
  1135. };
  1136. // Allow a 10ms timeout
  1137. // exceeding this timeout means it would probably never succeed anyway
  1138. struct timespec timeout = { 0, 10000000 };
  1139. // Wait forever since we shoud be the one who has it
  1140. if (semtimedop(sem, sops, 1, &timeout)) {
  1141. applog(LOG_ERR,
  1142. "SEM: %s USB failed to release '%s' err (%d) %s",
  1143. drv->dname, name, errno, strerror(errno));
  1144. }
  1145. remove_in_use(bus_number, device_address);
  1146. return;
  1147. #endif
  1148. }
  1149. static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
  1150. {
  1151. cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1152. }
  1153. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  1154. {
  1155. applog(LOG_DEBUG, "USB free %s", cgusb->found->name);
  1156. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  1157. free(cgusb->serial_string);
  1158. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  1159. free(cgusb->manuf_string);
  1160. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  1161. free(cgusb->prod_string);
  1162. free(cgusb->descriptor);
  1163. free(cgusb->found);
  1164. free(cgusb);
  1165. return NULL;
  1166. }
  1167. void usb_uninit(struct cgpu_info *cgpu)
  1168. {
  1169. applog(LOG_DEBUG, "USB uninit %s%i",
  1170. cgpu->drv->name, cgpu->device_id);
  1171. // May have happened already during a failed initialisation
  1172. // if release_cgpu() was called due to a USB NODEV(err)
  1173. if (!cgpu->usbdev)
  1174. return;
  1175. libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface);
  1176. libusb_close(cgpu->usbdev->handle);
  1177. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  1178. }
  1179. static void release_cgpu(struct cgpu_info *cgpu)
  1180. {
  1181. struct cg_usb_device *cgusb = cgpu->usbdev;
  1182. struct cgpu_info *lookcgpu;
  1183. int i;
  1184. applog(LOG_DEBUG, "USB release %s%i",
  1185. cgpu->drv->name, cgpu->device_id);
  1186. // It has already been done
  1187. if (cgpu->usbinfo.nodev)
  1188. return;
  1189. total_count--;
  1190. drv_count[cgpu->drv->drv_id].count--;
  1191. cgpu->usbinfo.nodev = true;
  1192. cgpu->usbinfo.nodev_count++;
  1193. cgtime(&cgpu->usbinfo.last_nodev);
  1194. // Any devices sharing the same USB device should be marked also
  1195. // Currently only MMQ shares a USB device
  1196. for (i = 0; i < total_devices; i++) {
  1197. lookcgpu = get_devices(i);
  1198. if (lookcgpu != cgpu && lookcgpu->usbdev == cgusb) {
  1199. total_count--;
  1200. drv_count[lookcgpu->drv->drv_id].count--;
  1201. lookcgpu->usbinfo.nodev = true;
  1202. lookcgpu->usbinfo.nodev_count++;
  1203. memcpy(&(lookcgpu->usbinfo.last_nodev),
  1204. &(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
  1205. lookcgpu->usbdev = NULL;
  1206. }
  1207. }
  1208. usb_uninit(cgpu);
  1209. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1210. }
  1211. #define USB_INIT_FAIL 0
  1212. #define USB_INIT_OK 1
  1213. #define USB_INIT_IGNORE 2
  1214. static int _usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1215. {
  1216. struct cg_usb_device *cgusb = NULL;
  1217. struct libusb_config_descriptor *config = NULL;
  1218. const struct libusb_interface_descriptor *idesc;
  1219. const struct libusb_endpoint_descriptor *epdesc;
  1220. unsigned char strbuf[STRBUFLEN+1];
  1221. char devstr[STRBUFLEN+1];
  1222. int err, i, j, k;
  1223. int bad = USB_INIT_FAIL;
  1224. cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
  1225. cgpu->usbinfo.device_address = libusb_get_device_address(dev);
  1226. sprintf(devstr, "- %s device %d:%d", found->name,
  1227. cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1228. cgusb = calloc(1, sizeof(*cgusb));
  1229. cgusb->found = found;
  1230. if (found->idVendor == IDVENDOR_FTDI)
  1231. cgusb->usb_type = USB_TYPE_FTDI;
  1232. cgusb->ident = found->ident;
  1233. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  1234. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  1235. if (err) {
  1236. applog(LOG_DEBUG,
  1237. "USB init failed to get descriptor, err %d %s",
  1238. err, devstr);
  1239. goto dame;
  1240. }
  1241. err = libusb_open(dev, &(cgusb->handle));
  1242. if (err) {
  1243. switch (err) {
  1244. case LIBUSB_ERROR_ACCESS:
  1245. applog(LOG_ERR,
  1246. "USB init open device failed, err %d, "
  1247. "you dont have priviledge to access %s",
  1248. err, devstr);
  1249. break;
  1250. #ifdef WIN32
  1251. // Windows specific message
  1252. case LIBUSB_ERROR_NOT_SUPPORTED:
  1253. applog(LOG_ERR,
  1254. "USB init, open device failed, err %d, "
  1255. "you need to install a Windows USB driver for %s",
  1256. err, devstr);
  1257. break;
  1258. #endif
  1259. default:
  1260. applog(LOG_DEBUG,
  1261. "USB init, open failed, err %d %s",
  1262. err, devstr);
  1263. }
  1264. goto dame;
  1265. }
  1266. #ifndef WIN32
  1267. if (libusb_kernel_driver_active(cgusb->handle, found->kernel) == 1) {
  1268. applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
  1269. err = libusb_detach_kernel_driver(cgusb->handle, found->kernel);
  1270. if (err == 0) {
  1271. applog(LOG_DEBUG,
  1272. "USB init, kernel detached successfully %s",
  1273. devstr);
  1274. } else {
  1275. applog(LOG_WARNING,
  1276. "USB init, kernel detach failed, err %d in use? %s",
  1277. err, devstr);
  1278. goto cldame;
  1279. }
  1280. }
  1281. #endif
  1282. if (found->iManufacturer) {
  1283. unsigned char man[STRBUFLEN+1];
  1284. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1285. cgusb->descriptor->iManufacturer,
  1286. man, STRBUFLEN);
  1287. if (err < 0) {
  1288. applog(LOG_DEBUG,
  1289. "USB init, failed to get iManufacturer, err %d %s",
  1290. err, devstr);
  1291. goto cldame;
  1292. }
  1293. if (strcmp((char *)man, found->iManufacturer)) {
  1294. applog(LOG_DEBUG, "USB init, iManufacturer mismatch %s",
  1295. devstr);
  1296. bad = USB_INIT_IGNORE;
  1297. goto cldame;
  1298. }
  1299. }
  1300. if (found->iProduct) {
  1301. unsigned char prod[STRBUFLEN+1];
  1302. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1303. cgusb->descriptor->iProduct,
  1304. prod, STRBUFLEN);
  1305. if (err < 0) {
  1306. applog(LOG_DEBUG,
  1307. "USB init, failed to get iProduct, err %d %s",
  1308. err, devstr);
  1309. goto cldame;
  1310. }
  1311. if (strcmp((char *)prod, found->iProduct)) {
  1312. applog(LOG_DEBUG, "USB init, iProduct mismatch %s",
  1313. devstr);
  1314. bad = USB_INIT_IGNORE;
  1315. goto cldame;
  1316. }
  1317. }
  1318. err = libusb_set_configuration(cgusb->handle, found->config);
  1319. if (err) {
  1320. switch(err) {
  1321. case LIBUSB_ERROR_BUSY:
  1322. applog(LOG_WARNING,
  1323. "USB init, set config %d in use %s",
  1324. found->config, devstr);
  1325. break;
  1326. default:
  1327. applog(LOG_DEBUG,
  1328. "USB init, failed to set config to %d, err %d %s",
  1329. found->config, err, devstr);
  1330. }
  1331. goto cldame;
  1332. }
  1333. err = libusb_get_active_config_descriptor(dev, &config);
  1334. if (err) {
  1335. applog(LOG_DEBUG,
  1336. "USB init, failed to get config descriptor, err %d %s",
  1337. err, devstr);
  1338. goto cldame;
  1339. }
  1340. if ((int)(config->bNumInterfaces) <= found->interface) {
  1341. applog(LOG_DEBUG, "USB init bNumInterfaces <= interface %s",
  1342. devstr);
  1343. goto cldame;
  1344. }
  1345. for (i = 0; i < found->epcount; i++)
  1346. found->eps[i].found = false;
  1347. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  1348. idesc = &(config->interface[found->interface].altsetting[i]);
  1349. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  1350. epdesc = &(idesc->endpoint[j]);
  1351. for (k = 0; k < found->epcount; k++) {
  1352. if (!found->eps[k].found) {
  1353. if (epdesc->bmAttributes == found->eps[k].att
  1354. && epdesc->wMaxPacketSize >= found->eps[k].size
  1355. && epdesc->bEndpointAddress == found->eps[k].ep) {
  1356. found->eps[k].found = true;
  1357. break;
  1358. }
  1359. }
  1360. }
  1361. }
  1362. }
  1363. for (i = 0; i < found->epcount; i++) {
  1364. if (found->eps[i].found == false) {
  1365. applog(LOG_DEBUG, "USB init found == false %s",
  1366. devstr);
  1367. goto cldame;
  1368. }
  1369. }
  1370. err = libusb_claim_interface(cgusb->handle, found->interface);
  1371. if (err) {
  1372. switch(err) {
  1373. case LIBUSB_ERROR_BUSY:
  1374. applog(LOG_WARNING,
  1375. "USB init, claim interface %d in use %s",
  1376. found->interface, devstr);
  1377. break;
  1378. default:
  1379. applog(LOG_DEBUG,
  1380. "USB init, claim interface %d failed, err %d %s",
  1381. found->interface, err, devstr);
  1382. }
  1383. goto cldame;
  1384. }
  1385. cgusb->usbver = cgusb->descriptor->bcdUSB;
  1386. // TODO: allow this with the right version of the libusb include and running library
  1387. // cgusb->speed = libusb_get_device_speed(dev);
  1388. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1389. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  1390. if (err > 0)
  1391. cgusb->prod_string = strdup((char *)strbuf);
  1392. else
  1393. cgusb->prod_string = (char *)BLANK;
  1394. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1395. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  1396. if (err > 0)
  1397. cgusb->manuf_string = strdup((char *)strbuf);
  1398. else
  1399. cgusb->manuf_string = (char *)BLANK;
  1400. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1401. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  1402. if (err > 0)
  1403. cgusb->serial_string = strdup((char *)strbuf);
  1404. else
  1405. cgusb->serial_string = (char *)BLANK;
  1406. // TODO: ?
  1407. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  1408. // cgusb->interfaceVersion
  1409. applog(LOG_DEBUG,
  1410. "USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
  1411. devstr, cgusb->usbver, cgusb->prod_string,
  1412. cgusb->manuf_string, cgusb->serial_string);
  1413. cgpu->usbdev = cgusb;
  1414. libusb_free_config_descriptor(config);
  1415. // Allow a name change based on the idVendor+idProduct
  1416. // N.B. must be done before calling add_cgpu()
  1417. if (strcmp(cgpu->drv->name, found->name)) {
  1418. if (!cgpu->drv->copy)
  1419. cgpu->drv = copy_drv(cgpu->drv);
  1420. cgpu->drv->name = (char *)(found->name);
  1421. }
  1422. return USB_INIT_OK;
  1423. cldame:
  1424. libusb_close(cgusb->handle);
  1425. dame:
  1426. if (config)
  1427. libusb_free_config_descriptor(config);
  1428. cgusb = free_cgusb(cgusb);
  1429. return bad;
  1430. }
  1431. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1432. {
  1433. int ret;
  1434. ret = _usb_init(cgpu, dev, found);
  1435. if (ret == USB_INIT_FAIL)
  1436. applog(LOG_ERR, "%s detect (%d:%d) failed to initialise (incorrect device?)",
  1437. cgpu->drv->dname,
  1438. (int)(cgpu->usbinfo.bus_number),
  1439. (int)(cgpu->usbinfo.device_address));
  1440. return (ret == USB_INIT_OK);
  1441. }
  1442. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  1443. {
  1444. struct libusb_device_descriptor desc;
  1445. int bus_number, device_address;
  1446. int err, i;
  1447. bool ok;
  1448. err = libusb_get_device_descriptor(dev, &desc);
  1449. if (err) {
  1450. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  1451. return false;
  1452. }
  1453. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  1454. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  1455. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  1456. return false;
  1457. }
  1458. if (busdev_count > 0) {
  1459. bus_number = (int)libusb_get_bus_number(dev);
  1460. device_address = (int)libusb_get_device_address(dev);
  1461. ok = false;
  1462. for (i = 0; i < busdev_count; i++) {
  1463. if (bus_number == busdev[i].bus_number) {
  1464. if (busdev[i].device_address == -1 ||
  1465. device_address == busdev[i].device_address) {
  1466. ok = true;
  1467. break;
  1468. }
  1469. }
  1470. }
  1471. if (!ok) {
  1472. applog(LOG_DEBUG, "%s rejected %s %04x:%04x with bus:dev (%d:%d)",
  1473. drv->name, look->name, look->idVendor, look->idProduct,
  1474. bus_number, device_address);
  1475. return false;
  1476. }
  1477. }
  1478. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  1479. drv->name, look->name, look->idVendor, look->idProduct);
  1480. return true;
  1481. }
  1482. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  1483. {
  1484. struct usb_find_devices *found;
  1485. int i;
  1486. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  1487. if (find_dev[i].drv == drvnum) {
  1488. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  1489. found = malloc(sizeof(*found));
  1490. memcpy(found, &(find_dev[i]), sizeof(*found));
  1491. return found;
  1492. }
  1493. }
  1494. return NULL;
  1495. }
  1496. static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
  1497. {
  1498. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1499. applog(LOG_DEBUG,
  1500. "USB scan devices3: %s limit %d reached",
  1501. drv->dname, drv_count[drv->drv_id].limit);
  1502. return NULL;
  1503. }
  1504. #ifdef USE_BFLSC
  1505. if (drv->drv_id == DRIVER_BFLSC)
  1506. return usb_check_each(DRV_BFLSC, drv, dev);
  1507. #endif
  1508. #ifdef USE_BITFORCE
  1509. if (drv->drv_id == DRIVER_BITFORCE)
  1510. return usb_check_each(DRV_BITFORCE, drv, dev);
  1511. #endif
  1512. #ifdef USE_MODMINER
  1513. if (drv->drv_id == DRIVER_MODMINER)
  1514. return usb_check_each(DRV_MODMINER, drv, dev);
  1515. #endif
  1516. #ifdef USE_ICARUS
  1517. if (drv->drv_id == DRIVER_ICARUS)
  1518. return usb_check_each(DRV_ICARUS, drv, dev);
  1519. #endif
  1520. #ifdef USE_AVALON
  1521. if (drv->drv_id == DRIVER_AVALON)
  1522. return usb_check_each(DRV_AVALON, drv, dev);
  1523. #endif
  1524. return NULL;
  1525. }
  1526. void usb_detect(struct device_drv *drv, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *))
  1527. {
  1528. libusb_device **list;
  1529. ssize_t count, i;
  1530. struct usb_find_devices *found;
  1531. applog(LOG_DEBUG, "USB scan devices: checking for %s devices", drv->name);
  1532. if (total_count >= total_limit) {
  1533. applog(LOG_DEBUG, "USB scan devices: total limit %d reached", total_limit);
  1534. return;
  1535. }
  1536. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1537. applog(LOG_DEBUG,
  1538. "USB scan devices: %s limit %d reached",
  1539. drv->dname, drv_count[drv->drv_id].limit);
  1540. return;
  1541. }
  1542. count = libusb_get_device_list(NULL, &list);
  1543. if (count < 0) {
  1544. applog(LOG_DEBUG, "USB scan devices: failed, err %zd", count);
  1545. return;
  1546. }
  1547. if (count == 0)
  1548. applog(LOG_DEBUG, "USB scan devices: found no devices");
  1549. for (i = 0; i < count; i++) {
  1550. if (total_count >= total_limit) {
  1551. applog(LOG_DEBUG, "USB scan devices2: total limit %d reached", total_limit);
  1552. break;
  1553. }
  1554. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1555. applog(LOG_DEBUG,
  1556. "USB scan devices2: %s limit %d reached",
  1557. drv->dname, drv_count[drv->drv_id].limit);
  1558. break;
  1559. }
  1560. found = usb_check(drv, list[i]);
  1561. if (found != NULL) {
  1562. if (is_in_use(list[i]) || cgminer_usb_lock(drv, list[i]) == false)
  1563. free(found);
  1564. else {
  1565. if (!device_detect(list[i], found))
  1566. cgminer_usb_unlock(drv, list[i]);
  1567. else {
  1568. total_count++;
  1569. drv_count[drv->drv_id].count++;
  1570. }
  1571. }
  1572. }
  1573. }
  1574. libusb_free_device_list(list, 1);
  1575. }
  1576. #if DO_USB_STATS
  1577. static void modes_str(char *buf, uint32_t modes)
  1578. {
  1579. bool first;
  1580. *buf = '\0';
  1581. if (modes == MODE_NONE)
  1582. strcpy(buf, MODE_NONE_STR);
  1583. else {
  1584. first = true;
  1585. if (modes & MODE_CTRL_READ) {
  1586. strcpy(buf, MODE_CTRL_READ_STR);
  1587. first = false;
  1588. }
  1589. if (modes & MODE_CTRL_WRITE) {
  1590. if (!first)
  1591. strcat(buf, MODE_SEP_STR);
  1592. strcat(buf, MODE_CTRL_WRITE_STR);
  1593. first = false;
  1594. }
  1595. if (modes & MODE_BULK_READ) {
  1596. if (!first)
  1597. strcat(buf, MODE_SEP_STR);
  1598. strcat(buf, MODE_BULK_READ_STR);
  1599. first = false;
  1600. }
  1601. if (modes & MODE_BULK_WRITE) {
  1602. if (!first)
  1603. strcat(buf, MODE_SEP_STR);
  1604. strcat(buf, MODE_BULK_WRITE_STR);
  1605. first = false;
  1606. }
  1607. }
  1608. }
  1609. #endif
  1610. // The stat data can be spurious due to not locking it before copying it -
  1611. // however that would require the stat() function to also lock and release
  1612. // a mutex every time a usb read or write is called which would slow
  1613. // things down more
  1614. struct api_data *api_usb_stats(__maybe_unused int *count)
  1615. {
  1616. #if DO_USB_STATS
  1617. struct cg_usb_stats_details *details;
  1618. struct cg_usb_stats *sta;
  1619. struct api_data *root = NULL;
  1620. int device;
  1621. int cmdseq;
  1622. char modes_s[32];
  1623. if (next_stat == 0)
  1624. return NULL;
  1625. while (*count < next_stat * C_MAX * 2) {
  1626. device = *count / (C_MAX * 2);
  1627. cmdseq = *count % (C_MAX * 2);
  1628. (*count)++;
  1629. sta = &(usb_stats[device]);
  1630. details = &(sta->details[cmdseq]);
  1631. // Only show stats that have results
  1632. if (details->item[CMD_CMD].count == 0 &&
  1633. details->item[CMD_TIMEOUT].count == 0 &&
  1634. details->item[CMD_ERROR].count == 0)
  1635. continue;
  1636. root = api_add_string(root, "Name", sta->name, false);
  1637. root = api_add_int(root, "ID", &(sta->device_id), false);
  1638. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  1639. root = api_add_int(root, "Seq", &(details->seq), true);
  1640. modes_str(modes_s, details->modes);
  1641. root = api_add_string(root, "Modes", modes_s, true);
  1642. root = api_add_uint64(root, "Count",
  1643. &(details->item[CMD_CMD].count), true);
  1644. root = api_add_double(root, "Total Delay",
  1645. &(details->item[CMD_CMD].total_delay), true);
  1646. root = api_add_double(root, "Min Delay",
  1647. &(details->item[CMD_CMD].min_delay), true);
  1648. root = api_add_double(root, "Max Delay",
  1649. &(details->item[CMD_CMD].max_delay), true);
  1650. root = api_add_uint64(root, "Timeout Count",
  1651. &(details->item[CMD_TIMEOUT].count), true);
  1652. root = api_add_double(root, "Timeout Total Delay",
  1653. &(details->item[CMD_TIMEOUT].total_delay), true);
  1654. root = api_add_double(root, "Timeout Min Delay",
  1655. &(details->item[CMD_TIMEOUT].min_delay), true);
  1656. root = api_add_double(root, "Timeout Max Delay",
  1657. &(details->item[CMD_TIMEOUT].max_delay), true);
  1658. root = api_add_uint64(root, "Error Count",
  1659. &(details->item[CMD_ERROR].count), true);
  1660. root = api_add_double(root, "Error Total Delay",
  1661. &(details->item[CMD_ERROR].total_delay), true);
  1662. root = api_add_double(root, "Error Min Delay",
  1663. &(details->item[CMD_ERROR].min_delay), true);
  1664. root = api_add_double(root, "Error Max Delay",
  1665. &(details->item[CMD_ERROR].max_delay), true);
  1666. root = api_add_timeval(root, "First Command",
  1667. &(details->item[CMD_CMD].first), true);
  1668. root = api_add_timeval(root, "Last Command",
  1669. &(details->item[CMD_CMD].last), true);
  1670. root = api_add_timeval(root, "First Timeout",
  1671. &(details->item[CMD_TIMEOUT].first), true);
  1672. root = api_add_timeval(root, "Last Timeout",
  1673. &(details->item[CMD_TIMEOUT].last), true);
  1674. root = api_add_timeval(root, "First Error",
  1675. &(details->item[CMD_ERROR].first), true);
  1676. root = api_add_timeval(root, "Last Error",
  1677. &(details->item[CMD_ERROR].last), true);
  1678. return root;
  1679. }
  1680. #endif
  1681. return NULL;
  1682. }
  1683. #if DO_USB_STATS
  1684. static void newstats(struct cgpu_info *cgpu)
  1685. {
  1686. int i;
  1687. mutex_lock(&cgusb_lock);
  1688. cgpu->usbinfo.usbstat = ++next_stat;
  1689. mutex_unlock(&cgusb_lock);
  1690. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * next_stat);
  1691. if (!usb_stats)
  1692. quit(1, "USB failed to realloc usb_stats %d", next_stat);
  1693. usb_stats[next_stat-1].name = cgpu->drv->name;
  1694. usb_stats[next_stat-1].device_id = -1;
  1695. usb_stats[next_stat-1].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  1696. if (!usb_stats[next_stat-1].details)
  1697. quit(1, "USB failed to calloc details for %d", next_stat);
  1698. for (i = 1; i < C_MAX * 2; i += 2)
  1699. usb_stats[next_stat-1].details[i].seq = 1;
  1700. }
  1701. #endif
  1702. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  1703. {
  1704. #if DO_USB_STATS
  1705. if (cgpu->usbinfo.usbstat < 1)
  1706. newstats(cgpu);
  1707. // we don't know the device_id until after add_cgpu()
  1708. usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
  1709. #endif
  1710. }
  1711. #if DO_USB_STATS
  1712. static void stats(struct cgpu_info *cgpu, struct timeval *tv_start, struct timeval *tv_finish, int err, int mode, enum usb_cmds cmd, int seq)
  1713. {
  1714. struct cg_usb_stats_details *details;
  1715. double diff;
  1716. int item;
  1717. if (cgpu->usbinfo.usbstat < 1)
  1718. newstats(cgpu);
  1719. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
  1720. details->modes |= mode;
  1721. diff = tdiff(tv_finish, tv_start);
  1722. switch (err) {
  1723. case LIBUSB_SUCCESS:
  1724. item = CMD_CMD;
  1725. break;
  1726. case LIBUSB_ERROR_TIMEOUT:
  1727. item = CMD_TIMEOUT;
  1728. break;
  1729. default:
  1730. item = CMD_ERROR;
  1731. break;
  1732. }
  1733. if (details->item[item].count == 0) {
  1734. details->item[item].min_delay = diff;
  1735. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  1736. } else if (diff < details->item[item].min_delay)
  1737. details->item[item].min_delay = diff;
  1738. if (diff > details->item[item].max_delay)
  1739. details->item[item].max_delay = diff;
  1740. details->item[item].total_delay += diff;
  1741. memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
  1742. details->item[item].count++;
  1743. }
  1744. static void rejected_inc(struct cgpu_info *cgpu, uint32_t mode)
  1745. {
  1746. struct cg_usb_stats_details *details;
  1747. int item = CMD_ERROR;
  1748. if (cgpu->usbinfo.usbstat < 1)
  1749. newstats(cgpu);
  1750. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  1751. details->modes |= mode;
  1752. details->item[item].count++;
  1753. }
  1754. #endif
  1755. #define USB_MAX_READ 8192
  1756. int _usb_read(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, const char *end, __maybe_unused enum usb_cmds cmd, bool readonce)
  1757. {
  1758. struct cg_usb_device *usbdev = cgpu->usbdev;
  1759. bool ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  1760. #if DO_USB_STATS
  1761. struct timeval tv_start;
  1762. #endif
  1763. struct timeval read_start, tv_finish;
  1764. unsigned int initial_timeout;
  1765. double max, done;
  1766. int bufleft, err, got, tot;
  1767. __maybe_unused bool first = true;
  1768. unsigned char *search;
  1769. int endlen;
  1770. // We add 4: 1 for null, 2 for FTDI status and 1 to round to 4 bytes
  1771. unsigned char usbbuf[USB_MAX_READ+4], *ptr;
  1772. size_t usbbufread;
  1773. USBDEBUG("USB debug: _usb_read(%s (nodev=%s),ep=%d,buf=%p,bufsiz=%zu,proc=%p,timeout=%u,end=%s,cmd=%s,ftdi=%s,readonce=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), ep, buf, bufsiz, processed, timeout, end ? (char *)str_text((char *)end) : "NULL", usb_cmdname(cmd), bool_str(ftdi), bool_str(readonce));
  1774. if (bufsiz > USB_MAX_READ)
  1775. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, bufsiz, USB_MAX_READ);
  1776. if (cgpu->usbinfo.nodev) {
  1777. *buf = '\0';
  1778. *processed = 0;
  1779. USB_REJECT(cgpu, MODE_BULK_READ);
  1780. return LIBUSB_ERROR_NO_DEVICE;
  1781. }
  1782. if (timeout == DEVTIMEOUT)
  1783. timeout = usbdev->found->timeout;
  1784. if (end == NULL) {
  1785. tot = 0;
  1786. ptr = usbbuf;
  1787. bufleft = bufsiz;
  1788. err = LIBUSB_SUCCESS;
  1789. initial_timeout = timeout;
  1790. max = ((double)timeout) / 1000.0;
  1791. cgtime(&read_start);
  1792. while (bufleft > 0) {
  1793. if (ftdi)
  1794. usbbufread = bufleft + 2;
  1795. else
  1796. usbbufread = bufleft;
  1797. got = 0;
  1798. STATS_TIMEVAL(&tv_start);
  1799. err = libusb_bulk_transfer(usbdev->handle,
  1800. usbdev->found->eps[ep].ep,
  1801. ptr, usbbufread, &got, timeout);
  1802. cgtime(&tv_finish);
  1803. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1804. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  1805. ptr[got] = '\0';
  1806. USBDEBUG("USB debug: @_usb_read(%s (nodev=%s)) first=%s err=%d%s got=%d ptr='%s' usbbufread=%zu", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), bool_str(first), err, isnodev(err), got, (char *)str_text((char *)ptr), usbbufread);
  1807. if (ftdi) {
  1808. // first 2 bytes returned are an FTDI status
  1809. if (got > 2) {
  1810. got -= 2;
  1811. memmove(ptr, ptr+2, got+1);
  1812. } else {
  1813. got = 0;
  1814. *ptr = '\0';
  1815. }
  1816. }
  1817. tot += got;
  1818. if (err || readonce)
  1819. break;
  1820. ptr += got;
  1821. bufleft -= got;
  1822. first = false;
  1823. done = tdiff(&tv_finish, &read_start);
  1824. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  1825. if (unlikely(done >= max))
  1826. break;
  1827. timeout = initial_timeout - (done * 1000);
  1828. }
  1829. *processed = tot;
  1830. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  1831. if (NODEV(err))
  1832. release_cgpu(cgpu);
  1833. return err;
  1834. }
  1835. tot = 0;
  1836. ptr = usbbuf;
  1837. bufleft = bufsiz;
  1838. endlen = strlen(end);
  1839. err = LIBUSB_SUCCESS;
  1840. initial_timeout = timeout;
  1841. max = ((double)timeout) / 1000.0;
  1842. cgtime(&read_start);
  1843. while (bufleft > 0) {
  1844. if (ftdi)
  1845. usbbufread = bufleft + 2;
  1846. else
  1847. usbbufread = bufleft;
  1848. got = 0;
  1849. STATS_TIMEVAL(&tv_start);
  1850. err = libusb_bulk_transfer(usbdev->handle,
  1851. usbdev->found->eps[ep].ep,
  1852. ptr, usbbufread, &got, timeout);
  1853. cgtime(&tv_finish);
  1854. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1855. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  1856. ptr[got] = '\0';
  1857. USBDEBUG("USB debug: @_usb_read(%s (nodev=%s)) first=%s err=%d%s got=%d ptr='%s' usbbufread=%zu", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), bool_str(first), err, isnodev(err), got, (char *)str_text((char *)ptr), usbbufread);
  1858. if (ftdi) {
  1859. // first 2 bytes returned are an FTDI status
  1860. if (got > 2) {
  1861. got -= 2;
  1862. memmove(ptr, ptr+2, got+1);
  1863. } else {
  1864. got = 0;
  1865. *ptr = '\0';
  1866. }
  1867. }
  1868. tot += got;
  1869. if (err || readonce)
  1870. break;
  1871. // WARNING - this will return data past END ('if' there is extra data)
  1872. if (endlen <= tot) {
  1873. // If END is only 1 char - do a faster search
  1874. if (endlen == 1) {
  1875. if (strchr((char *)ptr, *end))
  1876. break;
  1877. } else {
  1878. // must allow END to have been chopped in 2 transfers
  1879. if ((tot - got) >= (endlen - 1))
  1880. search = ptr - (endlen - 1);
  1881. else
  1882. search = ptr - (tot - got);
  1883. if (strstr((char *)search, end))
  1884. break;
  1885. }
  1886. }
  1887. ptr += got;
  1888. bufleft -= got;
  1889. first = false;
  1890. done = tdiff(&tv_finish, &read_start);
  1891. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  1892. if (unlikely(done >= max))
  1893. break;
  1894. timeout = initial_timeout - (done * 1000);
  1895. }
  1896. *processed = tot;
  1897. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  1898. if (NODEV(err))
  1899. release_cgpu(cgpu);
  1900. return err;
  1901. }
  1902. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  1903. #define FTDI_RS0_CTS (1 << 4)
  1904. #define FTDI_RS0_DSR (1 << 5)
  1905. #define FTDI_RS0_RI (1 << 6)
  1906. #define FTDI_RS0_RLSD (1 << 7)
  1907. int usb_ftdi_cts(struct cgpu_info *cgpu)
  1908. {
  1909. libusb_control_transfer(usbdev->handle, (uint8_t)FTDI_TYPE_IN,
  1910. (uint8_t)5, (uint16_t)0, (uint16_t)0, buf, 2,
  1911. DEVTIMEOUT);
  1912. ret = buf[0] & FTDI_STATUS_B0_MASK;
  1913. return (ret & FTDI_RS0_CTS);
  1914. }
  1915. int _usb_write(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, __maybe_unused enum usb_cmds cmd)
  1916. {
  1917. struct cg_usb_device *usbdev = cgpu->usbdev;
  1918. #if DO_USB_STATS
  1919. struct timeval tv_start;
  1920. #endif
  1921. struct timeval read_start, tv_finish;
  1922. unsigned int initial_timeout;
  1923. double max, done;
  1924. __maybe_unused bool first = true;
  1925. int err, sent, tot;
  1926. USBDEBUG("USB debug: _usb_write(%s (nodev=%s),ep=%d,buf='%s',bufsiz=%zu,proc=%p,timeout=%u,cmd=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), ep, (char *)str_text(buf), bufsiz, processed, timeout, usb_cmdname(cmd));
  1927. *processed = 0;
  1928. if (cgpu->usbinfo.nodev) {
  1929. USB_REJECT(cgpu, MODE_BULK_WRITE);
  1930. return LIBUSB_ERROR_NO_DEVICE;
  1931. }
  1932. if (timeout == DEVTIMEOUT)
  1933. timeout = usbdev->found->timeout;
  1934. tot = 0;
  1935. err = LIBUSB_SUCCESS;
  1936. initial_timeout = timeout;
  1937. max = ((double)timeout) / 1000.0;
  1938. cgtime(&read_start);
  1939. while (bufsiz > 0) {
  1940. sent = 0;
  1941. STATS_TIMEVAL(&tv_start);
  1942. err = libusb_bulk_transfer(usbdev->handle,
  1943. usbdev->found->eps[ep].ep,
  1944. (unsigned char *)buf,
  1945. bufsiz, &sent, timeout);
  1946. cgtime(&tv_finish);
  1947. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1948. MODE_BULK_WRITE, cmd, first ? SEQ0 : SEQ1);
  1949. USBDEBUG("USB debug: @_usb_write(%s (nodev=%s)) err=%d%s sent=%d", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err), sent);
  1950. tot += sent;
  1951. if (err)
  1952. break;
  1953. buf += sent;
  1954. bufsiz -= sent;
  1955. first = false;
  1956. done = tdiff(&tv_finish, &read_start);
  1957. // N.B. this is: return LIBUSB_SUCCESS with whatever size was written
  1958. if (unlikely(done >= max))
  1959. break;
  1960. timeout = initial_timeout - (done * 1000);
  1961. }
  1962. *processed = tot;
  1963. if (NODEV(err))
  1964. release_cgpu(cgpu);
  1965. return err;
  1966. }
  1967. int _usb_transfer(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, uint32_t *data, int siz, unsigned int timeout, __maybe_unused enum usb_cmds cmd)
  1968. {
  1969. struct cg_usb_device *usbdev = cgpu->usbdev;
  1970. #if DO_USB_STATS
  1971. struct timeval tv_start, tv_finish;
  1972. #endif
  1973. uint32_t *buf = NULL;
  1974. int err, i, bufsiz;
  1975. USBDEBUG("USB debug: _usb_transfer(%s (nodev=%s),type=%"PRIu8",req=%"PRIu8",value=%"PRIu16",index=%"PRIu16",siz=%d,timeout=%u,cmd=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), request_type, bRequest, wValue, wIndex, siz, timeout, usb_cmdname(cmd));
  1976. if (cgpu->usbinfo.nodev) {
  1977. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  1978. return LIBUSB_ERROR_NO_DEVICE;
  1979. }
  1980. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  1981. if (siz > 0) {
  1982. bufsiz = siz - 1;
  1983. bufsiz >>= 2;
  1984. bufsiz++;
  1985. buf = malloc(bufsiz << 2);
  1986. if (unlikely(!buf))
  1987. quit(1, "Failed to malloc in _usb_transfer");
  1988. for (i = 0; i < bufsiz; i++)
  1989. buf[i] = htole32(data[i]);
  1990. }
  1991. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex((unsigned char *)buf, (size_t)siz));
  1992. STATS_TIMEVAL(&tv_start);
  1993. err = libusb_control_transfer(usbdev->handle, request_type,
  1994. bRequest, htole16(wValue), htole16(wIndex),
  1995. (unsigned char *)buf, (uint16_t)siz,
  1996. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1997. STATS_TIMEVAL(&tv_finish);
  1998. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0);
  1999. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  2000. if (buf)
  2001. free(buf);
  2002. if (NODEV(err))
  2003. release_cgpu(cgpu);
  2004. return err;
  2005. }
  2006. int _usb_transfer_read(struct cgpu_info *cgpu, uint8_t request_type, uint8_t bRequest, uint16_t wValue, uint16_t wIndex, char *buf, int bufsiz, int *amount, unsigned int timeout, __maybe_unused enum usb_cmds cmd)
  2007. {
  2008. struct cg_usb_device *usbdev = cgpu->usbdev;
  2009. #if DO_USB_STATS
  2010. struct timeval tv_start, tv_finish;
  2011. #endif
  2012. int err;
  2013. USBDEBUG("USB debug: _usb_transfer_read(%s (nodev=%s),type=%"PRIu8",req=%"PRIu8",value=%"PRIu16",index=%"PRIu16",bufsiz=%d,timeout=%u,cmd=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), request_type, bRequest, wValue, wIndex, bufsiz, timeout, usb_cmdname(cmd));
  2014. if (cgpu->usbinfo.nodev) {
  2015. USB_REJECT(cgpu, MODE_CTRL_READ);
  2016. return LIBUSB_ERROR_NO_DEVICE;
  2017. }
  2018. *amount = 0;
  2019. STATS_TIMEVAL(&tv_start);
  2020. err = libusb_control_transfer(usbdev->handle, request_type,
  2021. bRequest, htole16(wValue), htole16(wIndex),
  2022. (unsigned char *)buf, (uint16_t)bufsiz,
  2023. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  2024. STATS_TIMEVAL(&tv_finish);
  2025. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0);
  2026. USBDEBUG("USB debug: @_usb_transfer_read(%s (nodev=%s)) amt/err=%d%s%s%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err), err > 0 ? " = " : BLANK, err > 0 ? bin2hex((unsigned char *)buf, (size_t)err) : BLANK);
  2027. if (err > 0) {
  2028. *amount = err;
  2029. err = 0;
  2030. } else if (NODEV(err))
  2031. release_cgpu(cgpu);
  2032. return err;
  2033. }
  2034. void usb_cleanup()
  2035. {
  2036. struct cgpu_info *cgpu;
  2037. int i;
  2038. hotplug_time = 0;
  2039. nmsleep(10);
  2040. for (i = 0; i < total_devices; i++) {
  2041. cgpu = devices[i];
  2042. switch (cgpu->drv->drv_id) {
  2043. case DRIVER_BFLSC:
  2044. case DRIVER_BITFORCE:
  2045. case DRIVER_MODMINER:
  2046. case DRIVER_ICARUS:
  2047. case DRIVER_AVALON:
  2048. release_cgpu(cgpu);
  2049. break;
  2050. default:
  2051. break;
  2052. }
  2053. }
  2054. }
  2055. void usb_initialise()
  2056. {
  2057. char *fre, *ptr, *comma, *colon;
  2058. int bus, dev, lim, i;
  2059. bool found;
  2060. for (i = 0; i < DRIVER_MAX; i++) {
  2061. drv_count[i].count = 0;
  2062. drv_count[i].limit = 999999;
  2063. }
  2064. cgusb_check_init();
  2065. if (opt_usb_select && *opt_usb_select) {
  2066. // Absolute device limit
  2067. if (*opt_usb_select == ':') {
  2068. total_limit = atoi(opt_usb_select+1);
  2069. if (total_limit < 0)
  2070. quit(1, "Invalid --usb total limit");
  2071. // Comma list of bus:dev devices to match
  2072. } else if (isdigit(*opt_usb_select)) {
  2073. fre = ptr = strdup(opt_usb_select);
  2074. do {
  2075. comma = strchr(ptr, ',');
  2076. if (comma)
  2077. *(comma++) = '\0';
  2078. colon = strchr(ptr, ':');
  2079. if (!colon)
  2080. quit(1, "Invalid --usb bus:dev missing ':'");
  2081. *(colon++) = '\0';
  2082. if (!isdigit(*ptr))
  2083. quit(1, "Invalid --usb bus:dev - bus must be a number");
  2084. if (!isdigit(*colon) && *colon != '*')
  2085. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  2086. bus = atoi(ptr);
  2087. if (bus <= 0)
  2088. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  2089. if (!colon == '*')
  2090. dev = -1;
  2091. else {
  2092. dev = atoi(colon);
  2093. if (dev <= 0)
  2094. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  2095. }
  2096. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  2097. busdev[busdev_count-1].bus_number = bus;
  2098. busdev[busdev_count-1].device_address = dev;
  2099. ptr = comma;
  2100. } while (ptr);
  2101. free(fre);
  2102. // Comma list of DRV:limit
  2103. } else {
  2104. fre = ptr = strdup(opt_usb_select);
  2105. do {
  2106. comma = strchr(ptr, ',');
  2107. if (comma)
  2108. *(comma++) = '\0';
  2109. colon = strchr(ptr, ':');
  2110. if (!colon)
  2111. quit(1, "Invalid --usb DRV:limit missing ':'");
  2112. *(colon++) = '\0';
  2113. if (!isdigit(*colon))
  2114. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  2115. lim = atoi(colon);
  2116. if (lim < 0)
  2117. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  2118. found = false;
  2119. #ifdef USE_BFLSC
  2120. if (strcasecmp(ptr, bflsc_drv.name) == 0) {
  2121. drv_count[bflsc_drv.drv_id].limit = lim;
  2122. found = true;
  2123. }
  2124. #endif
  2125. #ifdef USE_BITFORCE
  2126. if (!found && strcasecmp(ptr, bitforce_drv.name) == 0) {
  2127. drv_count[bitforce_drv.drv_id].limit = lim;
  2128. found = true;
  2129. }
  2130. #endif
  2131. #ifdef USE_MODMINER
  2132. if (!found && strcasecmp(ptr, modminer_drv.name) == 0) {
  2133. drv_count[modminer_drv.drv_id].limit = lim;
  2134. found = true;
  2135. }
  2136. #endif
  2137. #ifdef USE_ICARUS
  2138. if (!found && strcasecmp(ptr, icarus_drv.name) == 0) {
  2139. drv_count[icarus_drv.drv_id].limit = lim;
  2140. found = true;
  2141. }
  2142. #endif
  2143. #ifdef USE_AVALON
  2144. if (!found && strcasecmp(ptr, avalon_drv.name) == 0) {
  2145. drv_count[avalon_drv.drv_id].limit = lim;
  2146. found = true;
  2147. }
  2148. #endif
  2149. if (!found)
  2150. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  2151. ptr = comma;
  2152. } while (ptr);
  2153. free(fre);
  2154. }
  2155. }
  2156. }