usbutils.c 53 KB

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