usbutils.c 77 KB

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