usbutils.c 64 KB

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