usbutils.c 98 KB

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