usbutils.c 97 KB

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