usbutils.c 96 KB

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