usbutils.c 97 KB

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