usbutils.c 94 KB

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