usbutils.c 97 KB

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