usbutils.c 97 KB

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