usbutils.c 99 KB

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