usbutils.c 93 KB

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