usbutils.c 78 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984
  1. /*
  2. * Copyright 2012-2013 Andrew Smith
  3. * Copyright 2013 Con Kolivas <kernel@kolivas.org>
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 3 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <ctype.h>
  12. #include <stdint.h>
  13. #include <stdbool.h>
  14. #include "logging.h"
  15. #include "miner.h"
  16. #include "usbutils.h"
  17. #define NODEV(err) ((err) == LIBUSB_ERROR_NO_DEVICE || \
  18. (err) == LIBUSB_ERROR_PIPE || \
  19. (err) == LIBUSB_ERROR_OTHER)
  20. #ifdef USE_BFLSC
  21. #define DRV_BFLSC 1
  22. #endif
  23. #ifdef USE_BITFORCE
  24. #define DRV_BITFORCE 2
  25. #endif
  26. #ifdef USE_MODMINER
  27. #define DRV_MODMINER 3
  28. #endif
  29. #ifdef USE_ZTEX
  30. #define DRV_ZTEX 4
  31. #endif
  32. #ifdef USE_ICARUS
  33. #define DRV_ICARUS 5
  34. #endif
  35. #ifdef USE_AVALON
  36. #define DRV_AVALON 6
  37. #endif
  38. #define DRV_LAST -1
  39. #define USB_CONFIG 1
  40. #ifdef WIN32
  41. #define BFLSC_TIMEOUT_MS 999
  42. #define BITFORCE_TIMEOUT_MS 999
  43. #define MODMINER_TIMEOUT_MS 999
  44. #define AVALON_TIMEOUT_MS 999
  45. #define ICARUS_TIMEOUT_MS 999
  46. #else
  47. #define BFLSC_TIMEOUT_MS 200
  48. #define BITFORCE_TIMEOUT_MS 200
  49. #define MODMINER_TIMEOUT_MS 100
  50. #define AVALON_TIMEOUT_MS 200
  51. #define ICARUS_TIMEOUT_MS 200
  52. #endif
  53. #define USB_READ_MINPOLL 40
  54. #ifdef USE_BFLSC
  55. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  56. static struct usb_endpoints bas_eps[] = {
  57. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  58. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  59. };
  60. #endif
  61. #ifdef USE_BITFORCE
  62. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  63. static struct usb_endpoints bfl_eps[] = {
  64. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  65. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  66. };
  67. #endif
  68. #ifdef USE_MODMINER
  69. static struct usb_endpoints mmq_eps[] = {
  70. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  71. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0 }
  72. };
  73. #endif
  74. #ifdef USE_AVALON
  75. static struct usb_endpoints ava_eps[] = {
  76. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  77. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  78. };
  79. #endif
  80. #ifdef USE_ICARUS
  81. static struct usb_endpoints ica_eps[] = {
  82. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  83. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  84. };
  85. static struct usb_endpoints amu_eps[] = {
  86. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  87. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0 }
  88. };
  89. static struct usb_endpoints llt_eps[] = {
  90. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  91. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  92. };
  93. static struct usb_endpoints cmr1_eps[] = {
  94. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  95. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  96. /*
  97. Interface 1
  98. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0 },
  99. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(4), 0 },
  100. Interface 2
  101. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(5), 0 },
  102. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(6), 0 },
  103. Interface 3
  104. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(7), 0 },
  105. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(8), 0 }
  106. */
  107. };
  108. static struct usb_endpoints cmr2_eps[] = {
  109. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0 },
  110. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0 }
  111. };
  112. #endif
  113. #define IDVENDOR_FTDI 0x0403
  114. // TODO: Add support for (at least) Isochronous endpoints
  115. static struct usb_find_devices find_dev[] = {
  116. #ifdef USE_BFLSC
  117. {
  118. .drv = DRV_BFLSC,
  119. .name = "BAS",
  120. .ident = IDENT_BAS,
  121. .idVendor = IDVENDOR_FTDI,
  122. .idProduct = 0x6014,
  123. .iManufacturer = "Butterfly Labs",
  124. .iProduct = "BitFORCE SHA256 SC",
  125. .kernel = 0,
  126. .config = 1,
  127. .interface = 0,
  128. .timeout = BFLSC_TIMEOUT_MS,
  129. .epcount = ARRAY_SIZE(bas_eps),
  130. .eps = bas_eps },
  131. #endif
  132. #ifdef USE_BITFORCE
  133. {
  134. .drv = DRV_BITFORCE,
  135. .name = "BFL",
  136. .ident = IDENT_BFL,
  137. .idVendor = IDVENDOR_FTDI,
  138. .idProduct = 0x6014,
  139. .iManufacturer = "Butterfly Labs Inc.",
  140. .iProduct = "BitFORCE SHA256",
  141. .kernel = 0,
  142. .config = 1,
  143. .interface = 0,
  144. .timeout = BITFORCE_TIMEOUT_MS,
  145. .epcount = ARRAY_SIZE(bfl_eps),
  146. .eps = bfl_eps },
  147. #endif
  148. #ifdef USE_MODMINER
  149. {
  150. .drv = DRV_MODMINER,
  151. .name = "MMQ",
  152. .ident = IDENT_MMQ,
  153. .idVendor = 0x1fc9,
  154. .idProduct = 0x0003,
  155. .kernel = 0,
  156. .config = 1,
  157. .interface = 1,
  158. .timeout = MODMINER_TIMEOUT_MS,
  159. .epcount = ARRAY_SIZE(mmq_eps),
  160. .eps = mmq_eps },
  161. #endif
  162. #ifdef USE_AVALON
  163. {
  164. .drv = DRV_AVALON,
  165. .name = "AVA",
  166. .ident = IDENT_AVA,
  167. .idVendor = IDVENDOR_FTDI,
  168. .idProduct = 0x6001,
  169. .kernel = 0,
  170. .config = 1,
  171. .interface = 0,
  172. .timeout = AVALON_TIMEOUT_MS,
  173. .epcount = ARRAY_SIZE(ava_eps),
  174. .eps = ava_eps },
  175. #endif
  176. #ifdef USE_ICARUS
  177. {
  178. .drv = DRV_ICARUS,
  179. .name = "ICA",
  180. .ident = IDENT_ICA,
  181. .idVendor = 0x067b,
  182. .idProduct = 0x2303,
  183. .kernel = 0,
  184. .config = 1,
  185. .interface = 0,
  186. .timeout = ICARUS_TIMEOUT_MS,
  187. .epcount = ARRAY_SIZE(ica_eps),
  188. .eps = ica_eps },
  189. {
  190. .drv = DRV_ICARUS,
  191. .name = "AMU",
  192. .ident = IDENT_AMU,
  193. .idVendor = 0x10c4,
  194. .idProduct = 0xea60,
  195. .kernel = 0,
  196. .config = 1,
  197. .interface = 0,
  198. .timeout = ICARUS_TIMEOUT_MS,
  199. .epcount = ARRAY_SIZE(amu_eps),
  200. .eps = amu_eps },
  201. {
  202. .drv = DRV_ICARUS,
  203. .name = "BLT",
  204. .ident = IDENT_BLT,
  205. .idVendor = IDVENDOR_FTDI,
  206. .idProduct = 0x6001,
  207. .iProduct = "FT232R USB UART",
  208. .kernel = 0,
  209. .config = 1,
  210. .interface = 0,
  211. .timeout = ICARUS_TIMEOUT_MS,
  212. .epcount = ARRAY_SIZE(llt_eps),
  213. .eps = llt_eps },
  214. // For any that don't match the above "BLT"
  215. {
  216. .drv = DRV_ICARUS,
  217. .name = "LLT",
  218. .ident = IDENT_LLT,
  219. .idVendor = IDVENDOR_FTDI,
  220. .idProduct = 0x6001,
  221. .kernel = 0,
  222. .config = 1,
  223. .interface = 0,
  224. .timeout = ICARUS_TIMEOUT_MS,
  225. .epcount = ARRAY_SIZE(llt_eps),
  226. .eps = llt_eps },
  227. {
  228. .drv = DRV_ICARUS,
  229. .name = "CMR",
  230. .ident = IDENT_CMR1,
  231. .idVendor = IDVENDOR_FTDI,
  232. .idProduct = 0x8350,
  233. .iProduct = "Cairnsmore1",
  234. .kernel = 0,
  235. .config = 1,
  236. .interface = 0,
  237. .timeout = ICARUS_TIMEOUT_MS,
  238. .epcount = ARRAY_SIZE(cmr1_eps),
  239. .eps = cmr1_eps },
  240. {
  241. .drv = DRV_ICARUS,
  242. .name = "CMR",
  243. .ident = IDENT_CMR2,
  244. .idVendor = IDVENDOR_FTDI,
  245. .idProduct = 0x6014,
  246. .iProduct = "Cairnsmore1",
  247. .kernel = 0,
  248. .config = 1,
  249. .interface = 0,
  250. .timeout = ICARUS_TIMEOUT_MS,
  251. .epcount = ARRAY_SIZE(cmr2_eps),
  252. .eps = cmr2_eps },
  253. #endif
  254. #ifdef USE_ZTEX
  255. // This is here so cgminer -n shows them
  256. // the ztex driver (as at 201303) doesn't use usbutils
  257. {
  258. .drv = DRV_ZTEX,
  259. .name = "ZTX",
  260. .ident = IDENT_ZTX,
  261. .idVendor = 0x221a,
  262. .idProduct = 0x0100,
  263. .kernel = 0,
  264. .config = 1,
  265. .interface = 1,
  266. .timeout = 100,
  267. .epcount = 0,
  268. .eps = NULL },
  269. #endif
  270. { DRV_LAST, NULL, 0, 0, 0, NULL, NULL, 0, 0, 0, 0, 0, NULL }
  271. };
  272. #ifdef USE_BFLSC
  273. extern struct device_drv bflsc_drv;
  274. #endif
  275. #ifdef USE_BITFORCE
  276. extern struct device_drv bitforce_drv;
  277. #endif
  278. #ifdef USE_MODMINER
  279. extern struct device_drv modminer_drv;
  280. #endif
  281. #ifdef USE_ICARUS
  282. extern struct device_drv icarus_drv;
  283. #endif
  284. #ifdef USE_AVALON
  285. extern struct device_drv avalon_drv;
  286. #endif
  287. #define STRBUFLEN 256
  288. static const char *BLANK = "";
  289. static const char *space = " ";
  290. static const char *nodatareturned = "no data returned ";
  291. #define IOERR_CHECK(cgpu, err) \
  292. if (err == LIBUSB_ERROR_IO) { \
  293. cgpu->usbinfo.ioerr_count++; \
  294. cgpu->usbinfo.continuous_ioerr_count++; \
  295. } else { \
  296. cgpu->usbinfo.continuous_ioerr_count = 0; \
  297. }
  298. #if 0 // enable USBDEBUG - only during development testing
  299. static const char *debug_true_str = "true";
  300. static const char *debug_false_str = "false";
  301. static const char *nodevstr = "=NODEV";
  302. #define bool_str(boo) ((boo) ? debug_true_str : debug_false_str)
  303. #define isnodev(err) (NODEV(err) ? nodevstr : BLANK)
  304. #define USBDEBUG(fmt, ...) applog(LOG_WARNING, fmt, ##__VA_ARGS__)
  305. #else
  306. #define USBDEBUG(fmt, ...)
  307. #endif
  308. // For device limits by driver
  309. static struct driver_count {
  310. uint32_t count;
  311. uint32_t limit;
  312. } drv_count[DRIVER_MAX];
  313. // For device limits by list of bus/dev
  314. static struct usb_busdev {
  315. int bus_number;
  316. int device_address;
  317. void *resource1;
  318. void *resource2;
  319. } *busdev;
  320. static int busdev_count = 0;
  321. // Total device limit
  322. static int total_count = 0;
  323. static int total_limit = 999999;
  324. struct usb_in_use_list {
  325. struct usb_busdev in_use;
  326. struct usb_in_use_list *prev;
  327. struct usb_in_use_list *next;
  328. };
  329. // List of in use devices
  330. static struct usb_in_use_list *in_use_head = NULL;
  331. struct resource_work {
  332. bool lock;
  333. const char *dname;
  334. uint8_t bus_number;
  335. uint8_t device_address;
  336. struct resource_work *next;
  337. };
  338. // Pending work for the reslock thread
  339. struct resource_work *res_work_head = NULL;
  340. struct resource_reply {
  341. uint8_t bus_number;
  342. uint8_t device_address;
  343. bool got;
  344. struct resource_reply *next;
  345. };
  346. // Replies to lock requests
  347. struct resource_reply *res_reply_head = NULL;
  348. // Set this to 0 to remove stats processing
  349. #define DO_USB_STATS 1
  350. static bool stats_initialised = false;
  351. #if DO_USB_STATS
  352. // NONE must be 0 - calloced
  353. #define MODE_NONE 0
  354. #define MODE_CTRL_READ (1 << 0)
  355. #define MODE_CTRL_WRITE (1 << 1)
  356. #define MODE_BULK_READ (1 << 2)
  357. #define MODE_BULK_WRITE (1 << 3)
  358. #define MODE_SEP_STR "+"
  359. #define MODE_NONE_STR "X"
  360. #define MODE_CTRL_READ_STR "cr"
  361. #define MODE_CTRL_WRITE_STR "cw"
  362. #define MODE_BULK_READ_STR "br"
  363. #define MODE_BULK_WRITE_STR "bw"
  364. // One for each CMD, TIMEOUT, ERROR
  365. struct cg_usb_stats_item {
  366. uint64_t count;
  367. double total_delay;
  368. double min_delay;
  369. double max_delay;
  370. struct timeval first;
  371. struct timeval last;
  372. };
  373. #define CMD_CMD 0
  374. #define CMD_TIMEOUT 1
  375. #define CMD_ERROR 2
  376. // One for each C_CMD
  377. struct cg_usb_stats_details {
  378. int seq;
  379. uint32_t modes;
  380. struct cg_usb_stats_item item[CMD_ERROR+1];
  381. };
  382. // One for each device
  383. struct cg_usb_stats {
  384. char *name;
  385. int device_id;
  386. struct cg_usb_stats_details *details;
  387. };
  388. #define SEQ0 0
  389. #define SEQ1 1
  390. static struct cg_usb_stats *usb_stats = NULL;
  391. static int next_stat = 0;
  392. #define USB_STATS(sgpu, sta, fin, err, mode, cmd, seq) \
  393. stats(cgpu, sta, fin, err, mode, cmd, seq)
  394. #define STATS_TIMEVAL(tv) cgtime(tv)
  395. #define USB_REJECT(sgpu, mode) rejected_inc(sgpu, mode)
  396. #else
  397. #define USB_STATS(sgpu, sta, fin, err, mode, cmd, seq)
  398. #define STATS_TIMEVAL(tv)
  399. #define USB_REJECT(sgpu, mode)
  400. #endif // DO_USB_STATS
  401. static const char **usb_commands;
  402. static const char *C_REJECTED_S = "RejectedNoDevice";
  403. static const char *C_PING_S = "Ping";
  404. static const char *C_CLEAR_S = "Clear";
  405. static const char *C_REQUESTVERSION_S = "RequestVersion";
  406. static const char *C_GETVERSION_S = "GetVersion";
  407. static const char *C_REQUESTFPGACOUNT_S = "RequestFPGACount";
  408. static const char *C_GETFPGACOUNT_S = "GetFPGACount";
  409. static const char *C_STARTPROGRAM_S = "StartProgram";
  410. static const char *C_STARTPROGRAMSTATUS_S = "StartProgramStatus";
  411. static const char *C_PROGRAM_S = "Program";
  412. static const char *C_PROGRAMSTATUS_S = "ProgramStatus";
  413. static const char *C_PROGRAMSTATUS2_S = "ProgramStatus2";
  414. static const char *C_FINALPROGRAMSTATUS_S = "FinalProgramStatus";
  415. static const char *C_SETCLOCK_S = "SetClock";
  416. static const char *C_REPLYSETCLOCK_S = "ReplySetClock";
  417. static const char *C_REQUESTUSERCODE_S = "RequestUserCode";
  418. static const char *C_GETUSERCODE_S = "GetUserCode";
  419. static const char *C_REQUESTTEMPERATURE_S = "RequestTemperature";
  420. static const char *C_GETTEMPERATURE_S = "GetTemperature";
  421. static const char *C_SENDWORK_S = "SendWork";
  422. static const char *C_SENDWORKSTATUS_S = "SendWorkStatus";
  423. static const char *C_REQUESTWORKSTATUS_S = "RequestWorkStatus";
  424. static const char *C_GETWORKSTATUS_S = "GetWorkStatus";
  425. static const char *C_REQUESTIDENTIFY_S = "RequestIdentify";
  426. static const char *C_GETIDENTIFY_S = "GetIdentify";
  427. static const char *C_REQUESTFLASH_S = "RequestFlash";
  428. static const char *C_REQUESTSENDWORK_S = "RequestSendWork";
  429. static const char *C_REQUESTSENDWORKSTATUS_S = "RequestSendWorkStatus";
  430. static const char *C_RESET_S = "Reset";
  431. static const char *C_SETBAUD_S = "SetBaud";
  432. static const char *C_SETDATA_S = "SetDataCtrl";
  433. static const char *C_SETFLOW_S = "SetFlowCtrl";
  434. static const char *C_SETMODEM_S = "SetModemCtrl";
  435. static const char *C_PURGERX_S = "PurgeRx";
  436. static const char *C_PURGETX_S = "PurgeTx";
  437. static const char *C_FLASHREPLY_S = "FlashReply";
  438. static const char *C_REQUESTDETAILS_S = "RequestDetails";
  439. static const char *C_GETDETAILS_S = "GetDetails";
  440. static const char *C_REQUESTRESULTS_S = "RequestResults";
  441. static const char *C_GETRESULTS_S = "GetResults";
  442. static const char *C_REQUESTQUEJOB_S = "RequestQueJob";
  443. static const char *C_REQUESTQUEJOBSTATUS_S = "RequestQueJobStatus";
  444. static const char *C_QUEJOB_S = "QueJob";
  445. static const char *C_QUEJOBSTATUS_S = "QueJobStatus";
  446. static const char *C_QUEFLUSH_S = "QueFlush";
  447. static const char *C_QUEFLUSHREPLY_S = "QueFlushReply";
  448. static const char *C_REQUESTVOLTS_S = "RequestVolts";
  449. static const char *C_SENDTESTWORK_S = "SendTestWork";
  450. static const char *C_LATENCY_S = "SetLatency";
  451. static const char *C_SETLINE_S = "SetLine";
  452. static const char *C_VENDOR_S = "Vendor";
  453. static const char *C_AVALON_TASK_S = "AvalonTask";
  454. static const char *C_AVALON_READ_S = "AvalonRead";
  455. static const char *C_GET_AVALON_READY_S = "AvalonReady";
  456. static const char *C_AVALON_RESET_S = "AvalonReset";
  457. static const char *C_GET_AVALON_RESET_S = "GetAvalonReset";
  458. static const char *C_FTDI_STATUS_S = "FTDIStatus";
  459. #ifdef EOL
  460. #undef EOL
  461. #endif
  462. #define EOL "\n"
  463. static const char *DESDEV = "Device";
  464. static const char *DESCON = "Config";
  465. static const char *DESSTR = "String";
  466. static const char *DESINT = "Interface";
  467. static const char *DESEP = "Endpoint";
  468. static const char *DESHID = "HID";
  469. static const char *DESRPT = "Report";
  470. static const char *DESPHY = "Physical";
  471. static const char *DESHUB = "Hub";
  472. static const char *EPIN = "In: ";
  473. static const char *EPOUT = "Out: ";
  474. static const char *EPX = "?: ";
  475. static const char *CONTROL = "Control";
  476. static const char *ISOCHRONOUS_X = "Isochronous+?";
  477. static const char *ISOCHRONOUS_N_X = "Isochronous+None+?";
  478. static const char *ISOCHRONOUS_N_D = "Isochronous+None+Data";
  479. static const char *ISOCHRONOUS_N_F = "Isochronous+None+Feedback";
  480. static const char *ISOCHRONOUS_N_I = "Isochronous+None+Implicit";
  481. static const char *ISOCHRONOUS_A_X = "Isochronous+Async+?";
  482. static const char *ISOCHRONOUS_A_D = "Isochronous+Async+Data";
  483. static const char *ISOCHRONOUS_A_F = "Isochronous+Async+Feedback";
  484. static const char *ISOCHRONOUS_A_I = "Isochronous+Async+Implicit";
  485. static const char *ISOCHRONOUS_D_X = "Isochronous+Adaptive+?";
  486. static const char *ISOCHRONOUS_D_D = "Isochronous+Adaptive+Data";
  487. static const char *ISOCHRONOUS_D_F = "Isochronous+Adaptive+Feedback";
  488. static const char *ISOCHRONOUS_D_I = "Isochronous+Adaptive+Implicit";
  489. static const char *ISOCHRONOUS_S_X = "Isochronous+Sync+?";
  490. static const char *ISOCHRONOUS_S_D = "Isochronous+Sync+Data";
  491. static const char *ISOCHRONOUS_S_F = "Isochronous+Sync+Feedback";
  492. static const char *ISOCHRONOUS_S_I = "Isochronous+Sync+Implicit";
  493. static const char *BULK = "Bulk";
  494. static const char *INTERRUPT = "Interrupt";
  495. static const char *UNKNOWN = "Unknown";
  496. static const char *err_io_str = " IO Error";
  497. static const char *err_access_str = " Access Denied-a";
  498. static const char *err_timeout_str = " Reply Timeout";
  499. static const char *err_pipe_str = " Access denied-p";
  500. static const char *err_other_str = " Access denied-o";
  501. static const char *usberrstr(int err)
  502. {
  503. switch (err) {
  504. case LIBUSB_ERROR_IO:
  505. return err_io_str;
  506. case LIBUSB_ERROR_ACCESS:
  507. return err_access_str;
  508. case LIBUSB_ERROR_TIMEOUT:
  509. return err_timeout_str;
  510. case LIBUSB_ERROR_PIPE:
  511. return err_pipe_str;
  512. case LIBUSB_ERROR_OTHER:
  513. return err_other_str;
  514. }
  515. return BLANK;
  516. }
  517. static const char *destype(uint8_t bDescriptorType)
  518. {
  519. switch (bDescriptorType) {
  520. case LIBUSB_DT_DEVICE:
  521. return DESDEV;
  522. case LIBUSB_DT_CONFIG:
  523. return DESCON;
  524. case LIBUSB_DT_STRING:
  525. return DESSTR;
  526. case LIBUSB_DT_INTERFACE:
  527. return DESINT;
  528. case LIBUSB_DT_ENDPOINT:
  529. return DESEP;
  530. case LIBUSB_DT_HID:
  531. return DESHID;
  532. case LIBUSB_DT_REPORT:
  533. return DESRPT;
  534. case LIBUSB_DT_PHYSICAL:
  535. return DESPHY;
  536. case LIBUSB_DT_HUB:
  537. return DESHUB;
  538. }
  539. return UNKNOWN;
  540. }
  541. static const char *epdir(uint8_t bEndpointAddress)
  542. {
  543. switch (bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) {
  544. case LIBUSB_ENDPOINT_IN:
  545. return EPIN;
  546. case LIBUSB_ENDPOINT_OUT:
  547. return EPOUT;
  548. }
  549. return EPX;
  550. }
  551. static const char *epatt(uint8_t bmAttributes)
  552. {
  553. switch(bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) {
  554. case LIBUSB_TRANSFER_TYPE_CONTROL:
  555. return CONTROL;
  556. case LIBUSB_TRANSFER_TYPE_BULK:
  557. return BULK;
  558. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  559. return INTERRUPT;
  560. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  561. switch(bmAttributes & LIBUSB_ISO_SYNC_TYPE_MASK) {
  562. case LIBUSB_ISO_SYNC_TYPE_NONE:
  563. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  564. case LIBUSB_ISO_USAGE_TYPE_DATA:
  565. return ISOCHRONOUS_N_D;
  566. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  567. return ISOCHRONOUS_N_F;
  568. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  569. return ISOCHRONOUS_N_I;
  570. }
  571. return ISOCHRONOUS_N_X;
  572. case LIBUSB_ISO_SYNC_TYPE_ASYNC:
  573. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  574. case LIBUSB_ISO_USAGE_TYPE_DATA:
  575. return ISOCHRONOUS_A_D;
  576. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  577. return ISOCHRONOUS_A_F;
  578. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  579. return ISOCHRONOUS_A_I;
  580. }
  581. return ISOCHRONOUS_A_X;
  582. case LIBUSB_ISO_SYNC_TYPE_ADAPTIVE:
  583. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  584. case LIBUSB_ISO_USAGE_TYPE_DATA:
  585. return ISOCHRONOUS_D_D;
  586. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  587. return ISOCHRONOUS_D_F;
  588. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  589. return ISOCHRONOUS_D_I;
  590. }
  591. return ISOCHRONOUS_D_X;
  592. case LIBUSB_ISO_SYNC_TYPE_SYNC:
  593. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  594. case LIBUSB_ISO_USAGE_TYPE_DATA:
  595. return ISOCHRONOUS_S_D;
  596. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  597. return ISOCHRONOUS_S_F;
  598. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  599. return ISOCHRONOUS_S_I;
  600. }
  601. return ISOCHRONOUS_S_X;
  602. }
  603. return ISOCHRONOUS_X;
  604. }
  605. return UNKNOWN;
  606. }
  607. static void append(char **buf, char *append, size_t *off, size_t *len)
  608. {
  609. int new = strlen(append);
  610. if ((new + *off) >= *len)
  611. {
  612. *len *= 2;
  613. *buf = realloc(*buf, *len);
  614. if (unlikely(!*buf))
  615. quit(1, "USB failed to realloc append");
  616. }
  617. strcpy(*buf + *off, append);
  618. *off += new;
  619. }
  620. 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)
  621. {
  622. char tmp[512];
  623. int err;
  624. err = libusb_set_configuration(handle, cd);
  625. if (err) {
  626. sprintf(tmp, EOL " ** dev %d: Failed to set config descriptor to %d, err %d",
  627. (int)count, cd, err);
  628. append(buf, tmp, off, len);
  629. return false;
  630. }
  631. err = libusb_get_active_config_descriptor(dev, config);
  632. if (err) {
  633. sprintf(tmp, EOL " ** dev %d: Failed to get active config descriptor set to %d, err %d",
  634. (int)count, cd, err);
  635. append(buf, tmp, off, len);
  636. return false;
  637. }
  638. sprintf(tmp, EOL " ** dev %d: Set & Got active config descriptor to %d, err %d",
  639. (int)count, cd, err);
  640. append(buf, tmp, off, len);
  641. return true;
  642. }
  643. static void usb_full(ssize_t *count, libusb_device *dev, char **buf, size_t *off, size_t *len, int level)
  644. {
  645. struct libusb_device_descriptor desc;
  646. uint8_t bus_number;
  647. uint8_t device_address;
  648. struct libusb_device_handle *handle;
  649. struct libusb_config_descriptor *config;
  650. const struct libusb_interface_descriptor *idesc;
  651. const struct libusb_endpoint_descriptor *epdesc;
  652. unsigned char man[STRBUFLEN+1];
  653. unsigned char prod[STRBUFLEN+1];
  654. unsigned char ser[STRBUFLEN+1];
  655. char tmp[512];
  656. int err, i, j, k;
  657. err = libusb_get_device_descriptor(dev, &desc);
  658. if (opt_usb_list_all && err) {
  659. sprintf(tmp, EOL ".USB dev %d: Failed to get descriptor, err %d",
  660. (int)(++(*count)), err);
  661. append(buf, tmp, off, len);
  662. return;
  663. }
  664. bus_number = libusb_get_bus_number(dev);
  665. device_address = libusb_get_device_address(dev);
  666. if (!opt_usb_list_all) {
  667. bool known = false;
  668. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  669. if ((find_dev[i].idVendor == desc.idVendor) &&
  670. (find_dev[i].idProduct == desc.idProduct)) {
  671. known = true;
  672. break;
  673. }
  674. if (!known)
  675. return;
  676. }
  677. (*count)++;
  678. if (level == 0) {
  679. sprintf(tmp, EOL ".USB dev %d: Bus %d Device %d ID: %04x:%04x",
  680. (int)(*count), (int)bus_number, (int)device_address,
  681. desc.idVendor, desc.idProduct);
  682. } else {
  683. sprintf(tmp, EOL ".USB dev %d: Bus %d Device %d Device Descriptor:" EOL "\tLength: %d" EOL
  684. "\tDescriptor Type: %s" EOL "\tUSB: %04x" EOL "\tDeviceClass: %d" EOL
  685. "\tDeviceSubClass: %d" EOL "\tDeviceProtocol: %d" EOL "\tMaxPacketSize0: %d" EOL
  686. "\tidVendor: %04x" EOL "\tidProduct: %04x" EOL "\tDeviceRelease: %x" EOL
  687. "\tNumConfigurations: %d",
  688. (int)(*count), (int)bus_number, (int)device_address,
  689. (int)(desc.bLength), destype(desc.bDescriptorType),
  690. desc.bcdUSB, (int)(desc.bDeviceClass), (int)(desc.bDeviceSubClass),
  691. (int)(desc.bDeviceProtocol), (int)(desc.bMaxPacketSize0),
  692. desc.idVendor, desc.idProduct, desc.bcdDevice,
  693. (int)(desc.bNumConfigurations));
  694. }
  695. append(buf, tmp, off, len);
  696. err = libusb_open(dev, &handle);
  697. if (err) {
  698. sprintf(tmp, EOL " ** dev %d: Failed to open, err %d", (int)(*count), err);
  699. append(buf, tmp, off, len);
  700. return;
  701. }
  702. err = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, man, STRBUFLEN);
  703. if (err < 0)
  704. sprintf((char *)man, "** err(%d)%s", err, usberrstr(err));
  705. err = libusb_get_string_descriptor_ascii(handle, desc.iProduct, prod, STRBUFLEN);
  706. if (err < 0)
  707. sprintf((char *)prod, "** err(%d)%s", err, usberrstr(err));
  708. if (level == 0) {
  709. libusb_close(handle);
  710. sprintf(tmp, EOL " Manufacturer: '%s'" EOL " Product: '%s'", man, prod);
  711. append(buf, tmp, off, len);
  712. return;
  713. }
  714. if (libusb_kernel_driver_active(handle, 0) == 1) {
  715. sprintf(tmp, EOL " * dev %d: kernel attached", (int)(*count));
  716. append(buf, tmp, off, len);
  717. }
  718. err = libusb_get_active_config_descriptor(dev, &config);
  719. if (err) {
  720. if (!setgetdes(*count, dev, handle, &config, 1, buf, off, len)
  721. && !setgetdes(*count, dev, handle, &config, 0, buf, off, len)) {
  722. libusb_close(handle);
  723. sprintf(tmp, EOL " ** dev %d: Failed to set config descriptor to %d or %d",
  724. (int)(*count), 1, 0);
  725. append(buf, tmp, off, len);
  726. return;
  727. }
  728. }
  729. sprintf(tmp, EOL " dev %d: Active Config:" EOL "\tDescriptorType: %s" EOL
  730. "\tNumInterfaces: %d" EOL "\tConfigurationValue: %d" EOL
  731. "\tAttributes: %d" EOL "\tMaxPower: %d",
  732. (int)(*count), destype(config->bDescriptorType),
  733. (int)(config->bNumInterfaces), (int)(config->iConfiguration),
  734. (int)(config->bmAttributes), (int)(config->MaxPower));
  735. append(buf, tmp, off, len);
  736. for (i = 0; i < (int)(config->bNumInterfaces); i++) {
  737. for (j = 0; j < config->interface[i].num_altsetting; j++) {
  738. idesc = &(config->interface[i].altsetting[j]);
  739. sprintf(tmp, EOL " _dev %d: Interface Descriptor %d:" EOL
  740. "\tDescriptorType: %s" EOL "\tInterfaceNumber: %d" EOL
  741. "\tNumEndpoints: %d" EOL "\tInterfaceClass: %d" EOL
  742. "\tInterfaceSubClass: %d" EOL "\tInterfaceProtocol: %d",
  743. (int)(*count), j, destype(idesc->bDescriptorType),
  744. (int)(idesc->bInterfaceNumber),
  745. (int)(idesc->bNumEndpoints),
  746. (int)(idesc->bInterfaceClass),
  747. (int)(idesc->bInterfaceSubClass),
  748. (int)(idesc->bInterfaceProtocol));
  749. append(buf, tmp, off, len);
  750. for (k = 0; k < (int)(idesc->bNumEndpoints); k++) {
  751. epdesc = &(idesc->endpoint[k]);
  752. sprintf(tmp, EOL " __dev %d: Interface %d Endpoint %d:" EOL
  753. "\tDescriptorType: %s" EOL
  754. "\tEndpointAddress: %s0x%x" EOL
  755. "\tAttributes: %s" EOL "\tMaxPacketSize: %d" EOL
  756. "\tInterval: %d" EOL "\tRefresh: %d",
  757. (int)(*count), (int)(idesc->bInterfaceNumber), k,
  758. destype(epdesc->bDescriptorType),
  759. epdir(epdesc->bEndpointAddress),
  760. (int)(epdesc->bEndpointAddress),
  761. epatt(epdesc->bmAttributes),
  762. epdesc->wMaxPacketSize,
  763. (int)(epdesc->bInterval),
  764. (int)(epdesc->bRefresh));
  765. append(buf, tmp, off, len);
  766. }
  767. }
  768. }
  769. libusb_free_config_descriptor(config);
  770. config = NULL;
  771. err = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, ser, STRBUFLEN);
  772. if (err < 0)
  773. sprintf((char *)ser, "** err(%d)%s", err, usberrstr(err));
  774. sprintf(tmp, EOL " dev %d: More Info:" EOL "\tManufacturer: '%s'" EOL
  775. "\tProduct: '%s'" EOL "\tSerial '%s'",
  776. (int)(*count), man, prod, ser);
  777. append(buf, tmp, off, len);
  778. libusb_close(handle);
  779. }
  780. // Function to dump all USB devices
  781. void usb_all(int level)
  782. {
  783. libusb_device **list;
  784. ssize_t count, i, j;
  785. char *buf;
  786. size_t len, off;
  787. count = libusb_get_device_list(NULL, &list);
  788. if (count < 0) {
  789. applog(LOG_ERR, "USB all: failed, err %d%s", (int)count, usberrstr((int)count));
  790. return;
  791. }
  792. if (count == 0)
  793. applog(LOG_WARNING, "USB all: found no devices");
  794. else
  795. {
  796. len = 10000;
  797. buf = malloc(len+1);
  798. if (unlikely(!buf))
  799. quit(1, "USB failed to malloc buf in usb_all");
  800. sprintf(buf, "USB all: found %d devices", (int)count);
  801. off = strlen(buf);
  802. if (!opt_usb_list_all)
  803. append(&buf, " - listing known devices", &off, &len);
  804. j = -1;
  805. for (i = 0; i < count; i++)
  806. usb_full(&j, list[i], &buf, &off, &len, level);
  807. applog(LOG_WARNING, "%s", buf);
  808. free(buf);
  809. if (j == -1)
  810. applog(LOG_WARNING, "No known USB devices");
  811. else
  812. applog(LOG_WARNING, "%d %sUSB devices",
  813. (int)(++j), opt_usb_list_all ? BLANK : "known ");
  814. }
  815. libusb_free_device_list(list, 1);
  816. }
  817. static void cgusb_check_init()
  818. {
  819. mutex_lock(&cgusb_lock);
  820. if (stats_initialised == false) {
  821. // N.B. environment LIBUSB_DEBUG also sets libusb_set_debug()
  822. if (opt_usbdump >= 0) {
  823. libusb_set_debug(NULL, opt_usbdump);
  824. usb_all(opt_usbdump);
  825. }
  826. usb_commands = malloc(sizeof(*usb_commands) * C_MAX);
  827. if (unlikely(!usb_commands))
  828. quit(1, "USB failed to malloc usb_commands");
  829. // use constants so the stat generation is very quick
  830. // and the association between number and name can't
  831. // be missalined easily
  832. usb_commands[C_REJECTED] = C_REJECTED_S;
  833. usb_commands[C_PING] = C_PING_S;
  834. usb_commands[C_CLEAR] = C_CLEAR_S;
  835. usb_commands[C_REQUESTVERSION] = C_REQUESTVERSION_S;
  836. usb_commands[C_GETVERSION] = C_GETVERSION_S;
  837. usb_commands[C_REQUESTFPGACOUNT] = C_REQUESTFPGACOUNT_S;
  838. usb_commands[C_GETFPGACOUNT] = C_GETFPGACOUNT_S;
  839. usb_commands[C_STARTPROGRAM] = C_STARTPROGRAM_S;
  840. usb_commands[C_STARTPROGRAMSTATUS] = C_STARTPROGRAMSTATUS_S;
  841. usb_commands[C_PROGRAM] = C_PROGRAM_S;
  842. usb_commands[C_PROGRAMSTATUS] = C_PROGRAMSTATUS_S;
  843. usb_commands[C_PROGRAMSTATUS2] = C_PROGRAMSTATUS2_S;
  844. usb_commands[C_FINALPROGRAMSTATUS] = C_FINALPROGRAMSTATUS_S;
  845. usb_commands[C_SETCLOCK] = C_SETCLOCK_S;
  846. usb_commands[C_REPLYSETCLOCK] = C_REPLYSETCLOCK_S;
  847. usb_commands[C_REQUESTUSERCODE] = C_REQUESTUSERCODE_S;
  848. usb_commands[C_GETUSERCODE] = C_GETUSERCODE_S;
  849. usb_commands[C_REQUESTTEMPERATURE] = C_REQUESTTEMPERATURE_S;
  850. usb_commands[C_GETTEMPERATURE] = C_GETTEMPERATURE_S;
  851. usb_commands[C_SENDWORK] = C_SENDWORK_S;
  852. usb_commands[C_SENDWORKSTATUS] = C_SENDWORKSTATUS_S;
  853. usb_commands[C_REQUESTWORKSTATUS] = C_REQUESTWORKSTATUS_S;
  854. usb_commands[C_GETWORKSTATUS] = C_GETWORKSTATUS_S;
  855. usb_commands[C_REQUESTIDENTIFY] = C_REQUESTIDENTIFY_S;
  856. usb_commands[C_GETIDENTIFY] = C_GETIDENTIFY_S;
  857. usb_commands[C_REQUESTFLASH] = C_REQUESTFLASH_S;
  858. usb_commands[C_REQUESTSENDWORK] = C_REQUESTSENDWORK_S;
  859. usb_commands[C_REQUESTSENDWORKSTATUS] = C_REQUESTSENDWORKSTATUS_S;
  860. usb_commands[C_RESET] = C_RESET_S;
  861. usb_commands[C_SETBAUD] = C_SETBAUD_S;
  862. usb_commands[C_SETDATA] = C_SETDATA_S;
  863. usb_commands[C_SETFLOW] = C_SETFLOW_S;
  864. usb_commands[C_SETMODEM] = C_SETMODEM_S;
  865. usb_commands[C_PURGERX] = C_PURGERX_S;
  866. usb_commands[C_PURGETX] = C_PURGETX_S;
  867. usb_commands[C_FLASHREPLY] = C_FLASHREPLY_S;
  868. usb_commands[C_REQUESTDETAILS] = C_REQUESTDETAILS_S;
  869. usb_commands[C_GETDETAILS] = C_GETDETAILS_S;
  870. usb_commands[C_REQUESTRESULTS] = C_REQUESTRESULTS_S;
  871. usb_commands[C_GETRESULTS] = C_GETRESULTS_S;
  872. usb_commands[C_REQUESTQUEJOB] = C_REQUESTQUEJOB_S;
  873. usb_commands[C_REQUESTQUEJOBSTATUS] = C_REQUESTQUEJOBSTATUS_S;
  874. usb_commands[C_QUEJOB] = C_QUEJOB_S;
  875. usb_commands[C_QUEJOBSTATUS] = C_QUEJOBSTATUS_S;
  876. usb_commands[C_QUEFLUSH] = C_QUEFLUSH_S;
  877. usb_commands[C_QUEFLUSHREPLY] = C_QUEFLUSHREPLY_S;
  878. usb_commands[C_REQUESTVOLTS] = C_REQUESTVOLTS_S;
  879. usb_commands[C_SENDTESTWORK] = C_SENDTESTWORK_S;
  880. usb_commands[C_LATENCY] = C_LATENCY_S;
  881. usb_commands[C_SETLINE] = C_SETLINE_S;
  882. usb_commands[C_VENDOR] = C_VENDOR_S;
  883. usb_commands[C_AVALON_TASK] = C_AVALON_TASK_S;
  884. usb_commands[C_AVALON_READ] = C_AVALON_READ_S;
  885. usb_commands[C_GET_AVALON_READY] = C_GET_AVALON_READY_S;
  886. usb_commands[C_AVALON_RESET] = C_AVALON_RESET_S;
  887. usb_commands[C_GET_AVALON_RESET] = C_GET_AVALON_RESET_S;
  888. usb_commands[C_FTDI_STATUS] = C_FTDI_STATUS_S;
  889. stats_initialised = true;
  890. }
  891. mutex_unlock(&cgusb_lock);
  892. }
  893. const char *usb_cmdname(enum usb_cmds cmd)
  894. {
  895. cgusb_check_init();
  896. return usb_commands[cmd];
  897. }
  898. void usb_applog(struct cgpu_info *cgpu, enum usb_cmds cmd, char *msg, int amount, int err)
  899. {
  900. if (msg && !*msg)
  901. msg = NULL;
  902. if (!msg && amount == 0 && err == LIBUSB_SUCCESS)
  903. msg = (char *)nodatareturned;
  904. applog(LOG_ERR, "%s%i: %s failed%s%s (err=%d amt=%d)",
  905. cgpu->drv->name, cgpu->device_id,
  906. usb_cmdname(cmd),
  907. msg ? space : BLANK, msg ? msg : BLANK,
  908. err, amount);
  909. }
  910. #ifdef WIN32
  911. static void in_use_store_ress(uint8_t bus_number, uint8_t device_address, void *resource1, void *resource2)
  912. {
  913. struct usb_in_use_list *in_use_tmp;
  914. bool found = false, empty = true;
  915. mutex_lock(&cgusb_lock);
  916. in_use_tmp = in_use_head;
  917. while (in_use_tmp) {
  918. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  919. in_use_tmp->in_use.device_address == (int)device_address) {
  920. found = true;
  921. if (in_use_tmp->in_use.resource1)
  922. empty = false;
  923. in_use_tmp->in_use.resource1 = resource1;
  924. if (in_use_tmp->in_use.resource2)
  925. empty = false;
  926. in_use_tmp->in_use.resource2 = resource2;
  927. break;
  928. }
  929. in_use_tmp = in_use_tmp->next;
  930. }
  931. mutex_unlock(&cgusb_lock);
  932. if (found == false)
  933. applog(LOG_ERR, "FAIL: USB store_ress not found (%d:%d)",
  934. (int)bus_number, (int)device_address);
  935. if (empty == false)
  936. applog(LOG_ERR, "FAIL: USB store_ress not empty (%d:%d)",
  937. (int)bus_number, (int)device_address);
  938. }
  939. static void in_use_get_ress(uint8_t bus_number, uint8_t device_address, void **resource1, void **resource2)
  940. {
  941. struct usb_in_use_list *in_use_tmp;
  942. bool found = false, empty = false;
  943. mutex_lock(&cgusb_lock);
  944. in_use_tmp = in_use_head;
  945. while (in_use_tmp) {
  946. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  947. in_use_tmp->in_use.device_address == (int)device_address) {
  948. found = true;
  949. if (!in_use_tmp->in_use.resource1)
  950. empty = true;
  951. *resource1 = in_use_tmp->in_use.resource1;
  952. in_use_tmp->in_use.resource1 = NULL;
  953. if (!in_use_tmp->in_use.resource2)
  954. empty = true;
  955. *resource2 = in_use_tmp->in_use.resource2;
  956. in_use_tmp->in_use.resource2 = NULL;
  957. break;
  958. }
  959. in_use_tmp = in_use_tmp->next;
  960. }
  961. mutex_unlock(&cgusb_lock);
  962. if (found == false)
  963. applog(LOG_ERR, "FAIL: USB get_lock not found (%d:%d)",
  964. (int)bus_number, (int)device_address);
  965. if (empty == true)
  966. applog(LOG_ERR, "FAIL: USB get_lock empty (%d:%d)",
  967. (int)bus_number, (int)device_address);
  968. }
  969. #endif
  970. static bool __is_in_use(uint8_t bus_number, uint8_t device_address)
  971. {
  972. struct usb_in_use_list *in_use_tmp;
  973. bool ret = false;
  974. in_use_tmp = in_use_head;
  975. while (in_use_tmp) {
  976. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  977. in_use_tmp->in_use.device_address == (int)device_address) {
  978. ret = true;
  979. break;
  980. }
  981. in_use_tmp = in_use_tmp->next;
  982. }
  983. return ret;
  984. }
  985. static bool is_in_use_bd(uint8_t bus_number, uint8_t device_address)
  986. {
  987. bool ret;
  988. mutex_lock(&cgusb_lock);
  989. ret = __is_in_use(bus_number, device_address);
  990. mutex_unlock(&cgusb_lock);
  991. return ret;
  992. }
  993. static bool is_in_use(libusb_device *dev)
  994. {
  995. return is_in_use_bd(libusb_get_bus_number(dev), libusb_get_device_address(dev));
  996. }
  997. static void add_in_use(uint8_t bus_number, uint8_t device_address)
  998. {
  999. struct usb_in_use_list *in_use_tmp;
  1000. bool found = false;
  1001. mutex_lock(&cgusb_lock);
  1002. if (unlikely(__is_in_use(bus_number, device_address))) {
  1003. found = true;
  1004. goto nofway;
  1005. }
  1006. in_use_tmp = calloc(1, sizeof(*in_use_tmp));
  1007. if (unlikely(!in_use_tmp))
  1008. quit(1, "USB failed to calloc in_use_tmp");
  1009. in_use_tmp->in_use.bus_number = (int)bus_number;
  1010. in_use_tmp->in_use.device_address = (int)device_address;
  1011. in_use_tmp->next = in_use_head;
  1012. if (in_use_head)
  1013. in_use_head->prev = in_use_tmp;
  1014. in_use_head = in_use_tmp;
  1015. nofway:
  1016. mutex_unlock(&cgusb_lock);
  1017. if (found)
  1018. applog(LOG_ERR, "FAIL: USB add already in use (%d:%d)",
  1019. (int)bus_number, (int)device_address);
  1020. }
  1021. static void remove_in_use(uint8_t bus_number, uint8_t device_address)
  1022. {
  1023. struct usb_in_use_list *in_use_tmp;
  1024. bool found = false;
  1025. mutex_lock(&cgusb_lock);
  1026. in_use_tmp = in_use_head;
  1027. while (in_use_tmp) {
  1028. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  1029. in_use_tmp->in_use.device_address == (int)device_address) {
  1030. found = true;
  1031. if (in_use_tmp == in_use_head) {
  1032. in_use_head = in_use_head->next;
  1033. if (in_use_head)
  1034. in_use_head->prev = NULL;
  1035. } else {
  1036. in_use_tmp->prev->next = in_use_tmp->next;
  1037. if (in_use_tmp->next)
  1038. in_use_tmp->next->prev = in_use_tmp->prev;
  1039. }
  1040. free(in_use_tmp);
  1041. break;
  1042. }
  1043. in_use_tmp = in_use_tmp->next;
  1044. }
  1045. mutex_unlock(&cgusb_lock);
  1046. if (!found)
  1047. applog(LOG_ERR, "FAIL: USB remove not already in use (%d:%d)",
  1048. (int)bus_number, (int)device_address);
  1049. }
  1050. static bool cgminer_usb_lock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  1051. {
  1052. struct resource_work *res_work;
  1053. bool ret;
  1054. applog(LOG_DEBUG, "USB lock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
  1055. res_work = calloc(1, sizeof(*res_work));
  1056. if (unlikely(!res_work))
  1057. quit(1, "USB failed to calloc lock res_work");
  1058. res_work->lock = true;
  1059. res_work->dname = (const char *)(drv->dname);
  1060. res_work->bus_number = bus_number;
  1061. res_work->device_address = device_address;
  1062. mutex_lock(&cgusbres_lock);
  1063. res_work->next = res_work_head;
  1064. res_work_head = res_work;
  1065. mutex_unlock(&cgusbres_lock);
  1066. sem_post(&usb_resource_sem);
  1067. // TODO: add a timeout fail - restart the resource thread?
  1068. while (true) {
  1069. nmsleep(50);
  1070. mutex_lock(&cgusbres_lock);
  1071. if (res_reply_head) {
  1072. struct resource_reply *res_reply_prev = NULL;
  1073. struct resource_reply *res_reply = res_reply_head;
  1074. while (res_reply) {
  1075. if (res_reply->bus_number == bus_number &&
  1076. res_reply->device_address == device_address) {
  1077. if (res_reply_prev)
  1078. res_reply_prev->next = res_reply->next;
  1079. else
  1080. res_reply_head = res_reply->next;
  1081. mutex_unlock(&cgusbres_lock);
  1082. ret = res_reply->got;
  1083. free(res_reply);
  1084. return ret;
  1085. }
  1086. res_reply_prev = res_reply;
  1087. res_reply = res_reply->next;
  1088. }
  1089. }
  1090. mutex_unlock(&cgusbres_lock);
  1091. }
  1092. }
  1093. static bool cgminer_usb_lock(struct device_drv *drv, libusb_device *dev)
  1094. {
  1095. return cgminer_usb_lock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1096. }
  1097. static void cgminer_usb_unlock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  1098. {
  1099. struct resource_work *res_work;
  1100. applog(LOG_DEBUG, "USB unlock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
  1101. res_work = calloc(1, sizeof(*res_work));
  1102. if (unlikely(!res_work))
  1103. quit(1, "USB failed to calloc unlock res_work");
  1104. res_work->lock = false;
  1105. res_work->dname = (const char *)(drv->dname);
  1106. res_work->bus_number = bus_number;
  1107. res_work->device_address = device_address;
  1108. mutex_lock(&cgusbres_lock);
  1109. res_work->next = res_work_head;
  1110. res_work_head = res_work;
  1111. mutex_unlock(&cgusbres_lock);
  1112. sem_post(&usb_resource_sem);
  1113. return;
  1114. }
  1115. static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
  1116. {
  1117. cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1118. }
  1119. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  1120. {
  1121. applog(LOG_DEBUG, "USB free %s", cgusb->found->name);
  1122. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  1123. free(cgusb->serial_string);
  1124. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  1125. free(cgusb->manuf_string);
  1126. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  1127. free(cgusb->prod_string);
  1128. free(cgusb->descriptor);
  1129. free(cgusb->found);
  1130. free(cgusb);
  1131. return NULL;
  1132. }
  1133. void usb_uninit(struct cgpu_info *cgpu)
  1134. {
  1135. applog(LOG_DEBUG, "USB uninit %s%i",
  1136. cgpu->drv->name, cgpu->device_id);
  1137. // May have happened already during a failed initialisation
  1138. // if release_cgpu() was called due to a USB NODEV(err)
  1139. if (!cgpu->usbdev)
  1140. return;
  1141. libusb_release_interface(cgpu->usbdev->handle, cgpu->usbdev->found->interface);
  1142. libusb_close(cgpu->usbdev->handle);
  1143. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  1144. }
  1145. static void release_cgpu(struct cgpu_info *cgpu)
  1146. {
  1147. struct cg_usb_device *cgusb = cgpu->usbdev;
  1148. struct cgpu_info *lookcgpu;
  1149. int i;
  1150. applog(LOG_DEBUG, "USB release %s%i",
  1151. cgpu->drv->name, cgpu->device_id);
  1152. // It has already been done
  1153. if (cgpu->usbinfo.nodev)
  1154. return;
  1155. total_count--;
  1156. drv_count[cgpu->drv->drv_id].count--;
  1157. cgpu->usbinfo.nodev = true;
  1158. cgpu->usbinfo.nodev_count++;
  1159. cgtime(&cgpu->usbinfo.last_nodev);
  1160. // Any devices sharing the same USB device should be marked also
  1161. // Currently only MMQ shares a USB device
  1162. for (i = 0; i < total_devices; i++) {
  1163. lookcgpu = get_devices(i);
  1164. if (lookcgpu != cgpu && lookcgpu->usbdev == cgusb) {
  1165. total_count--;
  1166. drv_count[lookcgpu->drv->drv_id].count--;
  1167. lookcgpu->usbinfo.nodev = true;
  1168. lookcgpu->usbinfo.nodev_count++;
  1169. memcpy(&(lookcgpu->usbinfo.last_nodev),
  1170. &(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
  1171. lookcgpu->usbdev = NULL;
  1172. }
  1173. }
  1174. usb_uninit(cgpu);
  1175. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1176. }
  1177. #define USB_INIT_FAIL 0
  1178. #define USB_INIT_OK 1
  1179. #define USB_INIT_IGNORE 2
  1180. static int _usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1181. {
  1182. struct cg_usb_device *cgusb = NULL;
  1183. struct libusb_config_descriptor *config = NULL;
  1184. const struct libusb_interface_descriptor *idesc;
  1185. const struct libusb_endpoint_descriptor *epdesc;
  1186. unsigned char strbuf[STRBUFLEN+1];
  1187. char devstr[STRBUFLEN+1];
  1188. int err, i, j, k;
  1189. int bad = USB_INIT_FAIL;
  1190. cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
  1191. cgpu->usbinfo.device_address = libusb_get_device_address(dev);
  1192. sprintf(devstr, "- %s device %d:%d", found->name,
  1193. cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1194. cgusb = calloc(1, sizeof(*cgusb));
  1195. if (unlikely(!cgusb))
  1196. quit(1, "USB failed to calloc _usb_init cgusb");
  1197. cgusb->found = found;
  1198. if (found->idVendor == IDVENDOR_FTDI)
  1199. cgusb->usb_type = USB_TYPE_FTDI;
  1200. cgusb->ident = found->ident;
  1201. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  1202. if (unlikely(!cgusb->descriptor))
  1203. quit(1, "USB failed to calloc _usb_init cgusb descriptor");
  1204. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  1205. if (err) {
  1206. applog(LOG_DEBUG,
  1207. "USB init failed to get descriptor, err %d %s",
  1208. err, devstr);
  1209. goto dame;
  1210. }
  1211. err = libusb_open(dev, &(cgusb->handle));
  1212. if (err) {
  1213. switch (err) {
  1214. case LIBUSB_ERROR_ACCESS:
  1215. applog(LOG_ERR,
  1216. "USB init open device failed, err %d, "
  1217. "you dont have priviledge to access %s",
  1218. err, devstr);
  1219. break;
  1220. #ifdef WIN32
  1221. // Windows specific message
  1222. case LIBUSB_ERROR_NOT_SUPPORTED:
  1223. applog(LOG_ERR,
  1224. "USB init, open device failed, err %d, "
  1225. "you need to install a Windows USB driver for %s",
  1226. err, devstr);
  1227. break;
  1228. #endif
  1229. default:
  1230. applog(LOG_DEBUG,
  1231. "USB init, open failed, err %d %s",
  1232. err, devstr);
  1233. }
  1234. goto dame;
  1235. }
  1236. #ifndef WIN32
  1237. if (libusb_kernel_driver_active(cgusb->handle, found->kernel) == 1) {
  1238. applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
  1239. err = libusb_detach_kernel_driver(cgusb->handle, found->kernel);
  1240. if (err == 0) {
  1241. applog(LOG_DEBUG,
  1242. "USB init, kernel detached successfully %s",
  1243. devstr);
  1244. } else {
  1245. applog(LOG_WARNING,
  1246. "USB init, kernel detach failed, err %d in use? %s",
  1247. err, devstr);
  1248. goto cldame;
  1249. }
  1250. }
  1251. #endif
  1252. if (found->iManufacturer) {
  1253. unsigned char man[STRBUFLEN+1];
  1254. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1255. cgusb->descriptor->iManufacturer,
  1256. man, STRBUFLEN);
  1257. if (err < 0) {
  1258. applog(LOG_DEBUG,
  1259. "USB init, failed to get iManufacturer, err %d %s",
  1260. err, devstr);
  1261. goto cldame;
  1262. }
  1263. if (strcmp((char *)man, found->iManufacturer)) {
  1264. applog(LOG_DEBUG, "USB init, iManufacturer mismatch %s",
  1265. devstr);
  1266. bad = USB_INIT_IGNORE;
  1267. goto cldame;
  1268. }
  1269. }
  1270. if (found->iProduct) {
  1271. unsigned char prod[STRBUFLEN+1];
  1272. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1273. cgusb->descriptor->iProduct,
  1274. prod, STRBUFLEN);
  1275. if (err < 0) {
  1276. applog(LOG_DEBUG,
  1277. "USB init, failed to get iProduct, err %d %s",
  1278. err, devstr);
  1279. goto cldame;
  1280. }
  1281. if (strcmp((char *)prod, found->iProduct)) {
  1282. applog(LOG_DEBUG, "USB init, iProduct mismatch %s",
  1283. devstr);
  1284. bad = USB_INIT_IGNORE;
  1285. goto cldame;
  1286. }
  1287. }
  1288. err = libusb_set_configuration(cgusb->handle, found->config);
  1289. if (err) {
  1290. switch(err) {
  1291. case LIBUSB_ERROR_BUSY:
  1292. applog(LOG_WARNING,
  1293. "USB init, set config %d in use %s",
  1294. found->config, devstr);
  1295. break;
  1296. default:
  1297. applog(LOG_DEBUG,
  1298. "USB init, failed to set config to %d, err %d %s",
  1299. found->config, err, devstr);
  1300. }
  1301. goto cldame;
  1302. }
  1303. err = libusb_get_active_config_descriptor(dev, &config);
  1304. if (err) {
  1305. applog(LOG_DEBUG,
  1306. "USB init, failed to get config descriptor, err %d %s",
  1307. err, devstr);
  1308. goto cldame;
  1309. }
  1310. if ((int)(config->bNumInterfaces) <= found->interface) {
  1311. applog(LOG_DEBUG, "USB init bNumInterfaces <= interface %s",
  1312. devstr);
  1313. goto cldame;
  1314. }
  1315. for (i = 0; i < found->epcount; i++)
  1316. found->eps[i].found = false;
  1317. for (i = 0; i < config->interface[found->interface].num_altsetting; i++) {
  1318. idesc = &(config->interface[found->interface].altsetting[i]);
  1319. for (j = 0; j < (int)(idesc->bNumEndpoints); j++) {
  1320. epdesc = &(idesc->endpoint[j]);
  1321. for (k = 0; k < found->epcount; k++) {
  1322. if (!found->eps[k].found) {
  1323. if (epdesc->bmAttributes == found->eps[k].att
  1324. && epdesc->wMaxPacketSize >= found->eps[k].size
  1325. && epdesc->bEndpointAddress == found->eps[k].ep) {
  1326. found->eps[k].found = true;
  1327. break;
  1328. }
  1329. }
  1330. }
  1331. }
  1332. }
  1333. for (i = 0; i < found->epcount; i++) {
  1334. if (found->eps[i].found == false) {
  1335. applog(LOG_DEBUG, "USB init found == false %s",
  1336. devstr);
  1337. goto cldame;
  1338. }
  1339. }
  1340. err = libusb_claim_interface(cgusb->handle, found->interface);
  1341. if (err) {
  1342. switch(err) {
  1343. case LIBUSB_ERROR_BUSY:
  1344. applog(LOG_WARNING,
  1345. "USB init, claim interface %d in use %s",
  1346. found->interface, devstr);
  1347. break;
  1348. default:
  1349. applog(LOG_DEBUG,
  1350. "USB init, claim interface %d failed, err %d %s",
  1351. found->interface, err, devstr);
  1352. }
  1353. goto cldame;
  1354. }
  1355. cgusb->usbver = cgusb->descriptor->bcdUSB;
  1356. // TODO: allow this with the right version of the libusb include and running library
  1357. // cgusb->speed = libusb_get_device_speed(dev);
  1358. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1359. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  1360. if (err > 0)
  1361. cgusb->prod_string = strdup((char *)strbuf);
  1362. else
  1363. cgusb->prod_string = (char *)BLANK;
  1364. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1365. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  1366. if (err > 0)
  1367. cgusb->manuf_string = strdup((char *)strbuf);
  1368. else
  1369. cgusb->manuf_string = (char *)BLANK;
  1370. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1371. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  1372. if (err > 0)
  1373. cgusb->serial_string = strdup((char *)strbuf);
  1374. else
  1375. cgusb->serial_string = (char *)BLANK;
  1376. // TODO: ?
  1377. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  1378. // cgusb->interfaceVersion
  1379. applog(LOG_DEBUG,
  1380. "USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
  1381. devstr, cgusb->usbver, cgusb->prod_string,
  1382. cgusb->manuf_string, cgusb->serial_string);
  1383. cgpu->usbdev = cgusb;
  1384. libusb_free_config_descriptor(config);
  1385. // Allow a name change based on the idVendor+idProduct
  1386. // N.B. must be done before calling add_cgpu()
  1387. if (strcmp(cgpu->drv->name, found->name)) {
  1388. if (!cgpu->drv->copy)
  1389. cgpu->drv = copy_drv(cgpu->drv);
  1390. cgpu->drv->name = (char *)(found->name);
  1391. }
  1392. return USB_INIT_OK;
  1393. cldame:
  1394. libusb_close(cgusb->handle);
  1395. dame:
  1396. if (config)
  1397. libusb_free_config_descriptor(config);
  1398. cgusb = free_cgusb(cgusb);
  1399. return bad;
  1400. }
  1401. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1402. {
  1403. int ret;
  1404. ret = _usb_init(cgpu, dev, found);
  1405. if (ret == USB_INIT_FAIL)
  1406. applog(LOG_ERR, "%s detect (%d:%d) failed to initialise (incorrect device?)",
  1407. cgpu->drv->dname,
  1408. (int)(cgpu->usbinfo.bus_number),
  1409. (int)(cgpu->usbinfo.device_address));
  1410. return (ret == USB_INIT_OK);
  1411. }
  1412. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  1413. {
  1414. struct libusb_device_descriptor desc;
  1415. int bus_number, device_address;
  1416. int err, i;
  1417. bool ok;
  1418. err = libusb_get_device_descriptor(dev, &desc);
  1419. if (err) {
  1420. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  1421. return false;
  1422. }
  1423. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  1424. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  1425. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  1426. return false;
  1427. }
  1428. if (busdev_count > 0) {
  1429. bus_number = (int)libusb_get_bus_number(dev);
  1430. device_address = (int)libusb_get_device_address(dev);
  1431. ok = false;
  1432. for (i = 0; i < busdev_count; i++) {
  1433. if (bus_number == busdev[i].bus_number) {
  1434. if (busdev[i].device_address == -1 ||
  1435. device_address == busdev[i].device_address) {
  1436. ok = true;
  1437. break;
  1438. }
  1439. }
  1440. }
  1441. if (!ok) {
  1442. applog(LOG_DEBUG, "%s rejected %s %04x:%04x with bus:dev (%d:%d)",
  1443. drv->name, look->name, look->idVendor, look->idProduct,
  1444. bus_number, device_address);
  1445. return false;
  1446. }
  1447. }
  1448. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  1449. drv->name, look->name, look->idVendor, look->idProduct);
  1450. return true;
  1451. }
  1452. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  1453. {
  1454. struct usb_find_devices *found;
  1455. int i;
  1456. for (i = 0; find_dev[i].drv != DRV_LAST; i++)
  1457. if (find_dev[i].drv == drvnum) {
  1458. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  1459. found = malloc(sizeof(*found));
  1460. if (unlikely(!found))
  1461. quit(1, "USB failed to malloc 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. #if DO_USB_STATS
  1549. static void modes_str(char *buf, uint32_t modes)
  1550. {
  1551. bool first;
  1552. *buf = '\0';
  1553. if (modes == MODE_NONE)
  1554. strcpy(buf, MODE_NONE_STR);
  1555. else {
  1556. first = true;
  1557. if (modes & MODE_CTRL_READ) {
  1558. strcpy(buf, MODE_CTRL_READ_STR);
  1559. first = false;
  1560. }
  1561. if (modes & MODE_CTRL_WRITE) {
  1562. if (!first)
  1563. strcat(buf, MODE_SEP_STR);
  1564. strcat(buf, MODE_CTRL_WRITE_STR);
  1565. first = false;
  1566. }
  1567. if (modes & MODE_BULK_READ) {
  1568. if (!first)
  1569. strcat(buf, MODE_SEP_STR);
  1570. strcat(buf, MODE_BULK_READ_STR);
  1571. first = false;
  1572. }
  1573. if (modes & MODE_BULK_WRITE) {
  1574. if (!first)
  1575. strcat(buf, MODE_SEP_STR);
  1576. strcat(buf, MODE_BULK_WRITE_STR);
  1577. first = false;
  1578. }
  1579. }
  1580. }
  1581. #endif
  1582. // The stat data can be spurious due to not locking it before copying it -
  1583. // however that would require the stat() function to also lock and release
  1584. // a mutex every time a usb read or write is called which would slow
  1585. // things down more
  1586. struct api_data *api_usb_stats(__maybe_unused int *count)
  1587. {
  1588. #if DO_USB_STATS
  1589. struct cg_usb_stats_details *details;
  1590. struct cg_usb_stats *sta;
  1591. struct api_data *root = NULL;
  1592. int device;
  1593. int cmdseq;
  1594. char modes_s[32];
  1595. if (next_stat == 0)
  1596. return NULL;
  1597. while (*count < next_stat * C_MAX * 2) {
  1598. device = *count / (C_MAX * 2);
  1599. cmdseq = *count % (C_MAX * 2);
  1600. (*count)++;
  1601. sta = &(usb_stats[device]);
  1602. details = &(sta->details[cmdseq]);
  1603. // Only show stats that have results
  1604. if (details->item[CMD_CMD].count == 0 &&
  1605. details->item[CMD_TIMEOUT].count == 0 &&
  1606. details->item[CMD_ERROR].count == 0)
  1607. continue;
  1608. root = api_add_string(root, "Name", sta->name, false);
  1609. root = api_add_int(root, "ID", &(sta->device_id), false);
  1610. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  1611. root = api_add_int(root, "Seq", &(details->seq), true);
  1612. modes_str(modes_s, details->modes);
  1613. root = api_add_string(root, "Modes", modes_s, true);
  1614. root = api_add_uint64(root, "Count",
  1615. &(details->item[CMD_CMD].count), true);
  1616. root = api_add_double(root, "Total Delay",
  1617. &(details->item[CMD_CMD].total_delay), true);
  1618. root = api_add_double(root, "Min Delay",
  1619. &(details->item[CMD_CMD].min_delay), true);
  1620. root = api_add_double(root, "Max Delay",
  1621. &(details->item[CMD_CMD].max_delay), true);
  1622. root = api_add_uint64(root, "Timeout Count",
  1623. &(details->item[CMD_TIMEOUT].count), true);
  1624. root = api_add_double(root, "Timeout Total Delay",
  1625. &(details->item[CMD_TIMEOUT].total_delay), true);
  1626. root = api_add_double(root, "Timeout Min Delay",
  1627. &(details->item[CMD_TIMEOUT].min_delay), true);
  1628. root = api_add_double(root, "Timeout Max Delay",
  1629. &(details->item[CMD_TIMEOUT].max_delay), true);
  1630. root = api_add_uint64(root, "Error Count",
  1631. &(details->item[CMD_ERROR].count), true);
  1632. root = api_add_double(root, "Error Total Delay",
  1633. &(details->item[CMD_ERROR].total_delay), true);
  1634. root = api_add_double(root, "Error Min Delay",
  1635. &(details->item[CMD_ERROR].min_delay), true);
  1636. root = api_add_double(root, "Error Max Delay",
  1637. &(details->item[CMD_ERROR].max_delay), true);
  1638. root = api_add_timeval(root, "First Command",
  1639. &(details->item[CMD_CMD].first), true);
  1640. root = api_add_timeval(root, "Last Command",
  1641. &(details->item[CMD_CMD].last), true);
  1642. root = api_add_timeval(root, "First Timeout",
  1643. &(details->item[CMD_TIMEOUT].first), true);
  1644. root = api_add_timeval(root, "Last Timeout",
  1645. &(details->item[CMD_TIMEOUT].last), true);
  1646. root = api_add_timeval(root, "First Error",
  1647. &(details->item[CMD_ERROR].first), true);
  1648. root = api_add_timeval(root, "Last Error",
  1649. &(details->item[CMD_ERROR].last), true);
  1650. return root;
  1651. }
  1652. #endif
  1653. return NULL;
  1654. }
  1655. #if DO_USB_STATS
  1656. static void newstats(struct cgpu_info *cgpu)
  1657. {
  1658. int i;
  1659. mutex_lock(&cgusb_lock);
  1660. cgpu->usbinfo.usbstat = ++next_stat;
  1661. mutex_unlock(&cgusb_lock);
  1662. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * next_stat);
  1663. if (unlikely(!usb_stats))
  1664. quit(1, "USB failed to realloc usb_stats %d", next_stat);
  1665. usb_stats[next_stat-1].name = cgpu->drv->name;
  1666. usb_stats[next_stat-1].device_id = -1;
  1667. usb_stats[next_stat-1].details = calloc(1, sizeof(struct cg_usb_stats_details) * C_MAX * 2);
  1668. if (unlikely(!usb_stats[next_stat-1].details))
  1669. quit(1, "USB failed to calloc details for %d", next_stat);
  1670. for (i = 1; i < C_MAX * 2; i += 2)
  1671. usb_stats[next_stat-1].details[i].seq = 1;
  1672. }
  1673. #endif
  1674. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  1675. {
  1676. #if DO_USB_STATS
  1677. if (cgpu->usbinfo.usbstat < 1)
  1678. newstats(cgpu);
  1679. // we don't know the device_id until after add_cgpu()
  1680. usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
  1681. #endif
  1682. }
  1683. #if DO_USB_STATS
  1684. 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)
  1685. {
  1686. struct cg_usb_stats_details *details;
  1687. double diff;
  1688. int item;
  1689. if (cgpu->usbinfo.usbstat < 1)
  1690. newstats(cgpu);
  1691. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
  1692. details->modes |= mode;
  1693. diff = tdiff(tv_finish, tv_start);
  1694. switch (err) {
  1695. case LIBUSB_SUCCESS:
  1696. item = CMD_CMD;
  1697. break;
  1698. case LIBUSB_ERROR_TIMEOUT:
  1699. item = CMD_TIMEOUT;
  1700. break;
  1701. default:
  1702. item = CMD_ERROR;
  1703. break;
  1704. }
  1705. if (details->item[item].count == 0) {
  1706. details->item[item].min_delay = diff;
  1707. memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  1708. } else if (diff < details->item[item].min_delay)
  1709. details->item[item].min_delay = diff;
  1710. if (diff > details->item[item].max_delay)
  1711. details->item[item].max_delay = diff;
  1712. details->item[item].total_delay += diff;
  1713. memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
  1714. details->item[item].count++;
  1715. }
  1716. static void rejected_inc(struct cgpu_info *cgpu, uint32_t mode)
  1717. {
  1718. struct cg_usb_stats_details *details;
  1719. int item = CMD_ERROR;
  1720. if (cgpu->usbinfo.usbstat < 1)
  1721. newstats(cgpu);
  1722. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  1723. details->modes |= mode;
  1724. details->item[item].count++;
  1725. }
  1726. #endif
  1727. #define USB_MAX_READ 8192
  1728. 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)
  1729. {
  1730. struct cg_usb_device *usbdev = cgpu->usbdev;
  1731. bool ftdi;
  1732. #if DO_USB_STATS
  1733. struct timeval tv_start;
  1734. #endif
  1735. struct timeval read_start, tv_finish;
  1736. unsigned int initial_timeout, sleep_time;
  1737. double max, done;
  1738. int bufleft, err, got, tot;
  1739. __maybe_unused bool first = true;
  1740. unsigned char *search;
  1741. int endlen;
  1742. // We add 4: 1 for null, 2 for FTDI status and 1 to round to 4 bytes
  1743. unsigned char usbbuf[USB_MAX_READ+4], *ptr;
  1744. size_t usbbufread;
  1745. if (cgpu->usbinfo.nodev) {
  1746. *buf = '\0';
  1747. *processed = 0;
  1748. USB_REJECT(cgpu, MODE_BULK_READ);
  1749. return LIBUSB_ERROR_NO_DEVICE;
  1750. }
  1751. ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  1752. 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));
  1753. if (bufsiz > USB_MAX_READ)
  1754. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, bufsiz, USB_MAX_READ);
  1755. if (timeout == DEVTIMEOUT)
  1756. timeout = usbdev->found->timeout;
  1757. if (end == NULL) {
  1758. tot = 0;
  1759. ptr = usbbuf;
  1760. bufleft = bufsiz;
  1761. err = LIBUSB_SUCCESS;
  1762. initial_timeout = timeout;
  1763. sleep_time = initial_timeout / 2;
  1764. if (sleep_time > USB_READ_MINPOLL)
  1765. sleep_time = USB_READ_MINPOLL;
  1766. max = ((double)timeout) / 1000.0;
  1767. cgtime(&read_start);
  1768. while (bufleft > 0) {
  1769. if (ftdi)
  1770. usbbufread = bufleft + 2;
  1771. else
  1772. usbbufread = bufleft;
  1773. got = 0;
  1774. STATS_TIMEVAL(&tv_start);
  1775. err = libusb_bulk_transfer(usbdev->handle,
  1776. usbdev->found->eps[ep].ep,
  1777. ptr, usbbufread, &got, timeout);
  1778. cgtime(&tv_finish);
  1779. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1780. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  1781. ptr[got] = '\0';
  1782. 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);
  1783. IOERR_CHECK(cgpu, err);
  1784. if (ftdi) {
  1785. // first 2 bytes returned are an FTDI status
  1786. if (got > 2) {
  1787. got -= 2;
  1788. memmove(ptr, ptr+2, got+1);
  1789. } else {
  1790. got = 0;
  1791. *ptr = '\0';
  1792. }
  1793. }
  1794. tot += got;
  1795. if (err || readonce)
  1796. break;
  1797. ptr += got;
  1798. bufleft -= got;
  1799. first = false;
  1800. done = tdiff(&tv_finish, &read_start);
  1801. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  1802. if (unlikely(done >= max))
  1803. break;
  1804. /* Controversial. Even though libusb gives the device
  1805. * a timeout, many devices (eg ftdi) simply time out
  1806. * after only 1ms making this function poll every ms
  1807. * if we don't sleep here, but do it only if we're not
  1808. * receiving any data. */
  1809. timeout = initial_timeout - (done * 1000);
  1810. if (!timeout)
  1811. break;
  1812. if (!got && sleep_time) {
  1813. if (timeout <= sleep_time)
  1814. sleep_time = timeout - 1;
  1815. timeout -= sleep_time;
  1816. nmsleep(sleep_time);
  1817. }
  1818. }
  1819. *processed = tot;
  1820. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  1821. if (NODEV(err))
  1822. release_cgpu(cgpu);
  1823. return err;
  1824. }
  1825. tot = 0;
  1826. ptr = usbbuf;
  1827. bufleft = bufsiz;
  1828. endlen = strlen(end);
  1829. err = LIBUSB_SUCCESS;
  1830. initial_timeout = timeout;
  1831. sleep_time = initial_timeout / 2;
  1832. if (sleep_time > USB_READ_MINPOLL)
  1833. sleep_time = USB_READ_MINPOLL;
  1834. max = ((double)timeout) / 1000.0;
  1835. cgtime(&read_start);
  1836. while (bufleft > 0) {
  1837. if (ftdi)
  1838. usbbufread = bufleft + 2;
  1839. else
  1840. usbbufread = bufleft;
  1841. got = 0;
  1842. STATS_TIMEVAL(&tv_start);
  1843. err = libusb_bulk_transfer(usbdev->handle,
  1844. usbdev->found->eps[ep].ep,
  1845. ptr, usbbufread, &got, timeout);
  1846. cgtime(&tv_finish);
  1847. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1848. MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1);
  1849. ptr[got] = '\0';
  1850. 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);
  1851. IOERR_CHECK(cgpu, err);
  1852. if (ftdi) {
  1853. // first 2 bytes returned are an FTDI status
  1854. if (got > 2) {
  1855. got -= 2;
  1856. memmove(ptr, ptr+2, got+1);
  1857. } else {
  1858. got = 0;
  1859. *ptr = '\0';
  1860. }
  1861. }
  1862. tot += got;
  1863. if (err || readonce)
  1864. break;
  1865. // WARNING - this will return data past END ('if' there is extra data)
  1866. if (endlen <= tot) {
  1867. // If END is only 1 char - do a faster search
  1868. if (endlen == 1) {
  1869. if (strchr((char *)ptr, *end))
  1870. break;
  1871. } else {
  1872. // must allow END to have been chopped in 2 transfers
  1873. if ((tot - got) >= (endlen - 1))
  1874. search = ptr - (endlen - 1);
  1875. else
  1876. search = ptr - (tot - got);
  1877. if (strstr((char *)search, end))
  1878. break;
  1879. }
  1880. }
  1881. ptr += got;
  1882. bufleft -= got;
  1883. first = false;
  1884. done = tdiff(&tv_finish, &read_start);
  1885. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  1886. if (unlikely(done >= max))
  1887. break;
  1888. timeout = initial_timeout - (done * 1000);
  1889. if (!timeout)
  1890. break;
  1891. if (!got && sleep_time) {
  1892. if (timeout <= sleep_time)
  1893. sleep_time = timeout - 1;
  1894. timeout -= sleep_time;
  1895. nmsleep(sleep_time);
  1896. }
  1897. }
  1898. *processed = tot;
  1899. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  1900. if (NODEV(err))
  1901. release_cgpu(cgpu);
  1902. return err;
  1903. }
  1904. 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)
  1905. {
  1906. struct cg_usb_device *usbdev = cgpu->usbdev;
  1907. #if DO_USB_STATS
  1908. struct timeval tv_start;
  1909. #endif
  1910. struct timeval read_start, tv_finish;
  1911. unsigned int initial_timeout;
  1912. double max, done;
  1913. __maybe_unused bool first = true;
  1914. int err, sent, tot;
  1915. 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));
  1916. *processed = 0;
  1917. if (cgpu->usbinfo.nodev) {
  1918. USB_REJECT(cgpu, MODE_BULK_WRITE);
  1919. return LIBUSB_ERROR_NO_DEVICE;
  1920. }
  1921. if (timeout == DEVTIMEOUT)
  1922. timeout = usbdev->found->timeout;
  1923. tot = 0;
  1924. err = LIBUSB_SUCCESS;
  1925. initial_timeout = timeout;
  1926. max = ((double)timeout) / 1000.0;
  1927. cgtime(&read_start);
  1928. while (bufsiz > 0) {
  1929. sent = 0;
  1930. STATS_TIMEVAL(&tv_start);
  1931. err = libusb_bulk_transfer(usbdev->handle,
  1932. usbdev->found->eps[ep].ep,
  1933. (unsigned char *)buf,
  1934. bufsiz, &sent, timeout);
  1935. cgtime(&tv_finish);
  1936. USB_STATS(cgpu, &tv_start, &tv_finish, err,
  1937. MODE_BULK_WRITE, cmd, first ? SEQ0 : SEQ1);
  1938. 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);
  1939. IOERR_CHECK(cgpu, err);
  1940. tot += sent;
  1941. if (err)
  1942. break;
  1943. buf += sent;
  1944. bufsiz -= sent;
  1945. first = false;
  1946. done = tdiff(&tv_finish, &read_start);
  1947. // N.B. this is: return LIBUSB_SUCCESS with whatever size was written
  1948. if (unlikely(done >= max))
  1949. break;
  1950. timeout = initial_timeout - (done * 1000);
  1951. }
  1952. *processed = tot;
  1953. if (NODEV(err))
  1954. release_cgpu(cgpu);
  1955. return err;
  1956. }
  1957. 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)
  1958. {
  1959. struct cg_usb_device *usbdev = cgpu->usbdev;
  1960. #if DO_USB_STATS
  1961. struct timeval tv_start, tv_finish;
  1962. #endif
  1963. uint32_t *buf = NULL;
  1964. int err, i, bufsiz;
  1965. 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));
  1966. if (cgpu->usbinfo.nodev) {
  1967. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  1968. return LIBUSB_ERROR_NO_DEVICE;
  1969. }
  1970. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  1971. if (siz > 0) {
  1972. bufsiz = siz - 1;
  1973. bufsiz >>= 2;
  1974. bufsiz++;
  1975. buf = malloc(bufsiz << 2);
  1976. if (unlikely(!buf))
  1977. quit(1, "Failed to malloc in _usb_transfer");
  1978. for (i = 0; i < bufsiz; i++)
  1979. buf[i] = htole32(data[i]);
  1980. }
  1981. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex((unsigned char *)buf, (size_t)siz));
  1982. STATS_TIMEVAL(&tv_start);
  1983. err = libusb_control_transfer(usbdev->handle, request_type,
  1984. bRequest, wValue, wIndex, (unsigned char *)buf, (uint16_t)siz,
  1985. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  1986. STATS_TIMEVAL(&tv_finish);
  1987. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0);
  1988. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  1989. IOERR_CHECK(cgpu, err);
  1990. if (buf)
  1991. free(buf);
  1992. if (NODEV(err))
  1993. release_cgpu(cgpu);
  1994. return err;
  1995. }
  1996. 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)
  1997. {
  1998. struct cg_usb_device *usbdev = cgpu->usbdev;
  1999. #if DO_USB_STATS
  2000. struct timeval tv_start, tv_finish;
  2001. #endif
  2002. int err;
  2003. 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));
  2004. if (cgpu->usbinfo.nodev) {
  2005. USB_REJECT(cgpu, MODE_CTRL_READ);
  2006. return LIBUSB_ERROR_NO_DEVICE;
  2007. }
  2008. *amount = 0;
  2009. STATS_TIMEVAL(&tv_start);
  2010. err = libusb_control_transfer(usbdev->handle, request_type,
  2011. bRequest, wValue, wIndex,
  2012. (unsigned char *)buf, (uint16_t)bufsiz,
  2013. timeout == DEVTIMEOUT ? usbdev->found->timeout : timeout);
  2014. STATS_TIMEVAL(&tv_finish);
  2015. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0);
  2016. 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);
  2017. IOERR_CHECK(cgpu, err);
  2018. if (err > 0) {
  2019. *amount = err;
  2020. err = 0;
  2021. } else if (NODEV(err))
  2022. release_cgpu(cgpu);
  2023. return err;
  2024. }
  2025. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  2026. #define FTDI_RS0_CTS (1 << 4)
  2027. #define FTDI_RS0_DSR (1 << 5)
  2028. #define FTDI_RS0_RI (1 << 6)
  2029. #define FTDI_RS0_RLSD (1 << 7)
  2030. /* Clear to send for FTDI */
  2031. int usb_ftdi_cts(struct cgpu_info *cgpu)
  2032. {
  2033. char buf[2], ret;
  2034. int err, amount;
  2035. err = _usb_transfer_read(cgpu, (uint8_t)FTDI_TYPE_IN, (uint8_t)5,
  2036. (uint16_t)0, (uint16_t)0, buf, 2,
  2037. &amount, DEVTIMEOUT, C_FTDI_STATUS);
  2038. /* We return true in case drivers are waiting indefinitely to try and
  2039. * write to something that's not there. */
  2040. if (err)
  2041. return true;
  2042. ret = buf[0] & FTDI_STATUS_B0_MASK;
  2043. return (ret & FTDI_RS0_CTS);
  2044. }
  2045. void usb_cleanup()
  2046. {
  2047. struct cgpu_info *cgpu;
  2048. int count;
  2049. int i;
  2050. hotplug_time = 0;
  2051. nmsleep(10);
  2052. count = 0;
  2053. for (i = 0; i < total_devices; i++) {
  2054. cgpu = devices[i];
  2055. switch (cgpu->drv->drv_id) {
  2056. case DRIVER_BFLSC:
  2057. case DRIVER_BITFORCE:
  2058. case DRIVER_MODMINER:
  2059. case DRIVER_ICARUS:
  2060. case DRIVER_AVALON:
  2061. release_cgpu(cgpu);
  2062. count++;
  2063. break;
  2064. default:
  2065. break;
  2066. }
  2067. }
  2068. /*
  2069. * Must attempt to wait for the resource thread to release coz
  2070. * during a restart it won't automatically release them in linux
  2071. */
  2072. if (count) {
  2073. struct timeval start, now;
  2074. cgtime(&start);
  2075. while (42) {
  2076. nmsleep(50);
  2077. mutex_lock(&cgusbres_lock);
  2078. if (!res_work_head)
  2079. break;
  2080. cgtime(&now);
  2081. if (tdiff(&now, &start) > 0.366) {
  2082. applog(LOG_WARNING,
  2083. "usb_cleanup gave up waiting for resource thread");
  2084. break;
  2085. }
  2086. mutex_unlock(&cgusbres_lock);
  2087. }
  2088. mutex_unlock(&cgusbres_lock);
  2089. }
  2090. }
  2091. void usb_initialise()
  2092. {
  2093. char *fre, *ptr, *comma, *colon;
  2094. int bus, dev, lim, i;
  2095. bool found;
  2096. for (i = 0; i < DRIVER_MAX; i++) {
  2097. drv_count[i].count = 0;
  2098. drv_count[i].limit = 999999;
  2099. }
  2100. cgusb_check_init();
  2101. if (opt_usb_select && *opt_usb_select) {
  2102. // Absolute device limit
  2103. if (*opt_usb_select == ':') {
  2104. total_limit = atoi(opt_usb_select+1);
  2105. if (total_limit < 0)
  2106. quit(1, "Invalid --usb total limit");
  2107. // Comma list of bus:dev devices to match
  2108. } else if (isdigit(*opt_usb_select)) {
  2109. fre = ptr = strdup(opt_usb_select);
  2110. do {
  2111. comma = strchr(ptr, ',');
  2112. if (comma)
  2113. *(comma++) = '\0';
  2114. colon = strchr(ptr, ':');
  2115. if (!colon)
  2116. quit(1, "Invalid --usb bus:dev missing ':'");
  2117. *(colon++) = '\0';
  2118. if (!isdigit(*ptr))
  2119. quit(1, "Invalid --usb bus:dev - bus must be a number");
  2120. if (!isdigit(*colon) && *colon != '*')
  2121. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  2122. bus = atoi(ptr);
  2123. if (bus <= 0)
  2124. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  2125. if (!colon == '*')
  2126. dev = -1;
  2127. else {
  2128. dev = atoi(colon);
  2129. if (dev <= 0)
  2130. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  2131. }
  2132. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  2133. if (unlikely(!busdev))
  2134. quit(1, "USB failed to realloc busdev");
  2135. busdev[busdev_count-1].bus_number = bus;
  2136. busdev[busdev_count-1].device_address = dev;
  2137. ptr = comma;
  2138. } while (ptr);
  2139. free(fre);
  2140. // Comma list of DRV:limit
  2141. } else {
  2142. fre = ptr = strdup(opt_usb_select);
  2143. do {
  2144. comma = strchr(ptr, ',');
  2145. if (comma)
  2146. *(comma++) = '\0';
  2147. colon = strchr(ptr, ':');
  2148. if (!colon)
  2149. quit(1, "Invalid --usb DRV:limit missing ':'");
  2150. *(colon++) = '\0';
  2151. if (!isdigit(*colon))
  2152. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  2153. lim = atoi(colon);
  2154. if (lim < 0)
  2155. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  2156. found = false;
  2157. #ifdef USE_BFLSC
  2158. if (strcasecmp(ptr, bflsc_drv.name) == 0) {
  2159. drv_count[bflsc_drv.drv_id].limit = lim;
  2160. found = true;
  2161. }
  2162. #endif
  2163. #ifdef USE_BITFORCE
  2164. if (!found && strcasecmp(ptr, bitforce_drv.name) == 0) {
  2165. drv_count[bitforce_drv.drv_id].limit = lim;
  2166. found = true;
  2167. }
  2168. #endif
  2169. #ifdef USE_MODMINER
  2170. if (!found && strcasecmp(ptr, modminer_drv.name) == 0) {
  2171. drv_count[modminer_drv.drv_id].limit = lim;
  2172. found = true;
  2173. }
  2174. #endif
  2175. #ifdef USE_ICARUS
  2176. if (!found && strcasecmp(ptr, icarus_drv.name) == 0) {
  2177. drv_count[icarus_drv.drv_id].limit = lim;
  2178. found = true;
  2179. }
  2180. #endif
  2181. #ifdef USE_AVALON
  2182. if (!found && strcasecmp(ptr, avalon_drv.name) == 0) {
  2183. drv_count[avalon_drv.drv_id].limit = lim;
  2184. found = true;
  2185. }
  2186. #endif
  2187. if (!found)
  2188. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  2189. ptr = comma;
  2190. } while (ptr);
  2191. free(fre);
  2192. }
  2193. }
  2194. }
  2195. #ifndef WIN32
  2196. #include <errno.h>
  2197. #include <unistd.h>
  2198. #include <sys/types.h>
  2199. #include <sys/ipc.h>
  2200. #include <sys/sem.h>
  2201. #include <sys/stat.h>
  2202. #include <fcntl.h>
  2203. #ifndef __APPLE__
  2204. union semun {
  2205. int val;
  2206. struct semid_ds *buf;
  2207. unsigned short *array;
  2208. struct seminfo *__buf;
  2209. };
  2210. #endif
  2211. #else
  2212. static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
  2213. {
  2214. FreeSid(((PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor))->Group);
  2215. free(sec->lpSecurityDescriptor);
  2216. free(sec);
  2217. return NULL;
  2218. }
  2219. static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
  2220. {
  2221. SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
  2222. PSID gsid = NULL;
  2223. LPSECURITY_ATTRIBUTES sec_att = NULL;
  2224. PSECURITY_DESCRIPTOR sec_des = NULL;
  2225. sec_des = malloc(sizeof(*sec_des));
  2226. if (unlikely(!sec_des))
  2227. quit(1, "MTX: Failed to malloc LPSECURITY_DESCRIPTOR");
  2228. if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
  2229. applog(LOG_ERR,
  2230. "MTX: %s (%d:%d) USB failed to init secdes err (%d)",
  2231. dname, (int)bus_number, (int)device_address,
  2232. GetLastError());
  2233. free(sec_des);
  2234. return NULL;
  2235. }
  2236. if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
  2237. applog(LOG_ERR,
  2238. "MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
  2239. dname, (int)bus_number, (int)device_address,
  2240. GetLastError());
  2241. free(sec_des);
  2242. return NULL;
  2243. }
  2244. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
  2245. applog(LOG_ERR,
  2246. "MTX: %s (%d:%d) USB failed to create gsid err (%d)",
  2247. dname, (int)bus_number, (int)device_address,
  2248. GetLastError());
  2249. free(sec_des);
  2250. return NULL;
  2251. }
  2252. if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
  2253. applog(LOG_ERR,
  2254. "MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
  2255. dname, (int)bus_number, (int)device_address,
  2256. GetLastError());
  2257. FreeSid(gsid);
  2258. free(sec_des);
  2259. return NULL;
  2260. }
  2261. sec_att = malloc(sizeof(*sec_att));
  2262. if (unlikely(!sec_att))
  2263. quit(1, "MTX: Failed to malloc LPSECURITY_ATTRIBUTES");
  2264. sec_att->nLength = sizeof(*sec_att);
  2265. sec_att->lpSecurityDescriptor = sec_des;
  2266. sec_att->bInheritHandle = FALSE;
  2267. return sec_att;
  2268. }
  2269. #endif
  2270. // Any errors should always be printed since they will rarely if ever occur
  2271. // and thus it is best to always display them
  2272. static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2273. {
  2274. applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2275. #ifdef WIN32
  2276. struct cgpu_info *cgpu;
  2277. LPSECURITY_ATTRIBUTES sec;
  2278. HANDLE usbMutex;
  2279. char name[64];
  2280. DWORD res;
  2281. int i;
  2282. if (is_in_use_bd(bus_number, device_address))
  2283. return false;
  2284. sprintf(name, "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2285. sec = mksec(dname, bus_number, device_address);
  2286. if (!sec)
  2287. return false;
  2288. usbMutex = CreateMutex(sec, FALSE, name);
  2289. if (usbMutex == NULL) {
  2290. applog(LOG_ERR,
  2291. "MTX: %s USB failed to get '%s' err (%d)",
  2292. dname, name, GetLastError());
  2293. sec = unsec(sec);
  2294. return false;
  2295. }
  2296. res = WaitForSingleObject(usbMutex, 0);
  2297. switch(res) {
  2298. case WAIT_OBJECT_0:
  2299. case WAIT_ABANDONED:
  2300. // Am I using it already?
  2301. for (i = 0; i < total_devices; i++) {
  2302. cgpu = get_devices(i);
  2303. if (cgpu->usbinfo.bus_number == bus_number &&
  2304. cgpu->usbinfo.device_address == device_address &&
  2305. cgpu->usbinfo.nodev == false) {
  2306. if (ReleaseMutex(usbMutex)) {
  2307. applog(LOG_WARNING,
  2308. "MTX: %s USB can't get '%s' - device in use",
  2309. dname, name);
  2310. goto fail;
  2311. }
  2312. applog(LOG_ERR,
  2313. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  2314. dname, name, GetLastError());
  2315. goto fail;
  2316. }
  2317. }
  2318. break;
  2319. case WAIT_TIMEOUT:
  2320. if (!hotplug_mode)
  2321. applog(LOG_WARNING,
  2322. "MTX: %s USB failed to get '%s' - device in use",
  2323. dname, name);
  2324. goto fail;
  2325. case WAIT_FAILED:
  2326. applog(LOG_ERR,
  2327. "MTX: %s USB failed to get '%s' err (%d)",
  2328. dname, name, GetLastError());
  2329. goto fail;
  2330. default:
  2331. applog(LOG_ERR,
  2332. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  2333. dname, name, res);
  2334. goto fail;
  2335. }
  2336. add_in_use(bus_number, device_address);
  2337. in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
  2338. return true;
  2339. fail:
  2340. CloseHandle(usbMutex);
  2341. sec = unsec(sec);
  2342. return false;
  2343. #else
  2344. struct semid_ds seminfo;
  2345. union semun opt;
  2346. char name[64];
  2347. key_t key;
  2348. int fd, sem, count;
  2349. if (is_in_use_bd(bus_number, device_address))
  2350. return false;
  2351. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2352. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2353. if (fd == -1) {
  2354. applog(LOG_ERR,
  2355. "SEM: %s USB open failed '%s' err (%d) %s",
  2356. dname, name, errno, strerror(errno));
  2357. return false;
  2358. }
  2359. close(fd);
  2360. key = ftok(name, 'K');
  2361. sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 438);
  2362. if (sem < 0) {
  2363. if (errno != EEXIST) {
  2364. applog(LOG_ERR,
  2365. "SEM: %s USB failed to get '%s' err (%d) %s",
  2366. dname, name, errno, strerror(errno));
  2367. return false;
  2368. }
  2369. sem = semget(key, 1, 0);
  2370. if (sem < 0) {
  2371. applog(LOG_ERR,
  2372. "SEM: %s USB failed to access '%s' err (%d) %s",
  2373. dname, name, errno, strerror(errno));
  2374. return false;
  2375. }
  2376. opt.buf = &seminfo;
  2377. count = 0;
  2378. while (++count) {
  2379. // Should NEVER take 100ms
  2380. if (count > 99) {
  2381. applog(LOG_ERR,
  2382. "SEM: %s USB timeout waiting for (%d) '%s'",
  2383. dname, sem, name);
  2384. return false;
  2385. }
  2386. if (semctl(sem, 0, IPC_STAT, opt) == -1) {
  2387. applog(LOG_ERR,
  2388. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  2389. dname, sem, name, count, errno, strerror(errno));
  2390. return false;
  2391. }
  2392. if (opt.buf->sem_otime != 0)
  2393. break;
  2394. nmsleep(1);
  2395. }
  2396. }
  2397. struct sembuf sops[] = {
  2398. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  2399. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  2400. };
  2401. if (semop(sem, sops, 2)) {
  2402. if (errno == EAGAIN) {
  2403. if (!hotplug_mode)
  2404. applog(LOG_WARNING,
  2405. "SEM: %s USB failed to get (%d) '%s' - device in use",
  2406. dname, sem, name);
  2407. } else {
  2408. applog(LOG_DEBUG,
  2409. "SEM: %s USB failed to get (%d) '%s' err (%d) %s",
  2410. dname, sem, name, errno, strerror(errno));
  2411. }
  2412. return false;
  2413. }
  2414. add_in_use(bus_number, device_address);
  2415. return true;
  2416. #endif
  2417. }
  2418. // Any errors should always be printed since they will rarely if ever occur
  2419. // and thus it is best to always display them
  2420. static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2421. {
  2422. applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2423. #ifdef WIN32
  2424. LPSECURITY_ATTRIBUTES sec = NULL;
  2425. HANDLE usbMutex = NULL;
  2426. char name[64];
  2427. sprintf(name, "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2428. in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
  2429. if (!usbMutex || !sec)
  2430. goto fila;
  2431. if (!ReleaseMutex(usbMutex))
  2432. applog(LOG_ERR,
  2433. "MTX: %s USB failed to release '%s' err (%d)",
  2434. dname, name, GetLastError());
  2435. fila:
  2436. if (usbMutex)
  2437. CloseHandle(usbMutex);
  2438. if (sec)
  2439. unsec(sec);
  2440. remove_in_use(bus_number, device_address);
  2441. return;
  2442. #else
  2443. char name[64];
  2444. key_t key;
  2445. int fd, sem;
  2446. sprintf(name, "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2447. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2448. if (fd == -1) {
  2449. applog(LOG_ERR,
  2450. "SEM: %s USB open failed '%s' for release err (%d) %s",
  2451. dname, name, errno, strerror(errno));
  2452. return;
  2453. }
  2454. close(fd);
  2455. key = ftok(name, 'K');
  2456. sem = semget(key, 1, 0);
  2457. if (sem < 0) {
  2458. applog(LOG_ERR,
  2459. "SEM: %s USB failed to get '%s' for release err (%d) %s",
  2460. dname, name, errno, strerror(errno));
  2461. return;
  2462. }
  2463. struct sembuf sops[] = {
  2464. { 0, -1, SEM_UNDO }
  2465. };
  2466. // Allow a 10ms timeout
  2467. // exceeding this timeout means it would probably never succeed anyway
  2468. struct timespec timeout = { 0, 10000000 };
  2469. if (semtimedop(sem, sops, 1, &timeout)) {
  2470. applog(LOG_ERR,
  2471. "SEM: %s USB failed to release '%s' err (%d) %s",
  2472. dname, name, errno, strerror(errno));
  2473. }
  2474. remove_in_use(bus_number, device_address);
  2475. return;
  2476. #endif
  2477. }
  2478. static void resource_process()
  2479. {
  2480. struct resource_work *res_work = NULL;
  2481. struct resource_reply *res_reply = NULL;
  2482. bool ok;
  2483. applog(LOG_DEBUG, "RES: %s (%d:%d) lock=%d",
  2484. res_work_head->dname,
  2485. (int)res_work_head->bus_number,
  2486. (int)res_work_head->device_address,
  2487. res_work_head->lock);
  2488. if (res_work_head->lock) {
  2489. ok = resource_lock(res_work_head->dname,
  2490. res_work_head->bus_number,
  2491. res_work_head->device_address);
  2492. applog(LOG_DEBUG, "RES: %s (%d:%d) lock ok=%d",
  2493. res_work_head->dname,
  2494. (int)res_work_head->bus_number,
  2495. (int)res_work_head->device_address,
  2496. ok);
  2497. res_reply = calloc(1, sizeof(*res_reply));
  2498. if (unlikely(!res_reply))
  2499. quit(1, "USB failed to calloc res_reply");
  2500. res_reply->bus_number = res_work_head->bus_number;
  2501. res_reply->device_address = res_work_head->device_address;
  2502. res_reply->got = ok;
  2503. res_reply->next = res_reply_head;
  2504. res_reply_head = res_reply;
  2505. }
  2506. else
  2507. resource_unlock(res_work_head->dname,
  2508. res_work_head->bus_number,
  2509. res_work_head->device_address);
  2510. res_work = res_work_head;
  2511. res_work_head = res_work_head->next;
  2512. free(res_work);
  2513. }
  2514. void *usb_resource_thread(void __maybe_unused *userdata)
  2515. {
  2516. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2517. RenameThread("usbresource");
  2518. applog(LOG_DEBUG, "RES: thread starting");
  2519. while (42) {
  2520. /* Wait to be told we have work to do */
  2521. sem_wait(&usb_resource_sem);
  2522. mutex_lock(&cgusbres_lock);
  2523. while (res_work_head)
  2524. resource_process();
  2525. mutex_unlock(&cgusbres_lock);
  2526. }
  2527. return NULL;
  2528. }