usbutils.c 96 KB

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