usbutils.c 87 KB

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