usbutils.c 82 KB

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