usbutils.c 100 KB

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