usbutils.c 81 KB

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