usbutils.c 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756
  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. cgsem_t cgsem;
  1885. struct libusb_transfer *transfer;
  1886. };
  1887. static void init_usb_transfer(struct usb_transfer *ut)
  1888. {
  1889. cgsem_init(&ut->cgsem);
  1890. ut->transfer = libusb_alloc_transfer(0);
  1891. if (unlikely(!ut->transfer))
  1892. quit(1, "Failed to libusb_alloc_transfer");
  1893. ut->transfer->user_data = ut;
  1894. }
  1895. static void LIBUSB_CALL transfer_callback(struct libusb_transfer *transfer)
  1896. {
  1897. struct usb_transfer *ut = transfer->user_data;
  1898. cgsem_post(&ut->cgsem);
  1899. }
  1900. /* Wait for callback function to tell us it has finished the USB transfer, but
  1901. * use our own timer to cancel the request if we go beyond the timeout. */
  1902. static int callback_wait(struct usb_transfer *ut, int *transferred, unsigned int timeout)
  1903. {
  1904. struct libusb_transfer *transfer= ut->transfer;
  1905. int ret;
  1906. ret = cgsem_mswait(&ut->cgsem, timeout);
  1907. if (ret == ETIMEDOUT) {
  1908. /* We are emulating a timeout ourself here */
  1909. libusb_cancel_transfer(transfer);
  1910. /* Now wait for the callback function to be invoked. */
  1911. cgsem_wait(&ut->cgsem);
  1912. }
  1913. ret = transfer->status;
  1914. if (ret == LIBUSB_TRANSFER_CANCELLED)
  1915. ret = LIBUSB_ERROR_TIMEOUT;
  1916. /* No need to sort out mutexes here since they won't be reused */
  1917. *transferred = transfer->actual_length;
  1918. return ret;
  1919. }
  1920. static int
  1921. usb_bulk_transfer(struct libusb_device_handle *dev_handle, int intinfo,
  1922. int epinfo, unsigned char *data, int length,
  1923. int *transferred, unsigned int timeout,
  1924. struct cgpu_info *cgpu, __maybe_unused int mode,
  1925. enum usb_cmds cmd, __maybe_unused int seq)
  1926. {
  1927. struct usb_epinfo *usb_epinfo;
  1928. struct usb_transfer ut;
  1929. unsigned char endpoint;
  1930. uint16_t MaxPacketSize;
  1931. int err, errn;
  1932. #if DO_USB_STATS
  1933. struct timeval tv_start, tv_finish;
  1934. #endif
  1935. unsigned char buf[512];
  1936. usb_epinfo = &(cgpu->usbdev->found->intinfos[intinfo].epinfos[epinfo]);
  1937. endpoint = usb_epinfo->ep;
  1938. /* Limit length of transfer to the largest this descriptor supports
  1939. * and leave the higher level functions to transfer more if needed. */
  1940. if (usb_epinfo->PrefPacketSize)
  1941. MaxPacketSize = usb_epinfo->PrefPacketSize;
  1942. else
  1943. MaxPacketSize = usb_epinfo->wMaxPacketSize;
  1944. if (length > MaxPacketSize)
  1945. length = MaxPacketSize;
  1946. if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)
  1947. memcpy(buf, data, length);
  1948. 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);
  1949. init_usb_transfer(&ut);
  1950. /* We give the transfer no timeout since we manage timeouts ourself */
  1951. libusb_fill_bulk_transfer(ut.transfer, dev_handle, endpoint, buf, length,
  1952. transfer_callback, &ut, 0);
  1953. STATS_TIMEVAL(&tv_start);
  1954. cg_rlock(&cgusb_fd_lock);
  1955. err = libusb_submit_transfer(ut.transfer);
  1956. cg_runlock(&cgusb_fd_lock);
  1957. errn = errno;
  1958. if (!err)
  1959. err = callback_wait(&ut, transferred, timeout);
  1960. libusb_free_transfer(ut.transfer);
  1961. STATS_TIMEVAL(&tv_finish);
  1962. USB_STATS(cgpu, &tv_start, &tv_finish, err, mode, cmd, seq, timeout);
  1963. if (err < 0)
  1964. applog(LOG_DEBUG, "%s%i: %s (amt=%d err=%d ern=%d)",
  1965. cgpu->drv->name, cgpu->device_id,
  1966. usb_cmdname(cmd), *transferred, err, errn);
  1967. if (err == LIBUSB_ERROR_PIPE || err == LIBUSB_TRANSFER_STALL) {
  1968. int retries = 0;
  1969. do {
  1970. cgpu->usbinfo.last_pipe = time(NULL);
  1971. cgpu->usbinfo.pipe_count++;
  1972. applog(LOG_INFO, "%s%i: libusb pipe error, trying to clear",
  1973. cgpu->drv->name, cgpu->device_id);
  1974. err = libusb_clear_halt(dev_handle, endpoint);
  1975. applog(LOG_DEBUG, "%s%i: libusb pipe error%scleared",
  1976. cgpu->drv->name, cgpu->device_id, err ? " not " : " ");
  1977. if (err)
  1978. cgpu->usbinfo.clear_fail_count++;
  1979. } while (err && ++retries < USB_RETRY_MAX);
  1980. }
  1981. if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
  1982. memcpy(data, buf, length);
  1983. return err;
  1984. }
  1985. 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)
  1986. {
  1987. struct cg_usb_device *usbdev;
  1988. bool ftdi;
  1989. struct timeval read_start, tv_finish;
  1990. unsigned int initial_timeout;
  1991. double max, done;
  1992. int bufleft, err, got, tot, pstate;
  1993. bool first = true;
  1994. char *search;
  1995. int endlen;
  1996. unsigned char *ptr, *usbbuf = cgpu->usbinfo.bulkbuf;
  1997. size_t usbbufread;
  1998. DEVRLOCK(cgpu, pstate);
  1999. if (cgpu->usbinfo.nodev) {
  2000. *buf = '\0';
  2001. *processed = 0;
  2002. USB_REJECT(cgpu, MODE_BULK_READ);
  2003. err = LIBUSB_ERROR_NO_DEVICE;
  2004. goto out_noerrmsg;
  2005. }
  2006. usbdev = cgpu->usbdev;
  2007. ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  2008. 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));
  2009. if (bufsiz > USB_MAX_READ)
  2010. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, (int)bufsiz, USB_MAX_READ);
  2011. if (timeout == DEVTIMEOUT)
  2012. timeout = usbdev->found->timeout;
  2013. if (end == NULL) {
  2014. if (usbdev->buffer && usbdev->bufamt) {
  2015. tot = usbdev->bufamt;
  2016. bufleft = bufsiz - tot;
  2017. memcpy(usbbuf, usbdev->buffer, tot);
  2018. ptr = usbbuf + tot;
  2019. usbdev->bufamt = 0;
  2020. } else {
  2021. tot = 0;
  2022. bufleft = bufsiz;
  2023. ptr = usbbuf;
  2024. }
  2025. err = LIBUSB_SUCCESS;
  2026. initial_timeout = timeout;
  2027. max = ((double)timeout) / 1000.0;
  2028. cgtime(&read_start);
  2029. while (bufleft > 0) {
  2030. // TODO: use (USB_MAX_READ - tot) always?
  2031. if (usbdev->buffer)
  2032. usbbufread = USB_MAX_READ - tot;
  2033. else {
  2034. if (ftdi)
  2035. usbbufread = bufleft + 2;
  2036. else
  2037. usbbufread = bufleft;
  2038. }
  2039. got = 0;
  2040. if (first && usbdev->usecps && usbdev->last_write_siz) {
  2041. cgtimer_t now, already_done;
  2042. double sleep_estimate;
  2043. double write_time = (double)(usbdev->last_write_siz) /
  2044. (double)(usbdev->cps);
  2045. cgtimer_time(&now);
  2046. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2047. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2048. if (sleep_estimate > 0.0) {
  2049. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2050. cgpu->usbinfo.read_delay_count++;
  2051. cgpu->usbinfo.total_read_delay += sleep_estimate;
  2052. }
  2053. }
  2054. err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
  2055. ptr, usbbufread, &got, timeout,
  2056. cgpu, MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  2057. cgtime(&tv_finish);
  2058. ptr[got] = '\0';
  2059. 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);
  2060. IOERR_CHECK(cgpu, err);
  2061. if (ftdi) {
  2062. // first 2 bytes returned are an FTDI status
  2063. if (got > 2) {
  2064. got -= 2;
  2065. memmove(ptr, ptr+2, got+1);
  2066. } else {
  2067. got = 0;
  2068. *ptr = '\0';
  2069. }
  2070. }
  2071. tot += got;
  2072. if (err || readonce)
  2073. break;
  2074. ptr += got;
  2075. bufleft -= got;
  2076. first = false;
  2077. done = tdiff(&tv_finish, &read_start);
  2078. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  2079. if (unlikely(done >= max))
  2080. break;
  2081. timeout = initial_timeout - (done * 1000);
  2082. if (!timeout)
  2083. break;
  2084. }
  2085. // N.B. usbdev->buffer was emptied before the while() loop
  2086. if (usbdev->buffer && tot > (int)bufsiz) {
  2087. usbdev->bufamt = tot - bufsiz;
  2088. memcpy(usbdev->buffer, usbbuf + bufsiz, usbdev->bufamt);
  2089. tot -= usbdev->bufamt;
  2090. usbbuf[tot] = '\0';
  2091. applog(LOG_INFO, "USB: %s%i read1 buffering %d extra bytes",
  2092. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2093. }
  2094. *processed = tot;
  2095. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2096. goto out_unlock;
  2097. }
  2098. if (usbdev->buffer && usbdev->bufamt) {
  2099. tot = usbdev->bufamt;
  2100. bufleft = bufsiz - tot;
  2101. memcpy(usbbuf, usbdev->buffer, tot);
  2102. ptr = usbbuf + tot;
  2103. usbdev->bufamt = 0;
  2104. } else {
  2105. tot = 0;
  2106. bufleft = bufsiz;
  2107. ptr = usbbuf;
  2108. }
  2109. endlen = strlen(end);
  2110. err = LIBUSB_SUCCESS;
  2111. initial_timeout = timeout;
  2112. max = ((double)timeout) / 1000.0;
  2113. cgtime(&read_start);
  2114. while (bufleft > 0) {
  2115. // TODO: use (USB_MAX_READ - tot) always?
  2116. if (usbdev->buffer)
  2117. usbbufread = USB_MAX_READ - tot;
  2118. else {
  2119. if (ftdi)
  2120. usbbufread = bufleft + 2;
  2121. else
  2122. usbbufread = bufleft;
  2123. }
  2124. got = 0;
  2125. if (first && usbdev->usecps && usbdev->last_write_siz) {
  2126. cgtimer_t now, already_done;
  2127. double sleep_estimate;
  2128. double write_time = (double)(usbdev->last_write_siz) /
  2129. (double)(usbdev->cps);
  2130. cgtimer_time(&now);
  2131. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2132. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2133. if (sleep_estimate > 0.0) {
  2134. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2135. cgpu->usbinfo.read_delay_count++;
  2136. cgpu->usbinfo.total_read_delay += sleep_estimate;
  2137. }
  2138. }
  2139. err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
  2140. ptr, usbbufread, &got, timeout,
  2141. cgpu, MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  2142. cgtime(&tv_finish);
  2143. ptr[got] = '\0';
  2144. 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);
  2145. IOERR_CHECK(cgpu, err);
  2146. if (ftdi) {
  2147. // first 2 bytes returned are an FTDI status
  2148. if (got > 2) {
  2149. got -= 2;
  2150. memmove(ptr, ptr+2, got+1);
  2151. } else {
  2152. got = 0;
  2153. *ptr = '\0';
  2154. }
  2155. }
  2156. tot += got;
  2157. if (err || readonce)
  2158. break;
  2159. if (find_end(usbbuf, ptr, got, tot, (char *)end, endlen, first))
  2160. break;
  2161. ptr += got;
  2162. bufleft -= got;
  2163. first = false;
  2164. done = tdiff(&tv_finish, &read_start);
  2165. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  2166. if (unlikely(done >= max))
  2167. break;
  2168. timeout = initial_timeout - (done * 1000);
  2169. if (!timeout)
  2170. break;
  2171. }
  2172. if (usbdev->buffer) {
  2173. bool dobuffer = false;
  2174. if ((search = find_end(usbbuf, usbbuf, tot, tot, (char *)end, endlen, true))) {
  2175. // end finishes after bufsiz
  2176. if ((search + endlen - (char *)usbbuf) > (int)bufsiz) {
  2177. usbdev->bufamt = tot - bufsiz;
  2178. dobuffer = true;
  2179. } else {
  2180. // extra data after end
  2181. if (*(search + endlen)) {
  2182. usbdev->bufamt = tot - (search + endlen - (char *)usbbuf);
  2183. dobuffer = true;
  2184. }
  2185. }
  2186. } else {
  2187. // no end, but still bigger than bufsiz
  2188. if (tot > (int)bufsiz) {
  2189. usbdev->bufamt = tot - bufsiz;
  2190. dobuffer = true;
  2191. }
  2192. }
  2193. if (dobuffer) {
  2194. tot -= usbdev->bufamt;
  2195. memcpy(usbdev->buffer, usbbuf + tot, usbdev->bufamt);
  2196. usbbuf[tot] = '\0';
  2197. applog(LOG_ERR, "USB: %s%i read2 buffering %d extra bytes",
  2198. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2199. }
  2200. }
  2201. *processed = tot;
  2202. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2203. out_unlock:
  2204. if (err && err != LIBUSB_ERROR_TIMEOUT) {
  2205. applog(LOG_WARNING, "%s %i usb read error: %s", cgpu->drv->name, cgpu->device_id,
  2206. libusb_error_name(err));
  2207. if (cgpu->usbinfo.continuous_ioerr_count > USB_RETRY_MAX)
  2208. err = LIBUSB_ERROR_OTHER;
  2209. }
  2210. out_noerrmsg:
  2211. if (NODEV(err)) {
  2212. cg_ruwlock(&cgpu->usbinfo.devlock);
  2213. release_cgpu(cgpu);
  2214. DEVWUNLOCK(cgpu, pstate);
  2215. } else
  2216. DEVRUNLOCK(cgpu, pstate);
  2217. return err;
  2218. }
  2219. 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)
  2220. {
  2221. struct cg_usb_device *usbdev;
  2222. struct timeval read_start, tv_finish;
  2223. unsigned int initial_timeout;
  2224. double max, done;
  2225. __maybe_unused bool first = true;
  2226. int err, sent, tot, pstate;
  2227. DEVRLOCK(cgpu, pstate);
  2228. 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));
  2229. *processed = 0;
  2230. if (cgpu->usbinfo.nodev) {
  2231. USB_REJECT(cgpu, MODE_BULK_WRITE);
  2232. err = LIBUSB_ERROR_NO_DEVICE;
  2233. goto out_noerrmsg;
  2234. }
  2235. usbdev = cgpu->usbdev;
  2236. if (timeout == DEVTIMEOUT)
  2237. timeout = usbdev->found->timeout;
  2238. tot = 0;
  2239. err = LIBUSB_SUCCESS;
  2240. initial_timeout = timeout;
  2241. max = ((double)timeout) / 1000.0;
  2242. cgtime(&read_start);
  2243. while (bufsiz > 0) {
  2244. sent = 0;
  2245. if (usbdev->usecps) {
  2246. if (usbdev->last_write_siz) {
  2247. cgtimer_t now, already_done;
  2248. double sleep_estimate;
  2249. double write_time = (double)(usbdev->last_write_siz) /
  2250. (double)(usbdev->cps);
  2251. cgtimer_time(&now);
  2252. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2253. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2254. if (sleep_estimate > 0.0) {
  2255. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2256. cgpu->usbinfo.write_delay_count++;
  2257. cgpu->usbinfo.total_write_delay += sleep_estimate;
  2258. }
  2259. }
  2260. cgsleep_prepare_r(&usbdev->cgt_last_write);
  2261. usbdev->last_write_siz = bufsiz;
  2262. }
  2263. err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
  2264. (unsigned char *)buf, bufsiz, &sent, timeout,
  2265. cgpu, MODE_BULK_WRITE, cmd, first ? SEQ0 : SEQ1);
  2266. cgtime(&tv_finish);
  2267. 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);
  2268. IOERR_CHECK(cgpu, err);
  2269. tot += sent;
  2270. if (err)
  2271. break;
  2272. buf += sent;
  2273. bufsiz -= sent;
  2274. first = false;
  2275. done = tdiff(&tv_finish, &read_start);
  2276. // N.B. this is: return LIBUSB_SUCCESS with whatever size was written
  2277. if (unlikely(done >= max))
  2278. break;
  2279. timeout = initial_timeout - (done * 1000);
  2280. if (!timeout)
  2281. break;
  2282. }
  2283. *processed = tot;
  2284. if (err) {
  2285. applog(LOG_WARNING, "%s %i usb write error: %s", cgpu->drv->name, cgpu->device_id,
  2286. libusb_error_name(err));
  2287. if (cgpu->usbinfo.continuous_ioerr_count > USB_RETRY_MAX)
  2288. err = LIBUSB_ERROR_OTHER;
  2289. }
  2290. out_noerrmsg:
  2291. if (NODEV(err)) {
  2292. cg_ruwlock(&cgpu->usbinfo.devlock);
  2293. release_cgpu(cgpu);
  2294. DEVWUNLOCK(cgpu, pstate);
  2295. } else
  2296. DEVRUNLOCK(cgpu, pstate);
  2297. return err;
  2298. }
  2299. /* As we do for bulk reads, emulate a sync function for control transfers using
  2300. * our own timeouts that takes the same parameters as libusb_control_transfer.
  2301. */
  2302. static int usb_control_transfer(libusb_device_handle *dev_handle, uint8_t bmRequestType,
  2303. uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
  2304. unsigned char *buffer, uint16_t wLength, unsigned int timeout)
  2305. {
  2306. struct usb_transfer ut;
  2307. unsigned char buf[70];
  2308. int err, transferred;
  2309. init_usb_transfer(&ut);
  2310. libusb_fill_control_setup(buf, bmRequestType, bRequest, wValue,
  2311. wIndex, wLength);
  2312. libusb_fill_control_transfer(ut.transfer, dev_handle, buf, transfer_callback,
  2313. &ut, 0);
  2314. err = libusb_submit_transfer(ut.transfer);
  2315. if (!err)
  2316. err = callback_wait(&ut, &transferred, timeout);
  2317. if (!err && transferred) {
  2318. unsigned char *ofbuf = libusb_control_transfer_get_data(ut.transfer);
  2319. memcpy(buffer, ofbuf, transferred);
  2320. err = transferred;
  2321. goto out;
  2322. }
  2323. if ((err) == LIBUSB_TRANSFER_CANCELLED)
  2324. err = LIBUSB_ERROR_TIMEOUT;
  2325. out:
  2326. libusb_free_transfer(ut.transfer);
  2327. return err;
  2328. }
  2329. 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)
  2330. {
  2331. struct cg_usb_device *usbdev;
  2332. #if DO_USB_STATS
  2333. struct timeval tv_start, tv_finish;
  2334. #endif
  2335. unsigned char buf[64];
  2336. uint32_t *buf32 = (uint32_t *)buf;
  2337. int err, i, bufsiz;
  2338. 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));
  2339. if (cgpu->usbinfo.nodev) {
  2340. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  2341. err = LIBUSB_ERROR_NO_DEVICE;
  2342. goto out_;
  2343. }
  2344. usbdev = cgpu->usbdev;
  2345. if (timeout == DEVTIMEOUT)
  2346. timeout = usbdev->found->timeout;
  2347. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  2348. if (siz > 0) {
  2349. bufsiz = siz - 1;
  2350. bufsiz >>= 2;
  2351. bufsiz++;
  2352. for (i = 0; i < bufsiz; i++)
  2353. buf32[i] = htole32(data[i]);
  2354. }
  2355. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex(buf, (size_t)siz));
  2356. if (usbdev->usecps) {
  2357. if (usbdev->last_write_siz) {
  2358. cgtimer_t now, already_done;
  2359. double sleep_estimate;
  2360. double write_time = (double)(usbdev->last_write_siz) /
  2361. (double)(usbdev->cps);
  2362. cgtimer_time(&now);
  2363. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2364. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2365. if (sleep_estimate > 0.0) {
  2366. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2367. cgpu->usbinfo.write_delay_count++;
  2368. cgpu->usbinfo.total_write_delay += sleep_estimate;
  2369. }
  2370. }
  2371. cgsleep_prepare_r(&usbdev->cgt_last_write);
  2372. usbdev->last_write_siz = siz;
  2373. }
  2374. STATS_TIMEVAL(&tv_start);
  2375. cg_rlock(&cgusb_fd_lock);
  2376. err = usb_control_transfer(usbdev->handle, request_type,
  2377. bRequest, wValue, wIndex, buf, (uint16_t)siz, timeout);
  2378. cg_runlock(&cgusb_fd_lock);
  2379. STATS_TIMEVAL(&tv_finish);
  2380. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0, timeout);
  2381. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  2382. IOERR_CHECK(cgpu, err);
  2383. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  2384. applog(LOG_WARNING, "%s %i usb transfer error(%d): %s", cgpu->drv->name, cgpu->device_id,
  2385. err, libusb_error_name(err));
  2386. }
  2387. out_:
  2388. return err;
  2389. }
  2390. /* We use the write devlock for control transfers since some control transfers
  2391. * are rare but may be changing settings within the device causing problems
  2392. * if concurrent transfers are happening. Using the write lock serialises
  2393. * any transfers. */
  2394. 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)
  2395. {
  2396. int pstate, err;
  2397. DEVWLOCK(cgpu, pstate);
  2398. err = __usb_transfer(cgpu, request_type, bRequest, wValue, wIndex, data, siz, timeout, cmd);
  2399. if (NOCONTROLDEV(err))
  2400. release_cgpu(cgpu);
  2401. DEVWUNLOCK(cgpu, pstate);
  2402. return err;
  2403. }
  2404. 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)
  2405. {
  2406. struct cg_usb_device *usbdev;
  2407. #if DO_USB_STATS
  2408. struct timeval tv_start, tv_finish;
  2409. #endif
  2410. unsigned char tbuf[64];
  2411. int err, pstate;
  2412. DEVWLOCK(cgpu, pstate);
  2413. 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));
  2414. if (cgpu->usbinfo.nodev) {
  2415. USB_REJECT(cgpu, MODE_CTRL_READ);
  2416. err = LIBUSB_ERROR_NO_DEVICE;
  2417. goto out_noerrmsg;
  2418. }
  2419. usbdev = cgpu->usbdev;
  2420. if (timeout == DEVTIMEOUT)
  2421. timeout = usbdev->found->timeout;
  2422. *amount = 0;
  2423. if (usbdev->usecps && usbdev->last_write_siz) {
  2424. cgtimer_t now, already_done;
  2425. double sleep_estimate;
  2426. double write_time = (double)(usbdev->last_write_siz) /
  2427. (double)(usbdev->cps);
  2428. cgtimer_time(&now);
  2429. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2430. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2431. if (sleep_estimate > 0.0) {
  2432. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2433. cgpu->usbinfo.read_delay_count++;
  2434. cgpu->usbinfo.total_read_delay += sleep_estimate;
  2435. }
  2436. }
  2437. memset(tbuf, 0, 64);
  2438. STATS_TIMEVAL(&tv_start);
  2439. cg_rlock(&cgusb_fd_lock);
  2440. err = usb_control_transfer(usbdev->handle, request_type,
  2441. bRequest, wValue, wIndex,
  2442. tbuf, (uint16_t)bufsiz, timeout);
  2443. cg_runlock(&cgusb_fd_lock);
  2444. STATS_TIMEVAL(&tv_finish);
  2445. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0, timeout);
  2446. memcpy(buf, tbuf, bufsiz);
  2447. 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);
  2448. IOERR_CHECK(cgpu, err);
  2449. if (err > 0) {
  2450. *amount = err;
  2451. err = 0;
  2452. }
  2453. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  2454. applog(LOG_WARNING, "%s %i usb transfer read error(%d): %s", cgpu->drv->name, cgpu->device_id,
  2455. err, libusb_error_name(err));
  2456. }
  2457. out_noerrmsg:
  2458. if (NOCONTROLDEV(err))
  2459. release_cgpu(cgpu);
  2460. DEVWUNLOCK(cgpu, pstate);
  2461. return err;
  2462. }
  2463. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  2464. #define FTDI_RS0_CTS (1 << 4)
  2465. #define FTDI_RS0_DSR (1 << 5)
  2466. #define FTDI_RS0_RI (1 << 6)
  2467. #define FTDI_RS0_RLSD (1 << 7)
  2468. /* Clear to send for FTDI */
  2469. int usb_ftdi_cts(struct cgpu_info *cgpu)
  2470. {
  2471. char buf[2], ret;
  2472. int err, amount;
  2473. err = _usb_transfer_read(cgpu, (uint8_t)FTDI_TYPE_IN, (uint8_t)5,
  2474. (uint16_t)0, (uint16_t)0, buf, 2,
  2475. &amount, DEVTIMEOUT, C_FTDI_STATUS);
  2476. /* We return true in case drivers are waiting indefinitely to try and
  2477. * write to something that's not there. */
  2478. if (err)
  2479. return true;
  2480. ret = buf[0] & FTDI_STATUS_B0_MASK;
  2481. return (ret & FTDI_RS0_CTS);
  2482. }
  2483. int _usb_ftdi_set_latency(struct cgpu_info *cgpu, int intinfo)
  2484. {
  2485. int err = 0;
  2486. int pstate;
  2487. DEVWLOCK(cgpu, pstate);
  2488. if (cgpu->usbdev) {
  2489. if (cgpu->usbdev->usb_type != USB_TYPE_FTDI) {
  2490. applog(LOG_ERR, "%s: cgid %d latency request on non-FTDI device",
  2491. cgpu->drv->name, cgpu->cgminer_id);
  2492. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2493. } else if (cgpu->usbdev->found->latency == LATENCY_UNUSED) {
  2494. applog(LOG_ERR, "%s: cgid %d invalid latency (UNUSED)",
  2495. cgpu->drv->name, cgpu->cgminer_id);
  2496. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2497. }
  2498. if (!err)
  2499. err = __usb_transfer(cgpu, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
  2500. cgpu->usbdev->found->latency,
  2501. USBIF(cgpu->usbdev, intinfo),
  2502. NULL, 0, DEVTIMEOUT, C_LATENCY);
  2503. }
  2504. DEVWUNLOCK(cgpu, pstate);
  2505. applog(LOG_DEBUG, "%s: cgid %d %s got err %d",
  2506. cgpu->drv->name, cgpu->cgminer_id,
  2507. usb_cmdname(C_LATENCY), err);
  2508. return err;
  2509. }
  2510. void usb_buffer_enable(struct cgpu_info *cgpu)
  2511. {
  2512. struct cg_usb_device *cgusb;
  2513. int pstate;
  2514. DEVWLOCK(cgpu, pstate);
  2515. cgusb = cgpu->usbdev;
  2516. if (cgusb && !cgusb->buffer) {
  2517. cgusb->bufamt = 0;
  2518. cgusb->buffer = malloc(USB_MAX_READ+1);
  2519. if (!cgusb->buffer)
  2520. quit(1, "Failed to malloc buffer for USB %s%i",
  2521. cgpu->drv->name, cgpu->device_id);
  2522. cgusb->bufsiz = USB_MAX_READ;
  2523. }
  2524. DEVWUNLOCK(cgpu, pstate);
  2525. }
  2526. void usb_buffer_disable(struct cgpu_info *cgpu)
  2527. {
  2528. struct cg_usb_device *cgusb;
  2529. int pstate;
  2530. DEVWLOCK(cgpu, pstate);
  2531. cgusb = cgpu->usbdev;
  2532. if (cgusb && cgusb->buffer) {
  2533. cgusb->bufamt = 0;
  2534. cgusb->bufsiz = 0;
  2535. free(cgusb->buffer);
  2536. cgusb->buffer = NULL;
  2537. }
  2538. DEVWUNLOCK(cgpu, pstate);
  2539. }
  2540. void usb_buffer_clear(struct cgpu_info *cgpu)
  2541. {
  2542. int pstate;
  2543. DEVWLOCK(cgpu, pstate);
  2544. if (cgpu->usbdev)
  2545. cgpu->usbdev->bufamt = 0;
  2546. DEVWUNLOCK(cgpu, pstate);
  2547. }
  2548. uint32_t usb_buffer_size(struct cgpu_info *cgpu)
  2549. {
  2550. uint32_t ret = 0;
  2551. int pstate;
  2552. DEVRLOCK(cgpu, pstate);
  2553. if (cgpu->usbdev)
  2554. ret = cgpu->usbdev->bufamt;
  2555. DEVRUNLOCK(cgpu, pstate);
  2556. return ret;
  2557. }
  2558. void usb_set_cps(struct cgpu_info *cgpu, int cps)
  2559. {
  2560. int pstate;
  2561. DEVWLOCK(cgpu, pstate);
  2562. if (cgpu->usbdev)
  2563. cgpu->usbdev->cps = cps;
  2564. DEVWUNLOCK(cgpu, pstate);
  2565. }
  2566. void usb_enable_cps(struct cgpu_info *cgpu)
  2567. {
  2568. int pstate;
  2569. DEVWLOCK(cgpu, pstate);
  2570. if (cgpu->usbdev)
  2571. cgpu->usbdev->usecps = true;
  2572. DEVWUNLOCK(cgpu, pstate);
  2573. }
  2574. void usb_disable_cps(struct cgpu_info *cgpu)
  2575. {
  2576. int pstate;
  2577. DEVWLOCK(cgpu, pstate);
  2578. if (cgpu->usbdev)
  2579. cgpu->usbdev->usecps = false;
  2580. DEVWUNLOCK(cgpu, pstate);
  2581. }
  2582. /*
  2583. * The value returned (0) when usbdev is NULL
  2584. * doesn't matter since it also means the next call to
  2585. * any usbutils function will fail with a nodev
  2586. * N.B. this is to get the interface number to use in a control_transfer
  2587. * which for some devices isn't actually the interface number
  2588. */
  2589. int _usb_interface(struct cgpu_info *cgpu, int intinfo)
  2590. {
  2591. int interface = 0;
  2592. int pstate;
  2593. DEVRLOCK(cgpu, pstate);
  2594. if (cgpu->usbdev)
  2595. interface = cgpu->usbdev->found->intinfos[intinfo].ctrl_transfer;
  2596. DEVRUNLOCK(cgpu, pstate);
  2597. return interface;
  2598. }
  2599. enum sub_ident usb_ident(struct cgpu_info *cgpu)
  2600. {
  2601. enum sub_ident ident = IDENT_UNK;
  2602. int pstate;
  2603. DEVRLOCK(cgpu, pstate);
  2604. if (cgpu->usbdev)
  2605. ident = cgpu->usbdev->ident;
  2606. DEVRUNLOCK(cgpu, pstate);
  2607. return ident;
  2608. }
  2609. /*
  2610. * If you pass both intinfo and epinfo as <0 then it will set all
  2611. * endpoints to PrefPacketSize
  2612. * If intinfo >=0 but epinfo <0 then it will set all endpoints
  2613. * for the given one intinfo to PrefPacketSize
  2614. * If both are >=0 then it will set only the specified single
  2615. * endpoint (intinfo,epinfo) to PrefPacketSize
  2616. */
  2617. void _usb_set_pps(struct cgpu_info *cgpu, int intinfo, int epinfo, uint16_t PrefPacketSize)
  2618. {
  2619. struct usb_find_devices *found;
  2620. int pstate;
  2621. DEVWLOCK(cgpu, pstate);
  2622. if (cgpu->usbdev) {
  2623. found = cgpu->usbdev->found;
  2624. if (intinfo >= 0 && epinfo >= 0)
  2625. found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
  2626. else {
  2627. if (intinfo >= 0) {
  2628. for (epinfo = 0; epinfo < found->intinfos[intinfo].epinfo_count; epinfo++)
  2629. found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
  2630. } else {
  2631. for (intinfo = 0; intinfo < found->intinfo_count ; intinfo++)
  2632. for (epinfo = 0; epinfo < found->intinfos[intinfo].epinfo_count; epinfo++)
  2633. found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
  2634. }
  2635. }
  2636. }
  2637. DEVWUNLOCK(cgpu, pstate);
  2638. }
  2639. // Need to set all devices with matching usbdev
  2640. void usb_set_dev_start(struct cgpu_info *cgpu)
  2641. {
  2642. struct cg_usb_device *cgusb;
  2643. struct cgpu_info *cgpu2;
  2644. struct timeval now;
  2645. int pstate;
  2646. DEVWLOCK(cgpu, pstate);
  2647. cgusb = cgpu->usbdev;
  2648. // If the device wasn't dropped
  2649. if (cgusb != NULL) {
  2650. int i;
  2651. cgtime(&now);
  2652. for (i = 0; i < total_devices; i++) {
  2653. cgpu2 = get_devices(i);
  2654. if (cgpu2->usbdev == cgusb)
  2655. copy_time(&(cgpu2->dev_start_tv), &now);
  2656. }
  2657. }
  2658. DEVWUNLOCK(cgpu, pstate);
  2659. }
  2660. void usb_cleanup(void)
  2661. {
  2662. struct cgpu_info *cgpu;
  2663. int count, pstate;
  2664. int i;
  2665. hotplug_time = 0;
  2666. cgsleep_ms(10);
  2667. count = 0;
  2668. for (i = 0; i < total_devices; i++) {
  2669. cgpu = devices[i];
  2670. switch (cgpu->drv->drv_id) {
  2671. case DRIVER_bflsc:
  2672. case DRIVER_bitforce:
  2673. case DRIVER_bitfury:
  2674. case DRIVER_modminer:
  2675. case DRIVER_icarus:
  2676. case DRIVER_avalon:
  2677. case DRIVER_klondike:
  2678. case DRIVER_hashfast:
  2679. DEVWLOCK(cgpu, pstate);
  2680. release_cgpu(cgpu);
  2681. DEVWUNLOCK(cgpu, pstate);
  2682. count++;
  2683. break;
  2684. default:
  2685. break;
  2686. }
  2687. }
  2688. /*
  2689. * Must attempt to wait for the resource thread to release coz
  2690. * during a restart it won't automatically release them in linux
  2691. */
  2692. if (count) {
  2693. struct timeval start, now;
  2694. cgtime(&start);
  2695. while (42) {
  2696. cgsleep_ms(50);
  2697. mutex_lock(&cgusbres_lock);
  2698. if (!res_work_head)
  2699. break;
  2700. cgtime(&now);
  2701. if (tdiff(&now, &start) > 0.366) {
  2702. applog(LOG_WARNING,
  2703. "usb_cleanup gave up waiting for resource thread");
  2704. break;
  2705. }
  2706. mutex_unlock(&cgusbres_lock);
  2707. }
  2708. mutex_unlock(&cgusbres_lock);
  2709. }
  2710. cgsem_destroy(&usb_resource_sem);
  2711. }
  2712. #define DRIVER_COUNT_FOUND(X) if (X##_drv.name && strcasecmp(ptr, X##_drv.name) == 0) { \
  2713. drv_count[X##_drv.drv_id].limit = lim; \
  2714. found = true; \
  2715. }
  2716. void usb_initialise()
  2717. {
  2718. char *fre, *ptr, *comma, *colon;
  2719. int bus, dev, lim, i;
  2720. bool found;
  2721. for (i = 0; i < DRIVER_MAX; i++) {
  2722. drv_count[i].count = 0;
  2723. drv_count[i].limit = 999999;
  2724. }
  2725. cgusb_check_init();
  2726. if (opt_usb_select && *opt_usb_select) {
  2727. // Absolute device limit
  2728. if (*opt_usb_select == ':') {
  2729. total_limit = atoi(opt_usb_select+1);
  2730. if (total_limit < 0)
  2731. quit(1, "Invalid --usb total limit");
  2732. // Comma list of bus:dev devices to match
  2733. } else if (isdigit(*opt_usb_select)) {
  2734. fre = ptr = strdup(opt_usb_select);
  2735. do {
  2736. comma = strchr(ptr, ',');
  2737. if (comma)
  2738. *(comma++) = '\0';
  2739. colon = strchr(ptr, ':');
  2740. if (!colon)
  2741. quit(1, "Invalid --usb bus:dev missing ':'");
  2742. *(colon++) = '\0';
  2743. if (!isdigit(*ptr))
  2744. quit(1, "Invalid --usb bus:dev - bus must be a number");
  2745. if (!isdigit(*colon) && *colon != '*')
  2746. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  2747. bus = atoi(ptr);
  2748. if (bus <= 0)
  2749. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  2750. if (*colon == '*')
  2751. dev = -1;
  2752. else {
  2753. dev = atoi(colon);
  2754. if (dev <= 0)
  2755. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  2756. }
  2757. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  2758. if (unlikely(!busdev))
  2759. quit(1, "USB failed to realloc busdev");
  2760. busdev[busdev_count-1].bus_number = bus;
  2761. busdev[busdev_count-1].device_address = dev;
  2762. ptr = comma;
  2763. } while (ptr);
  2764. free(fre);
  2765. // Comma list of DRV:limit
  2766. } else {
  2767. fre = ptr = strdup(opt_usb_select);
  2768. do {
  2769. comma = strchr(ptr, ',');
  2770. if (comma)
  2771. *(comma++) = '\0';
  2772. colon = strchr(ptr, ':');
  2773. if (!colon)
  2774. quit(1, "Invalid --usb DRV:limit missing ':'");
  2775. *(colon++) = '\0';
  2776. if (!isdigit(*colon))
  2777. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  2778. lim = atoi(colon);
  2779. if (lim < 0)
  2780. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  2781. found = false;
  2782. /* Use the DRIVER_PARSE_COMMANDS macro to iterate
  2783. * over all the drivers. */
  2784. DRIVER_PARSE_COMMANDS(DRIVER_COUNT_FOUND)
  2785. if (!found)
  2786. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  2787. ptr = comma;
  2788. } while (ptr);
  2789. free(fre);
  2790. }
  2791. }
  2792. }
  2793. #ifndef WIN32
  2794. #include <errno.h>
  2795. #include <unistd.h>
  2796. #include <sys/types.h>
  2797. #include <sys/ipc.h>
  2798. #include <sys/sem.h>
  2799. #include <sys/stat.h>
  2800. #include <fcntl.h>
  2801. #ifndef __APPLE__
  2802. union semun {
  2803. int val;
  2804. struct semid_ds *buf;
  2805. unsigned short *array;
  2806. struct seminfo *__buf;
  2807. };
  2808. #endif
  2809. #else
  2810. static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
  2811. {
  2812. FreeSid(((PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor))->Group);
  2813. free(sec->lpSecurityDescriptor);
  2814. free(sec);
  2815. return NULL;
  2816. }
  2817. static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
  2818. {
  2819. SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
  2820. PSID gsid = NULL;
  2821. LPSECURITY_ATTRIBUTES sec_att = NULL;
  2822. PSECURITY_DESCRIPTOR sec_des = NULL;
  2823. sec_des = malloc(sizeof(*sec_des));
  2824. if (unlikely(!sec_des))
  2825. quit(1, "MTX: Failed to malloc LPSECURITY_DESCRIPTOR");
  2826. if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
  2827. applog(LOG_ERR,
  2828. "MTX: %s (%d:%d) USB failed to init secdes err (%d)",
  2829. dname, (int)bus_number, (int)device_address,
  2830. (int)GetLastError());
  2831. free(sec_des);
  2832. return NULL;
  2833. }
  2834. if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
  2835. applog(LOG_ERR,
  2836. "MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
  2837. dname, (int)bus_number, (int)device_address,
  2838. (int)GetLastError());
  2839. free(sec_des);
  2840. return NULL;
  2841. }
  2842. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
  2843. applog(LOG_ERR,
  2844. "MTX: %s (%d:%d) USB failed to create gsid err (%d)",
  2845. dname, (int)bus_number, (int)device_address,
  2846. (int)GetLastError());
  2847. free(sec_des);
  2848. return NULL;
  2849. }
  2850. if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
  2851. applog(LOG_ERR,
  2852. "MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
  2853. dname, (int)bus_number, (int)device_address,
  2854. (int)GetLastError());
  2855. FreeSid(gsid);
  2856. free(sec_des);
  2857. return NULL;
  2858. }
  2859. sec_att = malloc(sizeof(*sec_att));
  2860. if (unlikely(!sec_att))
  2861. quit(1, "MTX: Failed to malloc LPSECURITY_ATTRIBUTES");
  2862. sec_att->nLength = sizeof(*sec_att);
  2863. sec_att->lpSecurityDescriptor = sec_des;
  2864. sec_att->bInheritHandle = FALSE;
  2865. return sec_att;
  2866. }
  2867. #endif
  2868. // Any errors should always be printed since they will rarely if ever occur
  2869. // and thus it is best to always display them
  2870. static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2871. {
  2872. applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2873. #ifdef WIN32
  2874. struct cgpu_info *cgpu;
  2875. LPSECURITY_ATTRIBUTES sec;
  2876. HANDLE usbMutex;
  2877. char name[64];
  2878. DWORD res;
  2879. int i;
  2880. if (is_in_use_bd(bus_number, device_address))
  2881. return false;
  2882. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2883. sec = mksec(dname, bus_number, device_address);
  2884. if (!sec)
  2885. return false;
  2886. usbMutex = CreateMutex(sec, FALSE, name);
  2887. if (usbMutex == NULL) {
  2888. applog(LOG_ERR,
  2889. "MTX: %s USB failed to get '%s' err (%d)",
  2890. dname, name, (int)GetLastError());
  2891. sec = unsec(sec);
  2892. return false;
  2893. }
  2894. res = WaitForSingleObject(usbMutex, 0);
  2895. switch(res) {
  2896. case WAIT_OBJECT_0:
  2897. case WAIT_ABANDONED:
  2898. // Am I using it already?
  2899. for (i = 0; i < total_devices; i++) {
  2900. cgpu = get_devices(i);
  2901. if (cgpu->usbinfo.bus_number == bus_number &&
  2902. cgpu->usbinfo.device_address == device_address &&
  2903. cgpu->usbinfo.nodev == false) {
  2904. if (ReleaseMutex(usbMutex)) {
  2905. applog(LOG_WARNING,
  2906. "MTX: %s USB can't get '%s' - device in use",
  2907. dname, name);
  2908. goto fail;
  2909. }
  2910. applog(LOG_ERR,
  2911. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  2912. dname, name, (int)GetLastError());
  2913. goto fail;
  2914. }
  2915. }
  2916. break;
  2917. case WAIT_TIMEOUT:
  2918. if (!hotplug_mode)
  2919. applog(LOG_WARNING,
  2920. "MTX: %s USB failed to get '%s' - device in use",
  2921. dname, name);
  2922. goto fail;
  2923. case WAIT_FAILED:
  2924. applog(LOG_ERR,
  2925. "MTX: %s USB failed to get '%s' err (%d)",
  2926. dname, name, (int)GetLastError());
  2927. goto fail;
  2928. default:
  2929. applog(LOG_ERR,
  2930. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  2931. dname, name, (int)res);
  2932. goto fail;
  2933. }
  2934. add_in_use(bus_number, device_address);
  2935. in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
  2936. return true;
  2937. fail:
  2938. CloseHandle(usbMutex);
  2939. sec = unsec(sec);
  2940. return false;
  2941. #else
  2942. struct semid_ds seminfo;
  2943. union semun opt;
  2944. char name[64];
  2945. key_t *key;
  2946. int *sem;
  2947. int fd, count;
  2948. if (is_in_use_bd(bus_number, device_address))
  2949. return false;
  2950. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2951. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2952. if (fd == -1) {
  2953. applog(LOG_ERR,
  2954. "SEM: %s USB open failed '%s' err (%d) %s",
  2955. dname, name, errno, strerror(errno));
  2956. goto _out;
  2957. }
  2958. close(fd);
  2959. key = malloc(sizeof(*key));
  2960. if (unlikely(!key))
  2961. quit(1, "SEM: Failed to malloc key");
  2962. sem = malloc(sizeof(*sem));
  2963. if (unlikely(!sem))
  2964. quit(1, "SEM: Failed to malloc sem");
  2965. *key = ftok(name, 'K');
  2966. *sem = semget(*key, 1, IPC_CREAT | IPC_EXCL | 438);
  2967. if (*sem < 0) {
  2968. if (errno != EEXIST) {
  2969. applog(LOG_ERR,
  2970. "SEM: %s USB failed to get '%s' err (%d) %s",
  2971. dname, name, errno, strerror(errno));
  2972. goto free_out;
  2973. }
  2974. *sem = semget(*key, 1, 0);
  2975. if (*sem < 0) {
  2976. applog(LOG_ERR,
  2977. "SEM: %s USB failed to access '%s' err (%d) %s",
  2978. dname, name, errno, strerror(errno));
  2979. goto free_out;
  2980. }
  2981. opt.buf = &seminfo;
  2982. count = 0;
  2983. while (++count) {
  2984. // Should NEVER take 100ms
  2985. if (count > 99) {
  2986. applog(LOG_ERR,
  2987. "SEM: %s USB timeout waiting for (%d) '%s'",
  2988. dname, *sem, name);
  2989. goto free_out;
  2990. }
  2991. if (semctl(*sem, 0, IPC_STAT, opt) == -1) {
  2992. applog(LOG_ERR,
  2993. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  2994. dname, *sem, name, count, errno, strerror(errno));
  2995. goto free_out;
  2996. }
  2997. if (opt.buf->sem_otime != 0)
  2998. break;
  2999. cgsleep_ms(1);
  3000. }
  3001. }
  3002. struct sembuf sops[] = {
  3003. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  3004. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  3005. };
  3006. if (semop(*sem, sops, 2)) {
  3007. if (errno == EAGAIN) {
  3008. if (!hotplug_mode)
  3009. applog(LOG_WARNING,
  3010. "SEM: %s USB failed to get (%d) '%s' - device in use",
  3011. dname, *sem, name);
  3012. } else {
  3013. applog(LOG_DEBUG,
  3014. "SEM: %s USB failed to get (%d) '%s' err (%d) %s",
  3015. dname, *sem, name, errno, strerror(errno));
  3016. }
  3017. goto free_out;
  3018. }
  3019. add_in_use(bus_number, device_address);
  3020. in_use_store_ress(bus_number, device_address, (void *)key, (void *)sem);
  3021. return true;
  3022. free_out:
  3023. free(sem);
  3024. free(key);
  3025. _out:
  3026. return false;
  3027. #endif
  3028. }
  3029. // Any errors should always be printed since they will rarely if ever occur
  3030. // and thus it is best to always display them
  3031. static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
  3032. {
  3033. applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
  3034. #ifdef WIN32
  3035. LPSECURITY_ATTRIBUTES sec = NULL;
  3036. HANDLE usbMutex = NULL;
  3037. char name[64];
  3038. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  3039. in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
  3040. if (!usbMutex || !sec)
  3041. goto fila;
  3042. if (!ReleaseMutex(usbMutex))
  3043. applog(LOG_ERR,
  3044. "MTX: %s USB failed to release '%s' err (%d)",
  3045. dname, name, (int)GetLastError());
  3046. fila:
  3047. if (usbMutex)
  3048. CloseHandle(usbMutex);
  3049. if (sec)
  3050. unsec(sec);
  3051. remove_in_use(bus_number, device_address);
  3052. return;
  3053. #else
  3054. char name[64];
  3055. key_t *key = NULL;
  3056. int *sem = NULL;
  3057. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  3058. in_use_get_ress(bus_number, device_address, (void **)(&key), (void **)(&sem));
  3059. if (!key || !sem)
  3060. goto fila;
  3061. struct sembuf sops[] = {
  3062. { 0, -1, SEM_UNDO }
  3063. };
  3064. // Allow a 10ms timeout
  3065. // exceeding this timeout means it would probably never succeed anyway
  3066. struct timespec timeout = { 0, 10000000 };
  3067. if (semtimedop(*sem, sops, 1, &timeout)) {
  3068. applog(LOG_ERR,
  3069. "SEM: %s USB failed to release '%s' err (%d) %s",
  3070. dname, name, errno, strerror(errno));
  3071. }
  3072. if (semctl(*sem, 0, IPC_RMID)) {
  3073. applog(LOG_WARNING,
  3074. "SEM: %s USB failed to remove SEM '%s' err (%d) %s",
  3075. dname, name, errno, strerror(errno));
  3076. }
  3077. fila:
  3078. free(sem);
  3079. free(key);
  3080. remove_in_use(bus_number, device_address);
  3081. return;
  3082. #endif
  3083. }
  3084. static void resource_process()
  3085. {
  3086. struct resource_work *res_work = NULL;
  3087. struct resource_reply *res_reply = NULL;
  3088. bool ok;
  3089. applog(LOG_DEBUG, "RES: %s (%d:%d) lock=%d",
  3090. res_work_head->dname,
  3091. (int)res_work_head->bus_number,
  3092. (int)res_work_head->device_address,
  3093. res_work_head->lock);
  3094. if (res_work_head->lock) {
  3095. ok = resource_lock(res_work_head->dname,
  3096. res_work_head->bus_number,
  3097. res_work_head->device_address);
  3098. applog(LOG_DEBUG, "RES: %s (%d:%d) lock ok=%d",
  3099. res_work_head->dname,
  3100. (int)res_work_head->bus_number,
  3101. (int)res_work_head->device_address,
  3102. ok);
  3103. res_reply = calloc(1, sizeof(*res_reply));
  3104. if (unlikely(!res_reply))
  3105. quit(1, "USB failed to calloc res_reply");
  3106. res_reply->bus_number = res_work_head->bus_number;
  3107. res_reply->device_address = res_work_head->device_address;
  3108. res_reply->got = ok;
  3109. res_reply->next = res_reply_head;
  3110. res_reply_head = res_reply;
  3111. }
  3112. else
  3113. resource_unlock(res_work_head->dname,
  3114. res_work_head->bus_number,
  3115. res_work_head->device_address);
  3116. res_work = res_work_head;
  3117. res_work_head = res_work_head->next;
  3118. free(res_work);
  3119. }
  3120. void *usb_resource_thread(void __maybe_unused *userdata)
  3121. {
  3122. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3123. RenameThread("usbresource");
  3124. applog(LOG_DEBUG, "RES: thread starting");
  3125. while (42) {
  3126. /* Wait to be told we have work to do */
  3127. cgsem_wait(&usb_resource_sem);
  3128. mutex_lock(&cgusbres_lock);
  3129. while (res_work_head)
  3130. resource_process();
  3131. mutex_unlock(&cgusbres_lock);
  3132. }
  3133. return NULL;
  3134. }