usbutils.c 95 KB

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