usbutils.c 95 KB

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