usbutils.c 52 KB

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