usbutils.c 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637
  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_GETVOLTS_S = "GetVolts";
  463. static const char *C_SENDTESTWORK_S = "SendTestWork";
  464. static const char *C_LATENCY_S = "SetLatency";
  465. static const char *C_SETLINE_S = "SetLine";
  466. static const char *C_VENDOR_S = "Vendor";
  467. static const char *C_SETFAN_S = "SetFan";
  468. static const char *C_FANREPLY_S = "GetFan";
  469. static const char *C_AVALON_TASK_S = "AvalonTask";
  470. static const char *C_AVALON_READ_S = "AvalonRead";
  471. static const char *C_GET_AVALON_READY_S = "AvalonReady";
  472. static const char *C_AVALON_RESET_S = "AvalonReset";
  473. static const char *C_GET_AVALON_RESET_S = "GetAvalonReset";
  474. static const char *C_FTDI_STATUS_S = "FTDIStatus";
  475. static const char *C_ENABLE_UART_S = "EnableUART";
  476. #ifdef EOL
  477. #undef EOL
  478. #endif
  479. #define EOL "\n"
  480. static const char *DESDEV = "Device";
  481. static const char *DESCON = "Config";
  482. static const char *DESSTR = "String";
  483. static const char *DESINT = "Interface";
  484. static const char *DESEP = "Endpoint";
  485. static const char *DESHID = "HID";
  486. static const char *DESRPT = "Report";
  487. static const char *DESPHY = "Physical";
  488. static const char *DESHUB = "Hub";
  489. static const char *EPIN = "In: ";
  490. static const char *EPOUT = "Out: ";
  491. static const char *EPX = "?: ";
  492. static const char *CONTROL = "Control";
  493. static const char *ISOCHRONOUS_X = "Isochronous+?";
  494. static const char *ISOCHRONOUS_N_X = "Isochronous+None+?";
  495. static const char *ISOCHRONOUS_N_D = "Isochronous+None+Data";
  496. static const char *ISOCHRONOUS_N_F = "Isochronous+None+Feedback";
  497. static const char *ISOCHRONOUS_N_I = "Isochronous+None+Implicit";
  498. static const char *ISOCHRONOUS_A_X = "Isochronous+Async+?";
  499. static const char *ISOCHRONOUS_A_D = "Isochronous+Async+Data";
  500. static const char *ISOCHRONOUS_A_F = "Isochronous+Async+Feedback";
  501. static const char *ISOCHRONOUS_A_I = "Isochronous+Async+Implicit";
  502. static const char *ISOCHRONOUS_D_X = "Isochronous+Adaptive+?";
  503. static const char *ISOCHRONOUS_D_D = "Isochronous+Adaptive+Data";
  504. static const char *ISOCHRONOUS_D_F = "Isochronous+Adaptive+Feedback";
  505. static const char *ISOCHRONOUS_D_I = "Isochronous+Adaptive+Implicit";
  506. static const char *ISOCHRONOUS_S_X = "Isochronous+Sync+?";
  507. static const char *ISOCHRONOUS_S_D = "Isochronous+Sync+Data";
  508. static const char *ISOCHRONOUS_S_F = "Isochronous+Sync+Feedback";
  509. static const char *ISOCHRONOUS_S_I = "Isochronous+Sync+Implicit";
  510. static const char *BULK = "Bulk";
  511. static const char *INTERRUPT = "Interrupt";
  512. static const char *UNKNOWN = "Unknown";
  513. static const char *err_io_str = " IO Error";
  514. static const char *err_access_str = " Access Denied-a";
  515. static const char *err_timeout_str = " Reply Timeout";
  516. static const char *err_pipe_str = " Access denied-p";
  517. static const char *err_other_str = " Access denied-o";
  518. static const char *usberrstr(int err)
  519. {
  520. switch (err) {
  521. case LIBUSB_ERROR_IO:
  522. return err_io_str;
  523. case LIBUSB_ERROR_ACCESS:
  524. return err_access_str;
  525. case LIBUSB_ERROR_TIMEOUT:
  526. return err_timeout_str;
  527. case LIBUSB_ERROR_PIPE:
  528. return err_pipe_str;
  529. case LIBUSB_ERROR_OTHER:
  530. return err_other_str;
  531. }
  532. return BLANK;
  533. }
  534. static const char *destype(uint8_t bDescriptorType)
  535. {
  536. switch (bDescriptorType) {
  537. case LIBUSB_DT_DEVICE:
  538. return DESDEV;
  539. case LIBUSB_DT_CONFIG:
  540. return DESCON;
  541. case LIBUSB_DT_STRING:
  542. return DESSTR;
  543. case LIBUSB_DT_INTERFACE:
  544. return DESINT;
  545. case LIBUSB_DT_ENDPOINT:
  546. return DESEP;
  547. case LIBUSB_DT_HID:
  548. return DESHID;
  549. case LIBUSB_DT_REPORT:
  550. return DESRPT;
  551. case LIBUSB_DT_PHYSICAL:
  552. return DESPHY;
  553. case LIBUSB_DT_HUB:
  554. return DESHUB;
  555. }
  556. return UNKNOWN;
  557. }
  558. static const char *epdir(uint8_t bEndpointAddress)
  559. {
  560. switch (bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) {
  561. case LIBUSB_ENDPOINT_IN:
  562. return EPIN;
  563. case LIBUSB_ENDPOINT_OUT:
  564. return EPOUT;
  565. }
  566. return EPX;
  567. }
  568. static const char *epatt(uint8_t bmAttributes)
  569. {
  570. switch(bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) {
  571. case LIBUSB_TRANSFER_TYPE_CONTROL:
  572. return CONTROL;
  573. case LIBUSB_TRANSFER_TYPE_BULK:
  574. return BULK;
  575. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  576. return INTERRUPT;
  577. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  578. switch(bmAttributes & LIBUSB_ISO_SYNC_TYPE_MASK) {
  579. case LIBUSB_ISO_SYNC_TYPE_NONE:
  580. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  581. case LIBUSB_ISO_USAGE_TYPE_DATA:
  582. return ISOCHRONOUS_N_D;
  583. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  584. return ISOCHRONOUS_N_F;
  585. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  586. return ISOCHRONOUS_N_I;
  587. }
  588. return ISOCHRONOUS_N_X;
  589. case LIBUSB_ISO_SYNC_TYPE_ASYNC:
  590. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  591. case LIBUSB_ISO_USAGE_TYPE_DATA:
  592. return ISOCHRONOUS_A_D;
  593. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  594. return ISOCHRONOUS_A_F;
  595. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  596. return ISOCHRONOUS_A_I;
  597. }
  598. return ISOCHRONOUS_A_X;
  599. case LIBUSB_ISO_SYNC_TYPE_ADAPTIVE:
  600. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  601. case LIBUSB_ISO_USAGE_TYPE_DATA:
  602. return ISOCHRONOUS_D_D;
  603. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  604. return ISOCHRONOUS_D_F;
  605. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  606. return ISOCHRONOUS_D_I;
  607. }
  608. return ISOCHRONOUS_D_X;
  609. case LIBUSB_ISO_SYNC_TYPE_SYNC:
  610. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  611. case LIBUSB_ISO_USAGE_TYPE_DATA:
  612. return ISOCHRONOUS_S_D;
  613. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  614. return ISOCHRONOUS_S_F;
  615. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  616. return ISOCHRONOUS_S_I;
  617. }
  618. return ISOCHRONOUS_S_X;
  619. }
  620. return ISOCHRONOUS_X;
  621. }
  622. return UNKNOWN;
  623. }
  624. static void append(char **buf, char *append, size_t *off, size_t *len)
  625. {
  626. int new = strlen(append);
  627. if ((new + *off) >= *len)
  628. {
  629. *len *= 2;
  630. *buf = realloc(*buf, *len);
  631. if (unlikely(!*buf))
  632. quit(1, "USB failed to realloc append");
  633. }
  634. strcpy(*buf + *off, append);
  635. *off += new;
  636. }
  637. 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)
  638. {
  639. char tmp[512];
  640. int err;
  641. err = libusb_set_configuration(handle, cd);
  642. if (err) {
  643. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Failed to set config descriptor to %d, err %d",
  644. (int)count, cd, err);
  645. append(buf, tmp, off, len);
  646. return false;
  647. }
  648. err = libusb_get_active_config_descriptor(dev, config);
  649. if (err) {
  650. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Failed to get active config descriptor set to %d, err %d",
  651. (int)count, cd, err);
  652. append(buf, tmp, off, len);
  653. return false;
  654. }
  655. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Set & Got active config descriptor to %d, err %d",
  656. (int)count, cd, err);
  657. append(buf, tmp, off, len);
  658. return true;
  659. }
  660. static void usb_full(ssize_t *count, libusb_device *dev, char **buf, size_t *off, size_t *len, int level)
  661. {
  662. struct libusb_device_descriptor desc;
  663. uint8_t bus_number;
  664. uint8_t device_address;
  665. struct libusb_device_handle *handle;
  666. struct libusb_config_descriptor *config;
  667. const struct libusb_interface_descriptor *idesc;
  668. const struct libusb_endpoint_descriptor *epdesc;
  669. unsigned char man[STRBUFLEN+1];
  670. unsigned char prod[STRBUFLEN+1];
  671. unsigned char ser[STRBUFLEN+1];
  672. char tmp[512];
  673. int err, i, j, k;
  674. err = libusb_get_device_descriptor(dev, &desc);
  675. if (opt_usb_list_all && err) {
  676. snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Failed to get descriptor, err %d",
  677. (int)(++(*count)), err);
  678. append(buf, tmp, off, len);
  679. return;
  680. }
  681. bus_number = libusb_get_bus_number(dev);
  682. device_address = libusb_get_device_address(dev);
  683. if (!opt_usb_list_all) {
  684. bool known = false;
  685. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  686. if ((find_dev[i].idVendor == desc.idVendor) &&
  687. (find_dev[i].idProduct == desc.idProduct)) {
  688. known = true;
  689. break;
  690. }
  691. if (!known)
  692. return;
  693. }
  694. (*count)++;
  695. if (level == 0) {
  696. snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Bus %d Device %d ID: %04x:%04x",
  697. (int)(*count), (int)bus_number, (int)device_address,
  698. desc.idVendor, desc.idProduct);
  699. } else {
  700. snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Bus %d Device %d Device Descriptor:" EOL "\tLength: %d" EOL
  701. "\tDescriptor Type: %s" EOL "\tUSB: %04x" EOL "\tDeviceClass: %d" EOL
  702. "\tDeviceSubClass: %d" EOL "\tDeviceProtocol: %d" EOL "\tMaxPacketSize0: %d" EOL
  703. "\tidVendor: %04x" EOL "\tidProduct: %04x" EOL "\tDeviceRelease: %x" EOL
  704. "\tNumConfigurations: %d",
  705. (int)(*count), (int)bus_number, (int)device_address,
  706. (int)(desc.bLength), destype(desc.bDescriptorType),
  707. desc.bcdUSB, (int)(desc.bDeviceClass), (int)(desc.bDeviceSubClass),
  708. (int)(desc.bDeviceProtocol), (int)(desc.bMaxPacketSize0),
  709. desc.idVendor, desc.idProduct, desc.bcdDevice,
  710. (int)(desc.bNumConfigurations));
  711. }
  712. append(buf, tmp, off, len);
  713. err = libusb_open(dev, &handle);
  714. if (err) {
  715. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Failed to open, err %d", (int)(*count), err);
  716. append(buf, tmp, off, len);
  717. return;
  718. }
  719. err = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, man, STRBUFLEN);
  720. if (err < 0)
  721. snprintf((char *)man, sizeof(man), "** err(%d)%s", err, usberrstr(err));
  722. err = libusb_get_string_descriptor_ascii(handle, desc.iProduct, prod, STRBUFLEN);
  723. if (err < 0)
  724. snprintf((char *)prod, sizeof(prod), "** err(%d)%s", err, usberrstr(err));
  725. if (level == 0) {
  726. libusb_close(handle);
  727. snprintf(tmp, sizeof(tmp), EOL " Manufacturer: '%s'" EOL " Product: '%s'", man, prod);
  728. append(buf, tmp, off, len);
  729. return;
  730. }
  731. if (libusb_kernel_driver_active(handle, 0) == 1) {
  732. snprintf(tmp, sizeof(tmp), EOL " * dev %d: kernel attached", (int)(*count));
  733. append(buf, tmp, off, len);
  734. }
  735. err = libusb_get_active_config_descriptor(dev, &config);
  736. if (err) {
  737. if (!setgetdes(*count, dev, handle, &config, 1, buf, off, len)
  738. && !setgetdes(*count, dev, handle, &config, 0, buf, off, len)) {
  739. libusb_close(handle);
  740. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Failed to set config descriptor to %d or %d",
  741. (int)(*count), 1, 0);
  742. append(buf, tmp, off, len);
  743. return;
  744. }
  745. }
  746. snprintf(tmp, sizeof(tmp), EOL " dev %d: Active Config:" EOL "\tDescriptorType: %s" EOL
  747. "\tNumInterfaces: %d" EOL "\tConfigurationValue: %d" EOL
  748. "\tAttributes: %d" EOL "\tMaxPower: %d",
  749. (int)(*count), destype(config->bDescriptorType),
  750. (int)(config->bNumInterfaces), (int)(config->iConfiguration),
  751. (int)(config->bmAttributes), (int)(config->MaxPower));
  752. append(buf, tmp, off, len);
  753. for (i = 0; i < (int)(config->bNumInterfaces); i++) {
  754. for (j = 0; j < config->interface[i].num_altsetting; j++) {
  755. idesc = &(config->interface[i].altsetting[j]);
  756. snprintf(tmp, sizeof(tmp), EOL " _dev %d: Interface Descriptor %d:" EOL
  757. "\tDescriptorType: %s" EOL "\tInterfaceNumber: %d" EOL
  758. "\tNumEndpoints: %d" EOL "\tInterfaceClass: %d" EOL
  759. "\tInterfaceSubClass: %d" EOL "\tInterfaceProtocol: %d",
  760. (int)(*count), j, destype(idesc->bDescriptorType),
  761. (int)(idesc->bInterfaceNumber),
  762. (int)(idesc->bNumEndpoints),
  763. (int)(idesc->bInterfaceClass),
  764. (int)(idesc->bInterfaceSubClass),
  765. (int)(idesc->bInterfaceProtocol));
  766. append(buf, tmp, off, len);
  767. for (k = 0; k < (int)(idesc->bNumEndpoints); k++) {
  768. epdesc = &(idesc->endpoint[k]);
  769. snprintf(tmp, sizeof(tmp), EOL " __dev %d: Interface %d Endpoint %d:" EOL
  770. "\tDescriptorType: %s" EOL
  771. "\tEndpointAddress: %s0x%x" EOL
  772. "\tAttributes: %s" EOL "\tMaxPacketSize: %d" EOL
  773. "\tInterval: %d" EOL "\tRefresh: %d",
  774. (int)(*count), (int)(idesc->bInterfaceNumber), k,
  775. destype(epdesc->bDescriptorType),
  776. epdir(epdesc->bEndpointAddress),
  777. (int)(epdesc->bEndpointAddress),
  778. epatt(epdesc->bmAttributes),
  779. epdesc->wMaxPacketSize,
  780. (int)(epdesc->bInterval),
  781. (int)(epdesc->bRefresh));
  782. append(buf, tmp, off, len);
  783. }
  784. }
  785. }
  786. libusb_free_config_descriptor(config);
  787. config = NULL;
  788. err = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, ser, STRBUFLEN);
  789. if (err < 0)
  790. snprintf((char *)ser, sizeof(ser), "** err(%d)%s", err, usberrstr(err));
  791. snprintf(tmp, sizeof(tmp), EOL " dev %d: More Info:" EOL "\tManufacturer: '%s'" EOL
  792. "\tProduct: '%s'" EOL "\tSerial '%s'",
  793. (int)(*count), man, prod, ser);
  794. append(buf, tmp, off, len);
  795. libusb_close(handle);
  796. }
  797. // Function to dump all USB devices
  798. void usb_all(int level)
  799. {
  800. libusb_device **list;
  801. ssize_t count, i, j;
  802. char *buf;
  803. size_t len, off;
  804. count = libusb_get_device_list(NULL, &list);
  805. if (count < 0) {
  806. applog(LOG_ERR, "USB all: failed, err %d%s", (int)count, usberrstr((int)count));
  807. return;
  808. }
  809. if (count == 0)
  810. applog(LOG_WARNING, "USB all: found no devices");
  811. else
  812. {
  813. len = 10000;
  814. buf = malloc(len+1);
  815. if (unlikely(!buf))
  816. quit(1, "USB failed to malloc buf in usb_all");
  817. sprintf(buf, "USB all: found %d devices", (int)count);
  818. off = strlen(buf);
  819. if (!opt_usb_list_all)
  820. append(&buf, " - listing known devices", &off, &len);
  821. j = -1;
  822. for (i = 0; i < count; i++)
  823. usb_full(&j, list[i], &buf, &off, &len, level);
  824. _applog(LOG_WARNING, buf);
  825. free(buf);
  826. if (j == -1)
  827. applog(LOG_WARNING, "No known USB devices");
  828. else
  829. applog(LOG_WARNING, "%d %sUSB devices",
  830. (int)(++j), opt_usb_list_all ? BLANK : "known ");
  831. }
  832. libusb_free_device_list(list, 1);
  833. }
  834. static void cgusb_check_init()
  835. {
  836. mutex_lock(&cgusb_lock);
  837. if (stats_initialised == false) {
  838. // N.B. environment LIBUSB_DEBUG also sets libusb_set_debug()
  839. if (opt_usbdump >= 0) {
  840. libusb_set_debug(NULL, opt_usbdump);
  841. usb_all(opt_usbdump);
  842. }
  843. usb_commands = malloc(sizeof(*usb_commands) * C_MAX);
  844. if (unlikely(!usb_commands))
  845. quit(1, "USB failed to malloc usb_commands");
  846. // use constants so the stat generation is very quick
  847. // and the association between number and name can't
  848. // be missalined easily
  849. usb_commands[C_REJECTED] = C_REJECTED_S;
  850. usb_commands[C_PING] = C_PING_S;
  851. usb_commands[C_CLEAR] = C_CLEAR_S;
  852. usb_commands[C_REQUESTVERSION] = C_REQUESTVERSION_S;
  853. usb_commands[C_GETVERSION] = C_GETVERSION_S;
  854. usb_commands[C_REQUESTFPGACOUNT] = C_REQUESTFPGACOUNT_S;
  855. usb_commands[C_GETFPGACOUNT] = C_GETFPGACOUNT_S;
  856. usb_commands[C_STARTPROGRAM] = C_STARTPROGRAM_S;
  857. usb_commands[C_STARTPROGRAMSTATUS] = C_STARTPROGRAMSTATUS_S;
  858. usb_commands[C_PROGRAM] = C_PROGRAM_S;
  859. usb_commands[C_PROGRAMSTATUS] = C_PROGRAMSTATUS_S;
  860. usb_commands[C_PROGRAMSTATUS2] = C_PROGRAMSTATUS2_S;
  861. usb_commands[C_FINALPROGRAMSTATUS] = C_FINALPROGRAMSTATUS_S;
  862. usb_commands[C_SETCLOCK] = C_SETCLOCK_S;
  863. usb_commands[C_REPLYSETCLOCK] = C_REPLYSETCLOCK_S;
  864. usb_commands[C_REQUESTUSERCODE] = C_REQUESTUSERCODE_S;
  865. usb_commands[C_GETUSERCODE] = C_GETUSERCODE_S;
  866. usb_commands[C_REQUESTTEMPERATURE] = C_REQUESTTEMPERATURE_S;
  867. usb_commands[C_GETTEMPERATURE] = C_GETTEMPERATURE_S;
  868. usb_commands[C_SENDWORK] = C_SENDWORK_S;
  869. usb_commands[C_SENDWORKSTATUS] = C_SENDWORKSTATUS_S;
  870. usb_commands[C_REQUESTWORKSTATUS] = C_REQUESTWORKSTATUS_S;
  871. usb_commands[C_GETWORKSTATUS] = C_GETWORKSTATUS_S;
  872. usb_commands[C_REQUESTIDENTIFY] = C_REQUESTIDENTIFY_S;
  873. usb_commands[C_GETIDENTIFY] = C_GETIDENTIFY_S;
  874. usb_commands[C_REQUESTFLASH] = C_REQUESTFLASH_S;
  875. usb_commands[C_REQUESTSENDWORK] = C_REQUESTSENDWORK_S;
  876. usb_commands[C_REQUESTSENDWORKSTATUS] = C_REQUESTSENDWORKSTATUS_S;
  877. usb_commands[C_RESET] = C_RESET_S;
  878. usb_commands[C_SETBAUD] = C_SETBAUD_S;
  879. usb_commands[C_SETDATA] = C_SETDATA_S;
  880. usb_commands[C_SETFLOW] = C_SETFLOW_S;
  881. usb_commands[C_SETMODEM] = C_SETMODEM_S;
  882. usb_commands[C_PURGERX] = C_PURGERX_S;
  883. usb_commands[C_PURGETX] = C_PURGETX_S;
  884. usb_commands[C_FLASHREPLY] = C_FLASHREPLY_S;
  885. usb_commands[C_REQUESTDETAILS] = C_REQUESTDETAILS_S;
  886. usb_commands[C_GETDETAILS] = C_GETDETAILS_S;
  887. usb_commands[C_REQUESTRESULTS] = C_REQUESTRESULTS_S;
  888. usb_commands[C_GETRESULTS] = C_GETRESULTS_S;
  889. usb_commands[C_REQUESTQUEJOB] = C_REQUESTQUEJOB_S;
  890. usb_commands[C_REQUESTQUEJOBSTATUS] = C_REQUESTQUEJOBSTATUS_S;
  891. usb_commands[C_QUEJOB] = C_QUEJOB_S;
  892. usb_commands[C_QUEJOBSTATUS] = C_QUEJOBSTATUS_S;
  893. usb_commands[C_QUEFLUSH] = C_QUEFLUSH_S;
  894. usb_commands[C_QUEFLUSHREPLY] = C_QUEFLUSHREPLY_S;
  895. usb_commands[C_REQUESTVOLTS] = C_REQUESTVOLTS_S;
  896. usb_commands[C_GETVOLTS] = C_GETVOLTS_S;
  897. usb_commands[C_SENDTESTWORK] = C_SENDTESTWORK_S;
  898. usb_commands[C_LATENCY] = C_LATENCY_S;
  899. usb_commands[C_SETLINE] = C_SETLINE_S;
  900. usb_commands[C_VENDOR] = C_VENDOR_S;
  901. usb_commands[C_SETFAN] = C_SETFAN_S;
  902. usb_commands[C_FANREPLY] = C_FANREPLY_S;
  903. usb_commands[C_AVALON_TASK] = C_AVALON_TASK_S;
  904. usb_commands[C_AVALON_READ] = C_AVALON_READ_S;
  905. usb_commands[C_GET_AVALON_READY] = C_GET_AVALON_READY_S;
  906. usb_commands[C_AVALON_RESET] = C_AVALON_RESET_S;
  907. usb_commands[C_GET_AVALON_RESET] = C_GET_AVALON_RESET_S;
  908. usb_commands[C_FTDI_STATUS] = C_FTDI_STATUS_S;
  909. usb_commands[C_ENABLE_UART] = C_ENABLE_UART_S;
  910. stats_initialised = true;
  911. }
  912. mutex_unlock(&cgusb_lock);
  913. }
  914. const char *usb_cmdname(enum usb_cmds cmd)
  915. {
  916. cgusb_check_init();
  917. return usb_commands[cmd];
  918. }
  919. void usb_applog(struct cgpu_info *cgpu, enum usb_cmds cmd, char *msg, int amount, int err)
  920. {
  921. if (msg && !*msg)
  922. msg = NULL;
  923. if (!msg && amount == 0 && err == LIBUSB_SUCCESS)
  924. msg = (char *)nodatareturned;
  925. applog(LOG_ERR, "%s%i: %s failed%s%s (err=%d amt=%d)",
  926. cgpu->drv->name, cgpu->device_id,
  927. usb_cmdname(cmd),
  928. msg ? space : BLANK, msg ? msg : BLANK,
  929. err, amount);
  930. }
  931. static void in_use_store_ress(uint8_t bus_number, uint8_t device_address, void *resource1, void *resource2)
  932. {
  933. struct usb_in_use_list *in_use_tmp;
  934. bool found = false, empty = true;
  935. mutex_lock(&cgusb_lock);
  936. in_use_tmp = in_use_head;
  937. while (in_use_tmp) {
  938. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  939. in_use_tmp->in_use.device_address == (int)device_address) {
  940. found = true;
  941. if (in_use_tmp->in_use.resource1)
  942. empty = false;
  943. in_use_tmp->in_use.resource1 = resource1;
  944. if (in_use_tmp->in_use.resource2)
  945. empty = false;
  946. in_use_tmp->in_use.resource2 = resource2;
  947. break;
  948. }
  949. in_use_tmp = in_use_tmp->next;
  950. }
  951. mutex_unlock(&cgusb_lock);
  952. if (found == false)
  953. applog(LOG_ERR, "FAIL: USB store_ress not found (%d:%d)",
  954. (int)bus_number, (int)device_address);
  955. if (empty == false)
  956. applog(LOG_ERR, "FAIL: USB store_ress not empty (%d:%d)",
  957. (int)bus_number, (int)device_address);
  958. }
  959. static void in_use_get_ress(uint8_t bus_number, uint8_t device_address, void **resource1, void **resource2)
  960. {
  961. struct usb_in_use_list *in_use_tmp;
  962. bool found = false, empty = false;
  963. mutex_lock(&cgusb_lock);
  964. in_use_tmp = in_use_head;
  965. while (in_use_tmp) {
  966. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  967. in_use_tmp->in_use.device_address == (int)device_address) {
  968. found = true;
  969. if (!in_use_tmp->in_use.resource1)
  970. empty = true;
  971. *resource1 = in_use_tmp->in_use.resource1;
  972. in_use_tmp->in_use.resource1 = NULL;
  973. if (!in_use_tmp->in_use.resource2)
  974. empty = true;
  975. *resource2 = in_use_tmp->in_use.resource2;
  976. in_use_tmp->in_use.resource2 = NULL;
  977. break;
  978. }
  979. in_use_tmp = in_use_tmp->next;
  980. }
  981. mutex_unlock(&cgusb_lock);
  982. if (found == false)
  983. applog(LOG_ERR, "FAIL: USB get_lock not found (%d:%d)",
  984. (int)bus_number, (int)device_address);
  985. if (empty == true)
  986. applog(LOG_ERR, "FAIL: USB get_lock empty (%d:%d)",
  987. (int)bus_number, (int)device_address);
  988. }
  989. static bool __is_in_use(uint8_t bus_number, uint8_t device_address)
  990. {
  991. struct usb_in_use_list *in_use_tmp;
  992. bool ret = false;
  993. in_use_tmp = in_use_head;
  994. while (in_use_tmp) {
  995. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  996. in_use_tmp->in_use.device_address == (int)device_address) {
  997. ret = true;
  998. break;
  999. }
  1000. in_use_tmp = in_use_tmp->next;
  1001. }
  1002. return ret;
  1003. }
  1004. static bool is_in_use_bd(uint8_t bus_number, uint8_t device_address)
  1005. {
  1006. bool ret;
  1007. mutex_lock(&cgusb_lock);
  1008. ret = __is_in_use(bus_number, device_address);
  1009. mutex_unlock(&cgusb_lock);
  1010. return ret;
  1011. }
  1012. static bool is_in_use(libusb_device *dev)
  1013. {
  1014. return is_in_use_bd(libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1015. }
  1016. static void add_in_use(uint8_t bus_number, uint8_t device_address)
  1017. {
  1018. struct usb_in_use_list *in_use_tmp;
  1019. bool found = false;
  1020. mutex_lock(&cgusb_lock);
  1021. if (unlikely(__is_in_use(bus_number, device_address))) {
  1022. found = true;
  1023. goto nofway;
  1024. }
  1025. in_use_tmp = calloc(1, sizeof(*in_use_tmp));
  1026. if (unlikely(!in_use_tmp))
  1027. quit(1, "USB failed to calloc in_use_tmp");
  1028. in_use_tmp->in_use.bus_number = (int)bus_number;
  1029. in_use_tmp->in_use.device_address = (int)device_address;
  1030. in_use_tmp->next = in_use_head;
  1031. if (in_use_head)
  1032. in_use_head->prev = in_use_tmp;
  1033. in_use_head = in_use_tmp;
  1034. nofway:
  1035. mutex_unlock(&cgusb_lock);
  1036. if (found)
  1037. applog(LOG_ERR, "FAIL: USB add already in use (%d:%d)",
  1038. (int)bus_number, (int)device_address);
  1039. }
  1040. static void remove_in_use(uint8_t bus_number, uint8_t device_address)
  1041. {
  1042. struct usb_in_use_list *in_use_tmp;
  1043. bool found = false;
  1044. mutex_lock(&cgusb_lock);
  1045. in_use_tmp = in_use_head;
  1046. while (in_use_tmp) {
  1047. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  1048. in_use_tmp->in_use.device_address == (int)device_address) {
  1049. found = true;
  1050. if (in_use_tmp == in_use_head) {
  1051. in_use_head = in_use_head->next;
  1052. if (in_use_head)
  1053. in_use_head->prev = NULL;
  1054. } else {
  1055. in_use_tmp->prev->next = in_use_tmp->next;
  1056. if (in_use_tmp->next)
  1057. in_use_tmp->next->prev = in_use_tmp->prev;
  1058. }
  1059. free(in_use_tmp);
  1060. break;
  1061. }
  1062. in_use_tmp = in_use_tmp->next;
  1063. }
  1064. mutex_unlock(&cgusb_lock);
  1065. if (!found)
  1066. applog(LOG_ERR, "FAIL: USB remove not already in use (%d:%d)",
  1067. (int)bus_number, (int)device_address);
  1068. }
  1069. static bool cgminer_usb_lock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  1070. {
  1071. struct resource_work *res_work;
  1072. bool ret;
  1073. applog(LOG_DEBUG, "USB lock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
  1074. res_work = calloc(1, sizeof(*res_work));
  1075. if (unlikely(!res_work))
  1076. quit(1, "USB failed to calloc lock res_work");
  1077. res_work->lock = true;
  1078. res_work->dname = (const char *)(drv->dname);
  1079. res_work->bus_number = bus_number;
  1080. res_work->device_address = device_address;
  1081. mutex_lock(&cgusbres_lock);
  1082. res_work->next = res_work_head;
  1083. res_work_head = res_work;
  1084. mutex_unlock(&cgusbres_lock);
  1085. cgsem_post(&usb_resource_sem);
  1086. // TODO: add a timeout fail - restart the resource thread?
  1087. while (true) {
  1088. nmsleep(50);
  1089. mutex_lock(&cgusbres_lock);
  1090. if (res_reply_head) {
  1091. struct resource_reply *res_reply_prev = NULL;
  1092. struct resource_reply *res_reply = res_reply_head;
  1093. while (res_reply) {
  1094. if (res_reply->bus_number == bus_number &&
  1095. res_reply->device_address == device_address) {
  1096. if (res_reply_prev)
  1097. res_reply_prev->next = res_reply->next;
  1098. else
  1099. res_reply_head = res_reply->next;
  1100. mutex_unlock(&cgusbres_lock);
  1101. ret = res_reply->got;
  1102. free(res_reply);
  1103. return ret;
  1104. }
  1105. res_reply_prev = res_reply;
  1106. res_reply = res_reply->next;
  1107. }
  1108. }
  1109. mutex_unlock(&cgusbres_lock);
  1110. }
  1111. }
  1112. static bool cgminer_usb_lock(struct device_drv *drv, libusb_device *dev)
  1113. {
  1114. return cgminer_usb_lock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1115. }
  1116. static void cgminer_usb_unlock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  1117. {
  1118. struct resource_work *res_work;
  1119. applog(LOG_DEBUG, "USB unlock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
  1120. res_work = calloc(1, sizeof(*res_work));
  1121. if (unlikely(!res_work))
  1122. quit(1, "USB failed to calloc unlock res_work");
  1123. res_work->lock = false;
  1124. res_work->dname = (const char *)(drv->dname);
  1125. res_work->bus_number = bus_number;
  1126. res_work->device_address = device_address;
  1127. mutex_lock(&cgusbres_lock);
  1128. res_work->next = res_work_head;
  1129. res_work_head = res_work;
  1130. mutex_unlock(&cgusbres_lock);
  1131. cgsem_post(&usb_resource_sem);
  1132. return;
  1133. }
  1134. static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
  1135. {
  1136. cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1137. }
  1138. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  1139. {
  1140. applog(LOG_DEBUG, "USB free %s", cgusb->found->name);
  1141. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  1142. free(cgusb->serial_string);
  1143. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  1144. free(cgusb->manuf_string);
  1145. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  1146. free(cgusb->prod_string);
  1147. free(cgusb->descriptor);
  1148. free(cgusb->found);
  1149. if (cgusb->buffer)
  1150. free(cgusb->buffer);
  1151. free(cgusb);
  1152. return NULL;
  1153. }
  1154. void usb_uninit(struct cgpu_info *cgpu)
  1155. {
  1156. applog(LOG_DEBUG, "USB uninit %s%i",
  1157. cgpu->drv->name, cgpu->device_id);
  1158. // May have happened already during a failed initialisation
  1159. // if release_cgpu() was called due to a USB NODEV(err)
  1160. if (!cgpu->usbdev)
  1161. return;
  1162. if (!libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface)) {
  1163. cg_wlock(&cgusb_fd_lock);
  1164. libusb_close(cgpu->usbdev->handle);
  1165. cg_wunlock(&cgusb_fd_lock);
  1166. }
  1167. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  1168. }
  1169. /*
  1170. * N.B. this is always called inside
  1171. * DEVLOCK(cgpu, pstate);
  1172. */
  1173. static void release_cgpu(struct cgpu_info *cgpu)
  1174. {
  1175. struct cg_usb_device *cgusb = cgpu->usbdev;
  1176. struct cgpu_info *lookcgpu;
  1177. int i;
  1178. applog(LOG_DEBUG, "USB release %s%i",
  1179. cgpu->drv->name, cgpu->device_id);
  1180. // It has already been done
  1181. if (cgpu->usbinfo.nodev)
  1182. return;
  1183. zombie_devs++;
  1184. total_count--;
  1185. drv_count[cgpu->drv->drv_id].count--;
  1186. cgpu->usbinfo.nodev = true;
  1187. cgpu->usbinfo.nodev_count++;
  1188. cgtime(&cgpu->usbinfo.last_nodev);
  1189. // Any devices sharing the same USB device should be marked also
  1190. // Currently only MMQ shares a USB device
  1191. for (i = 0; i < total_devices; i++) {
  1192. lookcgpu = get_devices(i);
  1193. if (lookcgpu != cgpu && lookcgpu->usbdev == cgusb) {
  1194. total_count--;
  1195. drv_count[lookcgpu->drv->drv_id].count--;
  1196. lookcgpu->usbinfo.nodev = true;
  1197. lookcgpu->usbinfo.nodev_count++;
  1198. memcpy(&(lookcgpu->usbinfo.last_nodev),
  1199. &(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
  1200. lookcgpu->usbdev = NULL;
  1201. }
  1202. }
  1203. usb_uninit(cgpu);
  1204. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1205. }
  1206. // Currently only used by MMQ
  1207. struct cgpu_info *usb_copy_cgpu(struct cgpu_info *orig)
  1208. {
  1209. struct cgpu_info *copy = calloc(1, sizeof(*copy));
  1210. if (unlikely(!copy))
  1211. quit(1, "Failed to calloc cgpu for %s in usb_copy_cgpu", orig->drv->dname);
  1212. copy->name = orig->name;
  1213. copy->drv = copy_drv(orig->drv);
  1214. copy->deven = orig->deven;
  1215. copy->threads = orig->threads;
  1216. copy->usbdev = orig->usbdev;
  1217. memcpy(&(copy->usbinfo), &(orig->usbinfo), sizeof(copy->usbinfo));
  1218. copy->usbinfo.nodev = (copy->usbdev == NULL);
  1219. copy->usbinfo.devlock = orig->usbinfo.devlock;
  1220. return copy;
  1221. }
  1222. struct cgpu_info *usb_alloc_cgpu(struct device_drv *drv, int threads)
  1223. {
  1224. struct cgpu_info *cgpu = calloc(1, sizeof(*cgpu));
  1225. if (unlikely(!cgpu))
  1226. quit(1, "Failed to calloc cgpu for %s in usb_alloc_cgpu", drv->dname);
  1227. cgpu->drv = drv;
  1228. cgpu->deven = DEV_ENABLED;
  1229. cgpu->threads = threads;
  1230. cgpu->usbinfo.nodev = true;
  1231. cgpu->usbinfo.devlock = calloc(1, sizeof(*(cgpu->usbinfo.devlock)));
  1232. if (unlikely(!cgpu->usbinfo.devlock))
  1233. quit(1, "Failed to calloc devlock for %s in usb_alloc_cgpu", drv->dname);
  1234. rwlock_init(cgpu->usbinfo.devlock);
  1235. return cgpu;
  1236. }
  1237. struct cgpu_info *usb_free_cgpu_devlock(struct cgpu_info *cgpu, bool free_devlock)
  1238. {
  1239. if (cgpu->drv->copy)
  1240. free(cgpu->drv);
  1241. free(cgpu->device_path);
  1242. if (free_devlock)
  1243. free(cgpu->usbinfo.devlock);
  1244. free(cgpu);
  1245. return NULL;
  1246. }
  1247. #define USB_INIT_FAIL 0
  1248. #define USB_INIT_OK 1
  1249. #define USB_INIT_IGNORE 2
  1250. /*
  1251. * WARNING - these assume DEVLOCK(cgpu, pstate) is called first and
  1252. * DEVUNLOCK(cgpu, pstate) in called in the same function with the same pstate
  1253. * given to DEVLOCK.
  1254. * You must call DEVUNLOCK(cgpu, pstate) before exiting the function or it will leave
  1255. * the thread Cancelability unrestored
  1256. */
  1257. #define DEVLOCK(cgpu, _pth_state) do { \
  1258. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &_pth_state); \
  1259. wr_lock(cgpu->usbinfo.devlock); \
  1260. } while (0)
  1261. #define DEVUNLOCK(cgpu, _pth_state) do { \
  1262. wr_unlock(cgpu->usbinfo.devlock); \
  1263. pthread_setcancelstate(_pth_state, NULL); \
  1264. } while (0)
  1265. static int _usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1266. {
  1267. struct cg_usb_device *cgusb = NULL;
  1268. struct libusb_config_descriptor *config = NULL;
  1269. const struct libusb_interface_descriptor *idesc;
  1270. const struct libusb_endpoint_descriptor *epdesc;
  1271. unsigned char strbuf[STRBUFLEN+1];
  1272. char devpath[32];
  1273. char devstr[STRBUFLEN+1];
  1274. int err, i, j, k, pstate;
  1275. int bad = USB_INIT_FAIL;
  1276. int cfg;
  1277. DEVLOCK(cgpu, pstate);
  1278. cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
  1279. cgpu->usbinfo.device_address = libusb_get_device_address(dev);
  1280. snprintf(devpath, sizeof(devpath), "%d:%d",
  1281. (int)(cgpu->usbinfo.bus_number),
  1282. (int)(cgpu->usbinfo.device_address));
  1283. cgpu->device_path = strdup(devpath);
  1284. snprintf(devstr, sizeof(devstr), "- %s device %s", found->name, devpath);
  1285. cgusb = calloc(1, sizeof(*cgusb));
  1286. if (unlikely(!cgusb))
  1287. quit(1, "USB failed to calloc _usb_init cgusb");
  1288. cgusb->found = found;
  1289. if (found->idVendor == IDVENDOR_FTDI)
  1290. cgusb->usb_type = USB_TYPE_FTDI;
  1291. cgusb->ident = found->ident;
  1292. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  1293. if (unlikely(!cgusb->descriptor))
  1294. quit(1, "USB failed to calloc _usb_init cgusb descriptor");
  1295. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  1296. if (err) {
  1297. applog(LOG_DEBUG,
  1298. "USB init failed to get descriptor, err %d %s",
  1299. err, devstr);
  1300. goto dame;
  1301. }
  1302. cg_wlock(&cgusb_fd_lock);
  1303. err = libusb_open(dev, &(cgusb->handle));
  1304. cg_wunlock(&cgusb_fd_lock);
  1305. if (err) {
  1306. switch (err) {
  1307. case LIBUSB_ERROR_ACCESS:
  1308. applog(LOG_ERR,
  1309. "USB init open device failed, err %d, "
  1310. "you dont have priviledge to access %s",
  1311. err, devstr);
  1312. break;
  1313. #ifdef WIN32
  1314. // Windows specific message
  1315. case LIBUSB_ERROR_NOT_SUPPORTED:
  1316. applog(LOG_ERR,
  1317. "USB init, open device failed, err %d, "
  1318. "you need to install a WinUSB driver for %s",
  1319. err, devstr);
  1320. break;
  1321. #endif
  1322. default:
  1323. applog(LOG_DEBUG,
  1324. "USB init, open failed, err %d %s",
  1325. err, devstr);
  1326. }
  1327. goto dame;
  1328. }
  1329. #ifndef WIN32
  1330. if (libusb_kernel_driver_active(cgusb->handle, found->kernel) == 1) {
  1331. applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
  1332. err = libusb_detach_kernel_driver(cgusb->handle, found->kernel);
  1333. if (err == 0) {
  1334. applog(LOG_DEBUG,
  1335. "USB init, kernel detached successfully %s",
  1336. devstr);
  1337. } else {
  1338. applog(LOG_WARNING,
  1339. "USB init, kernel detach failed, err %d in use? %s",
  1340. err, devstr);
  1341. goto cldame;
  1342. }
  1343. }
  1344. #endif
  1345. if (found->iManufacturer) {
  1346. unsigned char man[STRBUFLEN+1];
  1347. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1348. cgusb->descriptor->iManufacturer,
  1349. man, STRBUFLEN);
  1350. if (err < 0) {
  1351. applog(LOG_DEBUG,
  1352. "USB init, failed to get iManufacturer, err %d %s",
  1353. err, devstr);
  1354. goto cldame;
  1355. }
  1356. if (strcmp((char *)man, found->iManufacturer)) {
  1357. applog(LOG_DEBUG, "USB init, iManufacturer mismatch %s",
  1358. devstr);
  1359. bad = USB_INIT_IGNORE;
  1360. goto cldame;
  1361. }
  1362. }
  1363. if (found->iProduct) {
  1364. unsigned char prod[STRBUFLEN+1];
  1365. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1366. cgusb->descriptor->iProduct,
  1367. prod, STRBUFLEN);
  1368. if (err < 0) {
  1369. applog(LOG_DEBUG,
  1370. "USB init, failed to get iProduct, err %d %s",
  1371. err, devstr);
  1372. goto cldame;
  1373. }
  1374. if (strcmp((char *)prod, found->iProduct)) {
  1375. applog(LOG_DEBUG, "USB init, iProduct mismatch %s",
  1376. devstr);
  1377. bad = USB_INIT_IGNORE;
  1378. goto cldame;
  1379. }
  1380. }
  1381. cfg = -1;
  1382. err = libusb_get_configuration(cgusb->handle, &cfg);
  1383. if (err)
  1384. cfg = -1;
  1385. // Try to set it if we can't read it or it's different
  1386. if (cfg != found->config) {
  1387. err = libusb_set_configuration(cgusb->handle, found->config);
  1388. if (err) {
  1389. switch(err) {
  1390. case LIBUSB_ERROR_BUSY:
  1391. applog(LOG_WARNING,
  1392. "USB init, set config %d in use %s",
  1393. found->config, devstr);
  1394. break;
  1395. default:
  1396. applog(LOG_DEBUG,
  1397. "USB init, failed to set config to %d, err %d %s",
  1398. found->config, err, devstr);
  1399. }
  1400. goto cldame;
  1401. }
  1402. }
  1403. err = libusb_get_active_config_descriptor(dev, &config);
  1404. if (err) {
  1405. applog(LOG_DEBUG,
  1406. "USB init, failed to get config descriptor, err %d %s",
  1407. err, devstr);
  1408. goto cldame;
  1409. }
  1410. if ((int)(config->bNumInterfaces) <= found->interface) {
  1411. applog(LOG_DEBUG, "USB init bNumInterfaces <= interface %s",
  1412. devstr);
  1413. goto cldame;
  1414. }
  1415. for (i = 0; i < found->epcount; i++)
  1416. found->eps[i].found = false;
  1417. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  1418. idesc = &(config->interface[found->interface].altsetting[i]);
  1419. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  1420. epdesc = &(idesc->endpoint[j]);
  1421. for (k = 0; k < found->epcount; k++) {
  1422. if (!found->eps[k].found) {
  1423. if (epdesc->bmAttributes == found->eps[k].att
  1424. && epdesc->wMaxPacketSize >= found->eps[k].size
  1425. && epdesc->bEndpointAddress == found->eps[k].ep) {
  1426. found->eps[k].found = true;
  1427. found->wMaxPacketSize = epdesc->wMaxPacketSize;
  1428. break;
  1429. }
  1430. }
  1431. }
  1432. }
  1433. }
  1434. for (i = 0; i < found->epcount; i++) {
  1435. if (found->eps[i].found == false) {
  1436. applog(LOG_DEBUG, "USB init found == false %s",
  1437. devstr);
  1438. goto cldame;
  1439. }
  1440. }
  1441. err = libusb_claim_interface(cgusb->handle, found->interface);
  1442. if (err) {
  1443. switch(err) {
  1444. case LIBUSB_ERROR_BUSY:
  1445. applog(LOG_WARNING,
  1446. "USB init, claim interface %d in use %s",
  1447. found->interface, devstr);
  1448. break;
  1449. default:
  1450. applog(LOG_DEBUG,
  1451. "USB init, claim interface %d failed, err %d %s",
  1452. found->interface, err, devstr);
  1453. }
  1454. goto cldame;
  1455. }
  1456. cfg = -1;
  1457. err = libusb_get_configuration(cgusb->handle, &cfg);
  1458. if (err)
  1459. cfg = -1;
  1460. if (cfg != found->config) {
  1461. applog(LOG_WARNING,
  1462. "USB init, incorrect config (%d!=%d) after claim of %s",
  1463. cfg, found->config, devstr);
  1464. goto reldame;
  1465. }
  1466. cgusb->usbver = cgusb->descriptor->bcdUSB;
  1467. // TODO: allow this with the right version of the libusb include and running library
  1468. // cgusb->speed = libusb_get_device_speed(dev);
  1469. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1470. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  1471. if (err > 0)
  1472. cgusb->prod_string = strdup((char *)strbuf);
  1473. else
  1474. cgusb->prod_string = (char *)BLANK;
  1475. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1476. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  1477. if (err > 0)
  1478. cgusb->manuf_string = strdup((char *)strbuf);
  1479. else
  1480. cgusb->manuf_string = (char *)BLANK;
  1481. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1482. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  1483. if (err > 0)
  1484. cgusb->serial_string = strdup((char *)strbuf);
  1485. else
  1486. cgusb->serial_string = (char *)BLANK;
  1487. // TODO: ?
  1488. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  1489. // cgusb->interfaceVersion
  1490. applog(LOG_DEBUG,
  1491. "USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
  1492. devstr, cgusb->usbver, cgusb->prod_string,
  1493. cgusb->manuf_string, cgusb->serial_string);
  1494. cgpu->usbdev = cgusb;
  1495. cgpu->usbinfo.nodev = false;
  1496. libusb_free_config_descriptor(config);
  1497. // Allow a name change based on the idVendor+idProduct
  1498. // N.B. must be done before calling add_cgpu()
  1499. if (strcmp(cgpu->drv->name, found->name)) {
  1500. if (!cgpu->drv->copy)
  1501. cgpu->drv = copy_drv(cgpu->drv);
  1502. cgpu->drv->name = (char *)(found->name);
  1503. }
  1504. bad = USB_INIT_OK;
  1505. goto out_unlock;
  1506. reldame:
  1507. libusb_release_interface(cgusb->handle, found->interface);
  1508. cldame:
  1509. cg_wlock(&cgusb_fd_lock);
  1510. libusb_close(cgusb->handle);
  1511. cg_wunlock(&cgusb_fd_lock);
  1512. dame:
  1513. if (config)
  1514. libusb_free_config_descriptor(config);
  1515. cgusb = free_cgusb(cgusb);
  1516. out_unlock:
  1517. DEVUNLOCK(cgpu, pstate);
  1518. return bad;
  1519. }
  1520. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1521. {
  1522. int ret;
  1523. ret = _usb_init(cgpu, dev, found);
  1524. if (ret == USB_INIT_FAIL)
  1525. applog(LOG_ERR, "%s detect (%d:%d) failed to initialise (incorrect device?)",
  1526. cgpu->drv->dname,
  1527. (int)(cgpu->usbinfo.bus_number),
  1528. (int)(cgpu->usbinfo.device_address));
  1529. return (ret == USB_INIT_OK);
  1530. }
  1531. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  1532. {
  1533. struct libusb_device_descriptor desc;
  1534. int bus_number, device_address;
  1535. int err, i;
  1536. bool ok;
  1537. err = libusb_get_device_descriptor(dev, &desc);
  1538. if (err) {
  1539. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  1540. return false;
  1541. }
  1542. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  1543. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  1544. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  1545. return false;
  1546. }
  1547. if (busdev_count > 0) {
  1548. bus_number = (int)libusb_get_bus_number(dev);
  1549. device_address = (int)libusb_get_device_address(dev);
  1550. ok = false;
  1551. for (i = 0; i < busdev_count; i++) {
  1552. if (bus_number == busdev[i].bus_number) {
  1553. if (busdev[i].device_address == -1 ||
  1554. device_address == busdev[i].device_address) {
  1555. ok = true;
  1556. break;
  1557. }
  1558. }
  1559. }
  1560. if (!ok) {
  1561. applog(LOG_DEBUG, "%s rejected %s %04x:%04x with bus:dev (%d:%d)",
  1562. drv->name, look->name, look->idVendor, look->idProduct,
  1563. bus_number, device_address);
  1564. return false;
  1565. }
  1566. }
  1567. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  1568. drv->name, look->name, look->idVendor, look->idProduct);
  1569. return true;
  1570. }
  1571. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  1572. {
  1573. struct usb_find_devices *found;
  1574. int i;
  1575. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  1576. if (find_dev[i].drv == drvnum) {
  1577. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  1578. found = malloc(sizeof(*found));
  1579. if (unlikely(!found))
  1580. quit(1, "USB failed to malloc found");
  1581. memcpy(found, &(find_dev[i]), sizeof(*found));
  1582. return found;
  1583. }
  1584. }
  1585. return NULL;
  1586. }
  1587. static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
  1588. {
  1589. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1590. applog(LOG_DEBUG,
  1591. "USB scan devices3: %s limit %d reached",
  1592. drv->dname, drv_count[drv->drv_id].limit);
  1593. return NULL;
  1594. }
  1595. #ifdef USE_BFLSC
  1596. if (drv->drv_id == DRIVER_BFLSC)
  1597. return usb_check_each(DRV_BFLSC, drv, dev);
  1598. #endif
  1599. #ifdef USE_BITFORCE
  1600. if (drv->drv_id == DRIVER_BITFORCE)
  1601. return usb_check_each(DRV_BITFORCE, drv, dev);
  1602. #endif
  1603. #ifdef USE_MODMINER
  1604. if (drv->drv_id == DRIVER_MODMINER)
  1605. return usb_check_each(DRV_MODMINER, drv, dev);
  1606. #endif
  1607. #ifdef USE_ICARUS
  1608. if (drv->drv_id == DRIVER_ICARUS)
  1609. return usb_check_each(DRV_ICARUS, drv, dev);
  1610. #endif
  1611. #ifdef USE_AVALON
  1612. if (drv->drv_id == DRIVER_AVALON)
  1613. return usb_check_each(DRV_AVALON, drv, dev);
  1614. #endif
  1615. return NULL;
  1616. }
  1617. void usb_detect(struct device_drv *drv, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *))
  1618. {
  1619. libusb_device **list;
  1620. ssize_t count, i;
  1621. struct usb_find_devices *found;
  1622. applog(LOG_DEBUG, "USB scan devices: checking for %s devices", drv->name);
  1623. if (total_count >= total_limit) {
  1624. applog(LOG_DEBUG, "USB scan devices: total limit %d reached", total_limit);
  1625. return;
  1626. }
  1627. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1628. applog(LOG_DEBUG,
  1629. "USB scan devices: %s limit %d reached",
  1630. drv->dname, drv_count[drv->drv_id].limit);
  1631. return;
  1632. }
  1633. count = libusb_get_device_list(NULL, &list);
  1634. if (count < 0) {
  1635. applog(LOG_DEBUG, "USB scan devices: failed, err %d", (int)count);
  1636. return;
  1637. }
  1638. if (count == 0)
  1639. applog(LOG_DEBUG, "USB scan devices: found no devices");
  1640. else
  1641. nmsleep(166);
  1642. for (i = 0; i < count; i++) {
  1643. if (total_count >= total_limit) {
  1644. applog(LOG_DEBUG, "USB scan devices2: total limit %d reached", total_limit);
  1645. break;
  1646. }
  1647. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1648. applog(LOG_DEBUG,
  1649. "USB scan devices2: %s limit %d reached",
  1650. drv->dname, drv_count[drv->drv_id].limit);
  1651. break;
  1652. }
  1653. found = usb_check(drv, list[i]);
  1654. if (found != NULL) {
  1655. if (is_in_use(list[i]) || cgminer_usb_lock(drv, list[i]) == false)
  1656. free(found);
  1657. else {
  1658. if (!device_detect(list[i], found))
  1659. cgminer_usb_unlock(drv, list[i]);
  1660. else {
  1661. total_count++;
  1662. drv_count[drv->drv_id].count++;
  1663. }
  1664. }
  1665. }
  1666. }
  1667. libusb_free_device_list(list, 1);
  1668. }
  1669. #if DO_USB_STATS
  1670. static void modes_str(char *buf, uint32_t modes)
  1671. {
  1672. bool first;
  1673. *buf = '\0';
  1674. if (modes == MODE_NONE)
  1675. strcpy(buf, MODE_NONE_STR);
  1676. else {
  1677. first = true;
  1678. if (modes & MODE_CTRL_READ) {
  1679. strcpy(buf, MODE_CTRL_READ_STR);
  1680. first = false;
  1681. }
  1682. if (modes & MODE_CTRL_WRITE) {
  1683. if (!first)
  1684. strcat(buf, MODE_SEP_STR);
  1685. strcat(buf, MODE_CTRL_WRITE_STR);
  1686. first = false;
  1687. }
  1688. if (modes & MODE_BULK_READ) {
  1689. if (!first)
  1690. strcat(buf, MODE_SEP_STR);
  1691. strcat(buf, MODE_BULK_READ_STR);
  1692. first = false;
  1693. }
  1694. if (modes & MODE_BULK_WRITE) {
  1695. if (!first)
  1696. strcat(buf, MODE_SEP_STR);
  1697. strcat(buf, MODE_BULK_WRITE_STR);
  1698. first = false;
  1699. }
  1700. }
  1701. }
  1702. #endif
  1703. // The stat data can be spurious due to not locking it before copying it -
  1704. // however that would require the stat() function to also lock and release
  1705. // a mutex every time a usb read or write is called which would slow
  1706. // things down more
  1707. struct api_data *api_usb_stats(__maybe_unused int *count)
  1708. {
  1709. #if DO_USB_STATS
  1710. struct cg_usb_stats_details *details;
  1711. struct cg_usb_stats *sta;
  1712. struct api_data *root = NULL;
  1713. int device;
  1714. int cmdseq;
  1715. char modes_s[32];
  1716. if (next_stat == USB_NOSTAT)
  1717. return NULL;
  1718. while (*count < next_stat * C_MAX * 2) {
  1719. device = *count / (C_MAX * 2);
  1720. cmdseq = *count % (C_MAX * 2);
  1721. (*count)++;
  1722. sta = &(usb_stats[device]);
  1723. details = &(sta->details[cmdseq]);
  1724. // Only show stats that have results
  1725. if (details->item[CMD_CMD].count == 0 &&
  1726. details->item[CMD_TIMEOUT].count == 0 &&
  1727. details->item[CMD_ERROR].count == 0)
  1728. continue;
  1729. root = api_add_string(root, "Name", sta->name, false);
  1730. root = api_add_int(root, "ID", &(sta->device_id), false);
  1731. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  1732. root = api_add_int(root, "Seq", &(details->seq), true);
  1733. modes_str(modes_s, details->modes);
  1734. root = api_add_string(root, "Modes", modes_s, true);
  1735. root = api_add_uint64(root, "Count",
  1736. &(details->item[CMD_CMD].count), true);
  1737. root = api_add_double(root, "Total Delay",
  1738. &(details->item[CMD_CMD].total_delay), true);
  1739. root = api_add_double(root, "Min Delay",
  1740. &(details->item[CMD_CMD].min_delay), true);
  1741. root = api_add_double(root, "Max Delay",
  1742. &(details->item[CMD_CMD].max_delay), true);
  1743. root = api_add_uint64(root, "Timeout Count",
  1744. &(details->item[CMD_TIMEOUT].count), true);
  1745. root = api_add_double(root, "Timeout Total Delay",
  1746. &(details->item[CMD_TIMEOUT].total_delay), true);
  1747. root = api_add_double(root, "Timeout Min Delay",
  1748. &(details->item[CMD_TIMEOUT].min_delay), true);
  1749. root = api_add_double(root, "Timeout Max Delay",
  1750. &(details->item[CMD_TIMEOUT].max_delay), true);
  1751. root = api_add_uint64(root, "Error Count",
  1752. &(details->item[CMD_ERROR].count), true);
  1753. root = api_add_double(root, "Error Total Delay",
  1754. &(details->item[CMD_ERROR].total_delay), true);
  1755. root = api_add_double(root, "Error Min Delay",
  1756. &(details->item[CMD_ERROR].min_delay), true);
  1757. root = api_add_double(root, "Error Max Delay",
  1758. &(details->item[CMD_ERROR].max_delay), true);
  1759. root = api_add_timeval(root, "First Command",
  1760. &(details->item[CMD_CMD].first), true);
  1761. root = api_add_timeval(root, "Last Command",
  1762. &(details->item[CMD_CMD].last), true);
  1763. root = api_add_timeval(root, "First Timeout",
  1764. &(details->item[CMD_TIMEOUT].first), true);
  1765. root = api_add_timeval(root, "Last Timeout",
  1766. &(details->item[CMD_TIMEOUT].last), true);
  1767. root = api_add_timeval(root, "First Error",
  1768. &(details->item[CMD_ERROR].first), true);
  1769. root = api_add_timeval(root, "Last Error",
  1770. &(details->item[CMD_ERROR].last), true);
  1771. return root;
  1772. }
  1773. #endif
  1774. return NULL;
  1775. }
  1776. #if DO_USB_STATS
  1777. static void newstats(struct cgpu_info *cgpu)
  1778. {
  1779. int i;
  1780. mutex_lock(&cgusb_lock);
  1781. cgpu->usbinfo.usbstat = next_stat + 1;
  1782. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * (next_stat+1));
  1783. if (unlikely(!usb_stats))
  1784. quit(1, "USB failed to realloc usb_stats %d", next_stat+1);
  1785. usb_stats[next_stat].name = cgpu->drv->name;
  1786. usb_stats[next_stat].device_id = -1;
  1787. usb_stats[next_stat].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  1788. if (unlikely(!usb_stats[next_stat].details))
  1789. quit(1, "USB failed to calloc details for %d", next_stat+1);
  1790. for (i = 1; i < C_MAX * 2; i += 2)
  1791. usb_stats[next_stat].details[i].seq = 1;
  1792. next_stat++;
  1793. mutex_unlock(&cgusb_lock);
  1794. }
  1795. #endif
  1796. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  1797. {
  1798. #if DO_USB_STATS
  1799. if (cgpu->usbinfo.usbstat < 1)
  1800. newstats(cgpu);
  1801. // we don't know the device_id until after add_cgpu()
  1802. usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
  1803. #endif
  1804. }
  1805. #if DO_USB_STATS
  1806. 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)
  1807. {
  1808. struct cg_usb_stats_details *details;
  1809. double diff;
  1810. int item;
  1811. if (cgpu->usbinfo.usbstat < 1)
  1812. newstats(cgpu);
  1813. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
  1814. details->modes |= mode;
  1815. diff = tdiff(tv_finish, tv_start);
  1816. switch (err) {
  1817. case LIBUSB_SUCCESS:
  1818. item = CMD_CMD;
  1819. break;
  1820. case LIBUSB_ERROR_TIMEOUT:
  1821. item = CMD_TIMEOUT;
  1822. break;
  1823. default:
  1824. item = CMD_ERROR;
  1825. break;
  1826. }
  1827. if (details->item[item].count == 0) {
  1828. details->item[item].min_delay = diff;
  1829. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  1830. } else if (diff < details->item[item].min_delay)
  1831. details->item[item].min_delay = diff;
  1832. if (diff > details->item[item].max_delay)
  1833. details->item[item].max_delay = diff;
  1834. details->item[item].total_delay += diff;
  1835. memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
  1836. details->item[item].count++;
  1837. }
  1838. static void rejected_inc(struct cgpu_info *cgpu, uint32_t mode)
  1839. {
  1840. struct cg_usb_stats_details *details;
  1841. int item = CMD_ERROR;
  1842. if (cgpu->usbinfo.usbstat < 1)
  1843. newstats(cgpu);
  1844. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  1845. details->modes |= mode;
  1846. details->item[item].count++;
  1847. }
  1848. #endif
  1849. static char *find_end(unsigned char *buf, unsigned char *ptr, int ptrlen, int tot, char *end, int endlen, bool first)
  1850. {
  1851. unsigned char *search;
  1852. if (endlen > tot)
  1853. return NULL;
  1854. // If end is only 1 char - do a faster search
  1855. if (endlen == 1) {
  1856. if (first)
  1857. search = buf;
  1858. else
  1859. search = ptr;
  1860. return strchr((char *)search, *end);
  1861. } else {
  1862. if (first)
  1863. search = buf;
  1864. else {
  1865. // must allow end to have been chopped in 2
  1866. if ((tot - ptrlen) >= (endlen - 1))
  1867. search = ptr - (endlen - 1);
  1868. else
  1869. search = ptr - (tot - ptrlen);
  1870. }
  1871. return strstr((char *)search, end);
  1872. }
  1873. }
  1874. #define USB_MAX_READ 8192
  1875. #define USB_RETRY_MAX 5
  1876. static int
  1877. usb_bulk_transfer(struct libusb_device_handle *dev_handle,
  1878. unsigned char endpoint, unsigned char *data, int length,
  1879. int *transferred, unsigned int timeout,
  1880. struct cgpu_info *cgpu, enum usb_cmds cmd)
  1881. {
  1882. uint16_t MaxPacketSize;
  1883. int err, errn, tries = 0;
  1884. /* Limit length of transfer to the largest this descriptor supports
  1885. * and leave the higher level functions to transfer more if needed. */
  1886. if (cgpu->usbdev->PrefPacketSize)
  1887. MaxPacketSize = cgpu->usbdev->PrefPacketSize;
  1888. else
  1889. MaxPacketSize = cgpu->usbdev->found->wMaxPacketSize;
  1890. if (length > MaxPacketSize)
  1891. length = MaxPacketSize;
  1892. cg_rlock(&cgusb_fd_lock);
  1893. err = libusb_bulk_transfer(dev_handle, endpoint, data, length,
  1894. transferred, timeout);
  1895. errn = errno;
  1896. cg_runlock(&cgusb_fd_lock);
  1897. if (err < 0)
  1898. applog(LOG_DEBUG, "%s%i: %s (amt=%d err=%d ern=%d)",
  1899. cgpu->drv->name, cgpu->device_id,
  1900. usb_cmdname(cmd), *transferred, err, errn);
  1901. if (err == LIBUSB_ERROR_PIPE) {
  1902. cgpu->usbinfo.last_pipe = time(NULL);
  1903. cgpu->usbinfo.pipe_count++;
  1904. applog(LOG_INFO, "%s%i: libusb pipe error, trying to clear",
  1905. cgpu->drv->name, cgpu->device_id);
  1906. do {
  1907. err = libusb_clear_halt(dev_handle, endpoint);
  1908. if (unlikely(err == LIBUSB_ERROR_NOT_FOUND ||
  1909. err == LIBUSB_ERROR_NO_DEVICE)) {
  1910. cgpu->usbinfo.clear_err_count++;
  1911. break;
  1912. }
  1913. cg_rlock(&cgusb_fd_lock);
  1914. err = libusb_bulk_transfer(dev_handle, endpoint, data,
  1915. length, transferred, timeout);
  1916. errn = errno;
  1917. cg_runlock(&cgusb_fd_lock);
  1918. if (err < 0)
  1919. applog(LOG_DEBUG, "%s%i: %s (amt=%d err=%d ern=%d)",
  1920. cgpu->drv->name, cgpu->device_id,
  1921. usb_cmdname(cmd), *transferred, err, errn);
  1922. if (err)
  1923. cgpu->usbinfo.retry_err_count++;
  1924. } while (err == LIBUSB_ERROR_PIPE && tries++ < USB_RETRY_MAX);
  1925. applog(LOG_DEBUG, "%s%i: libusb pipe error%scleared",
  1926. cgpu->drv->name, cgpu->device_id, err ? " not " : " ");
  1927. if (err)
  1928. cgpu->usbinfo.clear_fail_count++;
  1929. }
  1930. return err;
  1931. }
  1932. int _usb_read(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, const char *end, enum usb_cmds cmd, bool readonce)
  1933. {
  1934. struct cg_usb_device *usbdev;
  1935. bool ftdi;
  1936. #if DO_USB_STATS
  1937. struct timeval tv_start;
  1938. #endif
  1939. struct timeval read_start, tv_finish;
  1940. unsigned int initial_timeout;
  1941. double max, done;
  1942. int bufleft, err, got, tot, pstate;
  1943. bool first = true;
  1944. char *search;
  1945. int endlen;
  1946. // We add 4: 1 for null, 2 for FTDI status and 1 to round to 4 bytes
  1947. unsigned char usbbuf[USB_MAX_READ+4], *ptr;
  1948. size_t usbbufread;
  1949. DEVLOCK(cgpu, pstate);
  1950. if (cgpu->usbinfo.nodev) {
  1951. *buf = '\0';
  1952. *processed = 0;
  1953. USB_REJECT(cgpu, MODE_BULK_READ);
  1954. err = LIBUSB_ERROR_NO_DEVICE;
  1955. goto out_unlock;
  1956. }
  1957. usbdev = cgpu->usbdev;
  1958. ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  1959. 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));
  1960. if (bufsiz > USB_MAX_READ)
  1961. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, (int)bufsiz, USB_MAX_READ);
  1962. if (timeout == DEVTIMEOUT)
  1963. timeout = usbdev->found->timeout;
  1964. if (end == NULL) {
  1965. if (usbdev->buffer && usbdev->bufamt) {
  1966. tot = usbdev->bufamt;
  1967. bufleft = bufsiz - tot;
  1968. memcpy(usbbuf, usbdev->buffer, tot);
  1969. ptr = usbbuf + tot;
  1970. usbdev->bufamt = 0;
  1971. } else {
  1972. tot = 0;
  1973. bufleft = bufsiz;
  1974. ptr = usbbuf;
  1975. }
  1976. err = LIBUSB_SUCCESS;
  1977. initial_timeout = timeout;
  1978. max = ((double)timeout) / 1000.0;
  1979. cgtime(&read_start);
  1980. while (bufleft > 0) {
  1981. // TODO: use (USB_MAX_READ - tot) always?
  1982. if (usbdev->buffer)
  1983. usbbufread = USB_MAX_READ - tot;
  1984. else {
  1985. if (ftdi)
  1986. usbbufread = bufleft + 2;
  1987. else
  1988. usbbufread = bufleft;
  1989. }
  1990. got = 0;
  1991. if (first && usbdev->usecps) {
  1992. if (usbdev->last_write_tv.tv_sec && usbdev->last_write_siz) {
  1993. struct timeval now;
  1994. double need;
  1995. cgtime(&now);
  1996. need = (double)(usbdev->last_write_siz) /
  1997. (double)(usbdev->cps) -
  1998. tdiff(&now, &(usbdev->last_write_tv));
  1999. // Simple error condition check/avoidance '< 1.0'
  2000. if (need > 0.0 && need < 1.0) {
  2001. cgpu->usbinfo.read_delay_count++;
  2002. cgpu->usbinfo.total_read_delay += need;
  2003. nmsleep((unsigned int)(need * 1000.0));
  2004. }
  2005. }
  2006. }
  2007. STATS_TIMEVAL(&tv_start);
  2008. err = usb_bulk_transfer(usbdev->handle,
  2009. usbdev->found->eps[ep].ep,
  2010. ptr, usbbufread, &got, timeout,
  2011. cgpu, cmd);
  2012. cgtime(&tv_finish);
  2013. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  2014. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  2015. ptr[got] = '\0';
  2016. 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);
  2017. IOERR_CHECK(cgpu, err);
  2018. if (ftdi) {
  2019. // first 2 bytes returned are an FTDI status
  2020. if (got > 2) {
  2021. got -= 2;
  2022. memmove(ptr, ptr+2, got+1);
  2023. } else {
  2024. got = 0;
  2025. *ptr = '\0';
  2026. }
  2027. }
  2028. tot += got;
  2029. if (err || readonce)
  2030. break;
  2031. ptr += got;
  2032. bufleft -= got;
  2033. first = false;
  2034. done = tdiff(&tv_finish, &read_start);
  2035. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  2036. if (unlikely(done >= max))
  2037. break;
  2038. timeout = initial_timeout - (done * 1000);
  2039. if (!timeout)
  2040. break;
  2041. }
  2042. // N.B. usbdev->buffer was emptied before the while() loop
  2043. if (usbdev->buffer && tot > (int)bufsiz) {
  2044. usbdev->bufamt = tot - bufsiz;
  2045. memcpy(usbdev->buffer, ptr + bufsiz, usbdev->bufamt);
  2046. tot -= usbdev->bufamt;
  2047. usbbuf[tot] = '\0';
  2048. applog(LOG_ERR, "USB: %s%i read1 buffering %d extra bytes",
  2049. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2050. }
  2051. *processed = tot;
  2052. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2053. if (NODEV(err))
  2054. release_cgpu(cgpu);
  2055. goto out_unlock;
  2056. }
  2057. if (usbdev->buffer && usbdev->bufamt) {
  2058. tot = usbdev->bufamt;
  2059. bufleft = bufsiz - tot;
  2060. memcpy(usbbuf, usbdev->buffer, tot);
  2061. ptr = usbbuf + tot;
  2062. usbdev->bufamt = 0;
  2063. } else {
  2064. tot = 0;
  2065. bufleft = bufsiz;
  2066. ptr = usbbuf;
  2067. }
  2068. endlen = strlen(end);
  2069. err = LIBUSB_SUCCESS;
  2070. initial_timeout = timeout;
  2071. max = ((double)timeout) / 1000.0;
  2072. cgtime(&read_start);
  2073. while (bufleft > 0) {
  2074. // TODO: use (USB_MAX_READ - tot) always?
  2075. if (usbdev->buffer)
  2076. usbbufread = USB_MAX_READ - tot;
  2077. else {
  2078. if (ftdi)
  2079. usbbufread = bufleft + 2;
  2080. else
  2081. usbbufread = bufleft;
  2082. }
  2083. got = 0;
  2084. if (first && usbdev->usecps) {
  2085. if (usbdev->last_write_tv.tv_sec && usbdev->last_write_siz) {
  2086. struct timeval now;
  2087. double need;
  2088. cgtime(&now);
  2089. need = (double)(usbdev->last_write_siz) /
  2090. (double)(usbdev->cps) -
  2091. tdiff(&now, &(usbdev->last_write_tv));
  2092. // Simple error condition check/avoidance '< 1.0'
  2093. if (need > 0.0 && need < 1.0) {
  2094. cgpu->usbinfo.read_delay_count++;
  2095. cgpu->usbinfo.total_read_delay += need;
  2096. nmsleep((unsigned int)(need * 1000.0));
  2097. }
  2098. }
  2099. }
  2100. STATS_TIMEVAL(&tv_start);
  2101. err = usb_bulk_transfer(usbdev->handle,
  2102. usbdev->found->eps[ep].ep, ptr,
  2103. usbbufread, &got, timeout,
  2104. cgpu, cmd);
  2105. cgtime(&tv_finish);
  2106. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  2107. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  2108. ptr[got] = '\0';
  2109. 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);
  2110. IOERR_CHECK(cgpu, err);
  2111. if (ftdi) {
  2112. // first 2 bytes returned are an FTDI status
  2113. if (got > 2) {
  2114. got -= 2;
  2115. memmove(ptr, ptr+2, got+1);
  2116. } else {
  2117. got = 0;
  2118. *ptr = '\0';
  2119. }
  2120. }
  2121. tot += got;
  2122. if (err || readonce)
  2123. break;
  2124. if (find_end(usbbuf, ptr, got, tot, (char *)end, endlen, first))
  2125. break;
  2126. ptr += got;
  2127. bufleft -= got;
  2128. first = false;
  2129. done = tdiff(&tv_finish, &read_start);
  2130. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  2131. if (unlikely(done >= max))
  2132. break;
  2133. timeout = initial_timeout - (done * 1000);
  2134. if (!timeout)
  2135. break;
  2136. }
  2137. if (usbdev->buffer) {
  2138. bool dobuffer = false;
  2139. if ((search = find_end(usbbuf, usbbuf, tot, tot, (char *)end, endlen, true))) {
  2140. // end finishes after bufsiz
  2141. if ((search + endlen - (char *)usbbuf) > (int)bufsiz) {
  2142. usbdev->bufamt = tot - bufsiz;
  2143. dobuffer = true;
  2144. } else {
  2145. // extra data after end
  2146. if (*(search + endlen)) {
  2147. usbdev->bufamt = tot - (search + endlen - (char *)usbbuf);
  2148. dobuffer = true;
  2149. }
  2150. }
  2151. } else {
  2152. // no end, but still bigger than bufsiz
  2153. if (tot > (int)bufsiz) {
  2154. usbdev->bufamt = tot - bufsiz;
  2155. dobuffer = true;
  2156. }
  2157. }
  2158. if (dobuffer) {
  2159. tot -= usbdev->bufamt;
  2160. memcpy(usbdev->buffer, usbbuf + tot, usbdev->bufamt);
  2161. usbbuf[tot] = '\0';
  2162. applog(LOG_ERR, "USB: %s%i read2 buffering %d extra bytes",
  2163. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2164. }
  2165. }
  2166. *processed = tot;
  2167. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2168. if (NODEV(err))
  2169. release_cgpu(cgpu);
  2170. out_unlock:
  2171. DEVUNLOCK(cgpu, pstate);
  2172. return err;
  2173. }
  2174. int _usb_write(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, enum usb_cmds cmd)
  2175. {
  2176. struct cg_usb_device *usbdev;
  2177. #if DO_USB_STATS
  2178. struct timeval tv_start;
  2179. #endif
  2180. struct timeval read_start, tv_finish;
  2181. unsigned int initial_timeout;
  2182. double max, done;
  2183. __maybe_unused bool first = true;
  2184. int err, sent, tot, pstate;
  2185. DEVLOCK(cgpu, pstate);
  2186. 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));
  2187. *processed = 0;
  2188. if (cgpu->usbinfo.nodev) {
  2189. USB_REJECT(cgpu, MODE_BULK_WRITE);
  2190. err = LIBUSB_ERROR_NO_DEVICE;
  2191. goto out_unlock;
  2192. }
  2193. usbdev = cgpu->usbdev;
  2194. if (timeout == DEVTIMEOUT)
  2195. timeout = usbdev->found->timeout;
  2196. tot = 0;
  2197. err = LIBUSB_SUCCESS;
  2198. initial_timeout = timeout;
  2199. max = ((double)timeout) / 1000.0;
  2200. cgtime(&read_start);
  2201. while (bufsiz > 0) {
  2202. sent = 0;
  2203. if (usbdev->usecps) {
  2204. if (usbdev->last_write_tv.tv_sec && usbdev->last_write_siz) {
  2205. struct timeval now;
  2206. double need;
  2207. cgtime(&now);
  2208. need = (double)(usbdev->last_write_siz) /
  2209. (double)(usbdev->cps) -
  2210. tdiff(&now, &(usbdev->last_write_tv));
  2211. // Simple error condition check/avoidance '< 1.0'
  2212. if (need > 0.0 && need < 1.0) {
  2213. cgpu->usbinfo.write_delay_count++;
  2214. cgpu->usbinfo.total_write_delay += need;
  2215. nmsleep((unsigned int)(need * 1000.0));
  2216. }
  2217. }
  2218. cgtime(&(usbdev->last_write_tv));
  2219. usbdev->last_write_siz = bufsiz;
  2220. }
  2221. STATS_TIMEVAL(&tv_start);
  2222. err = usb_bulk_transfer(usbdev->handle,
  2223. usbdev->found->eps[ep].ep,
  2224. (unsigned char *)buf, bufsiz, &sent,
  2225. timeout, cgpu, cmd);
  2226. cgtime(&tv_finish);
  2227. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  2228. MODE_BULK_WRITE, cmd, first ? SEQ0 : SEQ1);
  2229. 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);
  2230. IOERR_CHECK(cgpu, err);
  2231. tot += sent;
  2232. if (err)
  2233. break;
  2234. buf += sent;
  2235. bufsiz -= sent;
  2236. first = false;
  2237. done = tdiff(&tv_finish, &read_start);
  2238. // N.B. this is: return LIBUSB_SUCCESS with whatever size was written
  2239. if (unlikely(done >= max))
  2240. break;
  2241. timeout = initial_timeout - (done * 1000);
  2242. if (!timeout)
  2243. break;
  2244. }
  2245. *processed = tot;
  2246. if (NODEV(err))
  2247. release_cgpu(cgpu);
  2248. out_unlock:
  2249. DEVUNLOCK(cgpu, pstate);
  2250. return err;
  2251. }
  2252. 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)
  2253. {
  2254. struct cg_usb_device *usbdev;
  2255. #if DO_USB_STATS
  2256. struct timeval tv_start, tv_finish;
  2257. #endif
  2258. uint32_t *buf = NULL;
  2259. int err, i, bufsiz;
  2260. 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));
  2261. if (cgpu->usbinfo.nodev) {
  2262. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  2263. err = LIBUSB_ERROR_NO_DEVICE;
  2264. goto out_;
  2265. }
  2266. usbdev = cgpu->usbdev;
  2267. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  2268. if (siz > 0) {
  2269. bufsiz = siz - 1;
  2270. bufsiz >>= 2;
  2271. bufsiz++;
  2272. buf = malloc(bufsiz << 2);
  2273. if (unlikely(!buf))
  2274. quit(1, "Failed to malloc in _usb_transfer");
  2275. for (i = 0; i < bufsiz; i++)
  2276. buf[i] = htole32(data[i]);
  2277. }
  2278. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex((unsigned char *)buf, (size_t)siz));
  2279. if (usbdev->usecps) {
  2280. if (usbdev->last_write_tv.tv_sec && usbdev->last_write_siz) {
  2281. struct timeval now;
  2282. double need;
  2283. cgtime(&now);
  2284. need = (double)(usbdev->last_write_siz) /
  2285. (double)(usbdev->cps) -
  2286. tdiff(&now, &(usbdev->last_write_tv));
  2287. // Simple error condition check/avoidance '< 1.0'
  2288. if (need > 0.0 && need < 1.0) {
  2289. cgpu->usbinfo.write_delay_count++;
  2290. cgpu->usbinfo.total_write_delay += need;
  2291. nmsleep((unsigned int)(need * 1000.0));
  2292. }
  2293. }
  2294. cgtime(&(usbdev->last_write_tv));
  2295. usbdev->last_write_siz = siz;
  2296. }
  2297. STATS_TIMEVAL(&tv_start);
  2298. cg_rlock(&cgusb_fd_lock);
  2299. err = libusb_control_transfer(usbdev->handle, request_type,
  2300. bRequest, wValue, wIndex, (unsigned char *)buf, (uint16_t)siz,
  2301. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  2302. cg_runlock(&cgusb_fd_lock);
  2303. STATS_TIMEVAL(&tv_finish);
  2304. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0);
  2305. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  2306. IOERR_CHECK(cgpu, err);
  2307. free(buf);
  2308. if (NOCONTROLDEV(err))
  2309. release_cgpu(cgpu);
  2310. out_:
  2311. return err;
  2312. }
  2313. 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)
  2314. {
  2315. int pstate, err;
  2316. DEVLOCK(cgpu, pstate);
  2317. err = __usb_transfer(cgpu, request_type, bRequest, wValue, wIndex, data, siz, timeout, cmd);
  2318. DEVUNLOCK(cgpu, pstate);
  2319. return err;
  2320. }
  2321. 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)
  2322. {
  2323. struct cg_usb_device *usbdev;
  2324. #if DO_USB_STATS
  2325. struct timeval tv_start, tv_finish;
  2326. #endif
  2327. int err, pstate;
  2328. DEVLOCK(cgpu, pstate);
  2329. 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));
  2330. if (cgpu->usbinfo.nodev) {
  2331. USB_REJECT(cgpu, MODE_CTRL_READ);
  2332. err = LIBUSB_ERROR_NO_DEVICE;
  2333. goto out_unlock;
  2334. }
  2335. usbdev = cgpu->usbdev;
  2336. *amount = 0;
  2337. if (usbdev->usecps) {
  2338. if (usbdev->last_write_tv.tv_sec && usbdev->last_write_siz) {
  2339. struct timeval now;
  2340. double need;
  2341. cgtime(&now);
  2342. need = (double)(usbdev->last_write_siz) /
  2343. (double)(usbdev->cps) -
  2344. tdiff(&now, &(usbdev->last_write_tv));
  2345. // Simple error condition check/avoidance '< 1.0'
  2346. if (need > 0.0 && need < 1.0) {
  2347. cgpu->usbinfo.read_delay_count++;
  2348. cgpu->usbinfo.total_read_delay += need;
  2349. nmsleep((unsigned int)(need * 1000.0));
  2350. }
  2351. }
  2352. }
  2353. STATS_TIMEVAL(&tv_start);
  2354. cg_rlock(&cgusb_fd_lock);
  2355. err = libusb_control_transfer(usbdev->handle, request_type,
  2356. bRequest, wValue, wIndex,
  2357. (unsigned char *)buf, (uint16_t)bufsiz,
  2358. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  2359. cg_runlock(&cgusb_fd_lock);
  2360. STATS_TIMEVAL(&tv_finish);
  2361. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0);
  2362. 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);
  2363. IOERR_CHECK(cgpu, err);
  2364. if (err > 0) {
  2365. *amount = err;
  2366. err = 0;
  2367. } else if (NOCONTROLDEV(err))
  2368. release_cgpu(cgpu);
  2369. out_unlock:
  2370. DEVUNLOCK(cgpu, pstate);
  2371. return err;
  2372. }
  2373. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  2374. #define FTDI_RS0_CTS (1 << 4)
  2375. #define FTDI_RS0_DSR (1 << 5)
  2376. #define FTDI_RS0_RI (1 << 6)
  2377. #define FTDI_RS0_RLSD (1 << 7)
  2378. /* Clear to send for FTDI */
  2379. int usb_ftdi_cts(struct cgpu_info *cgpu)
  2380. {
  2381. char buf[2], ret;
  2382. int err, amount;
  2383. err = _usb_transfer_read(cgpu, (uint8_t)FTDI_TYPE_IN, (uint8_t)5,
  2384. (uint16_t)0, (uint16_t)0, buf, 2,
  2385. &amount, DEVTIMEOUT, C_FTDI_STATUS);
  2386. /* We return true in case drivers are waiting indefinitely to try and
  2387. * write to something that's not there. */
  2388. if (err)
  2389. return true;
  2390. ret = buf[0] & FTDI_STATUS_B0_MASK;
  2391. return (ret & FTDI_RS0_CTS);
  2392. }
  2393. int usb_ftdi_set_latency(struct cgpu_info *cgpu)
  2394. {
  2395. int err = 0;
  2396. int pstate;
  2397. DEVLOCK(cgpu, pstate);
  2398. if (cgpu->usbdev) {
  2399. if (cgpu->usbdev->usb_type != USB_TYPE_FTDI) {
  2400. applog(LOG_ERR, "%s: cgid %d latency request on non-FTDI device",
  2401. cgpu->drv->name, cgpu->cgminer_id);
  2402. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2403. } else if (cgpu->usbdev->found->latency == LATENCY_UNUSED) {
  2404. applog(LOG_ERR, "%s: cgid %d invalid latency (UNUSED)",
  2405. cgpu->drv->name, cgpu->cgminer_id);
  2406. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2407. }
  2408. if (!err)
  2409. err = __usb_transfer(cgpu, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
  2410. cgpu->usbdev->found->latency,
  2411. cgpu->usbdev->found->interface,
  2412. NULL, 0, DEVTIMEOUT, C_LATENCY);
  2413. }
  2414. DEVUNLOCK(cgpu, pstate);
  2415. applog(LOG_DEBUG, "%s: cgid %d %s got err %d",
  2416. cgpu->drv->name, cgpu->cgminer_id,
  2417. usb_cmdname(C_LATENCY), err);
  2418. return err;
  2419. }
  2420. void usb_buffer_enable(struct cgpu_info *cgpu)
  2421. {
  2422. struct cg_usb_device *cgusb;
  2423. int pstate;
  2424. DEVLOCK(cgpu, pstate);
  2425. cgusb = cgpu->usbdev;
  2426. if (cgusb && !cgusb->buffer) {
  2427. cgusb->bufamt = 0;
  2428. cgusb->buffer = malloc(USB_MAX_READ+1);
  2429. if (!cgusb->buffer)
  2430. quit(1, "Failed to malloc buffer for USB %s%i",
  2431. cgpu->drv->name, cgpu->device_id);
  2432. cgusb->bufsiz = USB_MAX_READ;
  2433. }
  2434. DEVUNLOCK(cgpu, pstate);
  2435. }
  2436. void usb_buffer_disable(struct cgpu_info *cgpu)
  2437. {
  2438. struct cg_usb_device *cgusb;
  2439. int pstate;
  2440. DEVLOCK(cgpu, pstate);
  2441. cgusb = cgpu->usbdev;
  2442. if (cgusb && cgusb->buffer) {
  2443. cgusb->bufamt = 0;
  2444. cgusb->bufsiz = 0;
  2445. free(cgusb->buffer);
  2446. cgusb->buffer = NULL;
  2447. }
  2448. DEVUNLOCK(cgpu, pstate);
  2449. }
  2450. void usb_buffer_clear(struct cgpu_info *cgpu)
  2451. {
  2452. int pstate;
  2453. DEVLOCK(cgpu, pstate);
  2454. if (cgpu->usbdev)
  2455. cgpu->usbdev->bufamt = 0;
  2456. DEVUNLOCK(cgpu, pstate);
  2457. }
  2458. uint32_t usb_buffer_size(struct cgpu_info *cgpu)
  2459. {
  2460. uint32_t ret = 0;
  2461. int pstate;
  2462. DEVLOCK(cgpu, pstate);
  2463. if (cgpu->usbdev)
  2464. ret = cgpu->usbdev->bufamt;
  2465. DEVUNLOCK(cgpu, pstate);
  2466. return ret;
  2467. }
  2468. void usb_set_cps(struct cgpu_info *cgpu, int cps)
  2469. {
  2470. int pstate;
  2471. DEVLOCK(cgpu, pstate);
  2472. if (cgpu->usbdev)
  2473. cgpu->usbdev->cps = cps;
  2474. DEVUNLOCK(cgpu, pstate);
  2475. }
  2476. void usb_enable_cps(struct cgpu_info *cgpu)
  2477. {
  2478. int pstate;
  2479. DEVLOCK(cgpu, pstate);
  2480. if (cgpu->usbdev)
  2481. cgpu->usbdev->usecps = true;
  2482. DEVUNLOCK(cgpu, pstate);
  2483. }
  2484. void usb_disable_cps(struct cgpu_info *cgpu)
  2485. {
  2486. int pstate;
  2487. DEVLOCK(cgpu, pstate);
  2488. if (cgpu->usbdev)
  2489. cgpu->usbdev->usecps = false;
  2490. DEVUNLOCK(cgpu, pstate);
  2491. }
  2492. /*
  2493. * The value returned (0) when usbdev is NULL
  2494. * doesn't matter since it also means the next call to
  2495. * any usbutils function will fail with a nodev
  2496. */
  2497. int usb_interface(struct cgpu_info *cgpu)
  2498. {
  2499. int interface = 0;
  2500. int pstate;
  2501. DEVLOCK(cgpu, pstate);
  2502. if (cgpu->usbdev)
  2503. interface = cgpu->usbdev->found->interface;
  2504. DEVUNLOCK(cgpu, pstate);
  2505. return interface;
  2506. }
  2507. enum sub_ident usb_ident(struct cgpu_info *cgpu)
  2508. {
  2509. enum sub_ident ident = IDENT_UNK;
  2510. int pstate;
  2511. DEVLOCK(cgpu, pstate);
  2512. if (cgpu->usbdev)
  2513. ident = cgpu->usbdev->ident;
  2514. DEVUNLOCK(cgpu, pstate);
  2515. return ident;
  2516. }
  2517. void usb_set_pps(struct cgpu_info *cgpu, uint16_t PrefPacketSize)
  2518. {
  2519. int pstate;
  2520. DEVLOCK(cgpu, pstate);
  2521. if (cgpu->usbdev)
  2522. cgpu->usbdev->PrefPacketSize = PrefPacketSize;
  2523. DEVUNLOCK(cgpu, pstate);
  2524. }
  2525. // Need to set all devices with matching usbdev
  2526. void usb_set_dev_start(struct cgpu_info *cgpu)
  2527. {
  2528. struct cg_usb_device *cgusb;
  2529. struct cgpu_info *cgpu2;
  2530. struct timeval now;
  2531. int pstate;
  2532. DEVLOCK(cgpu, pstate);
  2533. cgusb = cgpu->usbdev;
  2534. // If the device wasn't dropped
  2535. if (cgusb != NULL) {
  2536. int i;
  2537. cgtime(&now);
  2538. for (i = 0; i < total_devices; i++) {
  2539. cgpu2 = get_devices(i);
  2540. if (cgpu2->usbdev == cgusb)
  2541. copy_time(&(cgpu2->dev_start_tv), &now);
  2542. }
  2543. }
  2544. DEVUNLOCK(cgpu, pstate);
  2545. }
  2546. void usb_cleanup()
  2547. {
  2548. struct cgpu_info *cgpu;
  2549. int count;
  2550. int i;
  2551. hotplug_time = 0;
  2552. nmsleep(10);
  2553. count = 0;
  2554. for (i = 0; i < total_devices; i++) {
  2555. cgpu = devices[i];
  2556. switch (cgpu->drv->drv_id) {
  2557. case DRIVER_BFLSC:
  2558. case DRIVER_BITFORCE:
  2559. case DRIVER_MODMINER:
  2560. case DRIVER_ICARUS:
  2561. case DRIVER_AVALON:
  2562. wr_lock(cgpu->usbinfo.devlock);
  2563. release_cgpu(cgpu);
  2564. wr_unlock(cgpu->usbinfo.devlock);
  2565. count++;
  2566. break;
  2567. default:
  2568. break;
  2569. }
  2570. }
  2571. /*
  2572. * Must attempt to wait for the resource thread to release coz
  2573. * during a restart it won't automatically release them in linux
  2574. */
  2575. if (count) {
  2576. struct timeval start, now;
  2577. cgtime(&start);
  2578. while (42) {
  2579. nmsleep(50);
  2580. mutex_lock(&cgusbres_lock);
  2581. if (!res_work_head)
  2582. break;
  2583. cgtime(&now);
  2584. if (tdiff(&now, &start) > 0.366) {
  2585. applog(LOG_WARNING,
  2586. "usb_cleanup gave up waiting for resource thread");
  2587. break;
  2588. }
  2589. mutex_unlock(&cgusbres_lock);
  2590. }
  2591. mutex_unlock(&cgusbres_lock);
  2592. }
  2593. cgsem_destroy(&usb_resource_sem);
  2594. }
  2595. void usb_initialise()
  2596. {
  2597. char *fre, *ptr, *comma, *colon;
  2598. int bus, dev, lim, i;
  2599. bool found;
  2600. for (i = 0; i < DRIVER_MAX; i++) {
  2601. drv_count[i].count = 0;
  2602. drv_count[i].limit = 999999;
  2603. }
  2604. cgusb_check_init();
  2605. if (opt_usb_select && *opt_usb_select) {
  2606. // Absolute device limit
  2607. if (*opt_usb_select == ':') {
  2608. total_limit = atoi(opt_usb_select+1);
  2609. if (total_limit < 0)
  2610. quit(1, "Invalid --usb total limit");
  2611. // Comma list of bus:dev devices to match
  2612. } else if (isdigit(*opt_usb_select)) {
  2613. fre = ptr = strdup(opt_usb_select);
  2614. do {
  2615. comma = strchr(ptr, ',');
  2616. if (comma)
  2617. *(comma++) = '\0';
  2618. colon = strchr(ptr, ':');
  2619. if (!colon)
  2620. quit(1, "Invalid --usb bus:dev missing ':'");
  2621. *(colon++) = '\0';
  2622. if (!isdigit(*ptr))
  2623. quit(1, "Invalid --usb bus:dev - bus must be a number");
  2624. if (!isdigit(*colon) && *colon != '*')
  2625. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  2626. bus = atoi(ptr);
  2627. if (bus <= 0)
  2628. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  2629. if (*colon == '*')
  2630. dev = -1;
  2631. else {
  2632. dev = atoi(colon);
  2633. if (dev <= 0)
  2634. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  2635. }
  2636. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  2637. if (unlikely(!busdev))
  2638. quit(1, "USB failed to realloc busdev");
  2639. busdev[busdev_count-1].bus_number = bus;
  2640. busdev[busdev_count-1].device_address = dev;
  2641. ptr = comma;
  2642. } while (ptr);
  2643. free(fre);
  2644. // Comma list of DRV:limit
  2645. } else {
  2646. fre = ptr = strdup(opt_usb_select);
  2647. do {
  2648. comma = strchr(ptr, ',');
  2649. if (comma)
  2650. *(comma++) = '\0';
  2651. colon = strchr(ptr, ':');
  2652. if (!colon)
  2653. quit(1, "Invalid --usb DRV:limit missing ':'");
  2654. *(colon++) = '\0';
  2655. if (!isdigit(*colon))
  2656. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  2657. lim = atoi(colon);
  2658. if (lim < 0)
  2659. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  2660. found = false;
  2661. #ifdef USE_BFLSC
  2662. if (strcasecmp(ptr, bflsc_drv.name) == 0) {
  2663. drv_count[bflsc_drv.drv_id].limit = lim;
  2664. found = true;
  2665. }
  2666. #endif
  2667. #ifdef USE_BITFORCE
  2668. if (!found && strcasecmp(ptr, bitforce_drv.name) == 0) {
  2669. drv_count[bitforce_drv.drv_id].limit = lim;
  2670. found = true;
  2671. }
  2672. #endif
  2673. #ifdef USE_MODMINER
  2674. if (!found && strcasecmp(ptr, modminer_drv.name) == 0) {
  2675. drv_count[modminer_drv.drv_id].limit = lim;
  2676. found = true;
  2677. }
  2678. #endif
  2679. #ifdef USE_ICARUS
  2680. if (!found && strcasecmp(ptr, icarus_drv.name) == 0) {
  2681. drv_count[icarus_drv.drv_id].limit = lim;
  2682. found = true;
  2683. }
  2684. #endif
  2685. #ifdef USE_AVALON
  2686. if (!found && strcasecmp(ptr, avalon_drv.name) == 0) {
  2687. drv_count[avalon_drv.drv_id].limit = lim;
  2688. found = true;
  2689. }
  2690. #endif
  2691. if (!found)
  2692. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  2693. ptr = comma;
  2694. } while (ptr);
  2695. free(fre);
  2696. }
  2697. }
  2698. }
  2699. #ifndef WIN32
  2700. #include <errno.h>
  2701. #include <unistd.h>
  2702. #include <sys/types.h>
  2703. #include <sys/ipc.h>
  2704. #include <sys/sem.h>
  2705. #include <sys/stat.h>
  2706. #include <fcntl.h>
  2707. #ifndef __APPLE__
  2708. union semun {
  2709. int val;
  2710. struct semid_ds *buf;
  2711. unsigned short *array;
  2712. struct seminfo *__buf;
  2713. };
  2714. #endif
  2715. #else
  2716. static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
  2717. {
  2718. FreeSid(((PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor))->Group);
  2719. free(sec->lpSecurityDescriptor);
  2720. free(sec);
  2721. return NULL;
  2722. }
  2723. static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
  2724. {
  2725. SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
  2726. PSID gsid = NULL;
  2727. LPSECURITY_ATTRIBUTES sec_att = NULL;
  2728. PSECURITY_DESCRIPTOR sec_des = NULL;
  2729. sec_des = malloc(sizeof(*sec_des));
  2730. if (unlikely(!sec_des))
  2731. quit(1, "MTX: Failed to malloc LPSECURITY_DESCRIPTOR");
  2732. if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
  2733. applog(LOG_ERR,
  2734. "MTX: %s (%d:%d) USB failed to init secdes err (%d)",
  2735. dname, (int)bus_number, (int)device_address,
  2736. (int)GetLastError());
  2737. free(sec_des);
  2738. return NULL;
  2739. }
  2740. if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
  2741. applog(LOG_ERR,
  2742. "MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
  2743. dname, (int)bus_number, (int)device_address,
  2744. (int)GetLastError());
  2745. free(sec_des);
  2746. return NULL;
  2747. }
  2748. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
  2749. applog(LOG_ERR,
  2750. "MTX: %s (%d:%d) USB failed to create gsid err (%d)",
  2751. dname, (int)bus_number, (int)device_address,
  2752. (int)GetLastError());
  2753. free(sec_des);
  2754. return NULL;
  2755. }
  2756. if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
  2757. applog(LOG_ERR,
  2758. "MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
  2759. dname, (int)bus_number, (int)device_address,
  2760. (int)GetLastError());
  2761. FreeSid(gsid);
  2762. free(sec_des);
  2763. return NULL;
  2764. }
  2765. sec_att = malloc(sizeof(*sec_att));
  2766. if (unlikely(!sec_att))
  2767. quit(1, "MTX: Failed to malloc LPSECURITY_ATTRIBUTES");
  2768. sec_att->nLength = sizeof(*sec_att);
  2769. sec_att->lpSecurityDescriptor = sec_des;
  2770. sec_att->bInheritHandle = FALSE;
  2771. return sec_att;
  2772. }
  2773. #endif
  2774. // Any errors should always be printed since they will rarely if ever occur
  2775. // and thus it is best to always display them
  2776. static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2777. {
  2778. applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2779. #ifdef WIN32
  2780. struct cgpu_info *cgpu;
  2781. LPSECURITY_ATTRIBUTES sec;
  2782. HANDLE usbMutex;
  2783. char name[64];
  2784. DWORD res;
  2785. int i;
  2786. if (is_in_use_bd(bus_number, device_address))
  2787. return false;
  2788. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2789. sec = mksec(dname, bus_number, device_address);
  2790. if (!sec)
  2791. return false;
  2792. usbMutex = CreateMutex(sec, FALSE, name);
  2793. if (usbMutex == NULL) {
  2794. applog(LOG_ERR,
  2795. "MTX: %s USB failed to get '%s' err (%d)",
  2796. dname, name, (int)GetLastError());
  2797. sec = unsec(sec);
  2798. return false;
  2799. }
  2800. res = WaitForSingleObject(usbMutex, 0);
  2801. switch(res) {
  2802. case WAIT_OBJECT_0:
  2803. case WAIT_ABANDONED:
  2804. // Am I using it already?
  2805. for (i = 0; i < total_devices; i++) {
  2806. cgpu = get_devices(i);
  2807. if (cgpu->usbinfo.bus_number == bus_number &&
  2808. cgpu->usbinfo.device_address == device_address &&
  2809. cgpu->usbinfo.nodev == false) {
  2810. if (ReleaseMutex(usbMutex)) {
  2811. applog(LOG_WARNING,
  2812. "MTX: %s USB can't get '%s' - device in use",
  2813. dname, name);
  2814. goto fail;
  2815. }
  2816. applog(LOG_ERR,
  2817. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  2818. dname, name, (int)GetLastError());
  2819. goto fail;
  2820. }
  2821. }
  2822. break;
  2823. case WAIT_TIMEOUT:
  2824. if (!hotplug_mode)
  2825. applog(LOG_WARNING,
  2826. "MTX: %s USB failed to get '%s' - device in use",
  2827. dname, name);
  2828. goto fail;
  2829. case WAIT_FAILED:
  2830. applog(LOG_ERR,
  2831. "MTX: %s USB failed to get '%s' err (%d)",
  2832. dname, name, (int)GetLastError());
  2833. goto fail;
  2834. default:
  2835. applog(LOG_ERR,
  2836. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  2837. dname, name, (int)res);
  2838. goto fail;
  2839. }
  2840. add_in_use(bus_number, device_address);
  2841. in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
  2842. return true;
  2843. fail:
  2844. CloseHandle(usbMutex);
  2845. sec = unsec(sec);
  2846. return false;
  2847. #else
  2848. struct semid_ds seminfo;
  2849. union semun opt;
  2850. char name[64];
  2851. key_t *key;
  2852. int *sem;
  2853. int fd, count;
  2854. if (is_in_use_bd(bus_number, device_address))
  2855. return false;
  2856. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2857. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2858. if (fd == -1) {
  2859. applog(LOG_ERR,
  2860. "SEM: %s USB open failed '%s' err (%d) %s",
  2861. dname, name, errno, strerror(errno));
  2862. goto _out;
  2863. }
  2864. close(fd);
  2865. key = malloc(sizeof(*key));
  2866. if (unlikely(!key))
  2867. quit(1, "SEM: Failed to malloc key");
  2868. sem = malloc(sizeof(*sem));
  2869. if (unlikely(!sem))
  2870. quit(1, "SEM: Failed to malloc sem");
  2871. *key = ftok(name, 'K');
  2872. *sem = semget(*key, 1, IPC_CREAT | IPC_EXCL | 438);
  2873. if (*sem < 0) {
  2874. if (errno != EEXIST) {
  2875. applog(LOG_ERR,
  2876. "SEM: %s USB failed to get '%s' err (%d) %s",
  2877. dname, name, errno, strerror(errno));
  2878. goto free_out;
  2879. }
  2880. *sem = semget(*key, 1, 0);
  2881. if (*sem < 0) {
  2882. applog(LOG_ERR,
  2883. "SEM: %s USB failed to access '%s' err (%d) %s",
  2884. dname, name, errno, strerror(errno));
  2885. goto free_out;
  2886. }
  2887. opt.buf = &seminfo;
  2888. count = 0;
  2889. while (++count) {
  2890. // Should NEVER take 100ms
  2891. if (count > 99) {
  2892. applog(LOG_ERR,
  2893. "SEM: %s USB timeout waiting for (%d) '%s'",
  2894. dname, *sem, name);
  2895. goto free_out;
  2896. }
  2897. if (semctl(*sem, 0, IPC_STAT, opt) == -1) {
  2898. applog(LOG_ERR,
  2899. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  2900. dname, *sem, name, count, errno, strerror(errno));
  2901. goto free_out;
  2902. }
  2903. if (opt.buf->sem_otime != 0)
  2904. break;
  2905. nmsleep(1);
  2906. }
  2907. }
  2908. struct sembuf sops[] = {
  2909. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  2910. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  2911. };
  2912. if (semop(*sem, sops, 2)) {
  2913. if (errno == EAGAIN) {
  2914. if (!hotplug_mode)
  2915. applog(LOG_WARNING,
  2916. "SEM: %s USB failed to get (%d) '%s' - device in use",
  2917. dname, *sem, name);
  2918. } else {
  2919. applog(LOG_DEBUG,
  2920. "SEM: %s USB failed to get (%d) '%s' err (%d) %s",
  2921. dname, *sem, name, errno, strerror(errno));
  2922. }
  2923. goto free_out;
  2924. }
  2925. add_in_use(bus_number, device_address);
  2926. in_use_store_ress(bus_number, device_address, (void *)key, (void *)sem);
  2927. return true;
  2928. free_out:
  2929. free(sem);
  2930. free(key);
  2931. _out:
  2932. return false;
  2933. #endif
  2934. }
  2935. // Any errors should always be printed since they will rarely if ever occur
  2936. // and thus it is best to always display them
  2937. static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2938. {
  2939. applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2940. #ifdef WIN32
  2941. LPSECURITY_ATTRIBUTES sec = NULL;
  2942. HANDLE usbMutex = NULL;
  2943. char name[64];
  2944. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2945. in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
  2946. if (!usbMutex || !sec)
  2947. goto fila;
  2948. if (!ReleaseMutex(usbMutex))
  2949. applog(LOG_ERR,
  2950. "MTX: %s USB failed to release '%s' err (%d)",
  2951. dname, name, (int)GetLastError());
  2952. fila:
  2953. if (usbMutex)
  2954. CloseHandle(usbMutex);
  2955. if (sec)
  2956. unsec(sec);
  2957. remove_in_use(bus_number, device_address);
  2958. return;
  2959. #else
  2960. char name[64];
  2961. key_t *key = NULL;
  2962. int *sem = NULL;
  2963. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2964. in_use_get_ress(bus_number, device_address, (void **)(&key), (void **)(&sem));
  2965. if (!key || !sem)
  2966. goto fila;
  2967. struct sembuf sops[] = {
  2968. { 0, -1, SEM_UNDO }
  2969. };
  2970. // Allow a 10ms timeout
  2971. // exceeding this timeout means it would probably never succeed anyway
  2972. struct timespec timeout = { 0, 10000000 };
  2973. if (semtimedop(*sem, sops, 1, &timeout)) {
  2974. applog(LOG_ERR,
  2975. "SEM: %s USB failed to release '%s' err (%d) %s",
  2976. dname, name, errno, strerror(errno));
  2977. }
  2978. if (semctl(*sem, 0, IPC_RMID)) {
  2979. applog(LOG_WARNING,
  2980. "SEM: %s USB failed to remove SEM '%s' err (%d) %s",
  2981. dname, name, errno, strerror(errno));
  2982. }
  2983. fila:
  2984. free(sem);
  2985. free(key);
  2986. remove_in_use(bus_number, device_address);
  2987. return;
  2988. #endif
  2989. }
  2990. static void resource_process()
  2991. {
  2992. struct resource_work *res_work = NULL;
  2993. struct resource_reply *res_reply = NULL;
  2994. bool ok;
  2995. applog(LOG_DEBUG, "RES: %s (%d:%d) lock=%d",
  2996. res_work_head->dname,
  2997. (int)res_work_head->bus_number,
  2998. (int)res_work_head->device_address,
  2999. res_work_head->lock);
  3000. if (res_work_head->lock) {
  3001. ok = resource_lock(res_work_head->dname,
  3002. res_work_head->bus_number,
  3003. res_work_head->device_address);
  3004. applog(LOG_DEBUG, "RES: %s (%d:%d) lock ok=%d",
  3005. res_work_head->dname,
  3006. (int)res_work_head->bus_number,
  3007. (int)res_work_head->device_address,
  3008. ok);
  3009. res_reply = calloc(1, sizeof(*res_reply));
  3010. if (unlikely(!res_reply))
  3011. quit(1, "USB failed to calloc res_reply");
  3012. res_reply->bus_number = res_work_head->bus_number;
  3013. res_reply->device_address = res_work_head->device_address;
  3014. res_reply->got = ok;
  3015. res_reply->next = res_reply_head;
  3016. res_reply_head = res_reply;
  3017. }
  3018. else
  3019. resource_unlock(res_work_head->dname,
  3020. res_work_head->bus_number,
  3021. res_work_head->device_address);
  3022. res_work = res_work_head;
  3023. res_work_head = res_work_head->next;
  3024. free(res_work);
  3025. }
  3026. void *usb_resource_thread(void __maybe_unused *userdata)
  3027. {
  3028. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3029. RenameThread("usbresource");
  3030. applog(LOG_DEBUG, "RES: thread starting");
  3031. while (42) {
  3032. /* Wait to be told we have work to do */
  3033. cgsem_wait(&usb_resource_sem);
  3034. mutex_lock(&cgusbres_lock);
  3035. while (res_work_head)
  3036. resource_process();
  3037. mutex_unlock(&cgusbres_lock);
  3038. }
  3039. return NULL;
  3040. }