usbutils.c 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418
  1. /*
  2. * Copyright 2012-2013 Andrew Smith
  3. * Copyright 2013 Con Kolivas <kernel@kolivas.org>
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 3 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <ctype.h>
  12. #include <stdint.h>
  13. #include <stdbool.h>
  14. #include "logging.h"
  15. #include "miner.h"
  16. #include "usbutils.h"
  17. #define NODEV(err) ((err) == LIBUSB_ERROR_NO_DEVICE || \
  18. (err) == LIBUSB_ERROR_PIPE || \
  19. (err) == LIBUSB_ERROR_OTHER)
  20. #define NOCONTROLDEV(err) ((err) == LIBUSB_ERROR_NO_DEVICE || \
  21. (err) == LIBUSB_ERROR_OTHER)
  22. #ifdef USE_BFLSC
  23. #define DRV_BFLSC 1
  24. #endif
  25. #ifdef USE_BITFORCE
  26. #define DRV_BITFORCE 2
  27. #endif
  28. #ifdef USE_MODMINER
  29. #define DRV_MODMINER 3
  30. #endif
  31. #ifdef USE_ZTEX
  32. #define DRV_ZTEX 4
  33. #endif
  34. #ifdef USE_ICARUS
  35. #define DRV_ICARUS 5
  36. #endif
  37. #ifdef USE_AVALON
  38. #define DRV_AVALON 6
  39. #endif
  40. #define DRV_LAST -1
  41. #define USB_CONFIG 1
  42. #ifdef WIN32
  43. #define BFLSC_TIMEOUT_MS 999
  44. #define BITFORCE_TIMEOUT_MS 999
  45. #define MODMINER_TIMEOUT_MS 999
  46. #define AVALON_TIMEOUT_MS 999
  47. #define ICARUS_TIMEOUT_MS 999
  48. #else
  49. #define BFLSC_TIMEOUT_MS 300
  50. #define BITFORCE_TIMEOUT_MS 200
  51. #define MODMINER_TIMEOUT_MS 100
  52. #define AVALON_TIMEOUT_MS 200
  53. #define ICARUS_TIMEOUT_MS 200
  54. #endif
  55. #define USB_READ_MINPOLL 40
  56. #ifdef USE_BFLSC
  57. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  58. static struct usb_endpoints bas_eps[] = {
  59. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  60. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  61. };
  62. #endif
  63. #ifdef USE_BITFORCE
  64. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  65. static struct usb_endpoints bfl_eps[] = {
  66. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  67. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  68. };
  69. #endif
  70. #ifdef USE_MODMINER
  71. static struct usb_endpoints mmq_eps[] = {
  72. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  73. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0 }
  74. };
  75. #endif
  76. #ifdef USE_AVALON
  77. static struct usb_endpoints ava_eps[] = {
  78. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  79. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  80. };
  81. #endif
  82. #ifdef USE_ICARUS
  83. static struct usb_endpoints ica_eps[] = {
  84. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  85. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  86. };
  87. static struct usb_endpoints amu_eps[] = {
  88. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  89. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0 }
  90. };
  91. static struct usb_endpoints llt_eps[] = {
  92. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  93. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  94. };
  95. static struct usb_endpoints cmr1_eps[] = {
  96. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  97. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  98. /*
  99. Interface 1
  100. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  101. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(4), 0 },
  102. Interface 2
  103. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(5), 0 },
  104. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(6), 0 },
  105. Interface 3
  106. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(7), 0 },
  107. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(8), 0 }
  108. */
  109. };
  110. static struct usb_endpoints cmr2_eps[] = {
  111. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  112. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  113. };
  114. #endif
  115. #define IDVENDOR_FTDI 0x0403
  116. // TODO: Add support for (at least) Isochronous endpoints
  117. static struct usb_find_devices find_dev[] = {
  118. #ifdef USE_BFLSC
  119. {
  120. .drv = DRV_BFLSC,
  121. .name = "BAS",
  122. .ident = IDENT_BAS,
  123. .idVendor = IDVENDOR_FTDI,
  124. .idProduct = 0x6014,
  125. .iManufacturer = "Butterfly Labs",
  126. .iProduct = "BitFORCE SHA256 SC",
  127. .kernel = 0,
  128. .config = 1,
  129. .interface = 0,
  130. .timeout = BFLSC_TIMEOUT_MS,
  131. .latency = LATENCY_STD,
  132. .epcount = ARRAY_SIZE(bas_eps),
  133. .eps = bas_eps },
  134. #endif
  135. #ifdef USE_BITFORCE
  136. {
  137. .drv = DRV_BITFORCE,
  138. .name = "BFL",
  139. .ident = IDENT_BFL,
  140. .idVendor = IDVENDOR_FTDI,
  141. .idProduct = 0x6014,
  142. .iManufacturer = "Butterfly Labs Inc.",
  143. .iProduct = "BitFORCE SHA256",
  144. .kernel = 0,
  145. .config = 1,
  146. .interface = 0,
  147. .timeout = BITFORCE_TIMEOUT_MS,
  148. .latency = LATENCY_STD,
  149. .epcount = ARRAY_SIZE(bfl_eps),
  150. .eps = bfl_eps },
  151. #endif
  152. #ifdef USE_MODMINER
  153. {
  154. .drv = DRV_MODMINER,
  155. .name = "MMQ",
  156. .ident = IDENT_MMQ,
  157. .idVendor = 0x1fc9,
  158. .idProduct = 0x0003,
  159. .kernel = 0,
  160. .config = 1,
  161. .interface = 1,
  162. .timeout = MODMINER_TIMEOUT_MS,
  163. .latency = LATENCY_UNUSED,
  164. .epcount = ARRAY_SIZE(mmq_eps),
  165. .eps = mmq_eps },
  166. #endif
  167. #ifdef USE_AVALON
  168. {
  169. .drv = DRV_AVALON,
  170. .name = "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, 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. static void in_use_store_ress(uint8_t bus_number, uint8_t device_address, void *resource1, void *resource2)
  930. {
  931. struct usb_in_use_list *in_use_tmp;
  932. bool found = false, empty = true;
  933. mutex_lock(&cgusb_lock);
  934. in_use_tmp = in_use_head;
  935. while (in_use_tmp) {
  936. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  937. in_use_tmp->in_use.device_address == (int)device_address) {
  938. found = true;
  939. if (in_use_tmp->in_use.resource1)
  940. empty = false;
  941. in_use_tmp->in_use.resource1 = resource1;
  942. if (in_use_tmp->in_use.resource2)
  943. empty = false;
  944. in_use_tmp->in_use.resource2 = resource2;
  945. break;
  946. }
  947. in_use_tmp = in_use_tmp->next;
  948. }
  949. mutex_unlock(&cgusb_lock);
  950. if (found == false)
  951. applog(LOG_ERR, "FAIL: USB store_ress not found (%d:%d)",
  952. (int)bus_number, (int)device_address);
  953. if (empty == false)
  954. applog(LOG_ERR, "FAIL: USB store_ress not empty (%d:%d)",
  955. (int)bus_number, (int)device_address);
  956. }
  957. static void in_use_get_ress(uint8_t bus_number, uint8_t device_address, void **resource1, void **resource2)
  958. {
  959. struct usb_in_use_list *in_use_tmp;
  960. bool found = false, empty = false;
  961. mutex_lock(&cgusb_lock);
  962. in_use_tmp = in_use_head;
  963. while (in_use_tmp) {
  964. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  965. in_use_tmp->in_use.device_address == (int)device_address) {
  966. found = true;
  967. if (!in_use_tmp->in_use.resource1)
  968. empty = true;
  969. *resource1 = in_use_tmp->in_use.resource1;
  970. in_use_tmp->in_use.resource1 = NULL;
  971. if (!in_use_tmp->in_use.resource2)
  972. empty = true;
  973. *resource2 = in_use_tmp->in_use.resource2;
  974. in_use_tmp->in_use.resource2 = NULL;
  975. break;
  976. }
  977. in_use_tmp = in_use_tmp->next;
  978. }
  979. mutex_unlock(&cgusb_lock);
  980. if (found == false)
  981. applog(LOG_ERR, "FAIL: USB get_lock not found (%d:%d)",
  982. (int)bus_number, (int)device_address);
  983. if (empty == true)
  984. applog(LOG_ERR, "FAIL: USB get_lock empty (%d:%d)",
  985. (int)bus_number, (int)device_address);
  986. }
  987. static bool __is_in_use(uint8_t bus_number, uint8_t device_address)
  988. {
  989. struct usb_in_use_list *in_use_tmp;
  990. bool ret = false;
  991. in_use_tmp = in_use_head;
  992. while (in_use_tmp) {
  993. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  994. in_use_tmp->in_use.device_address == (int)device_address) {
  995. ret = true;
  996. break;
  997. }
  998. in_use_tmp = in_use_tmp->next;
  999. }
  1000. return ret;
  1001. }
  1002. static bool is_in_use_bd(uint8_t bus_number, uint8_t device_address)
  1003. {
  1004. bool ret;
  1005. mutex_lock(&cgusb_lock);
  1006. ret = __is_in_use(bus_number, device_address);
  1007. mutex_unlock(&cgusb_lock);
  1008. return ret;
  1009. }
  1010. static bool is_in_use(libusb_device *dev)
  1011. {
  1012. return is_in_use_bd(libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1013. }
  1014. static void add_in_use(uint8_t bus_number, uint8_t device_address)
  1015. {
  1016. struct usb_in_use_list *in_use_tmp;
  1017. bool found = false;
  1018. mutex_lock(&cgusb_lock);
  1019. if (unlikely(__is_in_use(bus_number, device_address))) {
  1020. found = true;
  1021. goto nofway;
  1022. }
  1023. in_use_tmp = calloc(1, sizeof(*in_use_tmp));
  1024. if (unlikely(!in_use_tmp))
  1025. quit(1, "USB failed to calloc in_use_tmp");
  1026. in_use_tmp->in_use.bus_number = (int)bus_number;
  1027. in_use_tmp->in_use.device_address = (int)device_address;
  1028. in_use_tmp->next = in_use_head;
  1029. if (in_use_head)
  1030. in_use_head->prev = in_use_tmp;
  1031. in_use_head = in_use_tmp;
  1032. nofway:
  1033. mutex_unlock(&cgusb_lock);
  1034. if (found)
  1035. applog(LOG_ERR, "FAIL: USB add already in use (%d:%d)",
  1036. (int)bus_number, (int)device_address);
  1037. }
  1038. static void remove_in_use(uint8_t bus_number, uint8_t device_address)
  1039. {
  1040. struct usb_in_use_list *in_use_tmp;
  1041. bool found = false;
  1042. mutex_lock(&cgusb_lock);
  1043. in_use_tmp = in_use_head;
  1044. while (in_use_tmp) {
  1045. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  1046. in_use_tmp->in_use.device_address == (int)device_address) {
  1047. found = true;
  1048. if (in_use_tmp == in_use_head) {
  1049. in_use_head = in_use_head->next;
  1050. if (in_use_head)
  1051. in_use_head->prev = NULL;
  1052. } else {
  1053. in_use_tmp->prev->next = in_use_tmp->next;
  1054. if (in_use_tmp->next)
  1055. in_use_tmp->next->prev = in_use_tmp->prev;
  1056. }
  1057. free(in_use_tmp);
  1058. break;
  1059. }
  1060. in_use_tmp = in_use_tmp->next;
  1061. }
  1062. mutex_unlock(&cgusb_lock);
  1063. if (!found)
  1064. applog(LOG_ERR, "FAIL: USB remove not already in use (%d:%d)",
  1065. (int)bus_number, (int)device_address);
  1066. }
  1067. static bool cgminer_usb_lock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  1068. {
  1069. struct resource_work *res_work;
  1070. bool ret;
  1071. applog(LOG_DEBUG, "USB lock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
  1072. res_work = calloc(1, sizeof(*res_work));
  1073. if (unlikely(!res_work))
  1074. quit(1, "USB failed to calloc lock res_work");
  1075. res_work->lock = true;
  1076. res_work->dname = (const char *)(drv->dname);
  1077. res_work->bus_number = bus_number;
  1078. res_work->device_address = device_address;
  1079. mutex_lock(&cgusbres_lock);
  1080. res_work->next = res_work_head;
  1081. res_work_head = res_work;
  1082. mutex_unlock(&cgusbres_lock);
  1083. cgsem_post(&usb_resource_sem);
  1084. // TODO: add a timeout fail - restart the resource thread?
  1085. while (true) {
  1086. nmsleep(50);
  1087. mutex_lock(&cgusbres_lock);
  1088. if (res_reply_head) {
  1089. struct resource_reply *res_reply_prev = NULL;
  1090. struct resource_reply *res_reply = res_reply_head;
  1091. while (res_reply) {
  1092. if (res_reply->bus_number == bus_number &&
  1093. res_reply->device_address == device_address) {
  1094. if (res_reply_prev)
  1095. res_reply_prev->next = res_reply->next;
  1096. else
  1097. res_reply_head = res_reply->next;
  1098. mutex_unlock(&cgusbres_lock);
  1099. ret = res_reply->got;
  1100. free(res_reply);
  1101. return ret;
  1102. }
  1103. res_reply_prev = res_reply;
  1104. res_reply = res_reply->next;
  1105. }
  1106. }
  1107. mutex_unlock(&cgusbres_lock);
  1108. }
  1109. }
  1110. static bool cgminer_usb_lock(struct device_drv *drv, libusb_device *dev)
  1111. {
  1112. return cgminer_usb_lock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1113. }
  1114. static void cgminer_usb_unlock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  1115. {
  1116. struct resource_work *res_work;
  1117. applog(LOG_DEBUG, "USB unlock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
  1118. res_work = calloc(1, sizeof(*res_work));
  1119. if (unlikely(!res_work))
  1120. quit(1, "USB failed to calloc unlock res_work");
  1121. res_work->lock = false;
  1122. res_work->dname = (const char *)(drv->dname);
  1123. res_work->bus_number = bus_number;
  1124. res_work->device_address = device_address;
  1125. mutex_lock(&cgusbres_lock);
  1126. res_work->next = res_work_head;
  1127. res_work_head = res_work;
  1128. mutex_unlock(&cgusbres_lock);
  1129. cgsem_post(&usb_resource_sem);
  1130. return;
  1131. }
  1132. static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
  1133. {
  1134. cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1135. }
  1136. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  1137. {
  1138. applog(LOG_DEBUG, "USB free %s", cgusb->found->name);
  1139. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  1140. free(cgusb->serial_string);
  1141. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  1142. free(cgusb->manuf_string);
  1143. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  1144. free(cgusb->prod_string);
  1145. free(cgusb->descriptor);
  1146. free(cgusb->found);
  1147. if (cgusb->buffer)
  1148. free(cgusb->buffer);
  1149. free(cgusb);
  1150. return NULL;
  1151. }
  1152. void usb_uninit(struct cgpu_info *cgpu)
  1153. {
  1154. applog(LOG_DEBUG, "USB uninit %s%i",
  1155. cgpu->drv->name, cgpu->device_id);
  1156. // May have happened already during a failed initialisation
  1157. // if release_cgpu() was called due to a USB NODEV(err)
  1158. if (!cgpu->usbdev)
  1159. return;
  1160. if (!libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface)) {
  1161. cg_wlock(&cgusb_fd_lock);
  1162. libusb_close(cgpu->usbdev->handle);
  1163. cg_wunlock(&cgusb_fd_lock);
  1164. }
  1165. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  1166. }
  1167. /*
  1168. * N.B. this is always called inside
  1169. * DEVLOCK(cgpu, pstate);
  1170. */
  1171. static void release_cgpu(struct cgpu_info *cgpu)
  1172. {
  1173. struct cg_usb_device *cgusb = cgpu->usbdev;
  1174. struct cgpu_info *lookcgpu;
  1175. int i;
  1176. applog(LOG_DEBUG, "USB release %s%i",
  1177. cgpu->drv->name, cgpu->device_id);
  1178. // It has already been done
  1179. if (cgpu->usbinfo.nodev)
  1180. return;
  1181. zombie_devs++;
  1182. total_count--;
  1183. drv_count[cgpu->drv->drv_id].count--;
  1184. cgpu->usbinfo.nodev = true;
  1185. cgpu->usbinfo.nodev_count++;
  1186. cgtime(&cgpu->usbinfo.last_nodev);
  1187. // Any devices sharing the same USB device should be marked also
  1188. // Currently only MMQ shares a USB device
  1189. for (i = 0; i < total_devices; i++) {
  1190. lookcgpu = get_devices(i);
  1191. if (lookcgpu != cgpu && lookcgpu->usbdev == cgusb) {
  1192. total_count--;
  1193. drv_count[lookcgpu->drv->drv_id].count--;
  1194. lookcgpu->usbinfo.nodev = true;
  1195. lookcgpu->usbinfo.nodev_count++;
  1196. memcpy(&(lookcgpu->usbinfo.last_nodev),
  1197. &(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
  1198. lookcgpu->usbdev = NULL;
  1199. }
  1200. }
  1201. usb_uninit(cgpu);
  1202. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1203. }
  1204. // Currently only used by MMQ
  1205. struct cgpu_info *usb_copy_cgpu(struct cgpu_info *orig)
  1206. {
  1207. struct cgpu_info *copy = calloc(1, sizeof(*copy));
  1208. if (unlikely(!copy))
  1209. quit(1, "Failed to calloc cgpu for %s in usb_copy_cgpu", orig->drv->dname);
  1210. copy->name = orig->name;
  1211. copy->drv = copy_drv(orig->drv);
  1212. copy->deven = orig->deven;
  1213. copy->threads = orig->threads;
  1214. copy->usbdev = orig->usbdev;
  1215. memcpy(&(copy->usbinfo), &(orig->usbinfo), sizeof(copy->usbinfo));
  1216. copy->usbinfo.nodev = (copy->usbdev == NULL);
  1217. copy->usbinfo.devlock = orig->usbinfo.devlock;
  1218. return copy;
  1219. }
  1220. struct cgpu_info *usb_alloc_cgpu(struct device_drv *drv, int threads)
  1221. {
  1222. struct cgpu_info *cgpu = calloc(1, sizeof(*cgpu));
  1223. if (unlikely(!cgpu))
  1224. quit(1, "Failed to calloc cgpu for %s in usb_alloc_cgpu", drv->dname);
  1225. cgpu->drv = drv;
  1226. cgpu->deven = DEV_ENABLED;
  1227. cgpu->threads = threads;
  1228. cgpu->usbinfo.nodev = true;
  1229. cgpu->usbinfo.devlock = calloc(1, sizeof(*(cgpu->usbinfo.devlock)));
  1230. if (unlikely(!cgpu->usbinfo.devlock))
  1231. quit(1, "Failed to calloc devlock for %s in usb_alloc_cgpu", drv->dname);
  1232. rwlock_init(cgpu->usbinfo.devlock);
  1233. return cgpu;
  1234. }
  1235. struct cgpu_info *usb_free_cgpu_devlock(struct cgpu_info *cgpu, bool free_devlock)
  1236. {
  1237. if (cgpu->drv->copy)
  1238. free(cgpu->drv);
  1239. free(cgpu->device_path);
  1240. if (free_devlock)
  1241. free(cgpu->usbinfo.devlock);
  1242. free(cgpu);
  1243. return NULL;
  1244. }
  1245. #define USB_INIT_FAIL 0
  1246. #define USB_INIT_OK 1
  1247. #define USB_INIT_IGNORE 2
  1248. /*
  1249. * WARNING - these assume DEVLOCK(cgpu, pstate) is called first and
  1250. * DEVUNLOCK(cgpu, pstate) in called in the same function with the same pstate
  1251. * given to DEVLOCK.
  1252. * You must call DEVUNLOCK(cgpu, pstate) before exiting the function or it will leave
  1253. * the thread Cancelability unrestored
  1254. */
  1255. #define DEVLOCK(cgpu, _pth_state) do { \
  1256. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &_pth_state); \
  1257. wr_lock(cgpu->usbinfo.devlock); \
  1258. } while (0)
  1259. #define DEVUNLOCK(cgpu, _pth_state) do { \
  1260. wr_unlock(cgpu->usbinfo.devlock); \
  1261. pthread_setcancelstate(_pth_state, NULL); \
  1262. } while (0)
  1263. static int _usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1264. {
  1265. struct cg_usb_device *cgusb = NULL;
  1266. struct libusb_config_descriptor *config = NULL;
  1267. const struct libusb_interface_descriptor *idesc;
  1268. const struct libusb_endpoint_descriptor *epdesc;
  1269. unsigned char strbuf[STRBUFLEN+1];
  1270. char devpath[32];
  1271. char devstr[STRBUFLEN+1];
  1272. int err, i, j, k, pstate;
  1273. int bad = USB_INIT_FAIL;
  1274. DEVLOCK(cgpu, pstate);
  1275. cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
  1276. cgpu->usbinfo.device_address = libusb_get_device_address(dev);
  1277. sprintf(devpath, "%d:%d",
  1278. (int)(cgpu->usbinfo.bus_number),
  1279. (int)(cgpu->usbinfo.device_address));
  1280. cgpu->device_path = strdup(devpath);
  1281. sprintf(devstr, "- %s device %s", found->name, devpath);
  1282. cgusb = calloc(1, sizeof(*cgusb));
  1283. if (unlikely(!cgusb))
  1284. quit(1, "USB failed to calloc _usb_init cgusb");
  1285. cgusb->found = found;
  1286. if (found->idVendor == IDVENDOR_FTDI)
  1287. cgusb->usb_type = USB_TYPE_FTDI;
  1288. cgusb->ident = found->ident;
  1289. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  1290. if (unlikely(!cgusb->descriptor))
  1291. quit(1, "USB failed to calloc _usb_init cgusb descriptor");
  1292. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  1293. if (err) {
  1294. applog(LOG_DEBUG,
  1295. "USB init failed to get descriptor, err %d %s",
  1296. err, devstr);
  1297. goto dame;
  1298. }
  1299. cg_wlock(&cgusb_fd_lock);
  1300. err = libusb_open(dev, &(cgusb->handle));
  1301. cg_wunlock(&cgusb_fd_lock);
  1302. if (err) {
  1303. switch (err) {
  1304. case LIBUSB_ERROR_ACCESS:
  1305. applog(LOG_ERR,
  1306. "USB init open device failed, err %d, "
  1307. "you dont have priviledge to access %s",
  1308. err, devstr);
  1309. break;
  1310. #ifdef WIN32
  1311. // Windows specific message
  1312. case LIBUSB_ERROR_NOT_SUPPORTED:
  1313. applog(LOG_ERR,
  1314. "USB init, open device failed, err %d, "
  1315. "you need to install a WinUSB driver for %s",
  1316. err, devstr);
  1317. break;
  1318. #endif
  1319. default:
  1320. applog(LOG_DEBUG,
  1321. "USB init, open failed, err %d %s",
  1322. err, devstr);
  1323. }
  1324. goto dame;
  1325. }
  1326. #ifndef WIN32
  1327. if (libusb_kernel_driver_active(cgusb->handle, found->kernel) == 1) {
  1328. applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
  1329. err = libusb_detach_kernel_driver(cgusb->handle, found->kernel);
  1330. if (err == 0) {
  1331. applog(LOG_DEBUG,
  1332. "USB init, kernel detached successfully %s",
  1333. devstr);
  1334. } else {
  1335. applog(LOG_WARNING,
  1336. "USB init, kernel detach failed, err %d in use? %s",
  1337. err, devstr);
  1338. goto cldame;
  1339. }
  1340. }
  1341. #endif
  1342. if (found->iManufacturer) {
  1343. unsigned char man[STRBUFLEN+1];
  1344. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1345. cgusb->descriptor->iManufacturer,
  1346. man, STRBUFLEN);
  1347. if (err < 0) {
  1348. applog(LOG_DEBUG,
  1349. "USB init, failed to get iManufacturer, err %d %s",
  1350. err, devstr);
  1351. goto cldame;
  1352. }
  1353. if (strcmp((char *)man, found->iManufacturer)) {
  1354. applog(LOG_DEBUG, "USB init, iManufacturer mismatch %s",
  1355. devstr);
  1356. bad = USB_INIT_IGNORE;
  1357. goto cldame;
  1358. }
  1359. }
  1360. if (found->iProduct) {
  1361. unsigned char prod[STRBUFLEN+1];
  1362. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1363. cgusb->descriptor->iProduct,
  1364. prod, STRBUFLEN);
  1365. if (err < 0) {
  1366. applog(LOG_DEBUG,
  1367. "USB init, failed to get iProduct, err %d %s",
  1368. err, devstr);
  1369. goto cldame;
  1370. }
  1371. if (strcmp((char *)prod, found->iProduct)) {
  1372. applog(LOG_DEBUG, "USB init, iProduct mismatch %s",
  1373. devstr);
  1374. bad = USB_INIT_IGNORE;
  1375. goto cldame;
  1376. }
  1377. }
  1378. err = libusb_set_configuration(cgusb->handle, found->config);
  1379. if (err) {
  1380. switch(err) {
  1381. case LIBUSB_ERROR_BUSY:
  1382. applog(LOG_WARNING,
  1383. "USB init, set config %d in use %s",
  1384. found->config, devstr);
  1385. break;
  1386. default:
  1387. applog(LOG_DEBUG,
  1388. "USB init, failed to set config to %d, err %d %s",
  1389. found->config, err, devstr);
  1390. }
  1391. goto cldame;
  1392. }
  1393. err = libusb_get_active_config_descriptor(dev, &config);
  1394. if (err) {
  1395. applog(LOG_DEBUG,
  1396. "USB init, failed to get config descriptor, err %d %s",
  1397. err, devstr);
  1398. goto cldame;
  1399. }
  1400. if ((int)(config->bNumInterfaces) <= found->interface) {
  1401. applog(LOG_DEBUG, "USB init bNumInterfaces <= interface %s",
  1402. devstr);
  1403. goto cldame;
  1404. }
  1405. for (i = 0; i < found->epcount; i++)
  1406. found->eps[i].found = false;
  1407. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  1408. idesc = &(config->interface[found->interface].altsetting[i]);
  1409. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  1410. epdesc = &(idesc->endpoint[j]);
  1411. for (k = 0; k < found->epcount; k++) {
  1412. if (!found->eps[k].found) {
  1413. if (epdesc->bmAttributes == found->eps[k].att
  1414. && epdesc->wMaxPacketSize >= found->eps[k].size
  1415. && epdesc->bEndpointAddress == found->eps[k].ep) {
  1416. found->eps[k].found = true;
  1417. found->wMaxPacketSize = epdesc->wMaxPacketSize;
  1418. break;
  1419. }
  1420. }
  1421. }
  1422. }
  1423. }
  1424. for (i = 0; i < found->epcount; i++) {
  1425. if (found->eps[i].found == false) {
  1426. applog(LOG_DEBUG, "USB init found == false %s",
  1427. devstr);
  1428. goto cldame;
  1429. }
  1430. }
  1431. err = libusb_claim_interface(cgusb->handle, found->interface);
  1432. if (err) {
  1433. switch(err) {
  1434. case LIBUSB_ERROR_BUSY:
  1435. applog(LOG_WARNING,
  1436. "USB init, claim interface %d in use %s",
  1437. found->interface, devstr);
  1438. break;
  1439. default:
  1440. applog(LOG_DEBUG,
  1441. "USB init, claim interface %d failed, err %d %s",
  1442. found->interface, err, devstr);
  1443. }
  1444. goto cldame;
  1445. }
  1446. cgusb->usbver = cgusb->descriptor->bcdUSB;
  1447. // TODO: allow this with the right version of the libusb include and running library
  1448. // cgusb->speed = libusb_get_device_speed(dev);
  1449. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1450. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  1451. if (err > 0)
  1452. cgusb->prod_string = strdup((char *)strbuf);
  1453. else
  1454. cgusb->prod_string = (char *)BLANK;
  1455. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1456. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  1457. if (err > 0)
  1458. cgusb->manuf_string = strdup((char *)strbuf);
  1459. else
  1460. cgusb->manuf_string = (char *)BLANK;
  1461. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1462. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  1463. if (err > 0)
  1464. cgusb->serial_string = strdup((char *)strbuf);
  1465. else
  1466. cgusb->serial_string = (char *)BLANK;
  1467. // TODO: ?
  1468. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  1469. // cgusb->interfaceVersion
  1470. applog(LOG_DEBUG,
  1471. "USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
  1472. devstr, cgusb->usbver, cgusb->prod_string,
  1473. cgusb->manuf_string, cgusb->serial_string);
  1474. cgpu->usbdev = cgusb;
  1475. cgpu->usbinfo.nodev = false;
  1476. libusb_free_config_descriptor(config);
  1477. // Allow a name change based on the idVendor+idProduct
  1478. // N.B. must be done before calling add_cgpu()
  1479. if (strcmp(cgpu->drv->name, found->name)) {
  1480. if (!cgpu->drv->copy)
  1481. cgpu->drv = copy_drv(cgpu->drv);
  1482. cgpu->drv->name = (char *)(found->name);
  1483. }
  1484. bad = USB_INIT_OK;
  1485. goto out_unlock;
  1486. cldame:
  1487. cg_wlock(&cgusb_fd_lock);
  1488. libusb_close(cgusb->handle);
  1489. cg_wunlock(&cgusb_fd_lock);
  1490. dame:
  1491. if (config)
  1492. libusb_free_config_descriptor(config);
  1493. cgusb = free_cgusb(cgusb);
  1494. out_unlock:
  1495. DEVUNLOCK(cgpu, pstate);
  1496. return bad;
  1497. }
  1498. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1499. {
  1500. int ret;
  1501. ret = _usb_init(cgpu, dev, found);
  1502. if (ret == USB_INIT_FAIL)
  1503. applog(LOG_ERR, "%s detect (%d:%d) failed to initialise (incorrect device?)",
  1504. cgpu->drv->dname,
  1505. (int)(cgpu->usbinfo.bus_number),
  1506. (int)(cgpu->usbinfo.device_address));
  1507. return (ret == USB_INIT_OK);
  1508. }
  1509. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  1510. {
  1511. struct libusb_device_descriptor desc;
  1512. int bus_number, device_address;
  1513. int err, i;
  1514. bool ok;
  1515. err = libusb_get_device_descriptor(dev, &desc);
  1516. if (err) {
  1517. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  1518. return false;
  1519. }
  1520. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  1521. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  1522. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  1523. return false;
  1524. }
  1525. if (busdev_count > 0) {
  1526. bus_number = (int)libusb_get_bus_number(dev);
  1527. device_address = (int)libusb_get_device_address(dev);
  1528. ok = false;
  1529. for (i = 0; i < busdev_count; i++) {
  1530. if (bus_number == busdev[i].bus_number) {
  1531. if (busdev[i].device_address == -1 ||
  1532. device_address == busdev[i].device_address) {
  1533. ok = true;
  1534. break;
  1535. }
  1536. }
  1537. }
  1538. if (!ok) {
  1539. applog(LOG_DEBUG, "%s rejected %s %04x:%04x with bus:dev (%d:%d)",
  1540. drv->name, look->name, look->idVendor, look->idProduct,
  1541. bus_number, device_address);
  1542. return false;
  1543. }
  1544. }
  1545. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  1546. drv->name, look->name, look->idVendor, look->idProduct);
  1547. return true;
  1548. }
  1549. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  1550. {
  1551. struct usb_find_devices *found;
  1552. int i;
  1553. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  1554. if (find_dev[i].drv == drvnum) {
  1555. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  1556. found = malloc(sizeof(*found));
  1557. if (unlikely(!found))
  1558. quit(1, "USB failed to malloc found");
  1559. memcpy(found, &(find_dev[i]), sizeof(*found));
  1560. return found;
  1561. }
  1562. }
  1563. return NULL;
  1564. }
  1565. static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
  1566. {
  1567. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1568. applog(LOG_DEBUG,
  1569. "USB scan devices3: %s limit %d reached",
  1570. drv->dname, drv_count[drv->drv_id].limit);
  1571. return NULL;
  1572. }
  1573. #ifdef USE_BFLSC
  1574. if (drv->drv_id == DRIVER_BFLSC)
  1575. return usb_check_each(DRV_BFLSC, drv, dev);
  1576. #endif
  1577. #ifdef USE_BITFORCE
  1578. if (drv->drv_id == DRIVER_BITFORCE)
  1579. return usb_check_each(DRV_BITFORCE, drv, dev);
  1580. #endif
  1581. #ifdef USE_MODMINER
  1582. if (drv->drv_id == DRIVER_MODMINER)
  1583. return usb_check_each(DRV_MODMINER, drv, dev);
  1584. #endif
  1585. #ifdef USE_ICARUS
  1586. if (drv->drv_id == DRIVER_ICARUS)
  1587. return usb_check_each(DRV_ICARUS, drv, dev);
  1588. #endif
  1589. #ifdef USE_AVALON
  1590. if (drv->drv_id == DRIVER_AVALON)
  1591. return usb_check_each(DRV_AVALON, drv, dev);
  1592. #endif
  1593. return NULL;
  1594. }
  1595. void usb_detect(struct device_drv *drv, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *))
  1596. {
  1597. libusb_device **list;
  1598. ssize_t count, i;
  1599. struct usb_find_devices *found;
  1600. applog(LOG_DEBUG, "USB scan devices: checking for %s devices", drv->name);
  1601. if (total_count >= total_limit) {
  1602. applog(LOG_DEBUG, "USB scan devices: total limit %d reached", total_limit);
  1603. return;
  1604. }
  1605. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1606. applog(LOG_DEBUG,
  1607. "USB scan devices: %s limit %d reached",
  1608. drv->dname, drv_count[drv->drv_id].limit);
  1609. return;
  1610. }
  1611. count = libusb_get_device_list(NULL, &list);
  1612. if (count < 0) {
  1613. applog(LOG_DEBUG, "USB scan devices: failed, err %d", (int)count);
  1614. return;
  1615. }
  1616. if (count == 0)
  1617. applog(LOG_DEBUG, "USB scan devices: found no devices");
  1618. for (i = 0; i < count; i++) {
  1619. if (total_count >= total_limit) {
  1620. applog(LOG_DEBUG, "USB scan devices2: total limit %d reached", total_limit);
  1621. break;
  1622. }
  1623. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1624. applog(LOG_DEBUG,
  1625. "USB scan devices2: %s limit %d reached",
  1626. drv->dname, drv_count[drv->drv_id].limit);
  1627. break;
  1628. }
  1629. found = usb_check(drv, list[i]);
  1630. if (found != NULL) {
  1631. if (is_in_use(list[i]) || cgminer_usb_lock(drv, list[i]) == false)
  1632. free(found);
  1633. else {
  1634. if (!device_detect(list[i], found))
  1635. cgminer_usb_unlock(drv, list[i]);
  1636. else {
  1637. total_count++;
  1638. drv_count[drv->drv_id].count++;
  1639. }
  1640. }
  1641. }
  1642. }
  1643. libusb_free_device_list(list, 1);
  1644. }
  1645. #if DO_USB_STATS
  1646. static void modes_str(char *buf, uint32_t modes)
  1647. {
  1648. bool first;
  1649. *buf = '\0';
  1650. if (modes == MODE_NONE)
  1651. strcpy(buf, MODE_NONE_STR);
  1652. else {
  1653. first = true;
  1654. if (modes & MODE_CTRL_READ) {
  1655. strcpy(buf, MODE_CTRL_READ_STR);
  1656. first = false;
  1657. }
  1658. if (modes & MODE_CTRL_WRITE) {
  1659. if (!first)
  1660. strcat(buf, MODE_SEP_STR);
  1661. strcat(buf, MODE_CTRL_WRITE_STR);
  1662. first = false;
  1663. }
  1664. if (modes & MODE_BULK_READ) {
  1665. if (!first)
  1666. strcat(buf, MODE_SEP_STR);
  1667. strcat(buf, MODE_BULK_READ_STR);
  1668. first = false;
  1669. }
  1670. if (modes & MODE_BULK_WRITE) {
  1671. if (!first)
  1672. strcat(buf, MODE_SEP_STR);
  1673. strcat(buf, MODE_BULK_WRITE_STR);
  1674. first = false;
  1675. }
  1676. }
  1677. }
  1678. #endif
  1679. // The stat data can be spurious due to not locking it before copying it -
  1680. // however that would require the stat() function to also lock and release
  1681. // a mutex every time a usb read or write is called which would slow
  1682. // things down more
  1683. struct api_data *api_usb_stats(__maybe_unused int *count)
  1684. {
  1685. #if DO_USB_STATS
  1686. struct cg_usb_stats_details *details;
  1687. struct cg_usb_stats *sta;
  1688. struct api_data *root = NULL;
  1689. int device;
  1690. int cmdseq;
  1691. char modes_s[32];
  1692. if (next_stat == USB_NOSTAT)
  1693. return NULL;
  1694. while (*count < next_stat * C_MAX * 2) {
  1695. device = *count / (C_MAX * 2);
  1696. cmdseq = *count % (C_MAX * 2);
  1697. (*count)++;
  1698. sta = &(usb_stats[device]);
  1699. details = &(sta->details[cmdseq]);
  1700. // Only show stats that have results
  1701. if (details->item[CMD_CMD].count == 0 &&
  1702. details->item[CMD_TIMEOUT].count == 0 &&
  1703. details->item[CMD_ERROR].count == 0)
  1704. continue;
  1705. root = api_add_string(root, "Name", sta->name, false);
  1706. root = api_add_int(root, "ID", &(sta->device_id), false);
  1707. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  1708. root = api_add_int(root, "Seq", &(details->seq), true);
  1709. modes_str(modes_s, details->modes);
  1710. root = api_add_string(root, "Modes", modes_s, true);
  1711. root = api_add_uint64(root, "Count",
  1712. &(details->item[CMD_CMD].count), true);
  1713. root = api_add_double(root, "Total Delay",
  1714. &(details->item[CMD_CMD].total_delay), true);
  1715. root = api_add_double(root, "Min Delay",
  1716. &(details->item[CMD_CMD].min_delay), true);
  1717. root = api_add_double(root, "Max Delay",
  1718. &(details->item[CMD_CMD].max_delay), true);
  1719. root = api_add_uint64(root, "Timeout Count",
  1720. &(details->item[CMD_TIMEOUT].count), true);
  1721. root = api_add_double(root, "Timeout Total Delay",
  1722. &(details->item[CMD_TIMEOUT].total_delay), true);
  1723. root = api_add_double(root, "Timeout Min Delay",
  1724. &(details->item[CMD_TIMEOUT].min_delay), true);
  1725. root = api_add_double(root, "Timeout Max Delay",
  1726. &(details->item[CMD_TIMEOUT].max_delay), true);
  1727. root = api_add_uint64(root, "Error Count",
  1728. &(details->item[CMD_ERROR].count), true);
  1729. root = api_add_double(root, "Error Total Delay",
  1730. &(details->item[CMD_ERROR].total_delay), true);
  1731. root = api_add_double(root, "Error Min Delay",
  1732. &(details->item[CMD_ERROR].min_delay), true);
  1733. root = api_add_double(root, "Error Max Delay",
  1734. &(details->item[CMD_ERROR].max_delay), true);
  1735. root = api_add_timeval(root, "First Command",
  1736. &(details->item[CMD_CMD].first), true);
  1737. root = api_add_timeval(root, "Last Command",
  1738. &(details->item[CMD_CMD].last), true);
  1739. root = api_add_timeval(root, "First Timeout",
  1740. &(details->item[CMD_TIMEOUT].first), true);
  1741. root = api_add_timeval(root, "Last Timeout",
  1742. &(details->item[CMD_TIMEOUT].last), true);
  1743. root = api_add_timeval(root, "First Error",
  1744. &(details->item[CMD_ERROR].first), true);
  1745. root = api_add_timeval(root, "Last Error",
  1746. &(details->item[CMD_ERROR].last), true);
  1747. return root;
  1748. }
  1749. #endif
  1750. return NULL;
  1751. }
  1752. #if DO_USB_STATS
  1753. static void newstats(struct cgpu_info *cgpu)
  1754. {
  1755. int i;
  1756. mutex_lock(&cgusb_lock);
  1757. cgpu->usbinfo.usbstat = next_stat + 1;
  1758. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * (next_stat+1));
  1759. if (unlikely(!usb_stats))
  1760. quit(1, "USB failed to realloc usb_stats %d", next_stat+1);
  1761. usb_stats[next_stat].name = cgpu->drv->name;
  1762. usb_stats[next_stat].device_id = -1;
  1763. usb_stats[next_stat].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  1764. if (unlikely(!usb_stats[next_stat].details))
  1765. quit(1, "USB failed to calloc details for %d", next_stat+1);
  1766. for (i = 1; i < C_MAX * 2; i += 2)
  1767. usb_stats[next_stat].details[i].seq = 1;
  1768. next_stat++;
  1769. mutex_unlock(&cgusb_lock);
  1770. }
  1771. #endif
  1772. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  1773. {
  1774. #if DO_USB_STATS
  1775. if (cgpu->usbinfo.usbstat < 1)
  1776. newstats(cgpu);
  1777. // we don't know the device_id until after add_cgpu()
  1778. usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
  1779. #endif
  1780. }
  1781. #if DO_USB_STATS
  1782. 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)
  1783. {
  1784. struct cg_usb_stats_details *details;
  1785. double diff;
  1786. int item;
  1787. if (cgpu->usbinfo.usbstat < 1)
  1788. newstats(cgpu);
  1789. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
  1790. details->modes |= mode;
  1791. diff = tdiff(tv_finish, tv_start);
  1792. switch (err) {
  1793. case LIBUSB_SUCCESS:
  1794. item = CMD_CMD;
  1795. break;
  1796. case LIBUSB_ERROR_TIMEOUT:
  1797. item = CMD_TIMEOUT;
  1798. break;
  1799. default:
  1800. item = CMD_ERROR;
  1801. break;
  1802. }
  1803. if (details->item[item].count == 0) {
  1804. details->item[item].min_delay = diff;
  1805. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  1806. } else if (diff < details->item[item].min_delay)
  1807. details->item[item].min_delay = diff;
  1808. if (diff > details->item[item].max_delay)
  1809. details->item[item].max_delay = diff;
  1810. details->item[item].total_delay += diff;
  1811. memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
  1812. details->item[item].count++;
  1813. }
  1814. static void rejected_inc(struct cgpu_info *cgpu, uint32_t mode)
  1815. {
  1816. struct cg_usb_stats_details *details;
  1817. int item = CMD_ERROR;
  1818. if (cgpu->usbinfo.usbstat < 1)
  1819. newstats(cgpu);
  1820. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  1821. details->modes |= mode;
  1822. details->item[item].count++;
  1823. }
  1824. #endif
  1825. static char *find_end(unsigned char *buf, unsigned char *ptr, int ptrlen, int tot, char *end, int endlen, bool first)
  1826. {
  1827. unsigned char *search;
  1828. if (endlen > tot)
  1829. return NULL;
  1830. // If end is only 1 char - do a faster search
  1831. if (endlen == 1) {
  1832. if (first)
  1833. search = buf;
  1834. else
  1835. search = ptr;
  1836. return strchr((char *)search, *end);
  1837. } else {
  1838. if (first)
  1839. search = buf;
  1840. else {
  1841. // must allow end to have been chopped in 2
  1842. if ((tot - ptrlen) >= (endlen - 1))
  1843. search = ptr - (endlen - 1);
  1844. else
  1845. search = ptr - (tot - ptrlen);
  1846. }
  1847. return strstr((char *)search, end);
  1848. }
  1849. }
  1850. #define USB_MAX_READ 8192
  1851. #define USB_RETRY_MAX 5
  1852. static int
  1853. usb_bulk_transfer(struct libusb_device_handle *dev_handle,
  1854. unsigned char endpoint, unsigned char *data, int length,
  1855. int *transferred, unsigned int timeout,
  1856. struct cgpu_info *cgpu)
  1857. {
  1858. int err, tries = 0;
  1859. /* Limit length of transfer to the largest this descriptor supports
  1860. * and leave the higher level functions to transfer more if needed. */
  1861. #if 0
  1862. if (length > cgpu->usbdev->found->wMaxPacketSize)
  1863. length = cgpu->usbdev->found->wMaxPacketSize;
  1864. #endif
  1865. if (length > 512)
  1866. length = 512;
  1867. cg_rlock(&cgusb_fd_lock);
  1868. err = libusb_bulk_transfer(dev_handle, endpoint, data, length,
  1869. transferred, timeout);
  1870. cg_runlock(&cgusb_fd_lock);
  1871. if (err == LIBUSB_ERROR_PIPE) {
  1872. cgpu->usbinfo.last_pipe = time(NULL);
  1873. cgpu->usbinfo.pipe_count++;
  1874. applog(LOG_INFO, "%s%i: libusb pipe error, trying to clear",
  1875. cgpu->drv->name, cgpu->device_id);
  1876. do {
  1877. err = libusb_clear_halt(dev_handle, endpoint);
  1878. if (unlikely(err == LIBUSB_ERROR_NOT_FOUND ||
  1879. err == LIBUSB_ERROR_NO_DEVICE)) {
  1880. cgpu->usbinfo.clear_err_count++;
  1881. break;
  1882. }
  1883. cg_rlock(&cgusb_fd_lock);
  1884. err = libusb_bulk_transfer(dev_handle, endpoint, data,
  1885. length, transferred, timeout);
  1886. cg_runlock(&cgusb_fd_lock);
  1887. if (err)
  1888. cgpu->usbinfo.retry_err_count++;
  1889. } while (err == LIBUSB_ERROR_PIPE && tries++ < USB_RETRY_MAX);
  1890. applog(LOG_DEBUG, "%s%i: libusb pipe error%scleared",
  1891. cgpu->drv->name, cgpu->device_id, err ? " not " : " ");
  1892. if (err)
  1893. cgpu->usbinfo.clear_fail_count++;
  1894. }
  1895. return err;
  1896. }
  1897. 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)
  1898. {
  1899. struct cg_usb_device *usbdev;
  1900. bool ftdi;
  1901. #if DO_USB_STATS
  1902. struct timeval tv_start;
  1903. #endif
  1904. struct timeval read_start, tv_finish;
  1905. unsigned int initial_timeout;
  1906. double max, done;
  1907. int bufleft, err, got, tot, pstate;
  1908. bool first = true;
  1909. char *search;
  1910. int endlen;
  1911. // We add 4: 1 for null, 2 for FTDI status and 1 to round to 4 bytes
  1912. unsigned char usbbuf[USB_MAX_READ+4], *ptr;
  1913. size_t usbbufread;
  1914. DEVLOCK(cgpu, pstate);
  1915. if (cgpu->usbinfo.nodev) {
  1916. *buf = '\0';
  1917. *processed = 0;
  1918. USB_REJECT(cgpu, MODE_BULK_READ);
  1919. err = LIBUSB_ERROR_NO_DEVICE;
  1920. goto out_unlock;
  1921. }
  1922. usbdev = cgpu->usbdev;
  1923. ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  1924. 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));
  1925. if (bufsiz > USB_MAX_READ)
  1926. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, (int)bufsiz, USB_MAX_READ);
  1927. if (timeout == DEVTIMEOUT)
  1928. timeout = usbdev->found->timeout;
  1929. if (end == NULL) {
  1930. if (usbdev->buffer && usbdev->bufamt) {
  1931. tot = usbdev->bufamt;
  1932. bufleft = bufsiz - tot;
  1933. memcpy(usbbuf, usbdev->buffer, tot);
  1934. ptr = usbbuf + tot;
  1935. usbdev->bufamt = 0;
  1936. } else {
  1937. tot = 0;
  1938. bufleft = bufsiz;
  1939. ptr = usbbuf;
  1940. }
  1941. err = LIBUSB_SUCCESS;
  1942. initial_timeout = timeout;
  1943. max = ((double)timeout) / 1000.0;
  1944. cgtime(&read_start);
  1945. while (bufleft > 0) {
  1946. // TODO: use (USB_MAX_READ - tot) always?
  1947. if (usbdev->buffer)
  1948. usbbufread = USB_MAX_READ - tot;
  1949. else {
  1950. if (ftdi)
  1951. usbbufread = bufleft + 2;
  1952. else
  1953. usbbufread = bufleft;
  1954. }
  1955. got = 0;
  1956. STATS_TIMEVAL(&tv_start);
  1957. err = usb_bulk_transfer(usbdev->handle,
  1958. usbdev->found->eps[ep].ep,
  1959. ptr, usbbufread, &got, timeout,
  1960. cgpu);
  1961. cgtime(&tv_finish);
  1962. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1963. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  1964. ptr[got] = '\0';
  1965. 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);
  1966. IOERR_CHECK(cgpu, err);
  1967. if (ftdi) {
  1968. // first 2 bytes returned are an FTDI status
  1969. if (got > 2) {
  1970. got -= 2;
  1971. memmove(ptr, ptr+2, got+1);
  1972. } else {
  1973. got = 0;
  1974. *ptr = '\0';
  1975. }
  1976. }
  1977. tot += got;
  1978. if (err || readonce)
  1979. break;
  1980. ptr += got;
  1981. bufleft -= got;
  1982. first = false;
  1983. done = tdiff(&tv_finish, &read_start);
  1984. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  1985. if (unlikely(done >= max))
  1986. break;
  1987. timeout = initial_timeout - (done * 1000);
  1988. if (!timeout)
  1989. break;
  1990. }
  1991. // N.B. usbdev->buffer was emptied before the while() loop
  1992. if (usbdev->buffer && tot > (int)bufsiz) {
  1993. usbdev->bufamt = tot - bufsiz;
  1994. memcpy(usbdev->buffer, ptr + bufsiz, usbdev->bufamt);
  1995. tot -= usbdev->bufamt;
  1996. usbbuf[tot] = '\0';
  1997. applog(LOG_ERR, "USB: %s%i read1 buffering %d extra bytes",
  1998. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  1999. }
  2000. *processed = tot;
  2001. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2002. if (NODEV(err))
  2003. release_cgpu(cgpu);
  2004. goto out_unlock;
  2005. }
  2006. if (usbdev->buffer && usbdev->bufamt) {
  2007. tot = usbdev->bufamt;
  2008. bufleft = bufsiz - tot;
  2009. memcpy(usbbuf, usbdev->buffer, tot);
  2010. ptr = usbbuf + tot;
  2011. usbdev->bufamt = 0;
  2012. } else {
  2013. tot = 0;
  2014. bufleft = bufsiz;
  2015. ptr = usbbuf;
  2016. }
  2017. endlen = strlen(end);
  2018. err = LIBUSB_SUCCESS;
  2019. initial_timeout = timeout;
  2020. max = ((double)timeout) / 1000.0;
  2021. cgtime(&read_start);
  2022. while (bufleft > 0) {
  2023. // TODO: use (USB_MAX_READ - tot) always?
  2024. if (usbdev->buffer)
  2025. usbbufread = USB_MAX_READ - tot;
  2026. else {
  2027. if (ftdi)
  2028. usbbufread = bufleft + 2;
  2029. else
  2030. usbbufread = bufleft;
  2031. }
  2032. got = 0;
  2033. STATS_TIMEVAL(&tv_start);
  2034. err = usb_bulk_transfer(usbdev->handle,
  2035. usbdev->found->eps[ep].ep, ptr,
  2036. usbbufread, &got, timeout, cgpu);
  2037. cgtime(&tv_finish);
  2038. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  2039. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  2040. ptr[got] = '\0';
  2041. 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);
  2042. IOERR_CHECK(cgpu, err);
  2043. if (ftdi) {
  2044. // first 2 bytes returned are an FTDI status
  2045. if (got > 2) {
  2046. got -= 2;
  2047. memmove(ptr, ptr+2, got+1);
  2048. } else {
  2049. got = 0;
  2050. *ptr = '\0';
  2051. }
  2052. }
  2053. tot += got;
  2054. if (err || readonce)
  2055. break;
  2056. if (find_end(usbbuf, ptr, got, tot, (char *)end, endlen, first))
  2057. break;
  2058. ptr += got;
  2059. bufleft -= got;
  2060. first = false;
  2061. done = tdiff(&tv_finish, &read_start);
  2062. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  2063. if (unlikely(done >= max))
  2064. break;
  2065. timeout = initial_timeout - (done * 1000);
  2066. if (!timeout)
  2067. break;
  2068. }
  2069. if (usbdev->buffer) {
  2070. bool dobuffer = false;
  2071. if ((search = find_end(usbbuf, usbbuf, tot, tot, (char *)end, endlen, true))) {
  2072. // end finishes after bufsiz
  2073. if ((search + endlen - (char *)usbbuf) > (int)bufsiz) {
  2074. usbdev->bufamt = tot - bufsiz;
  2075. dobuffer = true;
  2076. } else {
  2077. // extra data after end
  2078. if (*(search + endlen)) {
  2079. usbdev->bufamt = tot - (search + endlen - (char *)usbbuf);
  2080. dobuffer = true;
  2081. }
  2082. }
  2083. } else {
  2084. // no end, but still bigger than bufsiz
  2085. if (tot > (int)bufsiz) {
  2086. usbdev->bufamt = tot - bufsiz;
  2087. dobuffer = true;
  2088. }
  2089. }
  2090. if (dobuffer) {
  2091. tot -= usbdev->bufamt;
  2092. memcpy(usbdev->buffer, usbbuf + tot, usbdev->bufamt);
  2093. usbbuf[tot] = '\0';
  2094. applog(LOG_ERR, "USB: %s%i read2 buffering %d extra bytes",
  2095. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2096. }
  2097. }
  2098. *processed = tot;
  2099. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2100. if (NODEV(err))
  2101. release_cgpu(cgpu);
  2102. out_unlock:
  2103. DEVUNLOCK(cgpu, pstate);
  2104. return err;
  2105. }
  2106. 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)
  2107. {
  2108. struct cg_usb_device *usbdev;
  2109. #if DO_USB_STATS
  2110. struct timeval tv_start;
  2111. #endif
  2112. struct timeval read_start, tv_finish;
  2113. unsigned int initial_timeout;
  2114. double max, done;
  2115. __maybe_unused bool first = true;
  2116. int err, sent, tot, pstate;
  2117. DEVLOCK(cgpu, pstate);
  2118. 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));
  2119. *processed = 0;
  2120. if (cgpu->usbinfo.nodev) {
  2121. USB_REJECT(cgpu, MODE_BULK_WRITE);
  2122. err = LIBUSB_ERROR_NO_DEVICE;
  2123. goto out_unlock;
  2124. }
  2125. usbdev = cgpu->usbdev;
  2126. if (timeout == DEVTIMEOUT)
  2127. timeout = usbdev->found->timeout;
  2128. tot = 0;
  2129. err = LIBUSB_SUCCESS;
  2130. initial_timeout = timeout;
  2131. max = ((double)timeout) / 1000.0;
  2132. cgtime(&read_start);
  2133. while (bufsiz > 0) {
  2134. sent = 0;
  2135. STATS_TIMEVAL(&tv_start);
  2136. err = usb_bulk_transfer(usbdev->handle,
  2137. usbdev->found->eps[ep].ep,
  2138. (unsigned char *)buf, bufsiz, &sent,
  2139. timeout, cgpu);
  2140. cgtime(&tv_finish);
  2141. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  2142. MODE_BULK_WRITE, cmd, first ? SEQ0 : SEQ1);
  2143. 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);
  2144. IOERR_CHECK(cgpu, err);
  2145. tot += sent;
  2146. if (err)
  2147. break;
  2148. buf += sent;
  2149. bufsiz -= sent;
  2150. first = false;
  2151. done = tdiff(&tv_finish, &read_start);
  2152. // N.B. this is: return LIBUSB_SUCCESS with whatever size was written
  2153. if (unlikely(done >= max))
  2154. break;
  2155. timeout = initial_timeout - (done * 1000);
  2156. if (!timeout)
  2157. break;
  2158. }
  2159. *processed = tot;
  2160. if (NODEV(err))
  2161. release_cgpu(cgpu);
  2162. out_unlock:
  2163. DEVUNLOCK(cgpu, pstate);
  2164. return err;
  2165. }
  2166. 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)
  2167. {
  2168. struct cg_usb_device *usbdev;
  2169. #if DO_USB_STATS
  2170. struct timeval tv_start, tv_finish;
  2171. #endif
  2172. uint32_t *buf = NULL;
  2173. int err, i, bufsiz;
  2174. 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));
  2175. if (cgpu->usbinfo.nodev) {
  2176. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  2177. err = LIBUSB_ERROR_NO_DEVICE;
  2178. goto out_;
  2179. }
  2180. usbdev = cgpu->usbdev;
  2181. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  2182. if (siz > 0) {
  2183. bufsiz = siz - 1;
  2184. bufsiz >>= 2;
  2185. bufsiz++;
  2186. buf = malloc(bufsiz << 2);
  2187. if (unlikely(!buf))
  2188. quit(1, "Failed to malloc in _usb_transfer");
  2189. for (i = 0; i < bufsiz; i++)
  2190. buf[i] = htole32(data[i]);
  2191. }
  2192. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex((unsigned char *)buf, (size_t)siz));
  2193. STATS_TIMEVAL(&tv_start);
  2194. cg_rlock(&cgusb_fd_lock);
  2195. err = libusb_control_transfer(usbdev->handle, request_type,
  2196. bRequest, wValue, wIndex, (unsigned char *)buf, (uint16_t)siz,
  2197. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  2198. cg_runlock(&cgusb_fd_lock);
  2199. STATS_TIMEVAL(&tv_finish);
  2200. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0);
  2201. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  2202. IOERR_CHECK(cgpu, err);
  2203. free(buf);
  2204. if (NOCONTROLDEV(err))
  2205. release_cgpu(cgpu);
  2206. out_:
  2207. return err;
  2208. }
  2209. 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)
  2210. {
  2211. int pstate, err;
  2212. DEVLOCK(cgpu, pstate);
  2213. err = __usb_transfer(cgpu, request_type, bRequest, wValue, wIndex, data, siz, timeout, cmd);
  2214. DEVUNLOCK(cgpu, pstate);
  2215. return err;
  2216. }
  2217. 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)
  2218. {
  2219. struct cg_usb_device *usbdev;
  2220. #if DO_USB_STATS
  2221. struct timeval tv_start, tv_finish;
  2222. #endif
  2223. int err, pstate;
  2224. DEVLOCK(cgpu, pstate);
  2225. 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));
  2226. if (cgpu->usbinfo.nodev) {
  2227. USB_REJECT(cgpu, MODE_CTRL_READ);
  2228. err = LIBUSB_ERROR_NO_DEVICE;
  2229. goto out_unlock;
  2230. }
  2231. usbdev = cgpu->usbdev;
  2232. *amount = 0;
  2233. STATS_TIMEVAL(&tv_start);
  2234. cg_rlock(&cgusb_fd_lock);
  2235. err = libusb_control_transfer(usbdev->handle, request_type,
  2236. bRequest, wValue, wIndex,
  2237. (unsigned char *)buf, (uint16_t)bufsiz,
  2238. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  2239. cg_runlock(&cgusb_fd_lock);
  2240. STATS_TIMEVAL(&tv_finish);
  2241. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0);
  2242. 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);
  2243. IOERR_CHECK(cgpu, err);
  2244. if (err > 0) {
  2245. *amount = err;
  2246. err = 0;
  2247. } else if (NOCONTROLDEV(err))
  2248. release_cgpu(cgpu);
  2249. out_unlock:
  2250. DEVUNLOCK(cgpu, pstate);
  2251. return err;
  2252. }
  2253. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  2254. #define FTDI_RS0_CTS (1 << 4)
  2255. #define FTDI_RS0_DSR (1 << 5)
  2256. #define FTDI_RS0_RI (1 << 6)
  2257. #define FTDI_RS0_RLSD (1 << 7)
  2258. /* Clear to send for FTDI */
  2259. int usb_ftdi_cts(struct cgpu_info *cgpu)
  2260. {
  2261. char buf[2], ret;
  2262. int err, amount;
  2263. err = _usb_transfer_read(cgpu, (uint8_t)FTDI_TYPE_IN, (uint8_t)5,
  2264. (uint16_t)0, (uint16_t)0, buf, 2,
  2265. &amount, DEVTIMEOUT, C_FTDI_STATUS);
  2266. /* We return true in case drivers are waiting indefinitely to try and
  2267. * write to something that's not there. */
  2268. if (err)
  2269. return true;
  2270. ret = buf[0] & FTDI_STATUS_B0_MASK;
  2271. return (ret & FTDI_RS0_CTS);
  2272. }
  2273. int usb_ftdi_set_latency(struct cgpu_info *cgpu)
  2274. {
  2275. int err = 0;
  2276. int pstate;
  2277. DEVLOCK(cgpu, pstate);
  2278. if (cgpu->usbdev) {
  2279. if (cgpu->usbdev->usb_type != USB_TYPE_FTDI) {
  2280. applog(LOG_ERR, "%s: cgid %d latency request on non-FTDI device",
  2281. cgpu->drv->name, cgpu->cgminer_id);
  2282. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2283. } else if (cgpu->usbdev->found->latency == LATENCY_UNUSED) {
  2284. applog(LOG_ERR, "%s: cgid %d invalid latency (UNUSED)",
  2285. cgpu->drv->name, cgpu->cgminer_id);
  2286. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2287. }
  2288. if (!err)
  2289. err = __usb_transfer(cgpu, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
  2290. cgpu->usbdev->found->latency,
  2291. cgpu->usbdev->found->interface,
  2292. NULL, 0, DEVTIMEOUT, C_LATENCY);
  2293. }
  2294. DEVUNLOCK(cgpu, pstate);
  2295. applog(LOG_DEBUG, "%s: cgid %d %s got err %d",
  2296. cgpu->drv->name, cgpu->cgminer_id,
  2297. usb_cmdname(C_LATENCY), err);
  2298. return err;
  2299. }
  2300. void usb_buffer_enable(struct cgpu_info *cgpu)
  2301. {
  2302. struct cg_usb_device *cgusb;
  2303. int pstate;
  2304. DEVLOCK(cgpu, pstate);
  2305. cgusb = cgpu->usbdev;
  2306. if (cgusb && !cgusb->buffer) {
  2307. cgusb->bufamt = 0;
  2308. cgusb->buffer = malloc(USB_MAX_READ+1);
  2309. if (!cgusb->buffer)
  2310. quit(1, "Failed to malloc buffer for USB %s%i",
  2311. cgpu->drv->name, cgpu->device_id);
  2312. cgusb->bufsiz = USB_MAX_READ;
  2313. }
  2314. DEVUNLOCK(cgpu, pstate);
  2315. }
  2316. void usb_buffer_disable(struct cgpu_info *cgpu)
  2317. {
  2318. struct cg_usb_device *cgusb;
  2319. int pstate;
  2320. DEVLOCK(cgpu, pstate);
  2321. cgusb = cgpu->usbdev;
  2322. if (cgusb && cgusb->buffer) {
  2323. cgusb->bufamt = 0;
  2324. cgusb->bufsiz = 0;
  2325. free(cgusb->buffer);
  2326. cgusb->buffer = NULL;
  2327. }
  2328. DEVUNLOCK(cgpu, pstate);
  2329. }
  2330. void usb_buffer_clear(struct cgpu_info *cgpu)
  2331. {
  2332. int pstate;
  2333. DEVLOCK(cgpu, pstate);
  2334. if (cgpu->usbdev)
  2335. cgpu->usbdev->bufamt = 0;
  2336. DEVUNLOCK(cgpu, pstate);
  2337. }
  2338. uint32_t usb_buffer_size(struct cgpu_info *cgpu)
  2339. {
  2340. uint32_t ret = 0;
  2341. int pstate;
  2342. DEVLOCK(cgpu, pstate);
  2343. if (cgpu->usbdev)
  2344. ret = cgpu->usbdev->bufamt;
  2345. DEVUNLOCK(cgpu, pstate);
  2346. return ret;
  2347. }
  2348. // Need to set all devices with matching usbdev
  2349. void usb_set_dev_start(struct cgpu_info *cgpu)
  2350. {
  2351. struct cg_usb_device *cgusb;
  2352. struct cgpu_info *cgpu2;
  2353. struct timeval now;
  2354. int pstate;
  2355. DEVLOCK(cgpu, pstate);
  2356. cgusb = cgpu->usbdev;
  2357. // If the device wasn't dropped
  2358. if (cgusb != NULL) {
  2359. int i;
  2360. cgtime(&now);
  2361. for (i = 0; i < total_devices; i++) {
  2362. cgpu2 = get_devices(i);
  2363. if (cgpu2->usbdev == cgusb)
  2364. copy_time(&(cgpu2->dev_start_tv), &now);
  2365. }
  2366. }
  2367. DEVUNLOCK(cgpu, pstate);
  2368. }
  2369. void usb_cleanup()
  2370. {
  2371. struct cgpu_info *cgpu;
  2372. int count;
  2373. int i;
  2374. hotplug_time = 0;
  2375. nmsleep(10);
  2376. count = 0;
  2377. for (i = 0; i < total_devices; i++) {
  2378. cgpu = devices[i];
  2379. switch (cgpu->drv->drv_id) {
  2380. case DRIVER_BFLSC:
  2381. case DRIVER_BITFORCE:
  2382. case DRIVER_MODMINER:
  2383. case DRIVER_ICARUS:
  2384. case DRIVER_AVALON:
  2385. wr_lock(cgpu->usbinfo.devlock);
  2386. release_cgpu(cgpu);
  2387. wr_unlock(cgpu->usbinfo.devlock);
  2388. count++;
  2389. break;
  2390. default:
  2391. break;
  2392. }
  2393. }
  2394. /*
  2395. * Must attempt to wait for the resource thread to release coz
  2396. * during a restart it won't automatically release them in linux
  2397. */
  2398. if (count) {
  2399. struct timeval start, now;
  2400. cgtime(&start);
  2401. while (42) {
  2402. nmsleep(50);
  2403. mutex_lock(&cgusbres_lock);
  2404. if (!res_work_head)
  2405. break;
  2406. cgtime(&now);
  2407. if (tdiff(&now, &start) > 0.366) {
  2408. applog(LOG_WARNING,
  2409. "usb_cleanup gave up waiting for resource thread");
  2410. break;
  2411. }
  2412. mutex_unlock(&cgusbres_lock);
  2413. }
  2414. mutex_unlock(&cgusbres_lock);
  2415. }
  2416. cgsem_destroy(&usb_resource_sem);
  2417. }
  2418. void usb_initialise()
  2419. {
  2420. char *fre, *ptr, *comma, *colon;
  2421. int bus, dev, lim, i;
  2422. bool found;
  2423. for (i = 0; i < DRIVER_MAX; i++) {
  2424. drv_count[i].count = 0;
  2425. drv_count[i].limit = 999999;
  2426. }
  2427. cgusb_check_init();
  2428. if (opt_usb_select && *opt_usb_select) {
  2429. // Absolute device limit
  2430. if (*opt_usb_select == ':') {
  2431. total_limit = atoi(opt_usb_select+1);
  2432. if (total_limit < 0)
  2433. quit(1, "Invalid --usb total limit");
  2434. // Comma list of bus:dev devices to match
  2435. } else if (isdigit(*opt_usb_select)) {
  2436. fre = ptr = strdup(opt_usb_select);
  2437. do {
  2438. comma = strchr(ptr, ',');
  2439. if (comma)
  2440. *(comma++) = '\0';
  2441. colon = strchr(ptr, ':');
  2442. if (!colon)
  2443. quit(1, "Invalid --usb bus:dev missing ':'");
  2444. *(colon++) = '\0';
  2445. if (!isdigit(*ptr))
  2446. quit(1, "Invalid --usb bus:dev - bus must be a number");
  2447. if (!isdigit(*colon) && *colon != '*')
  2448. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  2449. bus = atoi(ptr);
  2450. if (bus <= 0)
  2451. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  2452. if (!colon == '*')
  2453. dev = -1;
  2454. else {
  2455. dev = atoi(colon);
  2456. if (dev <= 0)
  2457. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  2458. }
  2459. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  2460. if (unlikely(!busdev))
  2461. quit(1, "USB failed to realloc busdev");
  2462. busdev[busdev_count-1].bus_number = bus;
  2463. busdev[busdev_count-1].device_address = dev;
  2464. ptr = comma;
  2465. } while (ptr);
  2466. free(fre);
  2467. // Comma list of DRV:limit
  2468. } else {
  2469. fre = ptr = strdup(opt_usb_select);
  2470. do {
  2471. comma = strchr(ptr, ',');
  2472. if (comma)
  2473. *(comma++) = '\0';
  2474. colon = strchr(ptr, ':');
  2475. if (!colon)
  2476. quit(1, "Invalid --usb DRV:limit missing ':'");
  2477. *(colon++) = '\0';
  2478. if (!isdigit(*colon))
  2479. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  2480. lim = atoi(colon);
  2481. if (lim < 0)
  2482. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  2483. found = false;
  2484. #ifdef USE_BFLSC
  2485. if (strcasecmp(ptr, bflsc_drv.name) == 0) {
  2486. drv_count[bflsc_drv.drv_id].limit = lim;
  2487. found = true;
  2488. }
  2489. #endif
  2490. #ifdef USE_BITFORCE
  2491. if (!found && strcasecmp(ptr, bitforce_drv.name) == 0) {
  2492. drv_count[bitforce_drv.drv_id].limit = lim;
  2493. found = true;
  2494. }
  2495. #endif
  2496. #ifdef USE_MODMINER
  2497. if (!found && strcasecmp(ptr, modminer_drv.name) == 0) {
  2498. drv_count[modminer_drv.drv_id].limit = lim;
  2499. found = true;
  2500. }
  2501. #endif
  2502. #ifdef USE_ICARUS
  2503. if (!found && strcasecmp(ptr, icarus_drv.name) == 0) {
  2504. drv_count[icarus_drv.drv_id].limit = lim;
  2505. found = true;
  2506. }
  2507. #endif
  2508. #ifdef USE_AVALON
  2509. if (!found && strcasecmp(ptr, avalon_drv.name) == 0) {
  2510. drv_count[avalon_drv.drv_id].limit = lim;
  2511. found = true;
  2512. }
  2513. #endif
  2514. if (!found)
  2515. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  2516. ptr = comma;
  2517. } while (ptr);
  2518. free(fre);
  2519. }
  2520. }
  2521. }
  2522. #ifndef WIN32
  2523. #include <errno.h>
  2524. #include <unistd.h>
  2525. #include <sys/types.h>
  2526. #include <sys/ipc.h>
  2527. #include <sys/sem.h>
  2528. #include <sys/stat.h>
  2529. #include <fcntl.h>
  2530. #ifndef __APPLE__
  2531. union semun {
  2532. int val;
  2533. struct semid_ds *buf;
  2534. unsigned short *array;
  2535. struct seminfo *__buf;
  2536. };
  2537. #endif
  2538. #else
  2539. static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
  2540. {
  2541. FreeSid(((PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor))->Group);
  2542. free(sec->lpSecurityDescriptor);
  2543. free(sec);
  2544. return NULL;
  2545. }
  2546. static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
  2547. {
  2548. SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
  2549. PSID gsid = NULL;
  2550. LPSECURITY_ATTRIBUTES sec_att = NULL;
  2551. PSECURITY_DESCRIPTOR sec_des = NULL;
  2552. sec_des = malloc(sizeof(*sec_des));
  2553. if (unlikely(!sec_des))
  2554. quit(1, "MTX: Failed to malloc LPSECURITY_DESCRIPTOR");
  2555. if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
  2556. applog(LOG_ERR,
  2557. "MTX: %s (%d:%d) USB failed to init secdes err (%d)",
  2558. dname, (int)bus_number, (int)device_address,
  2559. (int)GetLastError());
  2560. free(sec_des);
  2561. return NULL;
  2562. }
  2563. if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
  2564. applog(LOG_ERR,
  2565. "MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
  2566. dname, (int)bus_number, (int)device_address,
  2567. (int)GetLastError());
  2568. free(sec_des);
  2569. return NULL;
  2570. }
  2571. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
  2572. applog(LOG_ERR,
  2573. "MTX: %s (%d:%d) USB failed to create gsid err (%d)",
  2574. dname, (int)bus_number, (int)device_address,
  2575. (int)GetLastError());
  2576. free(sec_des);
  2577. return NULL;
  2578. }
  2579. if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
  2580. applog(LOG_ERR,
  2581. "MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
  2582. dname, (int)bus_number, (int)device_address,
  2583. (int)GetLastError());
  2584. FreeSid(gsid);
  2585. free(sec_des);
  2586. return NULL;
  2587. }
  2588. sec_att = malloc(sizeof(*sec_att));
  2589. if (unlikely(!sec_att))
  2590. quit(1, "MTX: Failed to malloc LPSECURITY_ATTRIBUTES");
  2591. sec_att->nLength = sizeof(*sec_att);
  2592. sec_att->lpSecurityDescriptor = sec_des;
  2593. sec_att->bInheritHandle = FALSE;
  2594. return sec_att;
  2595. }
  2596. #endif
  2597. // Any errors should always be printed since they will rarely if ever occur
  2598. // and thus it is best to always display them
  2599. static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2600. {
  2601. applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2602. #ifdef WIN32
  2603. struct cgpu_info *cgpu;
  2604. LPSECURITY_ATTRIBUTES sec;
  2605. HANDLE usbMutex;
  2606. char name[64];
  2607. DWORD res;
  2608. int i;
  2609. if (is_in_use_bd(bus_number, device_address))
  2610. return false;
  2611. sprintf(name, "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2612. sec = mksec(dname, bus_number, device_address);
  2613. if (!sec)
  2614. return false;
  2615. usbMutex = CreateMutex(sec, FALSE, name);
  2616. if (usbMutex == NULL) {
  2617. applog(LOG_ERR,
  2618. "MTX: %s USB failed to get '%s' err (%d)",
  2619. dname, name, (int)GetLastError());
  2620. sec = unsec(sec);
  2621. return false;
  2622. }
  2623. res = WaitForSingleObject(usbMutex, 0);
  2624. switch(res) {
  2625. case WAIT_OBJECT_0:
  2626. case WAIT_ABANDONED:
  2627. // Am I using it already?
  2628. for (i = 0; i < total_devices; i++) {
  2629. cgpu = get_devices(i);
  2630. if (cgpu->usbinfo.bus_number == bus_number &&
  2631. cgpu->usbinfo.device_address == device_address &&
  2632. cgpu->usbinfo.nodev == false) {
  2633. if (ReleaseMutex(usbMutex)) {
  2634. applog(LOG_WARNING,
  2635. "MTX: %s USB can't get '%s' - device in use",
  2636. dname, name);
  2637. goto fail;
  2638. }
  2639. applog(LOG_ERR,
  2640. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  2641. dname, name, (int)GetLastError());
  2642. goto fail;
  2643. }
  2644. }
  2645. break;
  2646. case WAIT_TIMEOUT:
  2647. if (!hotplug_mode)
  2648. applog(LOG_WARNING,
  2649. "MTX: %s USB failed to get '%s' - device in use",
  2650. dname, name);
  2651. goto fail;
  2652. case WAIT_FAILED:
  2653. applog(LOG_ERR,
  2654. "MTX: %s USB failed to get '%s' err (%d)",
  2655. dname, name, (int)GetLastError());
  2656. goto fail;
  2657. default:
  2658. applog(LOG_ERR,
  2659. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  2660. dname, name, (int)res);
  2661. goto fail;
  2662. }
  2663. add_in_use(bus_number, device_address);
  2664. in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
  2665. return true;
  2666. fail:
  2667. CloseHandle(usbMutex);
  2668. sec = unsec(sec);
  2669. return false;
  2670. #else
  2671. struct semid_ds seminfo;
  2672. union semun opt;
  2673. char name[64];
  2674. key_t *key;
  2675. int *sem;
  2676. int fd, count;
  2677. if (is_in_use_bd(bus_number, device_address))
  2678. return false;
  2679. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2680. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2681. if (fd == -1) {
  2682. applog(LOG_ERR,
  2683. "SEM: %s USB open failed '%s' err (%d) %s",
  2684. dname, name, errno, strerror(errno));
  2685. goto _out;
  2686. }
  2687. close(fd);
  2688. key = malloc(sizeof(*key));
  2689. if (unlikely(!key))
  2690. quit(1, "SEM: Failed to malloc key");
  2691. sem = malloc(sizeof(*sem));
  2692. if (unlikely(!sem))
  2693. quit(1, "SEM: Failed to malloc sem");
  2694. *key = ftok(name, 'K');
  2695. *sem = semget(*key, 1, IPC_CREAT | IPC_EXCL | 438);
  2696. if (*sem < 0) {
  2697. if (errno != EEXIST) {
  2698. applog(LOG_ERR,
  2699. "SEM: %s USB failed to get '%s' err (%d) %s",
  2700. dname, name, errno, strerror(errno));
  2701. goto free_out;
  2702. }
  2703. *sem = semget(*key, 1, 0);
  2704. if (*sem < 0) {
  2705. applog(LOG_ERR,
  2706. "SEM: %s USB failed to access '%s' err (%d) %s",
  2707. dname, name, errno, strerror(errno));
  2708. goto free_out;
  2709. }
  2710. opt.buf = &seminfo;
  2711. count = 0;
  2712. while (++count) {
  2713. // Should NEVER take 100ms
  2714. if (count > 99) {
  2715. applog(LOG_ERR,
  2716. "SEM: %s USB timeout waiting for (%d) '%s'",
  2717. dname, *sem, name);
  2718. goto free_out;
  2719. }
  2720. if (semctl(*sem, 0, IPC_STAT, opt) == -1) {
  2721. applog(LOG_ERR,
  2722. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  2723. dname, *sem, name, count, errno, strerror(errno));
  2724. goto free_out;
  2725. }
  2726. if (opt.buf->sem_otime != 0)
  2727. break;
  2728. nmsleep(1);
  2729. }
  2730. }
  2731. struct sembuf sops[] = {
  2732. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  2733. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  2734. };
  2735. if (semop(*sem, sops, 2)) {
  2736. if (errno == EAGAIN) {
  2737. if (!hotplug_mode)
  2738. applog(LOG_WARNING,
  2739. "SEM: %s USB failed to get (%d) '%s' - device in use",
  2740. dname, *sem, name);
  2741. } else {
  2742. applog(LOG_DEBUG,
  2743. "SEM: %s USB failed to get (%d) '%s' err (%d) %s",
  2744. dname, *sem, name, errno, strerror(errno));
  2745. }
  2746. goto free_out;
  2747. }
  2748. add_in_use(bus_number, device_address);
  2749. in_use_store_ress(bus_number, device_address, (void *)key, (void *)sem);
  2750. return true;
  2751. free_out:
  2752. free(sem);
  2753. free(key);
  2754. _out:
  2755. return false;
  2756. #endif
  2757. }
  2758. // Any errors should always be printed since they will rarely if ever occur
  2759. // and thus it is best to always display them
  2760. static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2761. {
  2762. applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2763. #ifdef WIN32
  2764. LPSECURITY_ATTRIBUTES sec = NULL;
  2765. HANDLE usbMutex = NULL;
  2766. char name[64];
  2767. sprintf(name, "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2768. in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
  2769. if (!usbMutex || !sec)
  2770. goto fila;
  2771. if (!ReleaseMutex(usbMutex))
  2772. applog(LOG_ERR,
  2773. "MTX: %s USB failed to release '%s' err (%d)",
  2774. dname, name, (int)GetLastError());
  2775. fila:
  2776. if (usbMutex)
  2777. CloseHandle(usbMutex);
  2778. if (sec)
  2779. unsec(sec);
  2780. remove_in_use(bus_number, device_address);
  2781. return;
  2782. #else
  2783. char name[64];
  2784. key_t *key = NULL;
  2785. int *sem = NULL;
  2786. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2787. in_use_get_ress(bus_number, device_address, (void **)(&key), (void **)(&sem));
  2788. if (!key || !sem)
  2789. goto fila;
  2790. struct sembuf sops[] = {
  2791. { 0, -1, SEM_UNDO }
  2792. };
  2793. // Allow a 10ms timeout
  2794. // exceeding this timeout means it would probably never succeed anyway
  2795. struct timespec timeout = { 0, 10000000 };
  2796. if (semtimedop(*sem, sops, 1, &timeout)) {
  2797. applog(LOG_ERR,
  2798. "SEM: %s USB failed to release '%s' err (%d) %s",
  2799. dname, name, errno, strerror(errno));
  2800. }
  2801. if (semctl(*sem, 0, IPC_RMID)) {
  2802. applog(LOG_WARNING,
  2803. "SEM: %s USB failed to remove SEM '%s' err (%d) %s",
  2804. dname, name, errno, strerror(errno));
  2805. }
  2806. fila:
  2807. free(sem);
  2808. free(key);
  2809. remove_in_use(bus_number, device_address);
  2810. return;
  2811. #endif
  2812. }
  2813. static void resource_process()
  2814. {
  2815. struct resource_work *res_work = NULL;
  2816. struct resource_reply *res_reply = NULL;
  2817. bool ok;
  2818. applog(LOG_DEBUG, "RES: %s (%d:%d) lock=%d",
  2819. res_work_head->dname,
  2820. (int)res_work_head->bus_number,
  2821. (int)res_work_head->device_address,
  2822. res_work_head->lock);
  2823. if (res_work_head->lock) {
  2824. ok = resource_lock(res_work_head->dname,
  2825. res_work_head->bus_number,
  2826. res_work_head->device_address);
  2827. applog(LOG_DEBUG, "RES: %s (%d:%d) lock ok=%d",
  2828. res_work_head->dname,
  2829. (int)res_work_head->bus_number,
  2830. (int)res_work_head->device_address,
  2831. ok);
  2832. res_reply = calloc(1, sizeof(*res_reply));
  2833. if (unlikely(!res_reply))
  2834. quit(1, "USB failed to calloc res_reply");
  2835. res_reply->bus_number = res_work_head->bus_number;
  2836. res_reply->device_address = res_work_head->device_address;
  2837. res_reply->got = ok;
  2838. res_reply->next = res_reply_head;
  2839. res_reply_head = res_reply;
  2840. }
  2841. else
  2842. resource_unlock(res_work_head->dname,
  2843. res_work_head->bus_number,
  2844. res_work_head->device_address);
  2845. res_work = res_work_head;
  2846. res_work_head = res_work_head->next;
  2847. free(res_work);
  2848. }
  2849. void *usb_resource_thread(void __maybe_unused *userdata)
  2850. {
  2851. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2852. RenameThread("usbresource");
  2853. applog(LOG_DEBUG, "RES: thread starting");
  2854. while (42) {
  2855. /* Wait to be told we have work to do */
  2856. cgsem_wait(&usb_resource_sem);
  2857. mutex_lock(&cgusbres_lock);
  2858. while (res_work_head)
  2859. resource_process();
  2860. mutex_unlock(&cgusbres_lock);
  2861. }
  2862. return NULL;
  2863. }