usbutils.c 68 KB

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