usbutils.c 95 KB

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