usbutils.c 56 KB

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