usbutils.c 105 KB

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