usbutils.c 64 KB

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