usbutils.c 93 KB

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