usbutils.c 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908
  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. nmsleep(46);
  1058. // TODO: add a timeout fail - restart the resource thread?
  1059. while (true) {
  1060. mutex_lock(&cgusbres_lock);
  1061. if (res_reply_head) {
  1062. struct resource_reply *res_reply_prev = NULL;
  1063. struct resource_reply *res_reply = res_reply_head;
  1064. while (res_reply) {
  1065. if (res_reply->bus_number == bus_number &&
  1066. res_reply->device_address == device_address) {
  1067. if (res_reply_prev)
  1068. res_reply_prev->next = res_reply->next;
  1069. else
  1070. res_reply_head = res_reply->next;
  1071. mutex_unlock(&cgusbres_lock);
  1072. ret = res_reply->got;
  1073. free(res_reply);
  1074. return ret;
  1075. }
  1076. res_reply_prev = res_reply;
  1077. res_reply = res_reply->next;
  1078. }
  1079. }
  1080. mutex_unlock(&cgusbres_lock);
  1081. nmsleep(45);
  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. return;
  1104. }
  1105. static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
  1106. {
  1107. cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1108. }
  1109. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  1110. {
  1111. applog(LOG_DEBUG, "USB free %s", cgusb->found->name);
  1112. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  1113. free(cgusb->serial_string);
  1114. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  1115. free(cgusb->manuf_string);
  1116. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  1117. free(cgusb->prod_string);
  1118. free(cgusb->descriptor);
  1119. free(cgusb->found);
  1120. free(cgusb);
  1121. return NULL;
  1122. }
  1123. void usb_uninit(struct cgpu_info *cgpu)
  1124. {
  1125. applog(LOG_DEBUG, "USB uninit %s%i",
  1126. cgpu->drv->name, cgpu->device_id);
  1127. // May have happened already during a failed initialisation
  1128. // if release_cgpu() was called due to a USB NODEV(err)
  1129. if (!cgpu->usbdev)
  1130. return;
  1131. libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface);
  1132. libusb_close(cgpu->usbdev->handle);
  1133. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  1134. }
  1135. static void release_cgpu(struct cgpu_info *cgpu)
  1136. {
  1137. struct cg_usb_device *cgusb = cgpu->usbdev;
  1138. struct cgpu_info *lookcgpu;
  1139. int i;
  1140. applog(LOG_DEBUG, "USB release %s%i",
  1141. cgpu->drv->name, cgpu->device_id);
  1142. // It has already been done
  1143. if (cgpu->usbinfo.nodev)
  1144. return;
  1145. total_count--;
  1146. drv_count[cgpu->drv->drv_id].count--;
  1147. cgpu->usbinfo.nodev = true;
  1148. cgpu->usbinfo.nodev_count++;
  1149. cgtime(&cgpu->usbinfo.last_nodev);
  1150. // Any devices sharing the same USB device should be marked also
  1151. // Currently only MMQ shares a USB device
  1152. for (i = 0; i < total_devices; i++) {
  1153. lookcgpu = get_devices(i);
  1154. if (lookcgpu != cgpu && lookcgpu->usbdev == cgusb) {
  1155. total_count--;
  1156. drv_count[lookcgpu->drv->drv_id].count--;
  1157. lookcgpu->usbinfo.nodev = true;
  1158. lookcgpu->usbinfo.nodev_count++;
  1159. memcpy(&(lookcgpu->usbinfo.last_nodev),
  1160. &(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
  1161. lookcgpu->usbdev = NULL;
  1162. }
  1163. }
  1164. usb_uninit(cgpu);
  1165. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1166. }
  1167. #define USB_INIT_FAIL 0
  1168. #define USB_INIT_OK 1
  1169. #define USB_INIT_IGNORE 2
  1170. static int _usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1171. {
  1172. struct cg_usb_device *cgusb = NULL;
  1173. struct libusb_config_descriptor *config = NULL;
  1174. const struct libusb_interface_descriptor *idesc;
  1175. const struct libusb_endpoint_descriptor *epdesc;
  1176. unsigned char strbuf[STRBUFLEN+1];
  1177. char devstr[STRBUFLEN+1];
  1178. int err, i, j, k;
  1179. int bad = USB_INIT_FAIL;
  1180. cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
  1181. cgpu->usbinfo.device_address = libusb_get_device_address(dev);
  1182. sprintf(devstr, "- %s device %d:%d", found->name,
  1183. cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1184. cgusb = calloc(1, sizeof(*cgusb));
  1185. if (unlikely(!cgusb))
  1186. quit(1, "USB failed to calloc _usb_init cgusb");
  1187. cgusb->found = found;
  1188. if (found->idVendor == IDVENDOR_FTDI)
  1189. cgusb->usb_type = USB_TYPE_FTDI;
  1190. cgusb->ident = found->ident;
  1191. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  1192. if (unlikely(!cgusb->descriptor))
  1193. quit(1, "USB failed to calloc _usb_init cgusb descriptor");
  1194. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  1195. if (err) {
  1196. applog(LOG_DEBUG,
  1197. "USB init failed to get descriptor, err %d %s",
  1198. err, devstr);
  1199. goto dame;
  1200. }
  1201. err = libusb_open(dev, &(cgusb->handle));
  1202. if (err) {
  1203. switch (err) {
  1204. case LIBUSB_ERROR_ACCESS:
  1205. applog(LOG_ERR,
  1206. "USB init open device failed, err %d, "
  1207. "you dont have priviledge to access %s",
  1208. err, devstr);
  1209. break;
  1210. #ifdef WIN32
  1211. // Windows specific message
  1212. case LIBUSB_ERROR_NOT_SUPPORTED:
  1213. applog(LOG_ERR,
  1214. "USB init, open device failed, err %d, "
  1215. "you need to install a Windows USB driver for %s",
  1216. err, devstr);
  1217. break;
  1218. #endif
  1219. default:
  1220. applog(LOG_DEBUG,
  1221. "USB init, open failed, err %d %s",
  1222. err, devstr);
  1223. }
  1224. goto dame;
  1225. }
  1226. #ifndef WIN32
  1227. if (libusb_kernel_driver_active(cgusb->handle, found->kernel) == 1) {
  1228. applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
  1229. err = libusb_detach_kernel_driver(cgusb->handle, found->kernel);
  1230. if (err == 0) {
  1231. applog(LOG_DEBUG,
  1232. "USB init, kernel detached successfully %s",
  1233. devstr);
  1234. } else {
  1235. applog(LOG_WARNING,
  1236. "USB init, kernel detach failed, err %d in use? %s",
  1237. err, devstr);
  1238. goto cldame;
  1239. }
  1240. }
  1241. #endif
  1242. if (found->iManufacturer) {
  1243. unsigned char man[STRBUFLEN+1];
  1244. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1245. cgusb->descriptor->iManufacturer,
  1246. man, STRBUFLEN);
  1247. if (err < 0) {
  1248. applog(LOG_DEBUG,
  1249. "USB init, failed to get iManufacturer, err %d %s",
  1250. err, devstr);
  1251. goto cldame;
  1252. }
  1253. if (strcmp((char *)man, found->iManufacturer)) {
  1254. applog(LOG_DEBUG, "USB init, iManufacturer mismatch %s",
  1255. devstr);
  1256. bad = USB_INIT_IGNORE;
  1257. goto cldame;
  1258. }
  1259. }
  1260. if (found->iProduct) {
  1261. unsigned char prod[STRBUFLEN+1];
  1262. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1263. cgusb->descriptor->iProduct,
  1264. prod, STRBUFLEN);
  1265. if (err < 0) {
  1266. applog(LOG_DEBUG,
  1267. "USB init, failed to get iProduct, err %d %s",
  1268. err, devstr);
  1269. goto cldame;
  1270. }
  1271. if (strcmp((char *)prod, found->iProduct)) {
  1272. applog(LOG_DEBUG, "USB init, iProduct mismatch %s",
  1273. devstr);
  1274. bad = USB_INIT_IGNORE;
  1275. goto cldame;
  1276. }
  1277. }
  1278. err = libusb_set_configuration(cgusb->handle, found->config);
  1279. if (err) {
  1280. switch(err) {
  1281. case LIBUSB_ERROR_BUSY:
  1282. applog(LOG_WARNING,
  1283. "USB init, set config %d in use %s",
  1284. found->config, devstr);
  1285. break;
  1286. default:
  1287. applog(LOG_DEBUG,
  1288. "USB init, failed to set config to %d, err %d %s",
  1289. found->config, err, devstr);
  1290. }
  1291. goto cldame;
  1292. }
  1293. err = libusb_get_active_config_descriptor(dev, &config);
  1294. if (err) {
  1295. applog(LOG_DEBUG,
  1296. "USB init, failed to get config descriptor, err %d %s",
  1297. err, devstr);
  1298. goto cldame;
  1299. }
  1300. if ((int)(config->bNumInterfaces) <= found->interface) {
  1301. applog(LOG_DEBUG, "USB init bNumInterfaces <= interface %s",
  1302. devstr);
  1303. goto cldame;
  1304. }
  1305. for (i = 0; i < found->epcount; i++)
  1306. found->eps[i].found = false;
  1307. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  1308. idesc = &(config->interface[found->interface].altsetting[i]);
  1309. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  1310. epdesc = &(idesc->endpoint[j]);
  1311. for (k = 0; k < found->epcount; k++) {
  1312. if (!found->eps[k].found) {
  1313. if (epdesc->bmAttributes == found->eps[k].att
  1314. && epdesc->wMaxPacketSize >= found->eps[k].size
  1315. && epdesc->bEndpointAddress == found->eps[k].ep) {
  1316. found->eps[k].found = true;
  1317. break;
  1318. }
  1319. }
  1320. }
  1321. }
  1322. }
  1323. for (i = 0; i < found->epcount; i++) {
  1324. if (found->eps[i].found == false) {
  1325. applog(LOG_DEBUG, "USB init found == false %s",
  1326. devstr);
  1327. goto cldame;
  1328. }
  1329. }
  1330. err = libusb_claim_interface(cgusb->handle, found->interface);
  1331. if (err) {
  1332. switch(err) {
  1333. case LIBUSB_ERROR_BUSY:
  1334. applog(LOG_WARNING,
  1335. "USB init, claim interface %d in use %s",
  1336. found->interface, devstr);
  1337. break;
  1338. default:
  1339. applog(LOG_DEBUG,
  1340. "USB init, claim interface %d failed, err %d %s",
  1341. found->interface, err, devstr);
  1342. }
  1343. goto cldame;
  1344. }
  1345. cgusb->usbver = cgusb->descriptor->bcdUSB;
  1346. // TODO: allow this with the right version of the libusb include and running library
  1347. // cgusb->speed = libusb_get_device_speed(dev);
  1348. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1349. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  1350. if (err > 0)
  1351. cgusb->prod_string = strdup((char *)strbuf);
  1352. else
  1353. cgusb->prod_string = (char *)BLANK;
  1354. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1355. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  1356. if (err > 0)
  1357. cgusb->manuf_string = strdup((char *)strbuf);
  1358. else
  1359. cgusb->manuf_string = (char *)BLANK;
  1360. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1361. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  1362. if (err > 0)
  1363. cgusb->serial_string = strdup((char *)strbuf);
  1364. else
  1365. cgusb->serial_string = (char *)BLANK;
  1366. // TODO: ?
  1367. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  1368. // cgusb->interfaceVersion
  1369. applog(LOG_DEBUG,
  1370. "USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
  1371. devstr, cgusb->usbver, cgusb->prod_string,
  1372. cgusb->manuf_string, cgusb->serial_string);
  1373. cgpu->usbdev = cgusb;
  1374. libusb_free_config_descriptor(config);
  1375. // Allow a name change based on the idVendor+idProduct
  1376. // N.B. must be done before calling add_cgpu()
  1377. if (strcmp(cgpu->drv->name, found->name)) {
  1378. if (!cgpu->drv->copy)
  1379. cgpu->drv = copy_drv(cgpu->drv);
  1380. cgpu->drv->name = (char *)(found->name);
  1381. }
  1382. return USB_INIT_OK;
  1383. cldame:
  1384. libusb_close(cgusb->handle);
  1385. dame:
  1386. if (config)
  1387. libusb_free_config_descriptor(config);
  1388. cgusb = free_cgusb(cgusb);
  1389. return bad;
  1390. }
  1391. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1392. {
  1393. int ret;
  1394. ret = _usb_init(cgpu, dev, found);
  1395. if (ret == USB_INIT_FAIL)
  1396. applog(LOG_ERR, "%s detect (%d:%d) failed to initialise (incorrect device?)",
  1397. cgpu->drv->dname,
  1398. (int)(cgpu->usbinfo.bus_number),
  1399. (int)(cgpu->usbinfo.device_address));
  1400. return (ret == USB_INIT_OK);
  1401. }
  1402. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  1403. {
  1404. struct libusb_device_descriptor desc;
  1405. int bus_number, device_address;
  1406. int err, i;
  1407. bool ok;
  1408. err = libusb_get_device_descriptor(dev, &desc);
  1409. if (err) {
  1410. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  1411. return false;
  1412. }
  1413. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  1414. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  1415. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  1416. return false;
  1417. }
  1418. if (busdev_count > 0) {
  1419. bus_number = (int)libusb_get_bus_number(dev);
  1420. device_address = (int)libusb_get_device_address(dev);
  1421. ok = false;
  1422. for (i = 0; i < busdev_count; i++) {
  1423. if (bus_number == busdev[i].bus_number) {
  1424. if (busdev[i].device_address == -1 ||
  1425. device_address == busdev[i].device_address) {
  1426. ok = true;
  1427. break;
  1428. }
  1429. }
  1430. }
  1431. if (!ok) {
  1432. applog(LOG_DEBUG, "%s rejected %s %04x:%04x with bus:dev (%d:%d)",
  1433. drv->name, look->name, look->idVendor, look->idProduct,
  1434. bus_number, device_address);
  1435. return false;
  1436. }
  1437. }
  1438. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  1439. drv->name, look->name, look->idVendor, look->idProduct);
  1440. return true;
  1441. }
  1442. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  1443. {
  1444. struct usb_find_devices *found;
  1445. int i;
  1446. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  1447. if (find_dev[i].drv == drvnum) {
  1448. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  1449. found = malloc(sizeof(*found));
  1450. if (unlikely(!found))
  1451. quit(1, "USB failed to malloc found");
  1452. memcpy(found, &(find_dev[i]), sizeof(*found));
  1453. return found;
  1454. }
  1455. }
  1456. return NULL;
  1457. }
  1458. static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
  1459. {
  1460. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1461. applog(LOG_DEBUG,
  1462. "USB scan devices3: %s limit %d reached",
  1463. drv->dname, drv_count[drv->drv_id].limit);
  1464. return NULL;
  1465. }
  1466. #ifdef USE_BFLSC
  1467. if (drv->drv_id == DRIVER_BFLSC)
  1468. return usb_check_each(DRV_BFLSC, drv, dev);
  1469. #endif
  1470. #ifdef USE_BITFORCE
  1471. if (drv->drv_id == DRIVER_BITFORCE)
  1472. return usb_check_each(DRV_BITFORCE, drv, dev);
  1473. #endif
  1474. #ifdef USE_MODMINER
  1475. if (drv->drv_id == DRIVER_MODMINER)
  1476. return usb_check_each(DRV_MODMINER, drv, dev);
  1477. #endif
  1478. #ifdef USE_ICARUS
  1479. if (drv->drv_id == DRIVER_ICARUS)
  1480. return usb_check_each(DRV_ICARUS, drv, dev);
  1481. #endif
  1482. #ifdef USE_AVALON
  1483. if (drv->drv_id == DRIVER_AVALON)
  1484. return usb_check_each(DRV_AVALON, drv, dev);
  1485. #endif
  1486. return NULL;
  1487. }
  1488. void usb_detect(struct device_drv *drv, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *))
  1489. {
  1490. libusb_device **list;
  1491. ssize_t count, i;
  1492. struct usb_find_devices *found;
  1493. applog(LOG_DEBUG, "USB scan devices: checking for %s devices", drv->name);
  1494. if (total_count >= total_limit) {
  1495. applog(LOG_DEBUG, "USB scan devices: total limit %d reached", total_limit);
  1496. return;
  1497. }
  1498. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1499. applog(LOG_DEBUG,
  1500. "USB scan devices: %s limit %d reached",
  1501. drv->dname, drv_count[drv->drv_id].limit);
  1502. return;
  1503. }
  1504. count = libusb_get_device_list(NULL, &list);
  1505. if (count < 0) {
  1506. applog(LOG_DEBUG, "USB scan devices: failed, err %zd", count);
  1507. return;
  1508. }
  1509. if (count == 0)
  1510. applog(LOG_DEBUG, "USB scan devices: found no devices");
  1511. for (i = 0; i < count; i++) {
  1512. if (total_count >= total_limit) {
  1513. applog(LOG_DEBUG, "USB scan devices2: total limit %d reached", total_limit);
  1514. break;
  1515. }
  1516. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1517. applog(LOG_DEBUG,
  1518. "USB scan devices2: %s limit %d reached",
  1519. drv->dname, drv_count[drv->drv_id].limit);
  1520. break;
  1521. }
  1522. found = usb_check(drv, list[i]);
  1523. if (found != NULL) {
  1524. if (is_in_use(list[i]) || cgminer_usb_lock(drv, list[i]) == false)
  1525. free(found);
  1526. else {
  1527. if (!device_detect(list[i], found))
  1528. cgminer_usb_unlock(drv, list[i]);
  1529. else {
  1530. total_count++;
  1531. drv_count[drv->drv_id].count++;
  1532. }
  1533. }
  1534. }
  1535. }
  1536. libusb_free_device_list(list, 1);
  1537. }
  1538. #if DO_USB_STATS
  1539. static void modes_str(char *buf, uint32_t modes)
  1540. {
  1541. bool first;
  1542. *buf = '\0';
  1543. if (modes == MODE_NONE)
  1544. strcpy(buf, MODE_NONE_STR);
  1545. else {
  1546. first = true;
  1547. if (modes & MODE_CTRL_READ) {
  1548. strcpy(buf, MODE_CTRL_READ_STR);
  1549. first = false;
  1550. }
  1551. if (modes & MODE_CTRL_WRITE) {
  1552. if (!first)
  1553. strcat(buf, MODE_SEP_STR);
  1554. strcat(buf, MODE_CTRL_WRITE_STR);
  1555. first = false;
  1556. }
  1557. if (modes & MODE_BULK_READ) {
  1558. if (!first)
  1559. strcat(buf, MODE_SEP_STR);
  1560. strcat(buf, MODE_BULK_READ_STR);
  1561. first = false;
  1562. }
  1563. if (modes & MODE_BULK_WRITE) {
  1564. if (!first)
  1565. strcat(buf, MODE_SEP_STR);
  1566. strcat(buf, MODE_BULK_WRITE_STR);
  1567. first = false;
  1568. }
  1569. }
  1570. }
  1571. #endif
  1572. // The stat data can be spurious due to not locking it before copying it -
  1573. // however that would require the stat() function to also lock and release
  1574. // a mutex every time a usb read or write is called which would slow
  1575. // things down more
  1576. struct api_data *api_usb_stats(__maybe_unused int *count)
  1577. {
  1578. #if DO_USB_STATS
  1579. struct cg_usb_stats_details *details;
  1580. struct cg_usb_stats *sta;
  1581. struct api_data *root = NULL;
  1582. int device;
  1583. int cmdseq;
  1584. char modes_s[32];
  1585. if (next_stat == 0)
  1586. return NULL;
  1587. while (*count < next_stat * C_MAX * 2) {
  1588. device = *count / (C_MAX * 2);
  1589. cmdseq = *count % (C_MAX * 2);
  1590. (*count)++;
  1591. sta = &(usb_stats[device]);
  1592. details = &(sta->details[cmdseq]);
  1593. // Only show stats that have results
  1594. if (details->item[CMD_CMD].count == 0 &&
  1595. details->item[CMD_TIMEOUT].count == 0 &&
  1596. details->item[CMD_ERROR].count == 0)
  1597. continue;
  1598. root = api_add_string(root, "Name", sta->name, false);
  1599. root = api_add_int(root, "ID", &(sta->device_id), false);
  1600. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  1601. root = api_add_int(root, "Seq", &(details->seq), true);
  1602. modes_str(modes_s, details->modes);
  1603. root = api_add_string(root, "Modes", modes_s, true);
  1604. root = api_add_uint64(root, "Count",
  1605. &(details->item[CMD_CMD].count), true);
  1606. root = api_add_double(root, "Total Delay",
  1607. &(details->item[CMD_CMD].total_delay), true);
  1608. root = api_add_double(root, "Min Delay",
  1609. &(details->item[CMD_CMD].min_delay), true);
  1610. root = api_add_double(root, "Max Delay",
  1611. &(details->item[CMD_CMD].max_delay), true);
  1612. root = api_add_uint64(root, "Timeout Count",
  1613. &(details->item[CMD_TIMEOUT].count), true);
  1614. root = api_add_double(root, "Timeout Total Delay",
  1615. &(details->item[CMD_TIMEOUT].total_delay), true);
  1616. root = api_add_double(root, "Timeout Min Delay",
  1617. &(details->item[CMD_TIMEOUT].min_delay), true);
  1618. root = api_add_double(root, "Timeout Max Delay",
  1619. &(details->item[CMD_TIMEOUT].max_delay), true);
  1620. root = api_add_uint64(root, "Error Count",
  1621. &(details->item[CMD_ERROR].count), true);
  1622. root = api_add_double(root, "Error Total Delay",
  1623. &(details->item[CMD_ERROR].total_delay), true);
  1624. root = api_add_double(root, "Error Min Delay",
  1625. &(details->item[CMD_ERROR].min_delay), true);
  1626. root = api_add_double(root, "Error Max Delay",
  1627. &(details->item[CMD_ERROR].max_delay), true);
  1628. root = api_add_timeval(root, "First Command",
  1629. &(details->item[CMD_CMD].first), true);
  1630. root = api_add_timeval(root, "Last Command",
  1631. &(details->item[CMD_CMD].last), true);
  1632. root = api_add_timeval(root, "First Timeout",
  1633. &(details->item[CMD_TIMEOUT].first), true);
  1634. root = api_add_timeval(root, "Last Timeout",
  1635. &(details->item[CMD_TIMEOUT].last), true);
  1636. root = api_add_timeval(root, "First Error",
  1637. &(details->item[CMD_ERROR].first), true);
  1638. root = api_add_timeval(root, "Last Error",
  1639. &(details->item[CMD_ERROR].last), true);
  1640. return root;
  1641. }
  1642. #endif
  1643. return NULL;
  1644. }
  1645. #if DO_USB_STATS
  1646. static void newstats(struct cgpu_info *cgpu)
  1647. {
  1648. int i;
  1649. mutex_lock(&cgusb_lock);
  1650. cgpu->usbinfo.usbstat = ++next_stat;
  1651. mutex_unlock(&cgusb_lock);
  1652. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * next_stat);
  1653. if (unlikely(!usb_stats))
  1654. quit(1, "USB failed to realloc usb_stats %d", next_stat);
  1655. usb_stats[next_stat-1].name = cgpu->drv->name;
  1656. usb_stats[next_stat-1].device_id = -1;
  1657. usb_stats[next_stat-1].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  1658. if (unlikely(!usb_stats[next_stat-1].details))
  1659. quit(1, "USB failed to calloc details for %d", next_stat);
  1660. for (i = 1; i < C_MAX * 2; i += 2)
  1661. usb_stats[next_stat-1].details[i].seq = 1;
  1662. }
  1663. #endif
  1664. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  1665. {
  1666. #if DO_USB_STATS
  1667. if (cgpu->usbinfo.usbstat < 1)
  1668. newstats(cgpu);
  1669. // we don't know the device_id until after add_cgpu()
  1670. usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
  1671. #endif
  1672. }
  1673. #if DO_USB_STATS
  1674. 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)
  1675. {
  1676. struct cg_usb_stats_details *details;
  1677. double diff;
  1678. int item;
  1679. if (cgpu->usbinfo.usbstat < 1)
  1680. newstats(cgpu);
  1681. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
  1682. details->modes |= mode;
  1683. diff = tdiff(tv_finish, tv_start);
  1684. switch (err) {
  1685. case LIBUSB_SUCCESS:
  1686. item = CMD_CMD;
  1687. break;
  1688. case LIBUSB_ERROR_TIMEOUT:
  1689. item = CMD_TIMEOUT;
  1690. break;
  1691. default:
  1692. item = CMD_ERROR;
  1693. break;
  1694. }
  1695. if (details->item[item].count == 0) {
  1696. details->item[item].min_delay = diff;
  1697. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  1698. } else if (diff < details->item[item].min_delay)
  1699. details->item[item].min_delay = diff;
  1700. if (diff > details->item[item].max_delay)
  1701. details->item[item].max_delay = diff;
  1702. details->item[item].total_delay += diff;
  1703. memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
  1704. details->item[item].count++;
  1705. }
  1706. static void rejected_inc(struct cgpu_info *cgpu, uint32_t mode)
  1707. {
  1708. struct cg_usb_stats_details *details;
  1709. int item = CMD_ERROR;
  1710. if (cgpu->usbinfo.usbstat < 1)
  1711. newstats(cgpu);
  1712. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  1713. details->modes |= mode;
  1714. details->item[item].count++;
  1715. }
  1716. #endif
  1717. #define USB_MAX_READ 8192
  1718. 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)
  1719. {
  1720. struct cg_usb_device *usbdev = cgpu->usbdev;
  1721. bool ftdi;
  1722. #if DO_USB_STATS
  1723. struct timeval tv_start;
  1724. #endif
  1725. struct timeval read_start, tv_finish;
  1726. unsigned int initial_timeout;
  1727. double max, done;
  1728. int bufleft, err, got, tot;
  1729. __maybe_unused bool first = true;
  1730. unsigned char *search;
  1731. int endlen;
  1732. // We add 4: 1 for null, 2 for FTDI status and 1 to round to 4 bytes
  1733. unsigned char usbbuf[USB_MAX_READ+4], *ptr;
  1734. size_t usbbufread;
  1735. if (cgpu->usbinfo.nodev) {
  1736. *buf = '\0';
  1737. *processed = 0;
  1738. USB_REJECT(cgpu, MODE_BULK_READ);
  1739. return LIBUSB_ERROR_NO_DEVICE;
  1740. }
  1741. ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  1742. 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));
  1743. if (bufsiz > USB_MAX_READ)
  1744. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, bufsiz, USB_MAX_READ);
  1745. if (timeout == DEVTIMEOUT)
  1746. timeout = usbdev->found->timeout;
  1747. if (end == NULL) {
  1748. tot = 0;
  1749. ptr = usbbuf;
  1750. bufleft = bufsiz;
  1751. err = LIBUSB_SUCCESS;
  1752. initial_timeout = timeout;
  1753. max = ((double)timeout) / 1000.0;
  1754. cgtime(&read_start);
  1755. while (bufleft > 0) {
  1756. if (ftdi)
  1757. usbbufread = bufleft + 2;
  1758. else
  1759. usbbufread = bufleft;
  1760. got = 0;
  1761. STATS_TIMEVAL(&tv_start);
  1762. err = libusb_bulk_transfer(usbdev->handle,
  1763. usbdev->found->eps[ep].ep,
  1764. ptr, usbbufread, &got, timeout);
  1765. cgtime(&tv_finish);
  1766. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1767. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  1768. ptr[got] = '\0';
  1769. 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);
  1770. if (ftdi) {
  1771. // first 2 bytes returned are an FTDI status
  1772. if (got > 2) {
  1773. got -= 2;
  1774. memmove(ptr, ptr+2, got+1);
  1775. } else {
  1776. got = 0;
  1777. *ptr = '\0';
  1778. }
  1779. }
  1780. tot += got;
  1781. if (err || readonce)
  1782. break;
  1783. ptr += got;
  1784. bufleft -= got;
  1785. first = false;
  1786. done = tdiff(&tv_finish, &read_start);
  1787. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  1788. if (unlikely(done >= max))
  1789. break;
  1790. timeout = initial_timeout - (done * 1000);
  1791. }
  1792. *processed = tot;
  1793. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  1794. if (NODEV(err))
  1795. release_cgpu(cgpu);
  1796. return err;
  1797. }
  1798. tot = 0;
  1799. ptr = usbbuf;
  1800. bufleft = bufsiz;
  1801. endlen = strlen(end);
  1802. err = LIBUSB_SUCCESS;
  1803. initial_timeout = timeout;
  1804. max = ((double)timeout) / 1000.0;
  1805. cgtime(&read_start);
  1806. while (bufleft > 0) {
  1807. if (ftdi)
  1808. usbbufread = bufleft + 2;
  1809. else
  1810. usbbufread = bufleft;
  1811. got = 0;
  1812. STATS_TIMEVAL(&tv_start);
  1813. err = libusb_bulk_transfer(usbdev->handle,
  1814. usbdev->found->eps[ep].ep,
  1815. ptr, usbbufread, &got, timeout);
  1816. cgtime(&tv_finish);
  1817. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1818. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  1819. ptr[got] = '\0';
  1820. 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);
  1821. if (ftdi) {
  1822. // first 2 bytes returned are an FTDI status
  1823. if (got > 2) {
  1824. got -= 2;
  1825. memmove(ptr, ptr+2, got+1);
  1826. } else {
  1827. got = 0;
  1828. *ptr = '\0';
  1829. }
  1830. }
  1831. tot += got;
  1832. if (err || readonce)
  1833. break;
  1834. // WARNING - this will return data past END ('if' there is extra data)
  1835. if (endlen <= tot) {
  1836. // If END is only 1 char - do a faster search
  1837. if (endlen == 1) {
  1838. if (strchr((char *)ptr, *end))
  1839. break;
  1840. } else {
  1841. // must allow END to have been chopped in 2 transfers
  1842. if ((tot - got) >= (endlen - 1))
  1843. search = ptr - (endlen - 1);
  1844. else
  1845. search = ptr - (tot - got);
  1846. if (strstr((char *)search, end))
  1847. break;
  1848. }
  1849. }
  1850. ptr += got;
  1851. bufleft -= got;
  1852. first = false;
  1853. done = tdiff(&tv_finish, &read_start);
  1854. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  1855. if (unlikely(done >= max))
  1856. break;
  1857. timeout = initial_timeout - (done * 1000);
  1858. }
  1859. *processed = tot;
  1860. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  1861. if (NODEV(err))
  1862. release_cgpu(cgpu);
  1863. return err;
  1864. }
  1865. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  1866. #define FTDI_RS0_CTS (1 << 4)
  1867. #define FTDI_RS0_DSR (1 << 5)
  1868. #define FTDI_RS0_RI (1 << 6)
  1869. #define FTDI_RS0_RLSD (1 << 7)
  1870. /* Clear to send for FTDI */
  1871. int usb_ftdi_cts(struct cgpu_info *cgpu)
  1872. {
  1873. struct cg_usb_device *usbdev = cgpu->usbdev;
  1874. unsigned char buf[2], ret;
  1875. /* We return true in case drivers are waiting indefinitely to try and
  1876. * write to something that's not there. */
  1877. if (cgpu->usbinfo.nodev)
  1878. return true;
  1879. libusb_control_transfer(usbdev->handle, (uint8_t)FTDI_TYPE_IN,
  1880. (uint8_t)5, (uint16_t)0, (uint16_t)0, buf, 2,
  1881. DEVTIMEOUT);
  1882. ret = buf[0] & FTDI_STATUS_B0_MASK;
  1883. return (ret & FTDI_RS0_CTS);
  1884. }
  1885. 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)
  1886. {
  1887. struct cg_usb_device *usbdev = cgpu->usbdev;
  1888. #if DO_USB_STATS
  1889. struct timeval tv_start;
  1890. #endif
  1891. struct timeval read_start, tv_finish;
  1892. unsigned int initial_timeout;
  1893. double max, done;
  1894. __maybe_unused bool first = true;
  1895. int err, sent, tot;
  1896. 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));
  1897. *processed = 0;
  1898. if (cgpu->usbinfo.nodev) {
  1899. USB_REJECT(cgpu, MODE_BULK_WRITE);
  1900. return LIBUSB_ERROR_NO_DEVICE;
  1901. }
  1902. if (timeout == DEVTIMEOUT)
  1903. timeout = usbdev->found->timeout;
  1904. tot = 0;
  1905. err = LIBUSB_SUCCESS;
  1906. initial_timeout = timeout;
  1907. max = ((double)timeout) / 1000.0;
  1908. cgtime(&read_start);
  1909. while (bufsiz > 0) {
  1910. sent = 0;
  1911. STATS_TIMEVAL(&tv_start);
  1912. err = libusb_bulk_transfer(usbdev->handle,
  1913. usbdev->found->eps[ep].ep,
  1914. (unsigned char *)buf,
  1915. bufsiz, &sent, timeout);
  1916. cgtime(&tv_finish);
  1917. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1918. MODE_BULK_WRITE, cmd, first ? SEQ0 : SEQ1);
  1919. 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);
  1920. tot += sent;
  1921. if (err)
  1922. break;
  1923. buf += sent;
  1924. bufsiz -= sent;
  1925. first = false;
  1926. done = tdiff(&tv_finish, &read_start);
  1927. // N.B. this is: return LIBUSB_SUCCESS with whatever size was written
  1928. if (unlikely(done >= max))
  1929. break;
  1930. timeout = initial_timeout - (done * 1000);
  1931. }
  1932. *processed = tot;
  1933. if (NODEV(err))
  1934. release_cgpu(cgpu);
  1935. return err;
  1936. }
  1937. 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)
  1938. {
  1939. struct cg_usb_device *usbdev = cgpu->usbdev;
  1940. #if DO_USB_STATS
  1941. struct timeval tv_start, tv_finish;
  1942. #endif
  1943. uint32_t *buf = NULL;
  1944. int err, i, bufsiz;
  1945. 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));
  1946. if (cgpu->usbinfo.nodev) {
  1947. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  1948. return LIBUSB_ERROR_NO_DEVICE;
  1949. }
  1950. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  1951. if (siz > 0) {
  1952. bufsiz = siz - 1;
  1953. bufsiz >>= 2;
  1954. bufsiz++;
  1955. buf = malloc(bufsiz << 2);
  1956. if (unlikely(!buf))
  1957. quit(1, "Failed to malloc in _usb_transfer");
  1958. for (i = 0; i < bufsiz; i++)
  1959. buf[i] = htole32(data[i]);
  1960. }
  1961. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex((unsigned char *)buf, (size_t)siz));
  1962. STATS_TIMEVAL(&tv_start);
  1963. err = libusb_control_transfer(usbdev->handle, request_type,
  1964. bRequest, wValue, wIndex, (unsigned char *)buf, (uint16_t)siz,
  1965. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1966. STATS_TIMEVAL(&tv_finish);
  1967. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0);
  1968. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  1969. if (buf)
  1970. free(buf);
  1971. if (NODEV(err))
  1972. release_cgpu(cgpu);
  1973. return err;
  1974. }
  1975. 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)
  1976. {
  1977. struct cg_usb_device *usbdev = cgpu->usbdev;
  1978. #if DO_USB_STATS
  1979. struct timeval tv_start, tv_finish;
  1980. #endif
  1981. int err;
  1982. 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));
  1983. if (cgpu->usbinfo.nodev) {
  1984. USB_REJECT(cgpu, MODE_CTRL_READ);
  1985. return LIBUSB_ERROR_NO_DEVICE;
  1986. }
  1987. *amount = 0;
  1988. STATS_TIMEVAL(&tv_start);
  1989. err = libusb_control_transfer(usbdev->handle, request_type,
  1990. bRequest, wValue, wIndex,
  1991. (unsigned char *)buf, (uint16_t)bufsiz,
  1992. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1993. STATS_TIMEVAL(&tv_finish);
  1994. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0);
  1995. 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);
  1996. if (err > 0) {
  1997. *amount = err;
  1998. err = 0;
  1999. } else if (NODEV(err))
  2000. release_cgpu(cgpu);
  2001. return err;
  2002. }
  2003. void usb_cleanup()
  2004. {
  2005. struct cgpu_info *cgpu;
  2006. int i;
  2007. hotplug_time = 0;
  2008. nmsleep(10);
  2009. for (i = 0; i < total_devices; i++) {
  2010. cgpu = devices[i];
  2011. switch (cgpu->drv->drv_id) {
  2012. case DRIVER_BFLSC:
  2013. case DRIVER_BITFORCE:
  2014. case DRIVER_MODMINER:
  2015. case DRIVER_ICARUS:
  2016. case DRIVER_AVALON:
  2017. release_cgpu(cgpu);
  2018. break;
  2019. default:
  2020. break;
  2021. }
  2022. }
  2023. }
  2024. void usb_initialise()
  2025. {
  2026. char *fre, *ptr, *comma, *colon;
  2027. int bus, dev, lim, i;
  2028. bool found;
  2029. for (i = 0; i < DRIVER_MAX; i++) {
  2030. drv_count[i].count = 0;
  2031. drv_count[i].limit = 999999;
  2032. }
  2033. cgusb_check_init();
  2034. if (opt_usb_select && *opt_usb_select) {
  2035. // Absolute device limit
  2036. if (*opt_usb_select == ':') {
  2037. total_limit = atoi(opt_usb_select+1);
  2038. if (total_limit < 0)
  2039. quit(1, "Invalid --usb total limit");
  2040. // Comma list of bus:dev devices to match
  2041. } else if (isdigit(*opt_usb_select)) {
  2042. fre = ptr = strdup(opt_usb_select);
  2043. do {
  2044. comma = strchr(ptr, ',');
  2045. if (comma)
  2046. *(comma++) = '\0';
  2047. colon = strchr(ptr, ':');
  2048. if (!colon)
  2049. quit(1, "Invalid --usb bus:dev missing ':'");
  2050. *(colon++) = '\0';
  2051. if (!isdigit(*ptr))
  2052. quit(1, "Invalid --usb bus:dev - bus must be a number");
  2053. if (!isdigit(*colon) && *colon != '*')
  2054. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  2055. bus = atoi(ptr);
  2056. if (bus <= 0)
  2057. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  2058. if (!colon == '*')
  2059. dev = -1;
  2060. else {
  2061. dev = atoi(colon);
  2062. if (dev <= 0)
  2063. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  2064. }
  2065. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  2066. if (unlikely(!busdev))
  2067. quit(1, "USB failed to realloc busdev");
  2068. busdev[busdev_count-1].bus_number = bus;
  2069. busdev[busdev_count-1].device_address = dev;
  2070. ptr = comma;
  2071. } while (ptr);
  2072. free(fre);
  2073. // Comma list of DRV:limit
  2074. } else {
  2075. fre = ptr = strdup(opt_usb_select);
  2076. do {
  2077. comma = strchr(ptr, ',');
  2078. if (comma)
  2079. *(comma++) = '\0';
  2080. colon = strchr(ptr, ':');
  2081. if (!colon)
  2082. quit(1, "Invalid --usb DRV:limit missing ':'");
  2083. *(colon++) = '\0';
  2084. if (!isdigit(*colon))
  2085. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  2086. lim = atoi(colon);
  2087. if (lim < 0)
  2088. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  2089. found = false;
  2090. #ifdef USE_BFLSC
  2091. if (strcasecmp(ptr, bflsc_drv.name) == 0) {
  2092. drv_count[bflsc_drv.drv_id].limit = lim;
  2093. found = true;
  2094. }
  2095. #endif
  2096. #ifdef USE_BITFORCE
  2097. if (!found && strcasecmp(ptr, bitforce_drv.name) == 0) {
  2098. drv_count[bitforce_drv.drv_id].limit = lim;
  2099. found = true;
  2100. }
  2101. #endif
  2102. #ifdef USE_MODMINER
  2103. if (!found && strcasecmp(ptr, modminer_drv.name) == 0) {
  2104. drv_count[modminer_drv.drv_id].limit = lim;
  2105. found = true;
  2106. }
  2107. #endif
  2108. #ifdef USE_ICARUS
  2109. if (!found && strcasecmp(ptr, icarus_drv.name) == 0) {
  2110. drv_count[icarus_drv.drv_id].limit = lim;
  2111. found = true;
  2112. }
  2113. #endif
  2114. #ifdef USE_AVALON
  2115. if (!found && strcasecmp(ptr, avalon_drv.name) == 0) {
  2116. drv_count[avalon_drv.drv_id].limit = lim;
  2117. found = true;
  2118. }
  2119. #endif
  2120. if (!found)
  2121. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  2122. ptr = comma;
  2123. } while (ptr);
  2124. free(fre);
  2125. }
  2126. }
  2127. }
  2128. #ifndef WIN32
  2129. #include <errno.h>
  2130. #include <unistd.h>
  2131. #include <sys/types.h>
  2132. #include <sys/ipc.h>
  2133. #include <sys/sem.h>
  2134. #include <sys/types.h>
  2135. #include <sys/stat.h>
  2136. #include <fcntl.h>
  2137. union semun {
  2138. int sem;
  2139. struct semid_ds *seminfo;
  2140. ushort *all;
  2141. };
  2142. #else
  2143. static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
  2144. {
  2145. FreeSid(((PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor))->Group);
  2146. free(sec->lpSecurityDescriptor);
  2147. free(sec);
  2148. return NULL;
  2149. }
  2150. static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
  2151. {
  2152. SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
  2153. PSID gsid = NULL;
  2154. LPSECURITY_ATTRIBUTES sec_att = NULL;
  2155. PSECURITY_DESCRIPTOR sec_des = NULL;
  2156. sec_des = malloc(sizeof(*sec_des));
  2157. if (unlikely(!sec_des))
  2158. quit(1, "MTX: Failed to malloc LPSECURITY_DESCRIPTOR");
  2159. if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
  2160. applog(LOG_ERR,
  2161. "MTX: %s (%d:%d) USB failed to init secdes err (%d)",
  2162. dname, (int)bus_number, (int)device_address,
  2163. GetLastError());
  2164. free(sec_des);
  2165. return NULL;
  2166. }
  2167. if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
  2168. applog(LOG_ERR,
  2169. "MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
  2170. dname, (int)bus_number, (int)device_address,
  2171. GetLastError());
  2172. free(sec_des);
  2173. return NULL;
  2174. }
  2175. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
  2176. applog(LOG_ERR,
  2177. "MTX: %s (%d:%d) USB failed to create gsid err (%d)",
  2178. dname, (int)bus_number, (int)device_address,
  2179. GetLastError());
  2180. free(sec_des);
  2181. return NULL;
  2182. }
  2183. if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
  2184. applog(LOG_ERR,
  2185. "MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
  2186. dname, (int)bus_number, (int)device_address,
  2187. GetLastError());
  2188. FreeSid(gsid);
  2189. free(sec_des);
  2190. return NULL;
  2191. }
  2192. sec_att = malloc(sizeof(*sec_att));
  2193. if (unlikely(!sec_att))
  2194. quit(1, "MTX: Failed to malloc LPSECURITY_ATTRIBUTES");
  2195. sec_att->nLength = sizeof(*sec_att);
  2196. sec_att->lpSecurityDescriptor = sec_des;
  2197. sec_att->bInheritHandle = FALSE;
  2198. return sec_att;
  2199. }
  2200. #endif
  2201. // Any errors should always be printed since they will rarely if ever occur
  2202. // and thus it is best to always display them
  2203. static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2204. {
  2205. applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2206. #ifdef WIN32
  2207. struct cgpu_info *cgpu;
  2208. LPSECURITY_ATTRIBUTES sec;
  2209. HANDLE usbMutex;
  2210. char name[64];
  2211. DWORD res;
  2212. int i;
  2213. if (is_in_use_bd(bus_number, device_address))
  2214. return false;
  2215. sprintf(name, "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2216. sec = mksec(dname, bus_number, device_address);
  2217. if (!sec)
  2218. return false;
  2219. usbMutex = CreateMutex(sec, FALSE, name);
  2220. if (usbMutex == NULL) {
  2221. applog(LOG_ERR,
  2222. "MTX: %s USB failed to get '%s' err (%d)",
  2223. dname, name, GetLastError());
  2224. sec = unsec(sec);
  2225. return false;
  2226. }
  2227. res = WaitForSingleObject(usbMutex, 0);
  2228. switch(res) {
  2229. case WAIT_OBJECT_0:
  2230. case WAIT_ABANDONED:
  2231. // Am I using it already?
  2232. for (i = 0; i < total_devices; i++) {
  2233. cgpu = get_devices(i);
  2234. if (cgpu->usbinfo.bus_number == bus_number &&
  2235. cgpu->usbinfo.device_address == device_address &&
  2236. cgpu->usbinfo.nodev == false) {
  2237. if (ReleaseMutex(usbMutex)) {
  2238. applog(LOG_WARNING,
  2239. "MTX: %s USB can't get '%s' - device in use",
  2240. dname, name);
  2241. goto fail;
  2242. }
  2243. applog(LOG_ERR,
  2244. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  2245. dname, name, GetLastError());
  2246. goto fail;
  2247. }
  2248. }
  2249. break;
  2250. case WAIT_TIMEOUT:
  2251. if (!hotplug_mode)
  2252. applog(LOG_WARNING,
  2253. "MTX: %s USB failed to get '%s' - device in use",
  2254. dname, name);
  2255. goto fail;
  2256. case WAIT_FAILED:
  2257. applog(LOG_ERR,
  2258. "MTX: %s USB failed to get '%s' err (%d)",
  2259. dname, name, GetLastError());
  2260. goto fail;
  2261. default:
  2262. applog(LOG_ERR,
  2263. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  2264. dname, name, res);
  2265. goto fail;
  2266. }
  2267. add_in_use(bus_number, device_address);
  2268. in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
  2269. return true;
  2270. fail:
  2271. CloseHandle(usbMutex);
  2272. sec = unsec(sec);
  2273. return false;
  2274. #else
  2275. struct semid_ds seminfo;
  2276. union semun opt;
  2277. char name[64];
  2278. key_t key;
  2279. int fd, sem, count;
  2280. if (is_in_use_bd(bus_number, device_address))
  2281. return false;
  2282. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2283. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2284. if (fd == -1) {
  2285. applog(LOG_ERR,
  2286. "SEM: %s USB open failed '%s' err (%d) %s",
  2287. dname, name, errno, strerror(errno));
  2288. return false;
  2289. }
  2290. close(fd);
  2291. key = ftok(name, 'K');
  2292. sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 438);
  2293. if (sem < 0) {
  2294. if (errno != EEXIST) {
  2295. applog(LOG_ERR,
  2296. "SEM: %s USB failed to get '%s' err (%d) %s",
  2297. dname, name, errno, strerror(errno));
  2298. return false;
  2299. }
  2300. sem = semget(key, 1, 0);
  2301. if (sem < 0) {
  2302. applog(LOG_ERR,
  2303. "SEM: %s USB failed to access '%s' err (%d) %s",
  2304. dname, name, errno, strerror(errno));
  2305. return false;
  2306. }
  2307. opt.seminfo = &seminfo;
  2308. count = 0;
  2309. while (++count) {
  2310. // Should NEVER take 100ms
  2311. if (count > 99) {
  2312. applog(LOG_ERR,
  2313. "SEM: %s USB timeout waiting for (%d) '%s'",
  2314. dname, sem, name);
  2315. return false;
  2316. }
  2317. if (semctl(sem, 0, IPC_STAT, opt) == -1) {
  2318. applog(LOG_ERR,
  2319. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  2320. dname, sem, name, count, errno, strerror(errno));
  2321. return false;
  2322. }
  2323. if (opt.seminfo->sem_otime != 0)
  2324. break;
  2325. nmsleep(1);
  2326. }
  2327. }
  2328. struct sembuf sops[] = {
  2329. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  2330. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  2331. };
  2332. if (semop(sem, sops, 2)) {
  2333. if (errno == EAGAIN) {
  2334. if (!hotplug_mode)
  2335. applog(LOG_WARNING,
  2336. "SEM: %s USB failed to get (%d) '%s' - device in use",
  2337. dname, sem, name);
  2338. } else {
  2339. applog(LOG_DEBUG,
  2340. "SEM: %s USB failed to get (%d) '%s' err (%d) %s",
  2341. dname, sem, name, errno, strerror(errno));
  2342. }
  2343. return false;
  2344. }
  2345. add_in_use(bus_number, device_address);
  2346. return true;
  2347. #endif
  2348. }
  2349. // Any errors should always be printed since they will rarely if ever occur
  2350. // and thus it is best to always display them
  2351. static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2352. {
  2353. applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2354. #ifdef WIN32
  2355. LPSECURITY_ATTRIBUTES sec = NULL;
  2356. HANDLE usbMutex = NULL;
  2357. char name[64];
  2358. sprintf(name, "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2359. in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
  2360. if (!usbMutex || !sec)
  2361. goto fila;
  2362. if (!ReleaseMutex(usbMutex))
  2363. applog(LOG_ERR,
  2364. "MTX: %s USB failed to release '%s' err (%d)",
  2365. dname, name, GetLastError());
  2366. fila:
  2367. if (usbMutex)
  2368. CloseHandle(usbMutex);
  2369. if (sec)
  2370. unsec(sec);
  2371. remove_in_use(bus_number, device_address);
  2372. return;
  2373. #else
  2374. char name[64];
  2375. key_t key;
  2376. int fd, sem;
  2377. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2378. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2379. if (fd == -1) {
  2380. applog(LOG_ERR,
  2381. "SEM: %s USB open failed '%s' for release err (%d) %s",
  2382. dname, name, errno, strerror(errno));
  2383. return;
  2384. }
  2385. close(fd);
  2386. key = ftok(name, 'K');
  2387. sem = semget(key, 1, 0);
  2388. if (sem < 0) {
  2389. applog(LOG_ERR,
  2390. "SEM: %s USB failed to get '%s' for release err (%d) %s",
  2391. dname, name, errno, strerror(errno));
  2392. return;
  2393. }
  2394. struct sembuf sops[] = {
  2395. { 0, -1, SEM_UNDO }
  2396. };
  2397. // Allow a 10ms timeout
  2398. // exceeding this timeout means it would probably never succeed anyway
  2399. struct timespec timeout = { 0, 10000000 };
  2400. // Wait forever since we shoud be the one who has it
  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 (0*1337+1) {
  2452. mutex_lock(&cgusbres_lock);
  2453. while (res_work_head)
  2454. resource_process();
  2455. mutex_unlock(&cgusbres_lock);
  2456. nmsleep(45);
  2457. }
  2458. return NULL;
  2459. }