usbutils.c 99 KB

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