usbutils.c 78 KB

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