usbutils.c 97 KB

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