usbutils.c 96 KB

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