usbutils.c 98 KB

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