usbutils.c 56 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133
  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. else {
  770. in_use_tmp->prev->next = in_use_tmp->next;
  771. if (in_use_tmp->next)
  772. in_use_tmp->next->prev = in_use_tmp->prev;
  773. }
  774. free(in_use_tmp);
  775. }
  776. in_use_tmp = in_use_tmp->next;
  777. }
  778. mutex_unlock(&cgusb_lock);
  779. if (!found)
  780. applog(LOG_ERR, "FAIL: USB remove not already in use (%d:%d)",
  781. (int)bus_number, (int)device_address);
  782. }
  783. #ifndef WIN32
  784. #include <errno.h>
  785. #include <unistd.h>
  786. #include <sys/types.h>
  787. #include <sys/ipc.h>
  788. #include <sys/sem.h>
  789. #include <sys/types.h>
  790. #include <sys/stat.h>
  791. #include <fcntl.h>
  792. union semun {
  793. int sem;
  794. struct semid_ds *seminfo;
  795. ushort *all;
  796. };
  797. #endif
  798. // Any errors should always be printed since they will rarely if ever occur
  799. // and thus it is best to always display them
  800. static bool cgminer_usb_lock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  801. {
  802. #ifdef WIN32
  803. struct cgpu_info *cgpu;
  804. HANDLE usbMutex;
  805. char name[64];
  806. DWORD res;
  807. int i;
  808. if (is_in_use_bd(bus_number, device_address))
  809. return false;
  810. sprintf(name, "cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  811. usbMutex = CreateMutex(NULL, FALSE, name);
  812. if (usbMutex == NULL) {
  813. applog(LOG_ERR,
  814. "MTX: %s USB failed to get '%s' err (%d)",
  815. drv->dname, name, GetLastError());
  816. return false;
  817. }
  818. res = WaitForSingleObject(usbMutex, 0);
  819. switch(res) {
  820. case WAIT_OBJECT_0:
  821. case WAIT_ABANDONED:
  822. // Am I using it already?
  823. for (i = 0; i < total_devices; i++) {
  824. cgpu = get_devices(i);
  825. if (cgpu->usbinfo.bus_number == bus_number &&
  826. cgpu->usbinfo.device_address == device_address &&
  827. cgpu->usbinfo.nodev == false) {
  828. if (ReleaseMutex(usbMutex)) {
  829. applog(LOG_WARNING,
  830. "MTX: %s USB can't get '%s' - device in use",
  831. drv->dname, name);
  832. goto fail;
  833. }
  834. applog(LOG_ERR,
  835. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  836. drv->dname, name, GetLastError());
  837. goto fail;
  838. }
  839. }
  840. return true;
  841. case WAIT_TIMEOUT:
  842. if (!hotplug_mode)
  843. applog(LOG_WARNING,
  844. "MTX: %s USB failed to get '%s' - device in use",
  845. drv->dname, name);
  846. goto fail;
  847. case WAIT_FAILED:
  848. applog(LOG_ERR,
  849. "MTX: %s USB failed to get '%s' err (%d)",
  850. drv->dname, name, GetLastError());
  851. goto fail;
  852. default:
  853. applog(LOG_ERR,
  854. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  855. drv->dname, name, res);
  856. goto fail;
  857. }
  858. CloseHandle(usbMutex);
  859. add_in_use(bus_number, device_address);
  860. return true;
  861. fail:
  862. CloseHandle(usbMutex);
  863. return false;
  864. #else
  865. struct semid_ds seminfo;
  866. union semun opt;
  867. char name[64];
  868. key_t key;
  869. int fd, sem, count;
  870. if (is_in_use_bd(bus_number, device_address))
  871. return false;
  872. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  873. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  874. if (fd == -1) {
  875. applog(LOG_ERR,
  876. "SEM: %s USB open failed '%s' err (%d) %s",
  877. drv->dname, name, errno, strerror(errno));
  878. return false;
  879. }
  880. close(fd);
  881. key = ftok(name, 'K');
  882. sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 438);
  883. if (sem < 0) {
  884. if (errno != EEXIST) {
  885. applog(LOG_ERR,
  886. "SEM: %s USB failed to get '%s' err (%d) %s",
  887. drv->dname, name, errno, strerror(errno));
  888. return false;
  889. }
  890. sem = semget(key, 1, 0);
  891. if (sem < 0) {
  892. applog(LOG_ERR,
  893. "SEM: %s USB failed to access '%s' err (%d) %s",
  894. drv->dname, name, errno, strerror(errno));
  895. return false;
  896. }
  897. opt.seminfo = &seminfo;
  898. count = 0;
  899. while (++count) {
  900. // Should NEVER take 100ms
  901. if (count > 99) {
  902. applog(LOG_ERR,
  903. "SEM: %s USB timeout waiting for (%d) '%s'",
  904. drv->dname, sem, name);
  905. return false;
  906. }
  907. if (semctl(sem, 0, IPC_STAT, opt) == -1) {
  908. applog(LOG_ERR,
  909. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  910. drv->dname, sem, name, count, errno, strerror(errno));
  911. return false;
  912. }
  913. if (opt.seminfo->sem_otime != 0)
  914. break;
  915. nmsleep(1);
  916. }
  917. }
  918. struct sembuf sops[] = {
  919. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  920. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  921. };
  922. if (semop(sem, sops, 2)) {
  923. if (errno == EAGAIN) {
  924. if (!hotplug_mode)
  925. applog(LOG_WARNING,
  926. "SEM: %s USB failed to get (%d) '%s' - device in use",
  927. drv->dname, sem, name);
  928. } else {
  929. applog(LOG_DEBUG,
  930. "SEM: %s USB failed to get (%d) '%s' err (%d) %s",
  931. drv->dname, sem, name, errno, strerror(errno));
  932. }
  933. return false;
  934. }
  935. add_in_use(bus_number, device_address);
  936. return true;
  937. #endif
  938. }
  939. static bool cgminer_usb_lock(struct device_drv *drv, libusb_device *dev)
  940. {
  941. return cgminer_usb_lock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  942. }
  943. // Any errors should always be printed since they will rarely if ever occur
  944. // and thus it is best to always display them
  945. static void cgminer_usb_unlock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  946. {
  947. #ifdef WIN32
  948. HANDLE usbMutex;
  949. char name[64];
  950. sprintf(name, "cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  951. usbMutex = CreateMutex(NULL, FALSE, name);
  952. if (usbMutex == NULL) {
  953. applog(LOG_ERR,
  954. "MTX: %s USB failed to get '%s' for release err (%d)",
  955. drv->dname, name, GetLastError());
  956. return;
  957. }
  958. if (!ReleaseMutex(usbMutex))
  959. applog(LOG_ERR,
  960. "MTX: %s USB failed to release '%s' err (%d)",
  961. drv->dname, name, GetLastError());
  962. CloseHandle(usbMutex);
  963. remove_in_use(bus_number, device_address);
  964. return;
  965. #else
  966. char name[64];
  967. key_t key;
  968. int fd, sem;
  969. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  970. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  971. if (fd == -1) {
  972. applog(LOG_ERR,
  973. "SEM: %s USB open failed '%s' for release err (%d) %s",
  974. drv->dname, name, errno, strerror(errno));
  975. return;
  976. }
  977. close(fd);
  978. key = ftok(name, 'K');
  979. sem = semget(key, 1, 0);
  980. if (sem < 0) {
  981. applog(LOG_ERR,
  982. "SEM: %s USB failed to get '%s' for release err (%d) %s",
  983. drv->dname, name, errno, strerror(errno));
  984. return;
  985. }
  986. struct sembuf sops[] = {
  987. { 0, -1, SEM_UNDO }
  988. };
  989. // Allow a 10ms timeout
  990. // exceeding this timeout means it would probably never succeed anyway
  991. struct timespec timeout = { 0, 10000000 };
  992. // Wait forever since we shoud be the one who has it
  993. if (semtimedop(sem, sops, 1, &timeout)) {
  994. applog(LOG_ERR,
  995. "SEM: %d USB failed to release '%s' err (%d) %s",
  996. drv->dname, name, errno, strerror(errno));
  997. }
  998. remove_in_use(bus_number, device_address);
  999. return;
  1000. #endif
  1001. }
  1002. static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
  1003. {
  1004. cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1005. }
  1006. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  1007. {
  1008. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  1009. free(cgusb->serial_string);
  1010. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  1011. free(cgusb->manuf_string);
  1012. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  1013. free(cgusb->prod_string);
  1014. free(cgusb->descriptor);
  1015. free(cgusb->found);
  1016. free(cgusb);
  1017. return NULL;
  1018. }
  1019. void usb_uninit(struct cgpu_info *cgpu)
  1020. {
  1021. // May have happened already during a failed initialisation
  1022. // if release_cgpu() was called due to a USB NODEV(err)
  1023. if (!cgpu->usbdev)
  1024. return;
  1025. libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface);
  1026. libusb_close(cgpu->usbdev->handle);
  1027. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  1028. }
  1029. static void release_cgpu(struct cgpu_info *cgpu)
  1030. {
  1031. struct cg_usb_device *cgusb = cgpu->usbdev;
  1032. struct cgpu_info *lookcgpu;
  1033. int i;
  1034. // It has already been done
  1035. if (cgpu->usbinfo.nodev)
  1036. return;
  1037. total_count--;
  1038. drv_count[cgpu->drv->drv_id].count--;
  1039. cgpu->usbinfo.nodev = true;
  1040. cgpu->usbinfo.nodev_count++;
  1041. cgtime(&cgpu->usbinfo.last_nodev);
  1042. // Any devices sharing the same USB device should be marked also
  1043. // Currently only MMQ shares a USB device
  1044. for (i = 0; i < total_devices; i++) {
  1045. lookcgpu = get_devices(i);
  1046. if (lookcgpu != cgpu && lookcgpu->usbdev == cgusb) {
  1047. total_count--;
  1048. drv_count[lookcgpu->drv->drv_id].count--;
  1049. lookcgpu->usbinfo.nodev = true;
  1050. lookcgpu->usbinfo.nodev_count++;
  1051. memcpy(&(lookcgpu->usbinfo.last_nodev),
  1052. &(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
  1053. lookcgpu->usbdev = NULL;
  1054. }
  1055. }
  1056. usb_uninit(cgpu);
  1057. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1058. }
  1059. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1060. {
  1061. struct cg_usb_device *cgusb = NULL;
  1062. struct libusb_config_descriptor *config = NULL;
  1063. const struct libusb_interface_descriptor *idesc;
  1064. const struct libusb_endpoint_descriptor *epdesc;
  1065. unsigned char strbuf[STRBUFLEN+1];
  1066. char devstr[STRBUFLEN+1];
  1067. int err, i, j, k;
  1068. cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
  1069. cgpu->usbinfo.device_address = libusb_get_device_address(dev);
  1070. sprintf(devstr, "- %s device %d:%d", found->name,
  1071. cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1072. cgusb = calloc(1, sizeof(*cgusb));
  1073. cgusb->found = found;
  1074. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  1075. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  1076. if (err) {
  1077. applog(LOG_DEBUG,
  1078. "USB init failed to get descriptor, err %d %s",
  1079. err, devstr);
  1080. goto dame;
  1081. }
  1082. err = libusb_open(dev, &(cgusb->handle));
  1083. if (err) {
  1084. switch (err) {
  1085. case LIBUSB_ERROR_ACCESS:
  1086. applog(LOG_ERR,
  1087. "USB init open device failed, err %d, "
  1088. "you dont have priviledge to access %s",
  1089. err, devstr);
  1090. break;
  1091. #ifdef WIN32
  1092. // Windows specific message
  1093. case LIBUSB_ERROR_NOT_SUPPORTED:
  1094. applog(LOG_ERR,
  1095. "USB init, open device failed, err %d, "
  1096. "you need to install a Windows USB driver for %s",
  1097. err, devstr);
  1098. break;
  1099. #endif
  1100. default:
  1101. applog(LOG_DEBUG,
  1102. "USB init, open failed, err %d %s",
  1103. err, devstr);
  1104. }
  1105. goto dame;
  1106. }
  1107. #ifndef WIN32
  1108. if (libusb_kernel_driver_active(cgusb->handle, found->kernel) == 1) {
  1109. applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
  1110. err = libusb_detach_kernel_driver(cgusb->handle, found->kernel);
  1111. if (err == 0) {
  1112. applog(LOG_DEBUG,
  1113. "USB init, kernel detached successfully %s",
  1114. devstr);
  1115. } else {
  1116. applog(LOG_WARNING,
  1117. "USB init, kernel detach failed, err %d in use? %s",
  1118. err, devstr);
  1119. goto cldame;
  1120. }
  1121. }
  1122. #endif
  1123. if (found->iManufacturer) {
  1124. unsigned char man[STRBUFLEN+1];
  1125. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1126. cgusb->descriptor->iManufacturer,
  1127. man, STRBUFLEN);
  1128. if (err < 0) {
  1129. applog(LOG_DEBUG,
  1130. "USB init, failed to get iManufacturer, err %d %s",
  1131. err, devstr);
  1132. goto cldame;
  1133. }
  1134. if (strcmp((char *)man, found->iManufacturer))
  1135. goto cldame;
  1136. }
  1137. if (found->iProduct) {
  1138. unsigned char prod[STRBUFLEN+1];
  1139. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1140. cgusb->descriptor->iProduct,
  1141. prod, STRBUFLEN);
  1142. if (err < 0) {
  1143. applog(LOG_DEBUG,
  1144. "USB init, failed to get iProduct, err %d %s",
  1145. err, devstr);
  1146. goto cldame;
  1147. }
  1148. if (strcmp((char *)prod, found->iProduct))
  1149. goto cldame;
  1150. }
  1151. err = libusb_set_configuration(cgusb->handle, found->config);
  1152. if (err) {
  1153. switch(err) {
  1154. case LIBUSB_ERROR_BUSY:
  1155. applog(LOG_WARNING,
  1156. "USB init, set config %d in use %s",
  1157. found->config, devstr);
  1158. break;
  1159. default:
  1160. applog(LOG_DEBUG,
  1161. "USB init, failed to set config to %d, err %d %s",
  1162. found->config, err, devstr);
  1163. }
  1164. goto cldame;
  1165. }
  1166. err = libusb_get_active_config_descriptor(dev, &config);
  1167. if (err) {
  1168. applog(LOG_DEBUG,
  1169. "USB init, failed to get config descriptor, err %d %s",
  1170. err, devstr);
  1171. goto cldame;
  1172. }
  1173. if ((int)(config->bNumInterfaces) <= found->interface)
  1174. goto cldame;
  1175. for (i = 0; i < found->epcount; i++)
  1176. found->eps[i].found = false;
  1177. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  1178. idesc = &(config->interface[found->interface].altsetting[i]);
  1179. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  1180. epdesc = &(idesc->endpoint[j]);
  1181. for (k = 0; k < found->epcount; k++) {
  1182. if (!found->eps[k].found) {
  1183. if (epdesc->bmAttributes == found->eps[k].att
  1184. && epdesc->wMaxPacketSize >= found->eps[k].size
  1185. && epdesc->bEndpointAddress == found->eps[k].ep) {
  1186. found->eps[k].found = true;
  1187. break;
  1188. }
  1189. }
  1190. }
  1191. }
  1192. }
  1193. for (i = 0; i < found->epcount; i++)
  1194. if (found->eps[i].found == false)
  1195. goto cldame;
  1196. err = libusb_claim_interface(cgusb->handle, found->interface);
  1197. if (err) {
  1198. switch(err) {
  1199. case LIBUSB_ERROR_BUSY:
  1200. applog(LOG_WARNING,
  1201. "USB init, claim interface %d in use %s",
  1202. found->interface, devstr);
  1203. break;
  1204. default:
  1205. applog(LOG_DEBUG,
  1206. "USB init, claim interface %d failed, err %d %s",
  1207. found->interface, err, devstr);
  1208. }
  1209. goto cldame;
  1210. }
  1211. cgusb->usbver = cgusb->descriptor->bcdUSB;
  1212. // TODO: allow this with the right version of the libusb include and running library
  1213. // cgusb->speed = libusb_get_device_speed(dev);
  1214. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1215. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  1216. if (err > 0)
  1217. cgusb->prod_string = strdup((char *)strbuf);
  1218. else
  1219. cgusb->prod_string = (char *)BLANK;
  1220. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1221. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  1222. if (err > 0)
  1223. cgusb->manuf_string = strdup((char *)strbuf);
  1224. else
  1225. cgusb->manuf_string = (char *)BLANK;
  1226. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1227. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  1228. if (err > 0)
  1229. cgusb->serial_string = strdup((char *)strbuf);
  1230. else
  1231. cgusb->serial_string = (char *)BLANK;
  1232. // TODO: ?
  1233. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  1234. // cgusb->interfaceVersion
  1235. applog(LOG_DEBUG,
  1236. "USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
  1237. devstr, cgusb->usbver, cgusb->prod_string,
  1238. cgusb->manuf_string, cgusb->serial_string);
  1239. cgpu->usbdev = cgusb;
  1240. libusb_free_config_descriptor(config);
  1241. // Allow a name change based on the idVendor+idProduct
  1242. // N.B. must be done before calling add_cgpu()
  1243. if (strcmp(cgpu->drv->name, found->name)) {
  1244. if (!cgpu->drv->copy)
  1245. cgpu->drv = copy_drv(cgpu->drv);
  1246. cgpu->drv->name = (char *)(found->name);
  1247. }
  1248. return true;
  1249. cldame:
  1250. libusb_close(cgusb->handle);
  1251. dame:
  1252. if (config)
  1253. libusb_free_config_descriptor(config);
  1254. cgusb = free_cgusb(cgusb);
  1255. return false;
  1256. }
  1257. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  1258. {
  1259. struct libusb_device_descriptor desc;
  1260. int bus_number, device_address;
  1261. int err, i;
  1262. bool ok;
  1263. err = libusb_get_device_descriptor(dev, &desc);
  1264. if (err) {
  1265. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  1266. return false;
  1267. }
  1268. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  1269. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  1270. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  1271. return false;
  1272. }
  1273. if (busdev_count > 0) {
  1274. bus_number = (int)libusb_get_bus_number(dev);
  1275. device_address = (int)libusb_get_device_address(dev);
  1276. ok = false;
  1277. for (i = 0; i < busdev_count; i++) {
  1278. if (bus_number == busdev[i].bus_number) {
  1279. if (busdev[i].device_address == -1 ||
  1280. device_address == busdev[i].device_address) {
  1281. ok = true;
  1282. break;
  1283. }
  1284. }
  1285. }
  1286. if (!ok) {
  1287. applog(LOG_DEBUG, "%s rejected %s %04x:%04x with bus:dev (%d:%d)",
  1288. drv->name, look->name, look->idVendor, look->idProduct,
  1289. bus_number, device_address);
  1290. return false;
  1291. }
  1292. }
  1293. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  1294. drv->name, look->name, look->idVendor, look->idProduct);
  1295. return true;
  1296. }
  1297. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  1298. {
  1299. struct usb_find_devices *found;
  1300. int i;
  1301. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  1302. if (find_dev[i].drv == drvnum) {
  1303. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  1304. found = malloc(sizeof(*found));
  1305. memcpy(found, &(find_dev[i]), sizeof(*found));
  1306. return found;
  1307. }
  1308. }
  1309. return NULL;
  1310. }
  1311. static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
  1312. {
  1313. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1314. applog(LOG_DEBUG,
  1315. "USB scan devices3: %s limit %d reached",
  1316. drv->dname, drv_count[drv->drv_id].limit);
  1317. return NULL;
  1318. }
  1319. #ifdef USE_BFLSC
  1320. if (drv->drv_id == DRIVER_BFLSC)
  1321. return usb_check_each(DRV_BFLSC, drv, dev);
  1322. #endif
  1323. #ifdef USE_BITFORCE
  1324. if (drv->drv_id == DRIVER_BITFORCE)
  1325. return usb_check_each(DRV_BITFORCE, drv, dev);
  1326. #endif
  1327. #ifdef USE_ICARUS
  1328. if (drv->drv_id == DRIVER_ICARUS)
  1329. return usb_check_each(DRV_ICARUS, drv, dev);
  1330. #endif
  1331. #ifdef USE_MODMINER
  1332. if (drv->drv_id == DRIVER_MODMINER)
  1333. return usb_check_each(DRV_MODMINER, drv, dev);
  1334. #endif
  1335. #ifdef USE_AVALON
  1336. if (drv->drv_id == DRIVER_AVALON)
  1337. return usb_check_each(DRV_AVALON, drv, dev);
  1338. #endif
  1339. return NULL;
  1340. }
  1341. void usb_detect(struct device_drv *drv, bool (*device_detect)(struct libusb_device *, struct usb_find_devices *))
  1342. {
  1343. libusb_device **list;
  1344. ssize_t count, i;
  1345. struct usb_find_devices *found;
  1346. applog(LOG_DEBUG, "USB scan devices: checking for %s devices", drv->name);
  1347. if (total_count >= total_limit) {
  1348. applog(LOG_DEBUG, "USB scan devices: total limit %d reached", total_limit);
  1349. return;
  1350. }
  1351. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1352. applog(LOG_DEBUG,
  1353. "USB scan devices: %s limit %d reached",
  1354. drv->dname, drv_count[drv->drv_id].limit);
  1355. return;
  1356. }
  1357. count = libusb_get_device_list(NULL, &list);
  1358. if (count < 0) {
  1359. applog(LOG_DEBUG, "USB scan devices: failed, err %d", count);
  1360. return;
  1361. }
  1362. if (count == 0)
  1363. applog(LOG_DEBUG, "USB scan devices: found no devices");
  1364. for (i = 0; i < count; i++) {
  1365. if (total_count >= total_limit) {
  1366. applog(LOG_DEBUG, "USB scan devices2: total limit %d reached", total_limit);
  1367. break;
  1368. }
  1369. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  1370. applog(LOG_DEBUG,
  1371. "USB scan devices2: %s limit %d reached",
  1372. drv->dname, drv_count[drv->drv_id].limit);
  1373. break;
  1374. }
  1375. found = usb_check(drv, list[i]);
  1376. if (found != NULL) {
  1377. if (is_in_use(list[i]) || cgminer_usb_lock(drv, list[i]) == false)
  1378. free(found);
  1379. else {
  1380. if (!device_detect(list[i], found))
  1381. cgminer_usb_unlock(drv, list[i]);
  1382. else {
  1383. total_count++;
  1384. drv_count[drv->drv_id].count++;
  1385. }
  1386. }
  1387. }
  1388. }
  1389. libusb_free_device_list(list, 1);
  1390. }
  1391. // Set this to 0 to remove stats processing
  1392. #define DO_USB_STATS 1
  1393. #if DO_USB_STATS
  1394. #define USB_STATS(sgpu, sta, fin, err, cmd, seq) stats(cgpu, sta, fin, err, cmd, seq)
  1395. #define STATS_TIMEVAL(tv) cgtime(tv)
  1396. #else
  1397. #define USB_STATS(sgpu, sta, fin, err, cmd, seq)
  1398. #define STATS_TIMEVAL(tv)
  1399. #endif
  1400. // The stat data can be spurious due to not locking it before copying it -
  1401. // however that would require the stat() function to also lock and release
  1402. // a mutex every time a usb read or write is called which would slow
  1403. // things down more
  1404. struct api_data *api_usb_stats(__maybe_unused int *count)
  1405. {
  1406. #if DO_USB_STATS
  1407. struct cg_usb_stats_details *details;
  1408. struct cg_usb_stats *sta;
  1409. struct api_data *root = NULL;
  1410. int device;
  1411. int cmdseq;
  1412. if (next_stat == 0)
  1413. return NULL;
  1414. while (*count < next_stat * C_MAX * 2) {
  1415. device = *count / (C_MAX * 2);
  1416. cmdseq = *count % (C_MAX * 2);
  1417. (*count)++;
  1418. sta = &(usb_stats[device]);
  1419. details = &(sta->details[cmdseq]);
  1420. // Only show stats that have results
  1421. if (details->item[CMD_CMD].count == 0 &&
  1422. details->item[CMD_TIMEOUT].count == 0 &&
  1423. details->item[CMD_ERROR].count == 0)
  1424. continue;
  1425. root = api_add_string(root, "Name", sta->name, false);
  1426. root = api_add_int(root, "ID", &(sta->device_id), false);
  1427. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  1428. root = api_add_int(root, "Seq", &(details->seq), true);
  1429. root = api_add_uint64(root, "Count",
  1430. &(details->item[CMD_CMD].count), true);
  1431. root = api_add_double(root, "Total Delay",
  1432. &(details->item[CMD_CMD].total_delay), true);
  1433. root = api_add_double(root, "Min Delay",
  1434. &(details->item[CMD_CMD].min_delay), true);
  1435. root = api_add_double(root, "Max Delay",
  1436. &(details->item[CMD_CMD].max_delay), true);
  1437. root = api_add_uint64(root, "Timeout Count",
  1438. &(details->item[CMD_TIMEOUT].count), true);
  1439. root = api_add_double(root, "Timeout Total Delay",
  1440. &(details->item[CMD_TIMEOUT].total_delay), true);
  1441. root = api_add_double(root, "Timeout Min Delay",
  1442. &(details->item[CMD_TIMEOUT].min_delay), true);
  1443. root = api_add_double(root, "Timeout Max Delay",
  1444. &(details->item[CMD_TIMEOUT].max_delay), true);
  1445. root = api_add_uint64(root, "Error Count",
  1446. &(details->item[CMD_ERROR].count), true);
  1447. root = api_add_double(root, "Error Total Delay",
  1448. &(details->item[CMD_ERROR].total_delay), true);
  1449. root = api_add_double(root, "Error Min Delay",
  1450. &(details->item[CMD_ERROR].min_delay), true);
  1451. root = api_add_double(root, "Error Max Delay",
  1452. &(details->item[CMD_ERROR].max_delay), true);
  1453. root = api_add_timeval(root, "First Command",
  1454. &(details->item[CMD_CMD].first), true);
  1455. root = api_add_timeval(root, "Last Command",
  1456. &(details->item[CMD_CMD].last), true);
  1457. root = api_add_timeval(root, "First Timeout",
  1458. &(details->item[CMD_TIMEOUT].first), true);
  1459. root = api_add_timeval(root, "Last Timeout",
  1460. &(details->item[CMD_TIMEOUT].last), true);
  1461. root = api_add_timeval(root, "First Error",
  1462. &(details->item[CMD_ERROR].first), true);
  1463. root = api_add_timeval(root, "Last Error",
  1464. &(details->item[CMD_ERROR].last), true);
  1465. return root;
  1466. }
  1467. #endif
  1468. return NULL;
  1469. }
  1470. #if DO_USB_STATS
  1471. static void newstats(struct cgpu_info *cgpu)
  1472. {
  1473. int i;
  1474. mutex_lock(&cgusb_lock);
  1475. cgpu->usbinfo.usbstat = ++next_stat;
  1476. mutex_unlock(&cgusb_lock);
  1477. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * next_stat);
  1478. usb_stats[next_stat-1].name = cgpu->drv->name;
  1479. usb_stats[next_stat-1].device_id = -1;
  1480. usb_stats[next_stat-1].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  1481. for (i = 1; i < C_MAX * 2; i += 2)
  1482. usb_stats[next_stat-1].details[i].seq = 1;
  1483. }
  1484. #endif
  1485. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  1486. {
  1487. #if DO_USB_STATS
  1488. if (cgpu->usbinfo.usbstat < 1)
  1489. newstats(cgpu);
  1490. // we don't know the device_id until after add_cgpu()
  1491. usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
  1492. #endif
  1493. }
  1494. #if DO_USB_STATS
  1495. static void stats(struct cgpu_info *cgpu, struct timeval *tv_start, struct timeval *tv_finish, int err, enum usb_cmds cmd, int seq)
  1496. {
  1497. struct cg_usb_stats_details *details;
  1498. double diff;
  1499. int item;
  1500. if (cgpu->usbinfo.usbstat < 1)
  1501. newstats(cgpu);
  1502. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
  1503. diff = tdiff(tv_finish, tv_start);
  1504. switch (err) {
  1505. case LIBUSB_SUCCESS:
  1506. item = CMD_CMD;
  1507. break;
  1508. case LIBUSB_ERROR_TIMEOUT:
  1509. item = CMD_TIMEOUT;
  1510. break;
  1511. default:
  1512. item = CMD_ERROR;
  1513. break;
  1514. }
  1515. if (details->item[item].count == 0) {
  1516. details->item[item].min_delay = diff;
  1517. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  1518. } else if (diff < details->item[item].min_delay)
  1519. details->item[item].min_delay = diff;
  1520. if (diff > details->item[item].max_delay)
  1521. details->item[item].max_delay = diff;
  1522. details->item[item].total_delay += diff;
  1523. memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
  1524. details->item[item].count++;
  1525. }
  1526. static void rejected_inc(struct cgpu_info *cgpu)
  1527. {
  1528. struct cg_usb_stats_details *details;
  1529. int item = CMD_ERROR;
  1530. if (cgpu->usbinfo.usbstat < 1)
  1531. newstats(cgpu);
  1532. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  1533. details->item[item].count++;
  1534. }
  1535. #endif
  1536. #define USB_MAX_READ 8192
  1537. 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)
  1538. {
  1539. struct cg_usb_device *usbdev = cgpu->usbdev;
  1540. #if DO_USB_STATS
  1541. struct timeval tv_start;
  1542. #endif
  1543. struct timeval read_start, tv_finish;
  1544. unsigned int initial_timeout;
  1545. double max, done;
  1546. int err, got, tot;
  1547. bool first = true;
  1548. unsigned char *search;
  1549. int endlen;
  1550. // We add 4: 1 for null, 2 for FTDI status and 1 to round to 4 bytes
  1551. unsigned char usbbuf[USB_MAX_READ+4], *ptr;
  1552. size_t usbbufread;
  1553. if (bufsiz > USB_MAX_READ)
  1554. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, bufsiz, USB_MAX_READ);
  1555. if (cgpu->usbinfo.nodev) {
  1556. *buf = '\0';
  1557. *processed = 0;
  1558. #if DO_USB_STATS
  1559. rejected_inc(cgpu);
  1560. #endif
  1561. return LIBUSB_ERROR_NO_DEVICE;
  1562. }
  1563. if (timeout == DEVTIMEOUT)
  1564. timeout = usbdev->found->timeout;
  1565. if (end == NULL) {
  1566. if (ftdi)
  1567. usbbufread = bufsiz + 2;
  1568. else
  1569. usbbufread = bufsiz;
  1570. got = 0;
  1571. STATS_TIMEVAL(&tv_start);
  1572. err = libusb_bulk_transfer(usbdev->handle,
  1573. usbdev->found->eps[ep].ep,
  1574. usbbuf, usbbufread, &got, timeout);
  1575. STATS_TIMEVAL(&tv_finish);
  1576. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1577. usbbuf[got] = '\0';
  1578. if (ftdi) {
  1579. // first 2 bytes returned are an FTDI status
  1580. if (got > 2) {
  1581. got -= 2;
  1582. memmove(usbbuf, usbbuf+2, got+1);
  1583. } else {
  1584. got = 0;
  1585. usbbuf[0] = '\0';
  1586. }
  1587. }
  1588. *processed = got;
  1589. memcpy((char *)buf, (const char *)usbbuf, (got < (int)bufsiz) ? got + 1 : (int)bufsiz);
  1590. if (NODEV(err))
  1591. release_cgpu(cgpu);
  1592. return err;
  1593. }
  1594. tot = 0;
  1595. ptr = usbbuf;
  1596. endlen = strlen(end);
  1597. err = LIBUSB_SUCCESS;
  1598. initial_timeout = timeout;
  1599. max = ((double)timeout) / 1000.0;
  1600. cgtime(&read_start);
  1601. while (bufsiz) {
  1602. if (ftdi)
  1603. usbbufread = bufsiz + 2;
  1604. else
  1605. usbbufread = bufsiz;
  1606. got = 0;
  1607. STATS_TIMEVAL(&tv_start);
  1608. err = libusb_bulk_transfer(usbdev->handle,
  1609. usbdev->found->eps[ep].ep,
  1610. ptr, usbbufread, &got, timeout);
  1611. cgtime(&tv_finish);
  1612. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, first ? SEQ0 : SEQ1);
  1613. ptr[got] = '\0';
  1614. if (ftdi) {
  1615. // first 2 bytes returned are an FTDI status
  1616. if (got > 2) {
  1617. got -= 2;
  1618. memmove(ptr, ptr+2, got+1);
  1619. } else {
  1620. got = 0;
  1621. *ptr = '\0';
  1622. }
  1623. }
  1624. tot += got;
  1625. if (err)
  1626. break;
  1627. // WARNING - this will return data past END ('if' there is extra data)
  1628. if (endlen <= tot) {
  1629. // If END is only 1 char - do a faster search
  1630. if (endlen == 1) {
  1631. if (strchr((char *)ptr, *end))
  1632. break;
  1633. } else {
  1634. // must allow END to have been chopped in 2 transfers
  1635. if ((tot - got) >= (endlen - 1))
  1636. search = ptr - (endlen - 1);
  1637. else
  1638. search = ptr - (tot - got);
  1639. if (strstr((char *)search, end))
  1640. break;
  1641. }
  1642. }
  1643. ptr += got;
  1644. bufsiz -= got;
  1645. first = false;
  1646. done = tdiff(&tv_finish, &read_start);
  1647. // N.B. this is return LIBUSB_SUCCESS with whatever size has already been read
  1648. if (unlikely(done >= max))
  1649. break;
  1650. timeout = initial_timeout - (done * 1000);
  1651. }
  1652. *processed = tot;
  1653. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  1654. if (NODEV(err))
  1655. release_cgpu(cgpu);
  1656. return err;
  1657. }
  1658. int _usb_write(struct cgpu_info *cgpu, int ep, char *buf, size_t bufsiz, int *processed, unsigned int timeout, enum usb_cmds cmd)
  1659. {
  1660. struct cg_usb_device *usbdev = cgpu->usbdev;
  1661. #if DO_USB_STATS
  1662. struct timeval tv_start, tv_finish;
  1663. #endif
  1664. int err, sent;
  1665. if (cgpu->usbinfo.nodev) {
  1666. *processed = 0;
  1667. #if DO_USB_STATS
  1668. rejected_inc(cgpu);
  1669. #endif
  1670. return LIBUSB_ERROR_NO_DEVICE;
  1671. }
  1672. sent = 0;
  1673. STATS_TIMEVAL(&tv_start);
  1674. err = libusb_bulk_transfer(usbdev->handle,
  1675. usbdev->found->eps[ep].ep,
  1676. (unsigned char *)buf,
  1677. bufsiz, &sent,
  1678. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1679. STATS_TIMEVAL(&tv_finish);
  1680. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1681. *processed = sent;
  1682. if (NODEV(err))
  1683. release_cgpu(cgpu);
  1684. return err;
  1685. }
  1686. 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)
  1687. {
  1688. struct cg_usb_device *usbdev = cgpu->usbdev;
  1689. #if DO_USB_STATS
  1690. struct timeval tv_start, tv_finish;
  1691. #endif
  1692. int err;
  1693. if (cgpu->usbinfo.nodev) {
  1694. #if DO_USB_STATS
  1695. rejected_inc(cgpu);
  1696. #endif
  1697. return LIBUSB_ERROR_NO_DEVICE;
  1698. }
  1699. STATS_TIMEVAL(&tv_start);
  1700. err = libusb_control_transfer(usbdev->handle, request_type,
  1701. bRequest, wValue, wIndex, NULL, 0,
  1702. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1703. STATS_TIMEVAL(&tv_finish);
  1704. USB_STATS(cgpu, &tv_start, &tv_finish, err, cmd, SEQ0);
  1705. if (NODEV(err))
  1706. release_cgpu(cgpu);
  1707. return err;
  1708. }
  1709. void usb_cleanup()
  1710. {
  1711. struct cgpu_info *cgpu;
  1712. int i;
  1713. hotplug_time = 0;
  1714. nmsleep(10);
  1715. for (i = 0; i < total_devices; i++) {
  1716. cgpu = devices[i];
  1717. switch (cgpu->drv->drv_id) {
  1718. case DRIVER_BFLSC:
  1719. case DRIVER_BITFORCE:
  1720. case DRIVER_MODMINER:
  1721. case DRIVER_AVALON:
  1722. release_cgpu(cgpu);
  1723. break;
  1724. default:
  1725. break;
  1726. }
  1727. }
  1728. }
  1729. void usb_initialise()
  1730. {
  1731. char *fre, *ptr, *comma, *colon;
  1732. int bus, dev, lim, i;
  1733. bool found;
  1734. for (i = 0; i < DRIVER_MAX; i++) {
  1735. drv_count[i].count = 0;
  1736. drv_count[i].limit = 999999;
  1737. }
  1738. cgusb_check_init();
  1739. if (opt_usb_select && *opt_usb_select) {
  1740. // Absolute device limit
  1741. if (*opt_usb_select == ':') {
  1742. total_limit = atoi(opt_usb_select+1);
  1743. if (total_limit < 0)
  1744. quit(1, "Invalid --usb total limit");
  1745. // Comma list of bus:dev devices to match
  1746. } else if (isdigit(*opt_usb_select)) {
  1747. fre = ptr = strdup(opt_usb_select);
  1748. do {
  1749. comma = strchr(ptr, ',');
  1750. if (comma)
  1751. *(comma++) = '\0';
  1752. colon = strchr(ptr, ':');
  1753. if (!colon)
  1754. quit(1, "Invalid --usb bus:dev missing ':'");
  1755. *(colon++) = '\0';
  1756. if (!isdigit(*ptr))
  1757. quit(1, "Invalid --usb bus:dev - bus must be a number");
  1758. if (!isdigit(*colon) && *colon != '*')
  1759. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  1760. bus = atoi(ptr);
  1761. if (bus <= 0)
  1762. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  1763. if (!colon == '*')
  1764. dev = -1;
  1765. else {
  1766. dev = atoi(colon);
  1767. if (dev <= 0)
  1768. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  1769. }
  1770. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  1771. busdev[busdev_count-1].bus_number = bus;
  1772. busdev[busdev_count-1].device_address = dev;
  1773. ptr = comma;
  1774. } while (ptr);
  1775. free(fre);
  1776. // Comma list of DRV:limit
  1777. } else {
  1778. fre = ptr = strdup(opt_usb_select);
  1779. do {
  1780. comma = strchr(ptr, ',');
  1781. if (comma)
  1782. *(comma++) = '\0';
  1783. colon = strchr(ptr, ':');
  1784. if (!colon)
  1785. quit(1, "Invalid --usb DRV:limit missing ':'");
  1786. *(colon++) = '\0';
  1787. if (!isdigit(*colon))
  1788. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  1789. lim = atoi(colon);
  1790. if (lim < 0)
  1791. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  1792. found = false;
  1793. #ifdef USE_BFLSC
  1794. if (strcasecmp(ptr, bflsc_drv.name) == 0) {
  1795. drv_count[bflsc_drv.drv_id].limit = lim;
  1796. found = true;
  1797. }
  1798. #endif
  1799. #ifdef USE_BITFORCE
  1800. if (!found && strcasecmp(ptr, bitforce_drv.name) == 0) {
  1801. drv_count[bitforce_drv.drv_id].limit = lim;
  1802. found = true;
  1803. }
  1804. #endif
  1805. #ifdef USE_MODMINER
  1806. if (!found && strcasecmp(ptr, modminer_drv.name) == 0) {
  1807. drv_count[modminer_drv.drv_id].limit = lim;
  1808. found = true;
  1809. }
  1810. #endif
  1811. #ifdef USE_AVALON
  1812. if (!found && strcasecmp(ptr, avalon_drv.name) == 0) {
  1813. drv_count[avalon_drv.drv_id].limit = lim;
  1814. found = true;
  1815. }
  1816. #endif
  1817. if (!found)
  1818. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  1819. ptr = comma;
  1820. } while (ptr);
  1821. free(fre);
  1822. }
  1823. }
  1824. }