usbutils.c 88 KB

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