usbutils.c 51 KB

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