usbutils.c 98 KB

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