usbutils.c 82 KB

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