usbutils.c 95 KB

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