usbutils.c 96 KB

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