usbutils.c 93 KB

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