usbutils.c 97 KB

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