usbutils.c 59 KB

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