usbutils.c 94 KB

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