usbutils.c 66 KB

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