usbutils.c 52 KB

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