usbutils.c 77 KB

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