usbutils.c 95 KB

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