usbutils.c 68 KB

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