usbutils.c 97 KB

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