usbutils.c 84 KB

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