usbutils.c 95 KB

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