usbutils.c 95 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696
  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_ERROR_TIMEOUT:
  1798. item = CMD_TIMEOUT;
  1799. break;
  1800. default:
  1801. item = CMD_ERROR;
  1802. break;
  1803. }
  1804. if (details->item[item].count == 0) {
  1805. details->item[item].min_delay = diff;
  1806. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  1807. } else if (diff < details->item[item].min_delay)
  1808. details->item[item].min_delay = diff;
  1809. if (diff > details->item[item].max_delay)
  1810. details->item[item].max_delay = diff;
  1811. details->item[item].total_delay += diff;
  1812. memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
  1813. details->item[item].count++;
  1814. }
  1815. static void rejected_inc(struct cgpu_info *cgpu, uint32_t mode)
  1816. {
  1817. struct cg_usb_stats_details *details;
  1818. int item = CMD_ERROR;
  1819. if (cgpu->usbinfo.usbstat < 1)
  1820. newstats(cgpu);
  1821. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  1822. details->modes |= mode;
  1823. details->item[item].count++;
  1824. }
  1825. #endif
  1826. static char *find_end(unsigned char *buf, unsigned char *ptr, int ptrlen, int tot, char *end, int endlen, bool first)
  1827. {
  1828. unsigned char *search;
  1829. if (endlen > tot)
  1830. return NULL;
  1831. // If end is only 1 char - do a faster search
  1832. if (endlen == 1) {
  1833. if (first)
  1834. search = buf;
  1835. else
  1836. search = ptr;
  1837. return strchr((char *)search, *end);
  1838. } else {
  1839. if (first)
  1840. search = buf;
  1841. else {
  1842. // must allow end to have been chopped in 2
  1843. if ((tot - ptrlen) >= (endlen - 1))
  1844. search = ptr - (endlen - 1);
  1845. else
  1846. search = ptr - (tot - ptrlen);
  1847. }
  1848. return strstr((char *)search, end);
  1849. }
  1850. }
  1851. #define USB_MAX_READ 8192
  1852. #define USB_RETRY_MAX 5
  1853. struct usb_transfer {
  1854. pthread_mutex_t mutex;
  1855. pthread_cond_t cond;
  1856. struct libusb_transfer *transfer;
  1857. };
  1858. static void init_usb_transfer(struct usb_transfer *ut)
  1859. {
  1860. mutex_init(&ut->mutex);
  1861. pthread_cond_init(&ut->cond, NULL);
  1862. ut->transfer = libusb_alloc_transfer(0);
  1863. if (unlikely(!ut->transfer))
  1864. quit(1, "Failed to libusb_alloc_transfer");
  1865. ut->transfer->user_data = ut;
  1866. }
  1867. static void LIBUSB_CALL bulk_callback(struct libusb_transfer *transfer)
  1868. {
  1869. struct usb_transfer *ut = transfer->user_data;
  1870. mutex_lock(&ut->mutex);
  1871. pthread_cond_signal(&ut->cond);
  1872. mutex_unlock(&ut->mutex);
  1873. }
  1874. /* Wait for callback function to tell us it has finished the USB transfer, but
  1875. * use our own timer to cancel the request if we go beyond the timeout. */
  1876. static int callback_wait(struct cgpu_info *cgpu, struct usb_transfer *ut, int *transferred,
  1877. unsigned int timeout)
  1878. {
  1879. struct libusb_transfer *transfer= ut->transfer;
  1880. struct timespec ts_now, ts_end;
  1881. struct timeval tv_now;
  1882. int ret;
  1883. cgtime(&tv_now);
  1884. timeout = timeout + USB_ASYNC_POLL;
  1885. ms_to_timespec(&ts_end, timeout);
  1886. timeval_to_spec(&ts_now, &tv_now);
  1887. timeraddspec(&ts_end, &ts_now);
  1888. ret = pthread_cond_timedwait(&ut->cond, &ut->mutex, &ts_end);
  1889. if (ret) {
  1890. /* Assume that if we timed out on the conditional then the
  1891. * transfer has stalled for some reason and attempt to clear
  1892. * a halt as a solution. Then cancel the transaction, treating
  1893. * it the same as a timeout. */
  1894. libusb_clear_halt(transfer->dev_handle, transfer->endpoint);
  1895. libusb_cancel_transfer(transfer);
  1896. applog(LOG_DEBUG, "%s%i: libusb cancelling async bulk transfer",
  1897. cgpu->drv->name, cgpu->device_id);
  1898. cgpu->usb_cancels++;
  1899. /* Now wait for the callback function to be invoked. */
  1900. pthread_cond_wait(&ut->cond, &ut->mutex);
  1901. /* Fake the timed out message since it's effectively that */
  1902. ret = LIBUSB_TRANSFER_TIMED_OUT;
  1903. } else
  1904. ret = transfer->status;
  1905. /* No need to sort out mutexes here since they won't be reused */
  1906. *transferred = transfer->actual_length;
  1907. libusb_free_transfer(transfer);
  1908. return ret;
  1909. }
  1910. static int
  1911. usb_bulk_transfer(struct libusb_device_handle *dev_handle, int intinfo,
  1912. int epinfo, unsigned char *data, int length,
  1913. int *transferred, unsigned int timeout,
  1914. struct cgpu_info *cgpu, __maybe_unused int mode,
  1915. enum usb_cmds cmd, __maybe_unused int seq)
  1916. {
  1917. struct usb_epinfo *usb_epinfo;
  1918. int err, errn, retries = 0;
  1919. struct usb_transfer ut;
  1920. unsigned char endpoint;
  1921. uint16_t MaxPacketSize;
  1922. #if DO_USB_STATS
  1923. struct timeval tv_start, tv_finish;
  1924. #endif
  1925. unsigned char buf[512];
  1926. usb_epinfo = &(cgpu->usbdev->found->intinfos[intinfo].epinfos[epinfo]);
  1927. endpoint = usb_epinfo->ep;
  1928. /* Limit length of transfer to the largest this descriptor supports
  1929. * and leave the higher level functions to transfer more if needed. */
  1930. if (usb_epinfo->PrefPacketSize)
  1931. MaxPacketSize = usb_epinfo->PrefPacketSize;
  1932. else
  1933. MaxPacketSize = usb_epinfo->wMaxPacketSize;
  1934. if (length > MaxPacketSize)
  1935. length = MaxPacketSize;
  1936. if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)
  1937. memcpy(buf, data, length);
  1938. 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);
  1939. init_usb_transfer(&ut);
  1940. mutex_lock(&ut.mutex);
  1941. libusb_fill_bulk_transfer(ut.transfer, dev_handle, endpoint, buf, length,
  1942. bulk_callback, &ut, timeout);
  1943. retry:
  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. }
  1958. if ((err == LIBUSB_ERROR_PIPE || err == LIBUSB_TRANSFER_STALL) && ++retries < USB_RETRY_MAX) {
  1959. cgpu->usbinfo.last_pipe = time(NULL);
  1960. cgpu->usbinfo.pipe_count++;
  1961. applog(LOG_INFO, "%s%i: libusb pipe error, trying to clear",
  1962. cgpu->drv->name, cgpu->device_id);
  1963. err = libusb_clear_halt(dev_handle, endpoint);
  1964. applog(LOG_DEBUG, "%s%i: libusb pipe error%scleared",
  1965. cgpu->drv->name, cgpu->device_id, err ? " not " : " ");
  1966. if (err)
  1967. cgpu->usbinfo.clear_fail_count++;
  1968. else
  1969. goto retry;
  1970. }
  1971. if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
  1972. memcpy(data, buf, length);
  1973. return err;
  1974. }
  1975. 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)
  1976. {
  1977. struct cg_usb_device *usbdev;
  1978. bool ftdi;
  1979. struct timeval read_start, tv_finish;
  1980. unsigned int initial_timeout;
  1981. double max, done;
  1982. int bufleft, err, got, tot, pstate;
  1983. bool first = true;
  1984. char *search;
  1985. int endlen;
  1986. unsigned char *ptr, *usbbuf = cgpu->usbinfo.bulkbuf;
  1987. size_t usbbufread;
  1988. DEVRLOCK(cgpu, pstate);
  1989. if (cgpu->usbinfo.nodev) {
  1990. *buf = '\0';
  1991. *processed = 0;
  1992. USB_REJECT(cgpu, MODE_BULK_READ);
  1993. err = LIBUSB_ERROR_NO_DEVICE;
  1994. goto out_noerrmsg;
  1995. }
  1996. usbdev = cgpu->usbdev;
  1997. ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  1998. 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));
  1999. if (bufsiz > USB_MAX_READ)
  2000. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, (int)bufsiz, USB_MAX_READ);
  2001. if (timeout == DEVTIMEOUT)
  2002. timeout = usbdev->found->timeout;
  2003. if (end == NULL) {
  2004. if (usbdev->buffer && usbdev->bufamt) {
  2005. tot = usbdev->bufamt;
  2006. bufleft = bufsiz - tot;
  2007. memcpy(usbbuf, usbdev->buffer, tot);
  2008. ptr = usbbuf + tot;
  2009. usbdev->bufamt = 0;
  2010. } else {
  2011. tot = 0;
  2012. bufleft = bufsiz;
  2013. ptr = usbbuf;
  2014. }
  2015. err = LIBUSB_SUCCESS;
  2016. initial_timeout = timeout;
  2017. max = ((double)timeout) / 1000.0;
  2018. cgtime(&read_start);
  2019. while (bufleft > 0) {
  2020. // TODO: use (USB_MAX_READ - tot) always?
  2021. if (usbdev->buffer)
  2022. usbbufread = USB_MAX_READ - tot;
  2023. else {
  2024. if (ftdi)
  2025. usbbufread = bufleft + 2;
  2026. else
  2027. usbbufread = bufleft;
  2028. }
  2029. got = 0;
  2030. if (first && usbdev->usecps && usbdev->last_write_siz) {
  2031. cgtimer_t now, already_done;
  2032. double sleep_estimate;
  2033. double write_time = (double)(usbdev->last_write_siz) /
  2034. (double)(usbdev->cps);
  2035. cgtimer_time(&now);
  2036. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2037. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2038. if (sleep_estimate > 0.0) {
  2039. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2040. cgpu->usbinfo.read_delay_count++;
  2041. cgpu->usbinfo.total_read_delay += sleep_estimate;
  2042. }
  2043. }
  2044. err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
  2045. ptr, usbbufread, &got, timeout,
  2046. cgpu, MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  2047. cgtime(&tv_finish);
  2048. ptr[got] = '\0';
  2049. 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);
  2050. IOERR_CHECK(cgpu, err);
  2051. if (ftdi) {
  2052. // first 2 bytes returned are an FTDI status
  2053. if (got > 2) {
  2054. got -= 2;
  2055. memmove(ptr, ptr+2, got+1);
  2056. } else {
  2057. got = 0;
  2058. *ptr = '\0';
  2059. }
  2060. }
  2061. tot += got;
  2062. if (err || readonce)
  2063. break;
  2064. ptr += got;
  2065. bufleft -= got;
  2066. first = false;
  2067. done = tdiff(&tv_finish, &read_start);
  2068. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  2069. if (unlikely(done >= max))
  2070. break;
  2071. timeout = initial_timeout - (done * 1000);
  2072. if (!timeout)
  2073. break;
  2074. }
  2075. // N.B. usbdev->buffer was emptied before the while() loop
  2076. if (usbdev->buffer && tot > (int)bufsiz) {
  2077. usbdev->bufamt = tot - bufsiz;
  2078. memcpy(usbdev->buffer, usbbuf + bufsiz, usbdev->bufamt);
  2079. tot -= usbdev->bufamt;
  2080. usbbuf[tot] = '\0';
  2081. applog(LOG_INFO, "USB: %s%i read1 buffering %d extra bytes",
  2082. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2083. }
  2084. *processed = tot;
  2085. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2086. goto out_unlock;
  2087. }
  2088. if (usbdev->buffer && usbdev->bufamt) {
  2089. tot = usbdev->bufamt;
  2090. bufleft = bufsiz - tot;
  2091. memcpy(usbbuf, usbdev->buffer, tot);
  2092. ptr = usbbuf + tot;
  2093. usbdev->bufamt = 0;
  2094. } else {
  2095. tot = 0;
  2096. bufleft = bufsiz;
  2097. ptr = usbbuf;
  2098. }
  2099. endlen = strlen(end);
  2100. err = LIBUSB_SUCCESS;
  2101. initial_timeout = timeout;
  2102. max = ((double)timeout) / 1000.0;
  2103. cgtime(&read_start);
  2104. while (bufleft > 0) {
  2105. // TODO: use (USB_MAX_READ - tot) always?
  2106. if (usbdev->buffer)
  2107. usbbufread = USB_MAX_READ - tot;
  2108. else {
  2109. if (ftdi)
  2110. usbbufread = bufleft + 2;
  2111. else
  2112. usbbufread = bufleft;
  2113. }
  2114. got = 0;
  2115. if (first && usbdev->usecps && usbdev->last_write_siz) {
  2116. cgtimer_t now, already_done;
  2117. double sleep_estimate;
  2118. double write_time = (double)(usbdev->last_write_siz) /
  2119. (double)(usbdev->cps);
  2120. cgtimer_time(&now);
  2121. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2122. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2123. if (sleep_estimate > 0.0) {
  2124. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2125. cgpu->usbinfo.read_delay_count++;
  2126. cgpu->usbinfo.total_read_delay += sleep_estimate;
  2127. }
  2128. }
  2129. err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
  2130. ptr, usbbufread, &got, timeout,
  2131. cgpu, MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  2132. cgtime(&tv_finish);
  2133. ptr[got] = '\0';
  2134. 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);
  2135. IOERR_CHECK(cgpu, err);
  2136. if (ftdi) {
  2137. // first 2 bytes returned are an FTDI status
  2138. if (got > 2) {
  2139. got -= 2;
  2140. memmove(ptr, ptr+2, got+1);
  2141. } else {
  2142. got = 0;
  2143. *ptr = '\0';
  2144. }
  2145. }
  2146. tot += got;
  2147. if (err || readonce)
  2148. break;
  2149. if (find_end(usbbuf, ptr, got, tot, (char *)end, endlen, first))
  2150. break;
  2151. ptr += got;
  2152. bufleft -= got;
  2153. first = false;
  2154. done = tdiff(&tv_finish, &read_start);
  2155. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  2156. if (unlikely(done >= max))
  2157. break;
  2158. timeout = initial_timeout - (done * 1000);
  2159. if (!timeout)
  2160. break;
  2161. }
  2162. if (usbdev->buffer) {
  2163. bool dobuffer = false;
  2164. if ((search = find_end(usbbuf, usbbuf, tot, tot, (char *)end, endlen, true))) {
  2165. // end finishes after bufsiz
  2166. if ((search + endlen - (char *)usbbuf) > (int)bufsiz) {
  2167. usbdev->bufamt = tot - bufsiz;
  2168. dobuffer = true;
  2169. } else {
  2170. // extra data after end
  2171. if (*(search + endlen)) {
  2172. usbdev->bufamt = tot - (search + endlen - (char *)usbbuf);
  2173. dobuffer = true;
  2174. }
  2175. }
  2176. } else {
  2177. // no end, but still bigger than bufsiz
  2178. if (tot > (int)bufsiz) {
  2179. usbdev->bufamt = tot - bufsiz;
  2180. dobuffer = true;
  2181. }
  2182. }
  2183. if (dobuffer) {
  2184. tot -= usbdev->bufamt;
  2185. memcpy(usbdev->buffer, usbbuf + tot, usbdev->bufamt);
  2186. usbbuf[tot] = '\0';
  2187. applog(LOG_ERR, "USB: %s%i read2 buffering %d extra bytes",
  2188. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2189. }
  2190. }
  2191. *processed = tot;
  2192. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2193. out_unlock:
  2194. if (err && err != LIBUSB_ERROR_TIMEOUT && err != LIBUSB_TRANSFER_TIMED_OUT) {
  2195. applog(LOG_WARNING, "%s %i usb read error: %s", cgpu->drv->name, cgpu->device_id,
  2196. libusb_error_name(err));
  2197. if (cgpu->usbinfo.continuous_ioerr_count > USB_RETRY_MAX)
  2198. err = LIBUSB_ERROR_OTHER;
  2199. }
  2200. out_noerrmsg:
  2201. DEVRUNLOCK(cgpu, pstate);
  2202. if (NODEV(err))
  2203. release_cgpu(cgpu);
  2204. return err;
  2205. }
  2206. 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)
  2207. {
  2208. struct cg_usb_device *usbdev;
  2209. struct timeval read_start, tv_finish;
  2210. unsigned int initial_timeout;
  2211. double max, done;
  2212. __maybe_unused bool first = true;
  2213. int err, sent, tot, pstate;
  2214. DEVRLOCK(cgpu, pstate);
  2215. 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));
  2216. *processed = 0;
  2217. if (cgpu->usbinfo.nodev) {
  2218. USB_REJECT(cgpu, MODE_BULK_WRITE);
  2219. err = LIBUSB_ERROR_NO_DEVICE;
  2220. goto out_noerrmsg;
  2221. }
  2222. usbdev = cgpu->usbdev;
  2223. if (timeout == DEVTIMEOUT)
  2224. timeout = usbdev->found->timeout;
  2225. tot = 0;
  2226. err = LIBUSB_SUCCESS;
  2227. initial_timeout = timeout;
  2228. max = ((double)timeout) / 1000.0;
  2229. cgtime(&read_start);
  2230. while (bufsiz > 0) {
  2231. sent = 0;
  2232. if (usbdev->usecps) {
  2233. if (usbdev->last_write_siz) {
  2234. cgtimer_t now, already_done;
  2235. double sleep_estimate;
  2236. double write_time = (double)(usbdev->last_write_siz) /
  2237. (double)(usbdev->cps);
  2238. cgtimer_time(&now);
  2239. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2240. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2241. if (sleep_estimate > 0.0) {
  2242. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2243. cgpu->usbinfo.write_delay_count++;
  2244. cgpu->usbinfo.total_write_delay += sleep_estimate;
  2245. }
  2246. }
  2247. cgsleep_prepare_r(&usbdev->cgt_last_write);
  2248. usbdev->last_write_siz = bufsiz;
  2249. }
  2250. err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
  2251. (unsigned char *)buf, bufsiz, &sent, timeout,
  2252. cgpu, MODE_BULK_WRITE, cmd, first ? SEQ0 : SEQ1);
  2253. cgtime(&tv_finish);
  2254. 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);
  2255. IOERR_CHECK(cgpu, err);
  2256. tot += sent;
  2257. if (err)
  2258. break;
  2259. buf += sent;
  2260. bufsiz -= sent;
  2261. first = false;
  2262. done = tdiff(&tv_finish, &read_start);
  2263. // N.B. this is: return LIBUSB_SUCCESS with whatever size was written
  2264. if (unlikely(done >= max))
  2265. break;
  2266. timeout = initial_timeout - (done * 1000);
  2267. if (!timeout)
  2268. break;
  2269. }
  2270. *processed = tot;
  2271. if (err) {
  2272. applog(LOG_WARNING, "%s %i usb write error: %s", cgpu->drv->name, cgpu->device_id,
  2273. libusb_error_name(err));
  2274. if (cgpu->usbinfo.continuous_ioerr_count > USB_RETRY_MAX)
  2275. err = LIBUSB_ERROR_OTHER;
  2276. }
  2277. out_noerrmsg:
  2278. DEVRUNLOCK(cgpu, pstate);
  2279. if (NODEV(err))
  2280. release_cgpu(cgpu);
  2281. return err;
  2282. }
  2283. 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)
  2284. {
  2285. struct cg_usb_device *usbdev;
  2286. #if DO_USB_STATS
  2287. struct timeval tv_start, tv_finish;
  2288. #endif
  2289. unsigned char buf[64];
  2290. uint32_t *buf32 = (uint32_t *)buf;
  2291. int err, i, bufsiz;
  2292. 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));
  2293. if (cgpu->usbinfo.nodev) {
  2294. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  2295. err = LIBUSB_ERROR_NO_DEVICE;
  2296. goto out_;
  2297. }
  2298. usbdev = cgpu->usbdev;
  2299. if (timeout == DEVTIMEOUT)
  2300. timeout = usbdev->found->timeout;
  2301. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  2302. if (siz > 0) {
  2303. bufsiz = siz - 1;
  2304. bufsiz >>= 2;
  2305. bufsiz++;
  2306. for (i = 0; i < bufsiz; i++)
  2307. buf32[i] = htole32(data[i]);
  2308. }
  2309. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex(buf, (size_t)siz));
  2310. if (usbdev->usecps) {
  2311. if (usbdev->last_write_siz) {
  2312. cgtimer_t now, already_done;
  2313. double sleep_estimate;
  2314. double write_time = (double)(usbdev->last_write_siz) /
  2315. (double)(usbdev->cps);
  2316. cgtimer_time(&now);
  2317. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2318. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2319. if (sleep_estimate > 0.0) {
  2320. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2321. cgpu->usbinfo.write_delay_count++;
  2322. cgpu->usbinfo.total_write_delay += sleep_estimate;
  2323. }
  2324. }
  2325. cgsleep_prepare_r(&usbdev->cgt_last_write);
  2326. usbdev->last_write_siz = siz;
  2327. }
  2328. STATS_TIMEVAL(&tv_start);
  2329. cg_rlock(&cgusb_fd_lock);
  2330. err = libusb_control_transfer(usbdev->handle, request_type,
  2331. bRequest, wValue, wIndex, buf, (uint16_t)siz, timeout);
  2332. cg_runlock(&cgusb_fd_lock);
  2333. STATS_TIMEVAL(&tv_finish);
  2334. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0, timeout);
  2335. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  2336. IOERR_CHECK(cgpu, err);
  2337. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  2338. applog(LOG_WARNING, "%s %i usb transfer error: %s", cgpu->drv->name, cgpu->device_id,
  2339. libusb_error_name(err));
  2340. }
  2341. out_:
  2342. return err;
  2343. }
  2344. 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)
  2345. {
  2346. int pstate, err;
  2347. DEVRLOCK(cgpu, pstate);
  2348. err = __usb_transfer(cgpu, request_type, bRequest, wValue, wIndex, data, siz, timeout, cmd);
  2349. DEVRUNLOCK(cgpu, pstate);
  2350. if (NOCONTROLDEV(err))
  2351. release_cgpu(cgpu);
  2352. return err;
  2353. }
  2354. 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)
  2355. {
  2356. struct cg_usb_device *usbdev;
  2357. #if DO_USB_STATS
  2358. struct timeval tv_start, tv_finish;
  2359. #endif
  2360. unsigned char tbuf[64];
  2361. int err, pstate;
  2362. DEVRLOCK(cgpu, pstate);
  2363. 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));
  2364. if (cgpu->usbinfo.nodev) {
  2365. USB_REJECT(cgpu, MODE_CTRL_READ);
  2366. err = LIBUSB_ERROR_NO_DEVICE;
  2367. goto out_noerrmsg;
  2368. }
  2369. usbdev = cgpu->usbdev;
  2370. if (timeout == DEVTIMEOUT)
  2371. timeout = usbdev->found->timeout;
  2372. *amount = 0;
  2373. if (usbdev->usecps && usbdev->last_write_siz) {
  2374. cgtimer_t now, already_done;
  2375. double sleep_estimate;
  2376. double write_time = (double)(usbdev->last_write_siz) /
  2377. (double)(usbdev->cps);
  2378. cgtimer_time(&now);
  2379. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2380. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2381. if (sleep_estimate > 0.0) {
  2382. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2383. cgpu->usbinfo.read_delay_count++;
  2384. cgpu->usbinfo.total_read_delay += sleep_estimate;
  2385. }
  2386. }
  2387. memset(tbuf, 0, 64);
  2388. STATS_TIMEVAL(&tv_start);
  2389. cg_rlock(&cgusb_fd_lock);
  2390. err = libusb_control_transfer(usbdev->handle, request_type,
  2391. bRequest, wValue, wIndex,
  2392. tbuf, (uint16_t)bufsiz, timeout);
  2393. cg_runlock(&cgusb_fd_lock);
  2394. STATS_TIMEVAL(&tv_finish);
  2395. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0, timeout);
  2396. memcpy(buf, tbuf, bufsiz);
  2397. 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);
  2398. IOERR_CHECK(cgpu, err);
  2399. if (err > 0) {
  2400. *amount = err;
  2401. err = 0;
  2402. }
  2403. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  2404. applog(LOG_WARNING, "%s %i usb transfer read error: %s", cgpu->drv->name, cgpu->device_id,
  2405. libusb_error_name(err));
  2406. }
  2407. out_noerrmsg:
  2408. DEVRUNLOCK(cgpu, pstate);
  2409. if (NOCONTROLDEV(err))
  2410. release_cgpu(cgpu);
  2411. return err;
  2412. }
  2413. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  2414. #define FTDI_RS0_CTS (1 << 4)
  2415. #define FTDI_RS0_DSR (1 << 5)
  2416. #define FTDI_RS0_RI (1 << 6)
  2417. #define FTDI_RS0_RLSD (1 << 7)
  2418. /* Clear to send for FTDI */
  2419. int usb_ftdi_cts(struct cgpu_info *cgpu)
  2420. {
  2421. char buf[2], ret;
  2422. int err, amount;
  2423. err = _usb_transfer_read(cgpu, (uint8_t)FTDI_TYPE_IN, (uint8_t)5,
  2424. (uint16_t)0, (uint16_t)0, buf, 2,
  2425. &amount, DEVTIMEOUT, C_FTDI_STATUS);
  2426. /* We return true in case drivers are waiting indefinitely to try and
  2427. * write to something that's not there. */
  2428. if (err)
  2429. return true;
  2430. ret = buf[0] & FTDI_STATUS_B0_MASK;
  2431. return (ret & FTDI_RS0_CTS);
  2432. }
  2433. int _usb_ftdi_set_latency(struct cgpu_info *cgpu, int intinfo)
  2434. {
  2435. int err = 0;
  2436. int pstate;
  2437. DEVWLOCK(cgpu, pstate);
  2438. if (cgpu->usbdev) {
  2439. if (cgpu->usbdev->usb_type != USB_TYPE_FTDI) {
  2440. applog(LOG_ERR, "%s: cgid %d latency request on non-FTDI device",
  2441. cgpu->drv->name, cgpu->cgminer_id);
  2442. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2443. } else if (cgpu->usbdev->found->latency == LATENCY_UNUSED) {
  2444. applog(LOG_ERR, "%s: cgid %d invalid latency (UNUSED)",
  2445. cgpu->drv->name, cgpu->cgminer_id);
  2446. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2447. }
  2448. if (!err)
  2449. err = __usb_transfer(cgpu, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
  2450. cgpu->usbdev->found->latency,
  2451. USBIF(cgpu->usbdev, intinfo),
  2452. NULL, 0, DEVTIMEOUT, C_LATENCY);
  2453. }
  2454. DEVWUNLOCK(cgpu, pstate);
  2455. applog(LOG_DEBUG, "%s: cgid %d %s got err %d",
  2456. cgpu->drv->name, cgpu->cgminer_id,
  2457. usb_cmdname(C_LATENCY), err);
  2458. return err;
  2459. }
  2460. void usb_buffer_enable(struct cgpu_info *cgpu)
  2461. {
  2462. struct cg_usb_device *cgusb;
  2463. int pstate;
  2464. DEVWLOCK(cgpu, pstate);
  2465. cgusb = cgpu->usbdev;
  2466. if (cgusb && !cgusb->buffer) {
  2467. cgusb->bufamt = 0;
  2468. cgusb->buffer = malloc(USB_MAX_READ+1);
  2469. if (!cgusb->buffer)
  2470. quit(1, "Failed to malloc buffer for USB %s%i",
  2471. cgpu->drv->name, cgpu->device_id);
  2472. cgusb->bufsiz = USB_MAX_READ;
  2473. }
  2474. DEVWUNLOCK(cgpu, pstate);
  2475. }
  2476. void usb_buffer_disable(struct cgpu_info *cgpu)
  2477. {
  2478. struct cg_usb_device *cgusb;
  2479. int pstate;
  2480. DEVWLOCK(cgpu, pstate);
  2481. cgusb = cgpu->usbdev;
  2482. if (cgusb && cgusb->buffer) {
  2483. cgusb->bufamt = 0;
  2484. cgusb->bufsiz = 0;
  2485. free(cgusb->buffer);
  2486. cgusb->buffer = NULL;
  2487. }
  2488. DEVWUNLOCK(cgpu, pstate);
  2489. }
  2490. void usb_buffer_clear(struct cgpu_info *cgpu)
  2491. {
  2492. int pstate;
  2493. DEVWLOCK(cgpu, pstate);
  2494. if (cgpu->usbdev)
  2495. cgpu->usbdev->bufamt = 0;
  2496. DEVWUNLOCK(cgpu, pstate);
  2497. }
  2498. uint32_t usb_buffer_size(struct cgpu_info *cgpu)
  2499. {
  2500. uint32_t ret = 0;
  2501. int pstate;
  2502. DEVRLOCK(cgpu, pstate);
  2503. if (cgpu->usbdev)
  2504. ret = cgpu->usbdev->bufamt;
  2505. DEVRUNLOCK(cgpu, pstate);
  2506. return ret;
  2507. }
  2508. void usb_set_cps(struct cgpu_info *cgpu, int cps)
  2509. {
  2510. int pstate;
  2511. DEVWLOCK(cgpu, pstate);
  2512. if (cgpu->usbdev)
  2513. cgpu->usbdev->cps = cps;
  2514. DEVWUNLOCK(cgpu, pstate);
  2515. }
  2516. void usb_enable_cps(struct cgpu_info *cgpu)
  2517. {
  2518. int pstate;
  2519. DEVWLOCK(cgpu, pstate);
  2520. if (cgpu->usbdev)
  2521. cgpu->usbdev->usecps = true;
  2522. DEVWUNLOCK(cgpu, pstate);
  2523. }
  2524. void usb_disable_cps(struct cgpu_info *cgpu)
  2525. {
  2526. int pstate;
  2527. DEVWLOCK(cgpu, pstate);
  2528. if (cgpu->usbdev)
  2529. cgpu->usbdev->usecps = false;
  2530. DEVWUNLOCK(cgpu, pstate);
  2531. }
  2532. /*
  2533. * The value returned (0) when usbdev is NULL
  2534. * doesn't matter since it also means the next call to
  2535. * any usbutils function will fail with a nodev
  2536. * N.B. this is to get the interface number to use in a control_transfer
  2537. * which for some devices isn't actually the interface number
  2538. */
  2539. int _usb_interface(struct cgpu_info *cgpu, int intinfo)
  2540. {
  2541. int interface = 0;
  2542. int pstate;
  2543. DEVRLOCK(cgpu, pstate);
  2544. if (cgpu->usbdev)
  2545. interface = cgpu->usbdev->found->intinfos[intinfo].ctrl_transfer;
  2546. DEVRUNLOCK(cgpu, pstate);
  2547. return interface;
  2548. }
  2549. enum sub_ident usb_ident(struct cgpu_info *cgpu)
  2550. {
  2551. enum sub_ident ident = IDENT_UNK;
  2552. int pstate;
  2553. DEVRLOCK(cgpu, pstate);
  2554. if (cgpu->usbdev)
  2555. ident = cgpu->usbdev->ident;
  2556. DEVRUNLOCK(cgpu, pstate);
  2557. return ident;
  2558. }
  2559. /*
  2560. * If you pass both intinfo and epinfo as <0 then it will set all
  2561. * endpoints to PrefPacketSize
  2562. * If intinfo >=0 but epinfo <0 then it will set all endpoints
  2563. * for the given one intinfo to PrefPacketSize
  2564. * If both are >=0 then it will set only the specified single
  2565. * endpoint (intinfo,epinfo) to PrefPacketSize
  2566. */
  2567. void _usb_set_pps(struct cgpu_info *cgpu, int intinfo, int epinfo, uint16_t PrefPacketSize)
  2568. {
  2569. struct usb_find_devices *found;
  2570. int pstate;
  2571. DEVWLOCK(cgpu, pstate);
  2572. if (cgpu->usbdev) {
  2573. found = cgpu->usbdev->found;
  2574. if (intinfo >= 0 && epinfo >= 0)
  2575. found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
  2576. else {
  2577. if (intinfo >= 0) {
  2578. for (epinfo = 0; epinfo < found->intinfos[intinfo].epinfo_count; epinfo++)
  2579. found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
  2580. } else {
  2581. for (intinfo = 0; intinfo < found->intinfo_count ; intinfo++)
  2582. for (epinfo = 0; epinfo < found->intinfos[intinfo].epinfo_count; epinfo++)
  2583. found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
  2584. }
  2585. }
  2586. }
  2587. DEVWUNLOCK(cgpu, pstate);
  2588. }
  2589. // Need to set all devices with matching usbdev
  2590. void usb_set_dev_start(struct cgpu_info *cgpu)
  2591. {
  2592. struct cg_usb_device *cgusb;
  2593. struct cgpu_info *cgpu2;
  2594. struct timeval now;
  2595. int pstate;
  2596. DEVWLOCK(cgpu, pstate);
  2597. cgusb = cgpu->usbdev;
  2598. // If the device wasn't dropped
  2599. if (cgusb != NULL) {
  2600. int i;
  2601. cgtime(&now);
  2602. for (i = 0; i < total_devices; i++) {
  2603. cgpu2 = get_devices(i);
  2604. if (cgpu2->usbdev == cgusb)
  2605. copy_time(&(cgpu2->dev_start_tv), &now);
  2606. }
  2607. }
  2608. DEVWUNLOCK(cgpu, pstate);
  2609. }
  2610. void usb_cleanup(void)
  2611. {
  2612. struct cgpu_info *cgpu;
  2613. int count;
  2614. int i;
  2615. hotplug_time = 0;
  2616. cgsleep_ms(10);
  2617. count = 0;
  2618. for (i = 0; i < total_devices; i++) {
  2619. cgpu = devices[i];
  2620. switch (cgpu->drv->drv_id) {
  2621. case DRIVER_bflsc:
  2622. case DRIVER_bitforce:
  2623. case DRIVER_bitfury:
  2624. case DRIVER_modminer:
  2625. case DRIVER_icarus:
  2626. case DRIVER_avalon:
  2627. case DRIVER_klondike:
  2628. release_cgpu(cgpu);
  2629. count++;
  2630. break;
  2631. default:
  2632. break;
  2633. }
  2634. }
  2635. /*
  2636. * Must attempt to wait for the resource thread to release coz
  2637. * during a restart it won't automatically release them in linux
  2638. */
  2639. if (count) {
  2640. struct timeval start, now;
  2641. cgtime(&start);
  2642. while (42) {
  2643. cgsleep_ms(50);
  2644. mutex_lock(&cgusbres_lock);
  2645. if (!res_work_head)
  2646. break;
  2647. cgtime(&now);
  2648. if (tdiff(&now, &start) > 0.366) {
  2649. applog(LOG_WARNING,
  2650. "usb_cleanup gave up waiting for resource thread");
  2651. break;
  2652. }
  2653. mutex_unlock(&cgusbres_lock);
  2654. }
  2655. mutex_unlock(&cgusbres_lock);
  2656. }
  2657. cgsem_destroy(&usb_resource_sem);
  2658. }
  2659. #define DRIVER_COUNT_FOUND(X) if (strcasecmp(ptr, X##_drv.name) == 0) { \
  2660. drv_count[X##_drv.drv_id].limit = lim; \
  2661. found = true; \
  2662. }
  2663. void usb_initialise()
  2664. {
  2665. char *fre, *ptr, *comma, *colon;
  2666. int bus, dev, lim, i;
  2667. bool found;
  2668. for (i = 0; i < DRIVER_MAX; i++) {
  2669. drv_count[i].count = 0;
  2670. drv_count[i].limit = 999999;
  2671. }
  2672. cgusb_check_init();
  2673. if (opt_usb_select && *opt_usb_select) {
  2674. // Absolute device limit
  2675. if (*opt_usb_select == ':') {
  2676. total_limit = atoi(opt_usb_select+1);
  2677. if (total_limit < 0)
  2678. quit(1, "Invalid --usb total limit");
  2679. // Comma list of bus:dev devices to match
  2680. } else if (isdigit(*opt_usb_select)) {
  2681. fre = ptr = strdup(opt_usb_select);
  2682. do {
  2683. comma = strchr(ptr, ',');
  2684. if (comma)
  2685. *(comma++) = '\0';
  2686. colon = strchr(ptr, ':');
  2687. if (!colon)
  2688. quit(1, "Invalid --usb bus:dev missing ':'");
  2689. *(colon++) = '\0';
  2690. if (!isdigit(*ptr))
  2691. quit(1, "Invalid --usb bus:dev - bus must be a number");
  2692. if (!isdigit(*colon) && *colon != '*')
  2693. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  2694. bus = atoi(ptr);
  2695. if (bus <= 0)
  2696. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  2697. if (*colon == '*')
  2698. dev = -1;
  2699. else {
  2700. dev = atoi(colon);
  2701. if (dev <= 0)
  2702. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  2703. }
  2704. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  2705. if (unlikely(!busdev))
  2706. quit(1, "USB failed to realloc busdev");
  2707. busdev[busdev_count-1].bus_number = bus;
  2708. busdev[busdev_count-1].device_address = dev;
  2709. ptr = comma;
  2710. } while (ptr);
  2711. free(fre);
  2712. // Comma list of DRV:limit
  2713. } else {
  2714. fre = ptr = strdup(opt_usb_select);
  2715. do {
  2716. comma = strchr(ptr, ',');
  2717. if (comma)
  2718. *(comma++) = '\0';
  2719. colon = strchr(ptr, ':');
  2720. if (!colon)
  2721. quit(1, "Invalid --usb DRV:limit missing ':'");
  2722. *(colon++) = '\0';
  2723. if (!isdigit(*colon))
  2724. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  2725. lim = atoi(colon);
  2726. if (lim < 0)
  2727. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  2728. found = false;
  2729. /* Use the DRIVER_PARSE_COMMANDS macro to iterate
  2730. * over all the drivers. */
  2731. DRIVER_PARSE_COMMANDS(DRIVER_COUNT_FOUND)
  2732. if (!found)
  2733. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  2734. ptr = comma;
  2735. } while (ptr);
  2736. free(fre);
  2737. }
  2738. }
  2739. }
  2740. #ifndef WIN32
  2741. #include <errno.h>
  2742. #include <unistd.h>
  2743. #include <sys/types.h>
  2744. #include <sys/ipc.h>
  2745. #include <sys/sem.h>
  2746. #include <sys/stat.h>
  2747. #include <fcntl.h>
  2748. #ifndef __APPLE__
  2749. union semun {
  2750. int val;
  2751. struct semid_ds *buf;
  2752. unsigned short *array;
  2753. struct seminfo *__buf;
  2754. };
  2755. #endif
  2756. #else
  2757. static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
  2758. {
  2759. FreeSid(((PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor))->Group);
  2760. free(sec->lpSecurityDescriptor);
  2761. free(sec);
  2762. return NULL;
  2763. }
  2764. static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
  2765. {
  2766. SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
  2767. PSID gsid = NULL;
  2768. LPSECURITY_ATTRIBUTES sec_att = NULL;
  2769. PSECURITY_DESCRIPTOR sec_des = NULL;
  2770. sec_des = malloc(sizeof(*sec_des));
  2771. if (unlikely(!sec_des))
  2772. quit(1, "MTX: Failed to malloc LPSECURITY_DESCRIPTOR");
  2773. if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
  2774. applog(LOG_ERR,
  2775. "MTX: %s (%d:%d) USB failed to init secdes err (%d)",
  2776. dname, (int)bus_number, (int)device_address,
  2777. (int)GetLastError());
  2778. free(sec_des);
  2779. return NULL;
  2780. }
  2781. if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
  2782. applog(LOG_ERR,
  2783. "MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
  2784. dname, (int)bus_number, (int)device_address,
  2785. (int)GetLastError());
  2786. free(sec_des);
  2787. return NULL;
  2788. }
  2789. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
  2790. applog(LOG_ERR,
  2791. "MTX: %s (%d:%d) USB failed to create gsid err (%d)",
  2792. dname, (int)bus_number, (int)device_address,
  2793. (int)GetLastError());
  2794. free(sec_des);
  2795. return NULL;
  2796. }
  2797. if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
  2798. applog(LOG_ERR,
  2799. "MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
  2800. dname, (int)bus_number, (int)device_address,
  2801. (int)GetLastError());
  2802. FreeSid(gsid);
  2803. free(sec_des);
  2804. return NULL;
  2805. }
  2806. sec_att = malloc(sizeof(*sec_att));
  2807. if (unlikely(!sec_att))
  2808. quit(1, "MTX: Failed to malloc LPSECURITY_ATTRIBUTES");
  2809. sec_att->nLength = sizeof(*sec_att);
  2810. sec_att->lpSecurityDescriptor = sec_des;
  2811. sec_att->bInheritHandle = FALSE;
  2812. return sec_att;
  2813. }
  2814. #endif
  2815. // Any errors should always be printed since they will rarely if ever occur
  2816. // and thus it is best to always display them
  2817. static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2818. {
  2819. applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2820. #ifdef WIN32
  2821. struct cgpu_info *cgpu;
  2822. LPSECURITY_ATTRIBUTES sec;
  2823. HANDLE usbMutex;
  2824. char name[64];
  2825. DWORD res;
  2826. int i;
  2827. if (is_in_use_bd(bus_number, device_address))
  2828. return false;
  2829. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2830. sec = mksec(dname, bus_number, device_address);
  2831. if (!sec)
  2832. return false;
  2833. usbMutex = CreateMutex(sec, FALSE, name);
  2834. if (usbMutex == NULL) {
  2835. applog(LOG_ERR,
  2836. "MTX: %s USB failed to get '%s' err (%d)",
  2837. dname, name, (int)GetLastError());
  2838. sec = unsec(sec);
  2839. return false;
  2840. }
  2841. res = WaitForSingleObject(usbMutex, 0);
  2842. switch(res) {
  2843. case WAIT_OBJECT_0:
  2844. case WAIT_ABANDONED:
  2845. // Am I using it already?
  2846. for (i = 0; i < total_devices; i++) {
  2847. cgpu = get_devices(i);
  2848. if (cgpu->usbinfo.bus_number == bus_number &&
  2849. cgpu->usbinfo.device_address == device_address &&
  2850. cgpu->usbinfo.nodev == false) {
  2851. if (ReleaseMutex(usbMutex)) {
  2852. applog(LOG_WARNING,
  2853. "MTX: %s USB can't get '%s' - device in use",
  2854. dname, name);
  2855. goto fail;
  2856. }
  2857. applog(LOG_ERR,
  2858. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  2859. dname, name, (int)GetLastError());
  2860. goto fail;
  2861. }
  2862. }
  2863. break;
  2864. case WAIT_TIMEOUT:
  2865. if (!hotplug_mode)
  2866. applog(LOG_WARNING,
  2867. "MTX: %s USB failed to get '%s' - device in use",
  2868. dname, name);
  2869. goto fail;
  2870. case WAIT_FAILED:
  2871. applog(LOG_ERR,
  2872. "MTX: %s USB failed to get '%s' err (%d)",
  2873. dname, name, (int)GetLastError());
  2874. goto fail;
  2875. default:
  2876. applog(LOG_ERR,
  2877. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  2878. dname, name, (int)res);
  2879. goto fail;
  2880. }
  2881. add_in_use(bus_number, device_address);
  2882. in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
  2883. return true;
  2884. fail:
  2885. CloseHandle(usbMutex);
  2886. sec = unsec(sec);
  2887. return false;
  2888. #else
  2889. struct semid_ds seminfo;
  2890. union semun opt;
  2891. char name[64];
  2892. key_t *key;
  2893. int *sem;
  2894. int fd, count;
  2895. if (is_in_use_bd(bus_number, device_address))
  2896. return false;
  2897. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2898. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2899. if (fd == -1) {
  2900. applog(LOG_ERR,
  2901. "SEM: %s USB open failed '%s' err (%d) %s",
  2902. dname, name, errno, strerror(errno));
  2903. goto _out;
  2904. }
  2905. close(fd);
  2906. key = malloc(sizeof(*key));
  2907. if (unlikely(!key))
  2908. quit(1, "SEM: Failed to malloc key");
  2909. sem = malloc(sizeof(*sem));
  2910. if (unlikely(!sem))
  2911. quit(1, "SEM: Failed to malloc sem");
  2912. *key = ftok(name, 'K');
  2913. *sem = semget(*key, 1, IPC_CREAT | IPC_EXCL | 438);
  2914. if (*sem < 0) {
  2915. if (errno != EEXIST) {
  2916. applog(LOG_ERR,
  2917. "SEM: %s USB failed to get '%s' err (%d) %s",
  2918. dname, name, errno, strerror(errno));
  2919. goto free_out;
  2920. }
  2921. *sem = semget(*key, 1, 0);
  2922. if (*sem < 0) {
  2923. applog(LOG_ERR,
  2924. "SEM: %s USB failed to access '%s' err (%d) %s",
  2925. dname, name, errno, strerror(errno));
  2926. goto free_out;
  2927. }
  2928. opt.buf = &seminfo;
  2929. count = 0;
  2930. while (++count) {
  2931. // Should NEVER take 100ms
  2932. if (count > 99) {
  2933. applog(LOG_ERR,
  2934. "SEM: %s USB timeout waiting for (%d) '%s'",
  2935. dname, *sem, name);
  2936. goto free_out;
  2937. }
  2938. if (semctl(*sem, 0, IPC_STAT, opt) == -1) {
  2939. applog(LOG_ERR,
  2940. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  2941. dname, *sem, name, count, errno, strerror(errno));
  2942. goto free_out;
  2943. }
  2944. if (opt.buf->sem_otime != 0)
  2945. break;
  2946. cgsleep_ms(1);
  2947. }
  2948. }
  2949. struct sembuf sops[] = {
  2950. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  2951. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  2952. };
  2953. if (semop(*sem, sops, 2)) {
  2954. if (errno == EAGAIN) {
  2955. if (!hotplug_mode)
  2956. applog(LOG_WARNING,
  2957. "SEM: %s USB failed to get (%d) '%s' - device in use",
  2958. dname, *sem, name);
  2959. } else {
  2960. applog(LOG_DEBUG,
  2961. "SEM: %s USB failed to get (%d) '%s' err (%d) %s",
  2962. dname, *sem, name, errno, strerror(errno));
  2963. }
  2964. goto free_out;
  2965. }
  2966. add_in_use(bus_number, device_address);
  2967. in_use_store_ress(bus_number, device_address, (void *)key, (void *)sem);
  2968. return true;
  2969. free_out:
  2970. free(sem);
  2971. free(key);
  2972. _out:
  2973. return false;
  2974. #endif
  2975. }
  2976. // Any errors should always be printed since they will rarely if ever occur
  2977. // and thus it is best to always display them
  2978. static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2979. {
  2980. applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2981. #ifdef WIN32
  2982. LPSECURITY_ATTRIBUTES sec = NULL;
  2983. HANDLE usbMutex = NULL;
  2984. char name[64];
  2985. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2986. in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
  2987. if (!usbMutex || !sec)
  2988. goto fila;
  2989. if (!ReleaseMutex(usbMutex))
  2990. applog(LOG_ERR,
  2991. "MTX: %s USB failed to release '%s' err (%d)",
  2992. dname, name, (int)GetLastError());
  2993. fila:
  2994. if (usbMutex)
  2995. CloseHandle(usbMutex);
  2996. if (sec)
  2997. unsec(sec);
  2998. remove_in_use(bus_number, device_address);
  2999. return;
  3000. #else
  3001. char name[64];
  3002. key_t *key = NULL;
  3003. int *sem = NULL;
  3004. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  3005. in_use_get_ress(bus_number, device_address, (void **)(&key), (void **)(&sem));
  3006. if (!key || !sem)
  3007. goto fila;
  3008. struct sembuf sops[] = {
  3009. { 0, -1, SEM_UNDO }
  3010. };
  3011. // Allow a 10ms timeout
  3012. // exceeding this timeout means it would probably never succeed anyway
  3013. struct timespec timeout = { 0, 10000000 };
  3014. if (semtimedop(*sem, sops, 1, &timeout)) {
  3015. applog(LOG_ERR,
  3016. "SEM: %s USB failed to release '%s' err (%d) %s",
  3017. dname, name, errno, strerror(errno));
  3018. }
  3019. if (semctl(*sem, 0, IPC_RMID)) {
  3020. applog(LOG_WARNING,
  3021. "SEM: %s USB failed to remove SEM '%s' err (%d) %s",
  3022. dname, name, errno, strerror(errno));
  3023. }
  3024. fila:
  3025. free(sem);
  3026. free(key);
  3027. remove_in_use(bus_number, device_address);
  3028. return;
  3029. #endif
  3030. }
  3031. static void resource_process()
  3032. {
  3033. struct resource_work *res_work = NULL;
  3034. struct resource_reply *res_reply = NULL;
  3035. bool ok;
  3036. applog(LOG_DEBUG, "RES: %s (%d:%d) lock=%d",
  3037. res_work_head->dname,
  3038. (int)res_work_head->bus_number,
  3039. (int)res_work_head->device_address,
  3040. res_work_head->lock);
  3041. if (res_work_head->lock) {
  3042. ok = resource_lock(res_work_head->dname,
  3043. res_work_head->bus_number,
  3044. res_work_head->device_address);
  3045. applog(LOG_DEBUG, "RES: %s (%d:%d) lock ok=%d",
  3046. res_work_head->dname,
  3047. (int)res_work_head->bus_number,
  3048. (int)res_work_head->device_address,
  3049. ok);
  3050. res_reply = calloc(1, sizeof(*res_reply));
  3051. if (unlikely(!res_reply))
  3052. quit(1, "USB failed to calloc res_reply");
  3053. res_reply->bus_number = res_work_head->bus_number;
  3054. res_reply->device_address = res_work_head->device_address;
  3055. res_reply->got = ok;
  3056. res_reply->next = res_reply_head;
  3057. res_reply_head = res_reply;
  3058. }
  3059. else
  3060. resource_unlock(res_work_head->dname,
  3061. res_work_head->bus_number,
  3062. res_work_head->device_address);
  3063. res_work = res_work_head;
  3064. res_work_head = res_work_head->next;
  3065. free(res_work);
  3066. }
  3067. void *usb_resource_thread(void __maybe_unused *userdata)
  3068. {
  3069. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3070. RenameThread("usbresource");
  3071. applog(LOG_DEBUG, "RES: thread starting");
  3072. while (42) {
  3073. /* Wait to be told we have work to do */
  3074. cgsem_wait(&usb_resource_sem);
  3075. mutex_lock(&cgusbres_lock);
  3076. while (res_work_head)
  3077. resource_process();
  3078. mutex_unlock(&cgusbres_lock);
  3079. }
  3080. return NULL;
  3081. }