usbutils.c 99 KB

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