usbutils.c 93 KB

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