usbutils.c 56 KB

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