usbutils.c 98 KB

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