usbutils.c 76 KB

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