usbutils.c 92 KB

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