usbutils.c 98 KB

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