usbutils.c 96 KB

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