usbutils.c 51 KB

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