usbutils.c 94 KB

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