usbutils.c 52 KB

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