usbutils.c 98 KB

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