usbutils.c 115 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456
  1. /*
  2. * Copyright 2012-2013 Andrew Smith
  3. * Copyright 2013-2014 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. static pthread_mutex_t cgusb_lock;
  18. static pthread_mutex_t cgusbres_lock;
  19. static cglock_t cgusb_fd_lock;
  20. static cgtimer_t usb11_cgt;
  21. #define NODEV(err) ((err) != LIBUSB_SUCCESS && (err) != LIBUSB_ERROR_TIMEOUT)
  22. #define NOCONTROLDEV(err) ((err) < 0 && NODEV(err))
  23. /*
  24. * WARNING - these assume DEVLOCK(cgpu, pstate) is called first and
  25. * DEVUNLOCK(cgpu, pstate) in called in the same function with the same pstate
  26. * given to DEVLOCK.
  27. * You must call DEVUNLOCK(cgpu, pstate) before exiting the function or it will leave
  28. * the thread Cancelability unrestored
  29. */
  30. #define DEVWLOCK(cgpu, _pth_state) do { \
  31. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &_pth_state); \
  32. cg_wlock(&cgpu->usbinfo.devlock); \
  33. } while (0)
  34. #define DEVWUNLOCK(cgpu, _pth_state) do { \
  35. cg_wunlock(&cgpu->usbinfo.devlock); \
  36. pthread_setcancelstate(_pth_state, NULL); \
  37. } while (0)
  38. #define DEVRLOCK(cgpu, _pth_state) do { \
  39. pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &_pth_state); \
  40. cg_rlock(&cgpu->usbinfo.devlock); \
  41. } while (0)
  42. #define DEVRUNLOCK(cgpu, _pth_state) do { \
  43. cg_runlock(&cgpu->usbinfo.devlock); \
  44. pthread_setcancelstate(_pth_state, NULL); \
  45. } while (0)
  46. #define USB_CONFIG 1
  47. #define BITFURY_TIMEOUT_MS 999
  48. #define DRILLBIT_TIMEOUT_MS 999
  49. #define ICARUS_TIMEOUT_MS 999
  50. #define BMSC_TIMEOUT_MS 999
  51. #ifdef WIN32
  52. #define BFLSC_TIMEOUT_MS 999
  53. #define BITFORCE_TIMEOUT_MS 999
  54. #define MODMINER_TIMEOUT_MS 999
  55. #define AVALON_TIMEOUT_MS 999
  56. #define AVALON4_TIMEOUT_MS 999
  57. #define BITMAIN_TIMEOUT_MS 999
  58. #define KLONDIKE_TIMEOUT_MS 999
  59. #define COINTERRA_TIMEOUT_MS 999
  60. #define HASHFAST_TIMEOUT_MS 999
  61. #define HASHRATIO_TIMEOUT_MS 999
  62. #define BLOCKERUPTER_TIMEOUT_MS 999
  63. /* The safety timeout we use, cancelling async transfers on windows that fail
  64. * to timeout on their own. */
  65. #define WIN_CALLBACK_EXTRA 40
  66. #define WIN_WRITE_CBEXTRA 5000
  67. #else
  68. #define BFLSC_TIMEOUT_MS 300
  69. #define BITFORCE_TIMEOUT_MS 200
  70. #define MODMINER_TIMEOUT_MS 100
  71. #define AVALON_TIMEOUT_MS 200
  72. #define AVALON4_TIMEOUT_MS 50
  73. #define BITMAIN_TIMEOUT_MS 200
  74. #define KLONDIKE_TIMEOUT_MS 200
  75. #define COINTERRA_TIMEOUT_MS 200
  76. #define HASHFAST_TIMEOUT_MS 500
  77. #define HASHRATIO_TIMEOUT_MS 200
  78. #define BLOCKERUPTER_TIMEOUT_MS 300
  79. #endif
  80. #define USB_EPS(_intx, _epinfosx) { \
  81. .interface = _intx, \
  82. .ctrl_transfer = _intx, \
  83. .epinfo_count = ARRAY_SIZE(_epinfosx), \
  84. .epinfos = _epinfosx \
  85. }
  86. #define USB_EPS_CTRL(_inty, _ctrlinty, _epinfosy) { \
  87. .interface = _inty, \
  88. .ctrl_transfer = _ctrlinty, \
  89. .epinfo_count = ARRAY_SIZE(_epinfosy), \
  90. .epinfos = _epinfosy \
  91. }
  92. /* Linked list of all async transfers in progress. Protected by cgusb_fd_lock.
  93. * This allows us to not stop the usb polling thread till all are complete, and
  94. * to find cancellable transfers. */
  95. static struct list_head ut_list;
  96. #ifdef USE_BFLSC
  97. static struct usb_epinfo bflsc_epinfos[] = {
  98. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPI(1), 0, 0 },
  99. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPO(2), 0, 0 }
  100. };
  101. static struct usb_intinfo bflsc_ints[] = {
  102. USB_EPS(0, bflsc_epinfos)
  103. };
  104. #endif
  105. #ifdef USE_BITFORCE
  106. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  107. static struct usb_epinfo bfl_epinfos[] = {
  108. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  109. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  110. };
  111. static struct usb_intinfo bfl_ints[] = {
  112. USB_EPS(0, bfl_epinfos)
  113. };
  114. #endif
  115. #ifdef USE_BITFURY
  116. static struct usb_epinfo bfu0_epinfos[] = {
  117. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(2), 0, 0 }
  118. };
  119. static struct usb_epinfo bfu1_epinfos[] = {
  120. { LIBUSB_TRANSFER_TYPE_BULK, 16, EPI(3), 0, 0 },
  121. { LIBUSB_TRANSFER_TYPE_BULK, 16, EPO(4), 0, 0 }
  122. };
  123. /* Default to interface 1 */
  124. static struct usb_intinfo bfu_ints[] = {
  125. USB_EPS(1, bfu1_epinfos),
  126. USB_EPS(0, bfu0_epinfos)
  127. };
  128. static struct usb_epinfo bxf0_epinfos[] = {
  129. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(1), 0, 0 }
  130. };
  131. static struct usb_epinfo bxf1_epinfos[] = {
  132. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(2), 0, 0 },
  133. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  134. };
  135. static struct usb_intinfo bxf_ints[] = {
  136. USB_EPS(1, bxf1_epinfos),
  137. USB_EPS(0, bxf0_epinfos)
  138. };
  139. static struct usb_epinfo nfu_epinfos[] = {
  140. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 64, EPI(1), 0, 0 },
  141. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 64, EPO(1), 0, 0 },
  142. };
  143. static struct usb_intinfo nfu_ints[] = {
  144. USB_EPS(0, nfu_epinfos)
  145. };
  146. static struct usb_epinfo bxm_epinfos[] = {
  147. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPI(1), 0, 0 },
  148. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPO(2), 0, 0 }
  149. };
  150. static struct usb_intinfo bxm_ints[] = {
  151. USB_EPS(0, bxm_epinfos)
  152. };
  153. #endif
  154. #ifdef USE_BLOCKERUPTER
  155. // BlockErupter Device
  156. static struct usb_epinfo bet_epinfos[] = {
  157. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  158. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  159. };
  160. static struct usb_intinfo bet_ints[] = {
  161. USB_EPS(0, bet_epinfos)
  162. };
  163. #endif
  164. #ifdef USE_DRILLBIT
  165. // Drillbit Bitfury devices
  166. static struct usb_epinfo drillbit_int_epinfos[] = {
  167. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(3), 0, 0 }
  168. };
  169. static struct usb_epinfo drillbit_bulk_epinfos[] = {
  170. { LIBUSB_TRANSFER_TYPE_BULK, 16, EPI(1), 0, 0 },
  171. { LIBUSB_TRANSFER_TYPE_BULK, 16, EPO(2), 0, 0 },
  172. };
  173. /* Default to interface 1 */
  174. static struct usb_intinfo drillbit_ints[] = {
  175. USB_EPS(1, drillbit_bulk_epinfos),
  176. USB_EPS(0, drillbit_int_epinfos)
  177. };
  178. #endif
  179. #ifdef USE_HASHFAST
  180. #include "driver-hashfast.h"
  181. static struct usb_epinfo hfa0_epinfos[] = {
  182. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(3), 0, 0 }
  183. };
  184. static struct usb_epinfo hfa1_epinfos[] = {
  185. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  186. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  187. };
  188. /* Default to interface 1 */
  189. static struct usb_intinfo hfa_ints[] = {
  190. USB_EPS(1, hfa1_epinfos),
  191. USB_EPS(0, hfa0_epinfos)
  192. };
  193. #endif
  194. #ifdef USE_HASHRATIO
  195. static struct usb_epinfo hro_epinfos[] = {
  196. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  197. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  198. };
  199. static struct usb_intinfo hro_ints[] = {
  200. USB_EPS(0, hro_epinfos)
  201. };
  202. #endif
  203. #ifdef USE_MODMINER
  204. static struct usb_epinfo mmq_epinfos[] = {
  205. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  206. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0, 0 }
  207. };
  208. static struct usb_intinfo mmq_ints[] = {
  209. USB_EPS(1, mmq_epinfos)
  210. };
  211. #endif
  212. #ifdef USE_AVALON
  213. static struct usb_epinfo ava_epinfos[] = {
  214. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  215. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  216. };
  217. static struct usb_intinfo ava_ints[] = {
  218. USB_EPS(0, ava_epinfos)
  219. };
  220. #endif
  221. #ifdef USE_AVALON2
  222. static struct usb_epinfo ava2_epinfos[] = {
  223. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  224. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  225. };
  226. static struct usb_intinfo ava2_ints[] = {
  227. USB_EPS(0, ava2_epinfos)
  228. };
  229. #endif
  230. #ifdef USE_AVALON4
  231. static struct usb_epinfo ava4_epinfos[] = {
  232. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  233. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  234. };
  235. static struct usb_intinfo ava4_ints[] = {
  236. USB_EPS(1, ava4_epinfos)
  237. };
  238. #endif
  239. #ifdef USE_KLONDIKE
  240. static struct usb_epinfo kln_epinfos[] = {
  241. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  242. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  243. };
  244. static struct usb_intinfo kln_ints[] = {
  245. USB_EPS(0, kln_epinfos)
  246. };
  247. static struct usb_epinfo kli0_epinfos[] = {
  248. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(1), 0, 0 }
  249. };
  250. static struct usb_epinfo kli1_epinfos[] = {
  251. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(2), 0, 0 },
  252. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  253. };
  254. static struct usb_intinfo kli_ints[] = {
  255. USB_EPS(1, kli1_epinfos),
  256. USB_EPS(0, kli0_epinfos)
  257. };
  258. #endif
  259. #ifdef USE_ICARUS
  260. static struct usb_epinfo ica_epinfos[] = {
  261. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  262. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  263. };
  264. static struct usb_intinfo ica_ints[] = {
  265. USB_EPS(0, ica_epinfos)
  266. };
  267. static struct usb_epinfo ica1_epinfos0[] = {
  268. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 16, EPI(0x82), 0, 0 }
  269. };
  270. static struct usb_epinfo ica1_epinfos1[] = {
  271. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(0x81), 0, 0 },
  272. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(0x01), 0, 0 }
  273. };
  274. static struct usb_intinfo ica1_ints[] = {
  275. USB_EPS(1, ica1_epinfos1),
  276. USB_EPS(0, ica1_epinfos0)
  277. };
  278. static struct usb_epinfo amu_epinfos[] = {
  279. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  280. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  281. };
  282. static struct usb_intinfo amu_ints[] = {
  283. USB_EPS(0, amu_epinfos)
  284. };
  285. static struct usb_epinfo llt_epinfos[] = {
  286. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  287. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  288. };
  289. static struct usb_intinfo llt_ints[] = {
  290. USB_EPS(0, llt_epinfos)
  291. };
  292. static struct usb_epinfo cmr1_epinfos[] = {
  293. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  294. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  295. };
  296. static struct usb_intinfo cmr1_ints[] = {
  297. USB_EPS(0, cmr1_epinfos)
  298. };
  299. static struct usb_epinfo cmr2_epinfos0[] = {
  300. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  301. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  302. };
  303. static struct usb_epinfo cmr2_epinfos1[] = {
  304. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  305. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(4), 0, 0 },
  306. };
  307. static struct usb_epinfo cmr2_epinfos2[] = {
  308. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(5), 0, 0 },
  309. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(6), 0, 0 },
  310. };
  311. static struct usb_epinfo cmr2_epinfos3[] = {
  312. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(7), 0, 0 },
  313. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(8), 0, 0 }
  314. };
  315. static struct usb_intinfo cmr2_ints[] = {
  316. USB_EPS_CTRL(0, 1, cmr2_epinfos0),
  317. USB_EPS_CTRL(1, 2, cmr2_epinfos1),
  318. USB_EPS_CTRL(2, 3, cmr2_epinfos2),
  319. USB_EPS_CTRL(3, 4, cmr2_epinfos3)
  320. };
  321. #endif
  322. #ifdef USE_COINTERRA
  323. static struct usb_epinfo cointerra_epinfos[] = {
  324. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  325. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  326. };
  327. static struct usb_intinfo cointerra_ints[] = {
  328. USB_EPS(0, cointerra_epinfos)
  329. };
  330. #endif
  331. #ifdef USE_BMSC
  332. static struct usb_epinfo ica_epinfos[] = {
  333. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  334. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  335. };
  336. static struct usb_intinfo ica_ints[] = {
  337. USB_EPS(0, ica_epinfos)
  338. };
  339. static struct usb_epinfo amu_epinfos[] = {
  340. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  341. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  342. };
  343. static struct usb_intinfo amu_ints[] = {
  344. USB_EPS(0, amu_epinfos)
  345. };
  346. static struct usb_epinfo llt_epinfos[] = {
  347. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  348. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  349. };
  350. static struct usb_intinfo llt_ints[] = {
  351. USB_EPS(0, llt_epinfos)
  352. };
  353. static struct usb_epinfo cmr1_epinfos[] = {
  354. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  355. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  356. };
  357. static struct usb_intinfo cmr1_ints[] = {
  358. USB_EPS(0, cmr1_epinfos)
  359. };
  360. static struct usb_epinfo cmr2_epinfos0[] = {
  361. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  362. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  363. };
  364. static struct usb_epinfo cmr2_epinfos1[] = {
  365. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  366. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(4), 0, 0 },
  367. };
  368. static struct usb_epinfo cmr2_epinfos2[] = {
  369. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(5), 0, 0 },
  370. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(6), 0, 0 },
  371. };
  372. static struct usb_epinfo cmr2_epinfos3[] = {
  373. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(7), 0, 0 },
  374. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(8), 0, 0 }
  375. };
  376. static struct usb_intinfo cmr2_ints[] = {
  377. USB_EPS_CTRL(0, 1, cmr2_epinfos0),
  378. USB_EPS_CTRL(1, 2, cmr2_epinfos1),
  379. USB_EPS_CTRL(2, 3, cmr2_epinfos2),
  380. USB_EPS_CTRL(3, 4, cmr2_epinfos3)
  381. };
  382. #endif
  383. #ifdef USE_BITMAIN
  384. static struct usb_epinfo btm_epinfos[] = {
  385. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  386. #ifdef WIN32
  387. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  388. #else
  389. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  390. #endif
  391. };
  392. static struct usb_intinfo btm_ints[] = {
  393. USB_EPS(0, btm_epinfos)
  394. };
  395. #endif
  396. #define IDVENDOR_FTDI 0x0403
  397. #define INTINFO(_ints) \
  398. .intinfo_count = ARRAY_SIZE(_ints), \
  399. .intinfos = _ints
  400. #define USBEP(_usbdev, _intinfo, _epinfo) (_usbdev->found->intinfos[_intinfo].epinfos[_epinfo].ep)
  401. #define THISIF(_found, _this) (_found->intinfos[_this].interface)
  402. #define USBIF(_usbdev, _this) THISIF(_usbdev->found, _this)
  403. // TODO: Add support for (at least) Isochronous endpoints
  404. static struct usb_find_devices find_dev[] = {
  405. #ifdef USE_BFLSC
  406. {
  407. .drv = DRIVER_bflsc,
  408. .name = "BAS",
  409. .ident = IDENT_BAS,
  410. .idVendor = IDVENDOR_FTDI,
  411. .idProduct = 0x6014,
  412. //.iManufacturer = "Butterfly Labs",
  413. .iProduct = "BitFORCE SHA256 SC",
  414. .config = 1,
  415. .timeout = BFLSC_TIMEOUT_MS,
  416. .latency = LATENCY_STD,
  417. INTINFO(bflsc_ints) },
  418. {
  419. .drv = DRIVER_bflsc,
  420. .name = "BMA",
  421. .ident = IDENT_BMA,
  422. .idVendor = IDVENDOR_FTDI,
  423. .idProduct = 0x6014,
  424. //.iManufacturer = "BUTTERFLY LABS"
  425. .iProduct = "BitFORCE SC-28nm",
  426. .config = 1,
  427. .timeout = BFLSC_TIMEOUT_MS,
  428. .latency = LATENCY_STD,
  429. INTINFO(bflsc_ints) },
  430. {
  431. .drv = DRIVER_bflsc,
  432. .name = "BMA",
  433. .ident = IDENT_BMA,
  434. .idVendor = IDVENDOR_FTDI,
  435. .idProduct = 0x6014,
  436. .iManufacturer = "BUTTERFLY LABS",
  437. .iProduct = "BitFORCE SHA256",
  438. .config = 1,
  439. .timeout = BFLSC_TIMEOUT_MS,
  440. .latency = LATENCY_STD,
  441. INTINFO(bflsc_ints) },
  442. #endif
  443. #ifdef USE_BITFORCE
  444. {
  445. .drv = DRIVER_bitforce,
  446. .name = "BFL",
  447. .ident = IDENT_BFL,
  448. .idVendor = IDVENDOR_FTDI,
  449. .idProduct = 0x6014,
  450. .iManufacturer = "Butterfly Labs Inc.",
  451. .iProduct = "BitFORCE SHA256",
  452. .config = 1,
  453. .timeout = BITFORCE_TIMEOUT_MS,
  454. .latency = LATENCY_STD,
  455. INTINFO(bfl_ints) },
  456. #endif
  457. #ifdef USE_BITFURY
  458. {
  459. .drv = DRIVER_bitfury,
  460. .name = "BF1",
  461. .ident = IDENT_BF1,
  462. .idVendor = 0x03eb,
  463. .idProduct = 0x204b,
  464. .config = 1,
  465. .timeout = BITFURY_TIMEOUT_MS,
  466. .latency = LATENCY_UNUSED,
  467. //.iManufacturer = "BPMC",
  468. .iProduct = "Bitfury BF1",
  469. INTINFO(bfu_ints)
  470. },
  471. {
  472. .drv = DRIVER_bitfury,
  473. .name = "BXF",
  474. .ident = IDENT_BXF,
  475. .idVendor = 0x198c,
  476. .idProduct = 0xb1f1,
  477. .config = 1,
  478. .timeout = BITFURY_TIMEOUT_MS,
  479. .latency = LATENCY_UNUSED,
  480. .iManufacturer = "c-scape",
  481. .iProduct = "bi?fury",
  482. INTINFO(bxf_ints)
  483. },
  484. {
  485. .drv = DRIVER_bitfury,
  486. .name = "OSM",
  487. .ident = IDENT_OSM,
  488. .idVendor = 0x198c,
  489. .idProduct = 0xb1f1,
  490. .config = 1,
  491. .timeout = BITFURY_TIMEOUT_MS,
  492. .latency = LATENCY_UNUSED,
  493. .iManufacturer = "c-scape",
  494. .iProduct = "OneString",
  495. INTINFO(bxf_ints)
  496. },
  497. {
  498. .drv = DRIVER_bitfury,
  499. .name = "NFU",
  500. .ident = IDENT_NFU,
  501. .idVendor = 0x04d8,
  502. .idProduct = 0x00de,
  503. .config = 1,
  504. .timeout = BITFURY_TIMEOUT_MS,
  505. .latency = LATENCY_UNUSED,
  506. INTINFO(nfu_ints)
  507. },
  508. {
  509. .drv = DRIVER_bitfury,
  510. .name = "BXM",
  511. .ident = IDENT_BXM,
  512. .idVendor = 0x0403,
  513. .idProduct = 0x6014,
  514. .config = 1,
  515. .timeout = BITFURY_TIMEOUT_MS,
  516. .latency = LATENCY_UNUSED,
  517. INTINFO(bxm_ints)
  518. },
  519. #endif
  520. #ifdef USE_BLOCKERUPTER
  521. {
  522. .drv = DRIVER_blockerupter,
  523. .name = "BET",
  524. .ident = IDENT_BET,
  525. .idVendor = 0x10c4,
  526. .idProduct = 0xea60,
  527. .config = 1,
  528. .timeout = BLOCKERUPTER_TIMEOUT_MS,
  529. .latency = LATENCY_UNUSED,
  530. INTINFO(bet_ints) },
  531. #endif
  532. #ifdef USE_DRILLBIT
  533. {
  534. .drv = DRIVER_drillbit,
  535. .name = "DRB",
  536. .ident = IDENT_DRB,
  537. .idVendor = 0x03eb,
  538. .idProduct = 0x2404,
  539. .config = 1,
  540. .timeout = DRILLBIT_TIMEOUT_MS,
  541. .latency = LATENCY_UNUSED,
  542. .iManufacturer = "Drillbit Systems",
  543. .iProduct = NULL, /* Can be Thumb or Eight, same driver */
  544. INTINFO(drillbit_ints)
  545. },
  546. #endif
  547. #ifdef USE_MODMINER
  548. {
  549. .drv = DRIVER_modminer,
  550. .name = "MMQ",
  551. .ident = IDENT_MMQ,
  552. .idVendor = 0x1fc9,
  553. .idProduct = 0x0003,
  554. .config = 1,
  555. .timeout = MODMINER_TIMEOUT_MS,
  556. .latency = LATENCY_UNUSED,
  557. INTINFO(mmq_ints) },
  558. #endif
  559. #ifdef USE_AVALON
  560. {
  561. .drv = DRIVER_avalon,
  562. .name = "BTB",
  563. .ident = IDENT_BTB,
  564. .idVendor = IDVENDOR_FTDI,
  565. .idProduct = 0x6001,
  566. .iManufacturer = "Burnin Electronics",
  567. .iProduct = "BitBurner",
  568. .config = 1,
  569. .timeout = AVALON_TIMEOUT_MS,
  570. .latency = 10,
  571. INTINFO(ava_ints) },
  572. {
  573. .drv = DRIVER_avalon,
  574. .name = "BBF",
  575. .ident = IDENT_BBF,
  576. .idVendor = IDVENDOR_FTDI,
  577. .idProduct = 0x6001,
  578. .iManufacturer = "Burnin Electronics",
  579. .iProduct = "BitBurner Fury",
  580. .config = 1,
  581. .timeout = AVALON_TIMEOUT_MS,
  582. .latency = 10,
  583. INTINFO(ava_ints) },
  584. {
  585. .drv = DRIVER_avalon,
  586. .name = "AVA",
  587. .ident = IDENT_AVA,
  588. .idVendor = IDVENDOR_FTDI,
  589. .idProduct = 0x6001,
  590. .config = 1,
  591. .timeout = AVALON_TIMEOUT_MS,
  592. .latency = 10,
  593. INTINFO(ava_ints) },
  594. #endif
  595. #ifdef USE_AVALON2
  596. {
  597. .drv = DRIVER_avalon2,
  598. .name = "AV2",
  599. .ident = IDENT_AV2,
  600. .idVendor = 0x067b,
  601. .idProduct = 0x2303,
  602. .config = 1,
  603. .timeout = AVALON_TIMEOUT_MS,
  604. .latency = LATENCY_UNUSED,
  605. INTINFO(ava2_ints) },
  606. #endif
  607. #ifdef USE_AVALON4
  608. {
  609. .drv = DRIVER_avalon4,
  610. .name = "AV4",
  611. .ident = IDENT_AV4,
  612. .idVendor = 0x29f1,
  613. .idProduct = 0x33f2,
  614. .iManufacturer = "CANAAN",
  615. .iProduct = "USB2IIC Converter",
  616. .config = 1,
  617. .timeout = AVALON4_TIMEOUT_MS,
  618. .latency = LATENCY_UNUSED,
  619. INTINFO(ava4_ints) },
  620. #endif
  621. #ifdef USE_HASHFAST
  622. {
  623. .drv = DRIVER_hashfast,
  624. .name = "HFA",
  625. .ident = IDENT_HFA,
  626. .idVendor = HF_USB_VENDOR_ID,
  627. .idProduct = HF_USB_PRODUCT_ID_G1,
  628. .iManufacturer = "HashFast LLC",
  629. .iProduct = "M1 Module",
  630. .config = 1,
  631. .timeout = HASHFAST_TIMEOUT_MS,
  632. .latency = LATENCY_UNUSED,
  633. INTINFO(hfa_ints) },
  634. #endif
  635. #ifdef USE_HASHRATIO
  636. {
  637. .drv = DRIVER_hashratio,
  638. .name = "HRO",
  639. .ident = IDENT_HRO,
  640. .idVendor = IDVENDOR_FTDI,
  641. .idProduct = 0x6001,
  642. .config = 1,
  643. .timeout = HASHRATIO_TIMEOUT_MS,
  644. .latency = LATENCY_UNUSED,
  645. INTINFO(hro_ints) },
  646. #endif
  647. #ifdef USE_KLONDIKE
  648. {
  649. .drv = DRIVER_klondike,
  650. .name = "KLN",
  651. .ident = IDENT_KLN,
  652. .idVendor = 0x04D8,
  653. .idProduct = 0xF60A,
  654. .config = 1,
  655. .timeout = KLONDIKE_TIMEOUT_MS,
  656. .latency = 10,
  657. INTINFO(kln_ints) },
  658. {
  659. .drv = DRIVER_klondike,
  660. .name = "KLI",
  661. .ident = IDENT_KLN,
  662. .idVendor = 0x04D8,
  663. .idProduct = 0xF60A,
  664. .config = 1,
  665. .timeout = KLONDIKE_TIMEOUT_MS,
  666. .latency = 10,
  667. INTINFO(kli_ints) },
  668. #endif
  669. #ifdef USE_ICARUS
  670. {
  671. .drv = DRIVER_icarus,
  672. .name = "ICA",
  673. .ident = IDENT_ICA,
  674. .idVendor = 0x067b,
  675. .idProduct = 0x2303,
  676. .config = 1,
  677. .timeout = ICARUS_TIMEOUT_MS,
  678. .latency = LATENCY_UNUSED,
  679. INTINFO(ica_ints) },
  680. {
  681. .drv = DRIVER_icarus,
  682. .name = "ICA",
  683. .ident = IDENT_AVA,
  684. .idVendor = 0x1fc9,
  685. .idProduct = 0x0083,
  686. .config = 1,
  687. .timeout = ICARUS_TIMEOUT_MS,
  688. .latency = LATENCY_UNUSED,
  689. INTINFO(ica1_ints) },
  690. {
  691. .drv = DRIVER_icarus,
  692. .name = "AMU",
  693. .ident = IDENT_AMU,
  694. .idVendor = 0x10c4,
  695. .idProduct = 0xea60,
  696. .config = 1,
  697. .timeout = ICARUS_TIMEOUT_MS,
  698. .latency = LATENCY_UNUSED,
  699. INTINFO(amu_ints) },
  700. {
  701. .drv = DRIVER_icarus,
  702. .name = "LIN",
  703. .ident = IDENT_LIN,
  704. .idVendor = 0x10c4,
  705. .idProduct = 0xea60,
  706. .config = 1,
  707. .timeout = ICARUS_TIMEOUT_MS,
  708. .latency = LATENCY_UNUSED,
  709. INTINFO(amu_ints) },
  710. {
  711. .drv = DRIVER_icarus,
  712. .name = "ANU",
  713. .ident = IDENT_ANU,
  714. .idVendor = 0x10c4,
  715. .idProduct = 0xea60,
  716. .config = 1,
  717. .timeout = ICARUS_TIMEOUT_MS,
  718. .latency = LATENCY_UNUSED,
  719. INTINFO(amu_ints) },
  720. {
  721. .drv = DRIVER_icarus,
  722. .name = "BLT",
  723. .ident = IDENT_BLT,
  724. .idVendor = IDVENDOR_FTDI,
  725. .idProduct = 0x6001,
  726. .iProduct = "FT232R USB UART",
  727. .config = 1,
  728. .timeout = ICARUS_TIMEOUT_MS,
  729. .latency = LATENCY_STD,
  730. INTINFO(llt_ints) },
  731. // For any that don't match the above "BLT"
  732. {
  733. .drv = DRIVER_icarus,
  734. .name = "LLT",
  735. .ident = IDENT_LLT,
  736. .idVendor = IDVENDOR_FTDI,
  737. .idProduct = 0x6001,
  738. .config = 1,
  739. .timeout = ICARUS_TIMEOUT_MS,
  740. .latency = LATENCY_STD,
  741. INTINFO(llt_ints) },
  742. {
  743. .drv = DRIVER_icarus,
  744. .name = "CMR",
  745. .ident = IDENT_CMR1,
  746. .idVendor = IDVENDOR_FTDI,
  747. .idProduct = 0x6014,
  748. .iProduct = "Cairnsmore1",
  749. .config = 1,
  750. .timeout = ICARUS_TIMEOUT_MS,
  751. .latency = LATENCY_STD,
  752. INTINFO(cmr1_ints) },
  753. {
  754. .drv = DRIVER_icarus,
  755. .name = "CMR",
  756. .ident = IDENT_CMR2,
  757. .idVendor = IDVENDOR_FTDI,
  758. .idProduct = 0x8350,
  759. .iProduct = "Cairnsmore1",
  760. .config = 1,
  761. .timeout = ICARUS_TIMEOUT_MS,
  762. .latency = LATENCY_STD,
  763. INTINFO(cmr2_ints) },
  764. #endif
  765. #ifdef USE_COINTERRA
  766. {
  767. .drv = DRIVER_cointerra,
  768. .name = "CTA",
  769. .ident = IDENT_CTA,
  770. .idVendor = 0x1cbe,
  771. .idProduct = 0x0003,
  772. .config = 1,
  773. .timeout = COINTERRA_TIMEOUT_MS,
  774. .latency = LATENCY_STD,
  775. INTINFO(cointerra_ints) },
  776. #endif
  777. #ifdef USE_BMSC
  778. {
  779. .drv = DRIVER_bmsc,
  780. .name = "ICA",
  781. .ident = IDENT_ICA,
  782. .idVendor = 0x067b,
  783. .idProduct = 0x2303,
  784. .config = 1,
  785. .timeout = ICARUS_TIMEOUT_MS,
  786. .latency = LATENCY_UNUSED,
  787. INTINFO(ica_ints) },
  788. {
  789. .drv = DRIVER_bmsc,
  790. .name = "AMU",
  791. .ident = IDENT_AMU,
  792. .idVendor = 0x10c4,
  793. .idProduct = 0xea60,
  794. .config = 1,
  795. .timeout = ICARUS_TIMEOUT_MS,
  796. .latency = LATENCY_UNUSED,
  797. INTINFO(amu_ints) },
  798. {
  799. .drv = DRIVER_bmsc,
  800. .name = "ANU",
  801. .ident = IDENT_ANU,
  802. .idVendor = 0x10c4,
  803. .idProduct = 0xea60,
  804. .config = 1,
  805. .timeout = ICARUS_TIMEOUT_MS,
  806. .latency = LATENCY_UNUSED,
  807. INTINFO(amu_ints) },
  808. {
  809. .drv = DRIVER_bmsc,
  810. .name = "BLT",
  811. .ident = IDENT_BLT,
  812. .idVendor = IDVENDOR_FTDI,
  813. .idProduct = 0x6001,
  814. .iProduct = "FT232R USB UART",
  815. .config = 1,
  816. .timeout = ICARUS_TIMEOUT_MS,
  817. .latency = LATENCY_STD,
  818. INTINFO(llt_ints) },
  819. // For any that don't match the above "BLT"
  820. {
  821. .drv = DRIVER_bmsc,
  822. .name = "LLT",
  823. .ident = IDENT_LLT,
  824. .idVendor = IDVENDOR_FTDI,
  825. .idProduct = 0x6001,
  826. .config = 1,
  827. .timeout = ICARUS_TIMEOUT_MS,
  828. .latency = LATENCY_STD,
  829. INTINFO(llt_ints) },
  830. {
  831. .drv = DRIVER_bmsc,
  832. .name = "CMR",
  833. .ident = IDENT_CMR1,
  834. .idVendor = IDVENDOR_FTDI,
  835. .idProduct = 0x6014,
  836. .iProduct = "Cairnsmore1",
  837. .config = 1,
  838. .timeout = ICARUS_TIMEOUT_MS,
  839. .latency = LATENCY_STD,
  840. INTINFO(cmr1_ints) },
  841. {
  842. .drv = DRIVER_bmsc,
  843. .name = "CMR",
  844. .ident = IDENT_CMR2,
  845. .idVendor = IDVENDOR_FTDI,
  846. .idProduct = 0x8350,
  847. .iProduct = "Cairnsmore1",
  848. .config = 1,
  849. .timeout = ICARUS_TIMEOUT_MS,
  850. .latency = LATENCY_STD,
  851. INTINFO(cmr2_ints) },
  852. #endif
  853. #ifdef USE_BITMAIN
  854. {
  855. .drv = DRIVER_bitmain,
  856. .name = "BMM",
  857. .ident = IDENT_BMM,
  858. #ifdef WIN32
  859. .idVendor = IDVENDOR_FTDI,
  860. .idProduct = 0x6001,
  861. #else
  862. .idVendor = 0x4254,
  863. .idProduct = 0x4153,
  864. #endif
  865. .config = 1,
  866. .timeout = BITMAIN_TIMEOUT_MS,
  867. .latency = 10,
  868. INTINFO(btm_ints) },
  869. {
  870. .drv = DRIVER_bitmain,
  871. .name = "BMS",
  872. .ident = IDENT_BMS,
  873. .idVendor = IDVENDOR_FTDI,
  874. .idProduct = 0x6602,
  875. .config = 1,
  876. .timeout = BITMAIN_TIMEOUT_MS,
  877. .latency = 10,
  878. INTINFO(btm_ints) },
  879. #endif
  880. { DRIVER_MAX, NULL, 0, 0, 0, NULL, NULL, 0, 0, 0, 0, NULL }
  881. };
  882. #define STRBUFLEN 256
  883. static const char *BLANK = "";
  884. static const char *space = " ";
  885. static const char *nodatareturned = "no data returned ";
  886. #if 0 // enable USBDEBUG - only during development testing
  887. static const char *debug_true_str = "true";
  888. static const char *debug_false_str = "false";
  889. static const char *nodevstr = "=NODEV";
  890. #define bool_str(boo) ((boo) ? debug_true_str : debug_false_str)
  891. #define isnodev(err) (NODEV(err) ? nodevstr : BLANK)
  892. #define USBDEBUG(fmt, ...) applog(LOG_WARNING, fmt, ##__VA_ARGS__)
  893. #else
  894. #define USBDEBUG(fmt, ...)
  895. #endif
  896. // For device limits by driver
  897. static struct driver_count {
  898. int count;
  899. int limit;
  900. } drv_count[DRIVER_MAX];
  901. // For device limits by list of bus/dev
  902. static struct usb_busdev {
  903. int bus_number;
  904. int device_address;
  905. #ifdef WIN32
  906. void *resource1;
  907. void *resource2;
  908. #else
  909. int fd;
  910. #endif
  911. } *busdev;
  912. static int busdev_count = 0;
  913. // Total device limit
  914. static int total_count = 0;
  915. static int total_limit = 999999;
  916. struct usb_in_use_list {
  917. struct usb_busdev in_use;
  918. struct usb_in_use_list *prev;
  919. struct usb_in_use_list *next;
  920. };
  921. // List of in use devices
  922. static struct usb_in_use_list *in_use_head = NULL;
  923. static struct usb_in_use_list *blacklist_head = NULL;
  924. struct resource_work {
  925. bool lock;
  926. const char *dname;
  927. uint8_t bus_number;
  928. uint8_t device_address;
  929. struct resource_work *next;
  930. };
  931. // Pending work for the reslock thread
  932. struct resource_work *res_work_head = NULL;
  933. struct resource_reply {
  934. uint8_t bus_number;
  935. uint8_t device_address;
  936. bool got;
  937. struct resource_reply *next;
  938. };
  939. // Replies to lock requests
  940. struct resource_reply *res_reply_head = NULL;
  941. // Some stats need to always be defined
  942. #define SEQ0 0
  943. #define SEQ1 1
  944. // NONE must be 0 - calloced
  945. #define MODE_NONE 0
  946. #define MODE_CTRL_READ (1 << 0)
  947. #define MODE_CTRL_WRITE (1 << 1)
  948. #define MODE_BULK_READ (1 << 2)
  949. #define MODE_BULK_WRITE (1 << 3)
  950. // Set this to 0 to remove stats processing
  951. #define DO_USB_STATS 1
  952. static bool stats_initialised = false;
  953. #if DO_USB_STATS
  954. #define MODE_SEP_STR "+"
  955. #define MODE_NONE_STR "X"
  956. #define MODE_CTRL_READ_STR "cr"
  957. #define MODE_CTRL_WRITE_STR "cw"
  958. #define MODE_BULK_READ_STR "br"
  959. #define MODE_BULK_WRITE_STR "bw"
  960. // One for each CMD, TIMEOUT, ERROR
  961. struct cg_usb_stats_item {
  962. uint64_t count;
  963. double total_delay;
  964. double min_delay;
  965. double max_delay;
  966. struct timeval first;
  967. struct timeval last;
  968. };
  969. #define CMD_CMD 0
  970. #define CMD_TIMEOUT 1
  971. #define CMD_ERROR 2
  972. // One for each C_CMD
  973. struct cg_usb_stats_details {
  974. int seq;
  975. uint32_t modes;
  976. struct cg_usb_stats_item item[CMD_ERROR+1];
  977. };
  978. // One for each device
  979. struct cg_usb_stats {
  980. char *name;
  981. int device_id;
  982. struct cg_usb_stats_details *details;
  983. };
  984. static struct cg_usb_stats *usb_stats = NULL;
  985. static int next_stat = USB_NOSTAT;
  986. #define SECTOMS(s) ((int)((s) * 1000))
  987. #define USB_STATS(sgpu_, sta_, fin_, err_, mode_, cmd_, seq_, tmo_) \
  988. stats(sgpu_, sta_, fin_, err_, mode_, cmd_, seq_, tmo_)
  989. #define STATS_TIMEVAL(tv_) cgtime(tv_)
  990. #define USB_REJECT(sgpu_, mode_) rejected_inc(sgpu_, mode_)
  991. #else
  992. #define USB_STATS(sgpu_, sta_, fin_, err_, mode_, cmd_, seq_, tmo_)
  993. #define STATS_TIMEVAL(tv_)
  994. #define USB_REJECT(sgpu_, mode_)
  995. #endif // DO_USB_STATS
  996. /* Create usb_commands array from USB_PARSE_COMMANDS macro in usbutils.h */
  997. char *usb_commands[] = {
  998. USB_PARSE_COMMANDS(JUMPTABLE)
  999. "Null"
  1000. };
  1001. #ifdef EOL
  1002. #undef EOL
  1003. #endif
  1004. #define EOL "\n"
  1005. static const char *DESDEV = "Device";
  1006. static const char *DESCON = "Config";
  1007. static const char *DESSTR = "String";
  1008. static const char *DESINT = "Interface";
  1009. static const char *DESEP = "Endpoint";
  1010. static const char *DESHID = "HID";
  1011. static const char *DESRPT = "Report";
  1012. static const char *DESPHY = "Physical";
  1013. static const char *DESHUB = "Hub";
  1014. static const char *EPIN = "In: ";
  1015. static const char *EPOUT = "Out: ";
  1016. static const char *EPX = "?: ";
  1017. static const char *CONTROL = "Control";
  1018. static const char *ISOCHRONOUS_X = "Isochronous+?";
  1019. static const char *ISOCHRONOUS_N_X = "Isochronous+None+?";
  1020. static const char *ISOCHRONOUS_N_D = "Isochronous+None+Data";
  1021. static const char *ISOCHRONOUS_N_F = "Isochronous+None+Feedback";
  1022. static const char *ISOCHRONOUS_N_I = "Isochronous+None+Implicit";
  1023. static const char *ISOCHRONOUS_A_X = "Isochronous+Async+?";
  1024. static const char *ISOCHRONOUS_A_D = "Isochronous+Async+Data";
  1025. static const char *ISOCHRONOUS_A_F = "Isochronous+Async+Feedback";
  1026. static const char *ISOCHRONOUS_A_I = "Isochronous+Async+Implicit";
  1027. static const char *ISOCHRONOUS_D_X = "Isochronous+Adaptive+?";
  1028. static const char *ISOCHRONOUS_D_D = "Isochronous+Adaptive+Data";
  1029. static const char *ISOCHRONOUS_D_F = "Isochronous+Adaptive+Feedback";
  1030. static const char *ISOCHRONOUS_D_I = "Isochronous+Adaptive+Implicit";
  1031. static const char *ISOCHRONOUS_S_X = "Isochronous+Sync+?";
  1032. static const char *ISOCHRONOUS_S_D = "Isochronous+Sync+Data";
  1033. static const char *ISOCHRONOUS_S_F = "Isochronous+Sync+Feedback";
  1034. static const char *ISOCHRONOUS_S_I = "Isochronous+Sync+Implicit";
  1035. static const char *BULK = "Bulk";
  1036. static const char *INTERRUPT = "Interrupt";
  1037. static const char *UNKNOWN = "Unknown";
  1038. static const char *destype(uint8_t bDescriptorType)
  1039. {
  1040. switch (bDescriptorType) {
  1041. case LIBUSB_DT_DEVICE:
  1042. return DESDEV;
  1043. case LIBUSB_DT_CONFIG:
  1044. return DESCON;
  1045. case LIBUSB_DT_STRING:
  1046. return DESSTR;
  1047. case LIBUSB_DT_INTERFACE:
  1048. return DESINT;
  1049. case LIBUSB_DT_ENDPOINT:
  1050. return DESEP;
  1051. case LIBUSB_DT_HID:
  1052. return DESHID;
  1053. case LIBUSB_DT_REPORT:
  1054. return DESRPT;
  1055. case LIBUSB_DT_PHYSICAL:
  1056. return DESPHY;
  1057. case LIBUSB_DT_HUB:
  1058. return DESHUB;
  1059. }
  1060. return UNKNOWN;
  1061. }
  1062. static const char *epdir(uint8_t bEndpointAddress)
  1063. {
  1064. switch (bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK) {
  1065. case LIBUSB_ENDPOINT_IN:
  1066. return EPIN;
  1067. case LIBUSB_ENDPOINT_OUT:
  1068. return EPOUT;
  1069. }
  1070. return EPX;
  1071. }
  1072. static const char *epatt(uint8_t bmAttributes)
  1073. {
  1074. switch(bmAttributes & LIBUSB_TRANSFER_TYPE_MASK) {
  1075. case LIBUSB_TRANSFER_TYPE_CONTROL:
  1076. return CONTROL;
  1077. case LIBUSB_TRANSFER_TYPE_BULK:
  1078. return BULK;
  1079. case LIBUSB_TRANSFER_TYPE_INTERRUPT:
  1080. return INTERRUPT;
  1081. case LIBUSB_TRANSFER_TYPE_ISOCHRONOUS:
  1082. switch(bmAttributes & LIBUSB_ISO_SYNC_TYPE_MASK) {
  1083. case LIBUSB_ISO_SYNC_TYPE_NONE:
  1084. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  1085. case LIBUSB_ISO_USAGE_TYPE_DATA:
  1086. return ISOCHRONOUS_N_D;
  1087. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  1088. return ISOCHRONOUS_N_F;
  1089. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  1090. return ISOCHRONOUS_N_I;
  1091. }
  1092. return ISOCHRONOUS_N_X;
  1093. case LIBUSB_ISO_SYNC_TYPE_ASYNC:
  1094. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  1095. case LIBUSB_ISO_USAGE_TYPE_DATA:
  1096. return ISOCHRONOUS_A_D;
  1097. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  1098. return ISOCHRONOUS_A_F;
  1099. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  1100. return ISOCHRONOUS_A_I;
  1101. }
  1102. return ISOCHRONOUS_A_X;
  1103. case LIBUSB_ISO_SYNC_TYPE_ADAPTIVE:
  1104. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  1105. case LIBUSB_ISO_USAGE_TYPE_DATA:
  1106. return ISOCHRONOUS_D_D;
  1107. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  1108. return ISOCHRONOUS_D_F;
  1109. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  1110. return ISOCHRONOUS_D_I;
  1111. }
  1112. return ISOCHRONOUS_D_X;
  1113. case LIBUSB_ISO_SYNC_TYPE_SYNC:
  1114. switch(bmAttributes & LIBUSB_ISO_USAGE_TYPE_MASK) {
  1115. case LIBUSB_ISO_USAGE_TYPE_DATA:
  1116. return ISOCHRONOUS_S_D;
  1117. case LIBUSB_ISO_USAGE_TYPE_FEEDBACK:
  1118. return ISOCHRONOUS_S_F;
  1119. case LIBUSB_ISO_USAGE_TYPE_IMPLICIT:
  1120. return ISOCHRONOUS_S_I;
  1121. }
  1122. return ISOCHRONOUS_S_X;
  1123. }
  1124. return ISOCHRONOUS_X;
  1125. }
  1126. return UNKNOWN;
  1127. }
  1128. static void append(char **buf, char *append, size_t *off, size_t *len)
  1129. {
  1130. int new = strlen(append);
  1131. if ((new + *off) >= *len)
  1132. {
  1133. *len *= 2;
  1134. *buf = realloc(*buf, *len);
  1135. if (unlikely(!*buf))
  1136. quit(1, "USB failed to realloc append");
  1137. }
  1138. strcpy(*buf + *off, append);
  1139. *off += new;
  1140. }
  1141. 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)
  1142. {
  1143. char tmp[512];
  1144. int err;
  1145. err = libusb_set_configuration(handle, cd);
  1146. if (err) {
  1147. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Failed to set config descriptor to %d, err %d",
  1148. (int)count, cd, err);
  1149. append(buf, tmp, off, len);
  1150. return false;
  1151. }
  1152. err = libusb_get_active_config_descriptor(dev, config);
  1153. if (err) {
  1154. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Failed to get active config descriptor set to %d, err %d",
  1155. (int)count, cd, err);
  1156. append(buf, tmp, off, len);
  1157. return false;
  1158. }
  1159. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Set & Got active config descriptor to %d, err %d",
  1160. (int)count, cd, err);
  1161. append(buf, tmp, off, len);
  1162. return true;
  1163. }
  1164. static void usb_full(ssize_t *count, libusb_device *dev, char **buf, size_t *off, size_t *len, int level)
  1165. {
  1166. struct libusb_device_descriptor desc;
  1167. uint8_t bus_number;
  1168. uint8_t device_address;
  1169. struct libusb_device_handle *handle;
  1170. struct libusb_config_descriptor *config;
  1171. const struct libusb_interface_descriptor *idesc;
  1172. const struct libusb_endpoint_descriptor *epdesc;
  1173. unsigned char man[STRBUFLEN+1];
  1174. unsigned char prod[STRBUFLEN+1];
  1175. unsigned char ser[STRBUFLEN+1];
  1176. char tmp[512];
  1177. int err, i, j, k;
  1178. err = libusb_get_device_descriptor(dev, &desc);
  1179. if (opt_usb_list_all && err) {
  1180. snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Failed to get descriptor, err %d",
  1181. (int)(++(*count)), err);
  1182. append(buf, tmp, off, len);
  1183. return;
  1184. }
  1185. bus_number = libusb_get_bus_number(dev);
  1186. device_address = libusb_get_device_address(dev);
  1187. if (!opt_usb_list_all) {
  1188. bool known = false;
  1189. for (i = 0; find_dev[i].drv != DRIVER_MAX; i++)
  1190. if ((find_dev[i].idVendor == desc.idVendor) &&
  1191. (find_dev[i].idProduct == desc.idProduct)) {
  1192. known = true;
  1193. break;
  1194. }
  1195. if (!known)
  1196. return;
  1197. }
  1198. (*count)++;
  1199. if (level == 0) {
  1200. snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Bus %d Device %d ID: %04x:%04x",
  1201. (int)(*count), (int)bus_number, (int)device_address,
  1202. desc.idVendor, desc.idProduct);
  1203. } else {
  1204. snprintf(tmp, sizeof(tmp), EOL ".USB dev %d: Bus %d Device %d Device Descriptor:" EOL "\tLength: %d" EOL
  1205. "\tDescriptor Type: %s" EOL "\tUSB: %04x" EOL "\tDeviceClass: %d" EOL
  1206. "\tDeviceSubClass: %d" EOL "\tDeviceProtocol: %d" EOL "\tMaxPacketSize0: %d" EOL
  1207. "\tidVendor: %04x" EOL "\tidProduct: %04x" EOL "\tDeviceRelease: %x" EOL
  1208. "\tNumConfigurations: %d",
  1209. (int)(*count), (int)bus_number, (int)device_address,
  1210. (int)(desc.bLength), destype(desc.bDescriptorType),
  1211. desc.bcdUSB, (int)(desc.bDeviceClass), (int)(desc.bDeviceSubClass),
  1212. (int)(desc.bDeviceProtocol), (int)(desc.bMaxPacketSize0),
  1213. desc.idVendor, desc.idProduct, desc.bcdDevice,
  1214. (int)(desc.bNumConfigurations));
  1215. }
  1216. append(buf, tmp, off, len);
  1217. err = libusb_open(dev, &handle);
  1218. if (err) {
  1219. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Failed to open, err %d", (int)(*count), err);
  1220. append(buf, tmp, off, len);
  1221. return;
  1222. }
  1223. err = libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, man, STRBUFLEN);
  1224. if (err < 0)
  1225. snprintf((char *)man, sizeof(man), "** err:(%d) %s", err, libusb_error_name(err));
  1226. err = libusb_get_string_descriptor_ascii(handle, desc.iProduct, prod, STRBUFLEN);
  1227. if (err < 0)
  1228. snprintf((char *)prod, sizeof(prod), "** err:(%d) %s", err, libusb_error_name(err));
  1229. if (level == 0) {
  1230. libusb_close(handle);
  1231. snprintf(tmp, sizeof(tmp), EOL " Manufacturer: '%s'" EOL " Product: '%s'", man, prod);
  1232. append(buf, tmp, off, len);
  1233. return;
  1234. }
  1235. if (libusb_kernel_driver_active(handle, 0) == 1) {
  1236. snprintf(tmp, sizeof(tmp), EOL " * dev %d: kernel attached", (int)(*count));
  1237. append(buf, tmp, off, len);
  1238. }
  1239. err = libusb_get_active_config_descriptor(dev, &config);
  1240. if (err) {
  1241. if (!setgetdes(*count, dev, handle, &config, 1, buf, off, len)
  1242. && !setgetdes(*count, dev, handle, &config, 0, buf, off, len)) {
  1243. libusb_close(handle);
  1244. snprintf(tmp, sizeof(tmp), EOL " ** dev %d: Failed to set config descriptor to %d or %d",
  1245. (int)(*count), 1, 0);
  1246. append(buf, tmp, off, len);
  1247. return;
  1248. }
  1249. }
  1250. snprintf(tmp, sizeof(tmp), EOL " dev %d: Active Config:" EOL "\tDescriptorType: %s" EOL
  1251. "\tNumInterfaces: %d" EOL "\tConfigurationValue: %d" EOL
  1252. "\tAttributes: %d" EOL "\tMaxPower: %d",
  1253. (int)(*count), destype(config->bDescriptorType),
  1254. (int)(config->bNumInterfaces), (int)(config->iConfiguration),
  1255. (int)(config->bmAttributes), (int)(config->MaxPower));
  1256. append(buf, tmp, off, len);
  1257. for (i = 0; i < (int)(config->bNumInterfaces); i++) {
  1258. for (j = 0; j < config->interface[i].num_altsetting; j++) {
  1259. idesc = &(config->interface[i].altsetting[j]);
  1260. snprintf(tmp, sizeof(tmp), EOL " _dev %d: Interface Descriptor %d:" EOL
  1261. "\tDescriptorType: %s" EOL "\tInterfaceNumber: %d" EOL
  1262. "\tNumEndpoints: %d" EOL "\tInterfaceClass: %d" EOL
  1263. "\tInterfaceSubClass: %d" EOL "\tInterfaceProtocol: %d",
  1264. (int)(*count), j, destype(idesc->bDescriptorType),
  1265. (int)(idesc->bInterfaceNumber),
  1266. (int)(idesc->bNumEndpoints),
  1267. (int)(idesc->bInterfaceClass),
  1268. (int)(idesc->bInterfaceSubClass),
  1269. (int)(idesc->bInterfaceProtocol));
  1270. append(buf, tmp, off, len);
  1271. for (k = 0; k < (int)(idesc->bNumEndpoints); k++) {
  1272. epdesc = &(idesc->endpoint[k]);
  1273. snprintf(tmp, sizeof(tmp), EOL " __dev %d: Interface %d Endpoint %d:" EOL
  1274. "\tDescriptorType: %s" EOL
  1275. "\tEndpointAddress: %s0x%x" EOL
  1276. "\tAttributes: %s" EOL "\tMaxPacketSize: %d" EOL
  1277. "\tInterval: %d" EOL "\tRefresh: %d",
  1278. (int)(*count), (int)(idesc->bInterfaceNumber), k,
  1279. destype(epdesc->bDescriptorType),
  1280. epdir(epdesc->bEndpointAddress),
  1281. (int)(epdesc->bEndpointAddress),
  1282. epatt(epdesc->bmAttributes),
  1283. epdesc->wMaxPacketSize,
  1284. (int)(epdesc->bInterval),
  1285. (int)(epdesc->bRefresh));
  1286. append(buf, tmp, off, len);
  1287. }
  1288. }
  1289. }
  1290. libusb_free_config_descriptor(config);
  1291. config = NULL;
  1292. err = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, ser, STRBUFLEN);
  1293. if (err < 0)
  1294. snprintf((char *)ser, sizeof(ser), "** err:(%d) %s", err, libusb_error_name(err));
  1295. snprintf(tmp, sizeof(tmp), EOL " dev %d: More Info:" EOL "\tManufacturer: '%s'" EOL
  1296. "\tProduct: '%s'" EOL "\tSerial '%s'",
  1297. (int)(*count), man, prod, ser);
  1298. append(buf, tmp, off, len);
  1299. libusb_close(handle);
  1300. }
  1301. // Function to dump all USB devices
  1302. void usb_all(int level)
  1303. {
  1304. libusb_device **list;
  1305. ssize_t count, i, j;
  1306. char *buf;
  1307. size_t len, off;
  1308. count = libusb_get_device_list(NULL, &list);
  1309. if (count < 0) {
  1310. applog(LOG_ERR, "USB all: failed, err:(%d) %s", (int)count, libusb_error_name((int)count));
  1311. return;
  1312. }
  1313. if (count == 0)
  1314. applog(LOG_WARNING, "USB all: found no devices");
  1315. else
  1316. {
  1317. len = 10000;
  1318. buf = malloc(len+1);
  1319. if (unlikely(!buf))
  1320. quit(1, "USB failed to malloc buf in usb_all");
  1321. sprintf(buf, "USB all: found %d devices", (int)count);
  1322. off = strlen(buf);
  1323. if (!opt_usb_list_all)
  1324. append(&buf, " - listing known devices", &off, &len);
  1325. j = -1;
  1326. for (i = 0; i < count; i++)
  1327. usb_full(&j, list[i], &buf, &off, &len, level);
  1328. _applog(LOG_WARNING, buf, false);
  1329. free(buf);
  1330. if (j == -1)
  1331. applog(LOG_WARNING, "No known USB devices");
  1332. else
  1333. applog(LOG_WARNING, "%d %sUSB devices",
  1334. (int)(++j), opt_usb_list_all ? BLANK : "known ");
  1335. }
  1336. libusb_free_device_list(list, 1);
  1337. }
  1338. static void cgusb_check_init()
  1339. {
  1340. mutex_lock(&cgusb_lock);
  1341. if (stats_initialised == false) {
  1342. // N.B. environment LIBUSB_DEBUG also sets libusb_set_debug()
  1343. if (opt_usbdump >= 0) {
  1344. libusb_set_debug(NULL, opt_usbdump);
  1345. usb_all(opt_usbdump);
  1346. }
  1347. stats_initialised = true;
  1348. }
  1349. mutex_unlock(&cgusb_lock);
  1350. }
  1351. const char *usb_cmdname(enum usb_cmds cmd)
  1352. {
  1353. cgusb_check_init();
  1354. return usb_commands[cmd];
  1355. }
  1356. void usb_applog(struct cgpu_info *cgpu, enum usb_cmds cmd, char *msg, int amount, int err)
  1357. {
  1358. if (msg && !*msg)
  1359. msg = NULL;
  1360. if (!msg && amount == 0 && err == LIBUSB_SUCCESS)
  1361. msg = (char *)nodatareturned;
  1362. applog(LOG_ERR, "%s%i: %s failed%s%s (err=%d amt=%d)",
  1363. cgpu->drv->name, cgpu->device_id,
  1364. usb_cmdname(cmd),
  1365. msg ? space : BLANK, msg ? msg : BLANK,
  1366. err, amount);
  1367. }
  1368. #ifdef WIN32
  1369. static void in_use_store_ress(uint8_t bus_number, uint8_t device_address, void *resource1, void *resource2)
  1370. {
  1371. struct usb_in_use_list *in_use_tmp;
  1372. bool found = false, empty = true;
  1373. mutex_lock(&cgusb_lock);
  1374. in_use_tmp = in_use_head;
  1375. while (in_use_tmp) {
  1376. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  1377. in_use_tmp->in_use.device_address == (int)device_address) {
  1378. found = true;
  1379. if (in_use_tmp->in_use.resource1)
  1380. empty = false;
  1381. in_use_tmp->in_use.resource1 = resource1;
  1382. if (in_use_tmp->in_use.resource2)
  1383. empty = false;
  1384. in_use_tmp->in_use.resource2 = resource2;
  1385. break;
  1386. }
  1387. in_use_tmp = in_use_tmp->next;
  1388. }
  1389. mutex_unlock(&cgusb_lock);
  1390. if (found == false)
  1391. applog(LOG_ERR, "FAIL: USB store_ress not found (%d:%d)",
  1392. (int)bus_number, (int)device_address);
  1393. if (empty == false)
  1394. applog(LOG_ERR, "FAIL: USB store_ress not empty (%d:%d)",
  1395. (int)bus_number, (int)device_address);
  1396. }
  1397. static void in_use_get_ress(uint8_t bus_number, uint8_t device_address, void **resource1, void **resource2)
  1398. {
  1399. struct usb_in_use_list *in_use_tmp;
  1400. bool found = false, empty = false;
  1401. mutex_lock(&cgusb_lock);
  1402. in_use_tmp = in_use_head;
  1403. while (in_use_tmp) {
  1404. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  1405. in_use_tmp->in_use.device_address == (int)device_address) {
  1406. found = true;
  1407. if (!in_use_tmp->in_use.resource1)
  1408. empty = true;
  1409. *resource1 = in_use_tmp->in_use.resource1;
  1410. in_use_tmp->in_use.resource1 = NULL;
  1411. if (!in_use_tmp->in_use.resource2)
  1412. empty = true;
  1413. *resource2 = in_use_tmp->in_use.resource2;
  1414. in_use_tmp->in_use.resource2 = NULL;
  1415. break;
  1416. }
  1417. in_use_tmp = in_use_tmp->next;
  1418. }
  1419. mutex_unlock(&cgusb_lock);
  1420. if (found == false)
  1421. applog(LOG_ERR, "FAIL: USB get_lock not found (%d:%d)",
  1422. (int)bus_number, (int)device_address);
  1423. if (empty == true)
  1424. applog(LOG_ERR, "FAIL: USB get_lock empty (%d:%d)",
  1425. (int)bus_number, (int)device_address);
  1426. }
  1427. #else
  1428. static void in_use_store_fd(uint8_t bus_number, uint8_t device_address, int fd)
  1429. {
  1430. struct usb_in_use_list *in_use_tmp;
  1431. bool found = false;
  1432. mutex_lock(&cgusb_lock);
  1433. in_use_tmp = in_use_head;
  1434. while (in_use_tmp) {
  1435. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  1436. in_use_tmp->in_use.device_address == (int)device_address) {
  1437. found = true;
  1438. in_use_tmp->in_use.fd = fd;
  1439. break;
  1440. }
  1441. in_use_tmp = in_use_tmp->next;
  1442. }
  1443. mutex_unlock(&cgusb_lock);
  1444. if (found == false) {
  1445. applog(LOG_ERR, "FAIL: USB store_fd not found (%d:%d)",
  1446. (int)bus_number, (int)device_address);
  1447. }
  1448. }
  1449. static int in_use_get_fd(uint8_t bus_number, uint8_t device_address)
  1450. {
  1451. struct usb_in_use_list *in_use_tmp;
  1452. bool found = false;
  1453. int fd = -1;
  1454. mutex_lock(&cgusb_lock);
  1455. in_use_tmp = in_use_head;
  1456. while (in_use_tmp) {
  1457. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  1458. in_use_tmp->in_use.device_address == (int)device_address) {
  1459. found = true;
  1460. fd = in_use_tmp->in_use.fd;
  1461. break;
  1462. }
  1463. in_use_tmp = in_use_tmp->next;
  1464. }
  1465. mutex_unlock(&cgusb_lock);
  1466. if (found == false) {
  1467. applog(LOG_ERR, "FAIL: USB get_lock not found (%d:%d)",
  1468. (int)bus_number, (int)device_address);
  1469. }
  1470. return fd;
  1471. }
  1472. #endif
  1473. static bool _in_use(struct usb_in_use_list *head, uint8_t bus_number,
  1474. uint8_t device_address)
  1475. {
  1476. struct usb_in_use_list *in_use_tmp;
  1477. bool ret = false;
  1478. in_use_tmp = head;
  1479. while (in_use_tmp) {
  1480. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  1481. in_use_tmp->in_use.device_address == (int)device_address) {
  1482. ret = true;
  1483. break;
  1484. }
  1485. in_use_tmp = in_use_tmp->next;
  1486. if (in_use_tmp == head)
  1487. break;
  1488. }
  1489. return ret;
  1490. }
  1491. static bool __is_in_use(uint8_t bus_number, uint8_t device_address)
  1492. {
  1493. if (_in_use(in_use_head, bus_number, device_address))
  1494. return true;
  1495. if (_in_use(blacklist_head, bus_number, device_address))
  1496. return true;
  1497. return false;
  1498. }
  1499. static bool is_in_use_bd(uint8_t bus_number, uint8_t device_address)
  1500. {
  1501. bool ret;
  1502. mutex_lock(&cgusb_lock);
  1503. ret = __is_in_use(bus_number, device_address);
  1504. mutex_unlock(&cgusb_lock);
  1505. return ret;
  1506. }
  1507. static bool is_in_use(libusb_device *dev)
  1508. {
  1509. return is_in_use_bd(libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1510. }
  1511. static bool how_in_use(uint8_t bus_number, uint8_t device_address, bool *blacklisted)
  1512. {
  1513. bool ret;
  1514. mutex_lock(&cgusb_lock);
  1515. ret = _in_use(in_use_head, bus_number, device_address);
  1516. if (!ret) {
  1517. if (_in_use(blacklist_head, bus_number, device_address))
  1518. *blacklisted = true;
  1519. }
  1520. mutex_unlock(&cgusb_lock);
  1521. return ret;
  1522. }
  1523. void usb_list(void)
  1524. {
  1525. struct libusb_device_descriptor desc;
  1526. struct libusb_device_handle *handle;
  1527. uint8_t bus_number;
  1528. uint8_t device_address;
  1529. libusb_device **list;
  1530. ssize_t count, i, j;
  1531. int err, total = 0;
  1532. count = libusb_get_device_list(NULL, &list);
  1533. if (count < 0) {
  1534. applog(LOG_ERR, "USB list: failed, err:(%d) %s", (int)count, libusb_error_name((int)count));
  1535. return;
  1536. }
  1537. if (count == 0) {
  1538. applog(LOG_WARNING, "USB list: found no devices");
  1539. return;
  1540. }
  1541. for (i = 0; i < count; i++) {
  1542. bool known = false, blacklisted = false, active;
  1543. unsigned char manuf[256], prod[256];
  1544. libusb_device *dev = list[i];
  1545. err = libusb_get_device_descriptor(dev, &desc);
  1546. if (err) {
  1547. applog(LOG_WARNING, "USB list: Failed to get descriptor %d", (int)i);
  1548. break;
  1549. }
  1550. bus_number = libusb_get_bus_number(dev);
  1551. device_address = libusb_get_device_address(dev);
  1552. for (j = 0; find_dev[j].drv != DRIVER_MAX; j++) {
  1553. if ((find_dev[j].idVendor == desc.idVendor) &&
  1554. (find_dev[j].idProduct == desc.idProduct)) {
  1555. known = true;
  1556. break;
  1557. }
  1558. }
  1559. if (!known)
  1560. continue;
  1561. err = libusb_open(dev, &handle);
  1562. if (err) {
  1563. applog(LOG_WARNING, "USB list: Failed to open %d", (int)i);
  1564. break;
  1565. }
  1566. libusb_get_string_descriptor_ascii(handle, desc.iManufacturer, manuf, 255);
  1567. libusb_get_string_descriptor_ascii(handle, desc.iProduct, prod, 255);
  1568. total++;
  1569. active = how_in_use(bus_number, device_address, &blacklisted);
  1570. simplelog(LOG_WARNING, "Bus %u Device %u ID: %04x:%04x %s %s %sactive %s",
  1571. bus_number, device_address, desc.idVendor, desc.idProduct,
  1572. manuf, prod, active ? "" : "in", blacklisted ? "blacklisted" : "");
  1573. }
  1574. libusb_free_device_list(list, 1);
  1575. simplelog(LOG_WARNING, "%d total known USB device%s", total, total > 1 ? "s": "");
  1576. }
  1577. static void add_in_use(uint8_t bus_number, uint8_t device_address, bool blacklist)
  1578. {
  1579. struct usb_in_use_list *in_use_tmp, **head;
  1580. bool found = false;
  1581. mutex_lock(&cgusb_lock);
  1582. if (unlikely(!blacklist && __is_in_use(bus_number, device_address))) {
  1583. found = true;
  1584. goto nofway;
  1585. }
  1586. if (blacklist)
  1587. head = &blacklist_head;
  1588. else
  1589. head = &in_use_head;
  1590. in_use_tmp = calloc(1, sizeof(*in_use_tmp));
  1591. if (unlikely(!in_use_tmp))
  1592. quit(1, "USB failed to calloc in_use_tmp");
  1593. in_use_tmp->in_use.bus_number = (int)bus_number;
  1594. in_use_tmp->in_use.device_address = (int)device_address;
  1595. in_use_tmp->next = in_use_head;
  1596. if (*head)
  1597. (*head)->prev = in_use_tmp;
  1598. *head = in_use_tmp;
  1599. nofway:
  1600. mutex_unlock(&cgusb_lock);
  1601. if (found)
  1602. applog(LOG_ERR, "FAIL: USB add already in use (%d:%d)",
  1603. (int)bus_number, (int)device_address);
  1604. }
  1605. static void __remove_in_use(uint8_t bus_number, uint8_t device_address, bool blacklist)
  1606. {
  1607. struct usb_in_use_list *in_use_tmp, **head;
  1608. bool found = false;
  1609. mutex_lock(&cgusb_lock);
  1610. if (blacklist)
  1611. head = &blacklist_head;
  1612. else
  1613. head = &in_use_head;
  1614. in_use_tmp = *head;
  1615. while (in_use_tmp) {
  1616. if (in_use_tmp->in_use.bus_number == (int)bus_number &&
  1617. in_use_tmp->in_use.device_address == (int)device_address) {
  1618. found = true;
  1619. if (in_use_tmp == *head) {
  1620. *head = (*head)->next;
  1621. if (*head)
  1622. (*head)->prev = NULL;
  1623. } else {
  1624. in_use_tmp->prev->next = in_use_tmp->next;
  1625. if (in_use_tmp->next)
  1626. in_use_tmp->next->prev = in_use_tmp->prev;
  1627. }
  1628. free(in_use_tmp);
  1629. break;
  1630. }
  1631. in_use_tmp = in_use_tmp->next;
  1632. if (in_use_tmp == *head)
  1633. break;
  1634. }
  1635. mutex_unlock(&cgusb_lock);
  1636. if (!found) {
  1637. applog(LOG_ERR, "FAIL: USB remove not already in use (%d:%d)",
  1638. (int)bus_number, (int)device_address);
  1639. }
  1640. }
  1641. static void remove_in_use(uint8_t bus_number, uint8_t device_address)
  1642. {
  1643. __remove_in_use(bus_number, device_address, false);
  1644. }
  1645. static bool cgminer_usb_lock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  1646. {
  1647. struct resource_work *res_work;
  1648. bool ret;
  1649. applog(LOG_DEBUG, "USB lock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
  1650. res_work = calloc(1, sizeof(*res_work));
  1651. if (unlikely(!res_work))
  1652. quit(1, "USB failed to calloc lock res_work");
  1653. res_work->lock = true;
  1654. res_work->dname = (const char *)(drv->dname);
  1655. res_work->bus_number = bus_number;
  1656. res_work->device_address = device_address;
  1657. mutex_lock(&cgusbres_lock);
  1658. res_work->next = res_work_head;
  1659. res_work_head = res_work;
  1660. mutex_unlock(&cgusbres_lock);
  1661. cgsem_post(&usb_resource_sem);
  1662. // TODO: add a timeout fail - restart the resource thread?
  1663. while (true) {
  1664. cgsleep_ms(50);
  1665. mutex_lock(&cgusbres_lock);
  1666. if (res_reply_head) {
  1667. struct resource_reply *res_reply_prev = NULL;
  1668. struct resource_reply *res_reply = res_reply_head;
  1669. while (res_reply) {
  1670. if (res_reply->bus_number == bus_number &&
  1671. res_reply->device_address == device_address) {
  1672. if (res_reply_prev)
  1673. res_reply_prev->next = res_reply->next;
  1674. else
  1675. res_reply_head = res_reply->next;
  1676. mutex_unlock(&cgusbres_lock);
  1677. ret = res_reply->got;
  1678. free(res_reply);
  1679. return ret;
  1680. }
  1681. res_reply_prev = res_reply;
  1682. res_reply = res_reply->next;
  1683. }
  1684. }
  1685. mutex_unlock(&cgusbres_lock);
  1686. }
  1687. }
  1688. static bool cgminer_usb_lock(struct device_drv *drv, libusb_device *dev)
  1689. {
  1690. return cgminer_usb_lock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1691. }
  1692. static void cgminer_usb_unlock_bd(struct device_drv *drv, uint8_t bus_number, uint8_t device_address)
  1693. {
  1694. struct resource_work *res_work;
  1695. applog(LOG_DEBUG, "USB unlock %s %d-%d", drv->dname, (int)bus_number, (int)device_address);
  1696. res_work = calloc(1, sizeof(*res_work));
  1697. if (unlikely(!res_work))
  1698. quit(1, "USB failed to calloc unlock res_work");
  1699. res_work->lock = false;
  1700. res_work->dname = (const char *)(drv->dname);
  1701. res_work->bus_number = bus_number;
  1702. res_work->device_address = device_address;
  1703. mutex_lock(&cgusbres_lock);
  1704. res_work->next = res_work_head;
  1705. res_work_head = res_work;
  1706. mutex_unlock(&cgusbres_lock);
  1707. cgsem_post(&usb_resource_sem);
  1708. return;
  1709. }
  1710. static void cgminer_usb_unlock(struct device_drv *drv, libusb_device *dev)
  1711. {
  1712. cgminer_usb_unlock_bd(drv, libusb_get_bus_number(dev), libusb_get_device_address(dev));
  1713. }
  1714. static struct cg_usb_device *free_cgusb(struct cg_usb_device *cgusb)
  1715. {
  1716. applog(LOG_DEBUG, "USB free %s", cgusb->found->name);
  1717. if (cgusb->serial_string && cgusb->serial_string != BLANK)
  1718. free(cgusb->serial_string);
  1719. if (cgusb->manuf_string && cgusb->manuf_string != BLANK)
  1720. free(cgusb->manuf_string);
  1721. if (cgusb->prod_string && cgusb->prod_string != BLANK)
  1722. free(cgusb->prod_string);
  1723. if (cgusb->descriptor)
  1724. free(cgusb->descriptor);
  1725. free(cgusb->found);
  1726. free(cgusb);
  1727. return NULL;
  1728. }
  1729. static void _usb_uninit(struct cgpu_info *cgpu)
  1730. {
  1731. int ifinfo;
  1732. // May have happened already during a failed initialisation
  1733. // if release_cgpu() was called due to a USB NODEV(err)
  1734. if (!cgpu->usbdev)
  1735. return;
  1736. applog(LOG_DEBUG, "USB uninit %s%i",
  1737. cgpu->drv->name, cgpu->device_id);
  1738. if (cgpu->usbdev->handle) {
  1739. for (ifinfo = cgpu->usbdev->found->intinfo_count - 1; ifinfo >= 0; ifinfo--) {
  1740. libusb_release_interface(cgpu->usbdev->handle,
  1741. THISIF(cgpu->usbdev->found, ifinfo));
  1742. }
  1743. #ifdef LINUX
  1744. libusb_attach_kernel_driver(cgpu->usbdev->handle, THISIF(cgpu->usbdev->found, ifinfo));
  1745. #endif
  1746. cg_wlock(&cgusb_fd_lock);
  1747. libusb_close(cgpu->usbdev->handle);
  1748. cgpu->usbdev->handle = NULL;
  1749. cg_wunlock(&cgusb_fd_lock);
  1750. }
  1751. cgpu->usbdev = free_cgusb(cgpu->usbdev);
  1752. }
  1753. void usb_uninit(struct cgpu_info *cgpu)
  1754. {
  1755. int pstate;
  1756. DEVWLOCK(cgpu, pstate);
  1757. _usb_uninit(cgpu);
  1758. DEVWUNLOCK(cgpu, pstate);
  1759. }
  1760. /* We have dropped the read devlock before entering this function but we pick
  1761. * up the write lock to prevent any attempts to work on dereferenced code once
  1762. * the nodev flag has been set. */
  1763. static bool __release_cgpu(struct cgpu_info *cgpu)
  1764. {
  1765. struct cg_usb_device *cgusb = cgpu->usbdev;
  1766. bool initted = cgpu->usbinfo.initialised;
  1767. struct cgpu_info *lookcgpu;
  1768. int i;
  1769. // It has already been done
  1770. if (cgpu->usbinfo.nodev)
  1771. return false;
  1772. applog(LOG_DEBUG, "USB release %s%i",
  1773. cgpu->drv->name, cgpu->device_id);
  1774. if (initted) {
  1775. zombie_devs++;
  1776. total_count--;
  1777. drv_count[cgpu->drv->drv_id].count--;
  1778. }
  1779. cgpu->usbinfo.nodev = true;
  1780. cgpu->usbinfo.nodev_count++;
  1781. cgtime(&cgpu->usbinfo.last_nodev);
  1782. // Any devices sharing the same USB device should be marked also
  1783. for (i = 0; i < total_devices; i++) {
  1784. lookcgpu = get_devices(i);
  1785. if (lookcgpu != cgpu && lookcgpu->usbdev == cgusb) {
  1786. if (initted) {
  1787. total_count--;
  1788. drv_count[lookcgpu->drv->drv_id].count--;
  1789. }
  1790. lookcgpu->usbinfo.nodev = true;
  1791. lookcgpu->usbinfo.nodev_count++;
  1792. cg_memcpy(&(lookcgpu->usbinfo.last_nodev),
  1793. &(cgpu->usbinfo.last_nodev), sizeof(struct timeval));
  1794. lookcgpu->usbdev = NULL;
  1795. }
  1796. }
  1797. _usb_uninit(cgpu);
  1798. return true;
  1799. }
  1800. static void release_cgpu(struct cgpu_info *cgpu)
  1801. {
  1802. if (__release_cgpu(cgpu))
  1803. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1804. }
  1805. void blacklist_cgpu(struct cgpu_info *cgpu)
  1806. {
  1807. if (cgpu->blacklisted) {
  1808. applog(LOG_WARNING, "Device already blacklisted");
  1809. return;
  1810. }
  1811. cgpu->blacklisted = true;
  1812. add_in_use(cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address, true);
  1813. if (__release_cgpu(cgpu))
  1814. cgminer_usb_unlock_bd(cgpu->drv, cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address);
  1815. }
  1816. void whitelist_cgpu(struct cgpu_info *cgpu)
  1817. {
  1818. if (!cgpu->blacklisted) {
  1819. applog(LOG_WARNING, "Device not blacklisted");
  1820. return;
  1821. }
  1822. __remove_in_use(cgpu->usbinfo.bus_number, cgpu->usbinfo.device_address, true);
  1823. cgpu->blacklisted = false;
  1824. }
  1825. /*
  1826. * Force a NODEV on a device so it goes back to hotplug
  1827. */
  1828. void usb_nodev(struct cgpu_info *cgpu)
  1829. {
  1830. int pstate;
  1831. DEVWLOCK(cgpu, pstate);
  1832. release_cgpu(cgpu);
  1833. DEVWUNLOCK(cgpu, pstate);
  1834. }
  1835. /*
  1836. * Use the same usbdev thus locking is across all related devices
  1837. */
  1838. struct cgpu_info *usb_copy_cgpu(struct cgpu_info *orig)
  1839. {
  1840. struct cgpu_info *copy;
  1841. int pstate;
  1842. DEVWLOCK(orig, pstate);
  1843. copy = calloc(1, sizeof(*copy));
  1844. if (unlikely(!copy))
  1845. quit(1, "Failed to calloc cgpu for %s in usb_copy_cgpu", orig->drv->dname);
  1846. copy->name = orig->name;
  1847. copy->drv = copy_drv(orig->drv);
  1848. copy->deven = orig->deven;
  1849. copy->threads = orig->threads;
  1850. copy->usbdev = orig->usbdev;
  1851. cg_memcpy(&(copy->usbinfo), &(orig->usbinfo), sizeof(copy->usbinfo));
  1852. copy->usbinfo.nodev = (copy->usbdev == NULL);
  1853. DEVWUNLOCK(orig, pstate);
  1854. return copy;
  1855. }
  1856. struct cgpu_info *usb_alloc_cgpu(struct device_drv *drv, int threads)
  1857. {
  1858. struct cgpu_info *cgpu = calloc(1, sizeof(*cgpu));
  1859. if (unlikely(!cgpu))
  1860. quit(1, "Failed to calloc cgpu for %s in usb_alloc_cgpu", drv->dname);
  1861. cgpu->drv = drv;
  1862. cgpu->deven = DEV_ENABLED;
  1863. cgpu->threads = threads;
  1864. cgpu->usbinfo.nodev = true;
  1865. cglock_init(&cgpu->usbinfo.devlock);
  1866. return cgpu;
  1867. }
  1868. struct cgpu_info *usb_free_cgpu(struct cgpu_info *cgpu)
  1869. {
  1870. if (cgpu->drv->copy)
  1871. free(cgpu->drv);
  1872. free(cgpu->device_path);
  1873. free(cgpu);
  1874. return NULL;
  1875. }
  1876. #define USB_INIT_FAIL 0
  1877. #define USB_INIT_OK 1
  1878. #define USB_INIT_IGNORE 2
  1879. static int _usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found)
  1880. {
  1881. unsigned char man[STRBUFLEN+1], prod[STRBUFLEN+1];
  1882. struct cg_usb_device *cgusb = NULL;
  1883. struct libusb_config_descriptor *config = NULL;
  1884. const struct libusb_interface_descriptor *idesc;
  1885. const struct libusb_endpoint_descriptor *epdesc;
  1886. unsigned char strbuf[STRBUFLEN+1];
  1887. char devpath[32];
  1888. char devstr[STRBUFLEN+1];
  1889. int err, ifinfo, epinfo, alt, epnum, pstate;
  1890. int bad = USB_INIT_FAIL;
  1891. int cfg, claimed = 0, i;
  1892. DEVWLOCK(cgpu, pstate);
  1893. cgpu->usbinfo.bus_number = libusb_get_bus_number(dev);
  1894. cgpu->usbinfo.device_address = libusb_get_device_address(dev);
  1895. if (found->intinfo_count > 1) {
  1896. snprintf(devpath, sizeof(devpath), "%d:%d-i%d",
  1897. (int)(cgpu->usbinfo.bus_number),
  1898. (int)(cgpu->usbinfo.device_address),
  1899. THISIF(found, 0));
  1900. } else {
  1901. snprintf(devpath, sizeof(devpath), "%d:%d",
  1902. (int)(cgpu->usbinfo.bus_number),
  1903. (int)(cgpu->usbinfo.device_address));
  1904. }
  1905. cgpu->device_path = strdup(devpath);
  1906. snprintf(devstr, sizeof(devstr), "- %s device %s", found->name, devpath);
  1907. cgusb = calloc(1, sizeof(*cgusb));
  1908. if (unlikely(!cgusb))
  1909. quit(1, "USB failed to calloc _usb_init cgusb");
  1910. cgusb->found = found;
  1911. if (found->idVendor == IDVENDOR_FTDI)
  1912. cgusb->usb_type = USB_TYPE_FTDI;
  1913. cgusb->ident = found->ident;
  1914. cgusb->descriptor = calloc(1, sizeof(*(cgusb->descriptor)));
  1915. if (unlikely(!cgusb->descriptor))
  1916. quit(1, "USB failed to calloc _usb_init cgusb descriptor");
  1917. err = libusb_get_device_descriptor(dev, cgusb->descriptor);
  1918. if (err) {
  1919. applog(LOG_DEBUG,
  1920. "USB init failed to get descriptor, err %d %s",
  1921. err, devstr);
  1922. goto dame;
  1923. }
  1924. cg_wlock(&cgusb_fd_lock);
  1925. err = libusb_open(dev, &(cgusb->handle));
  1926. cg_wunlock(&cgusb_fd_lock);
  1927. if (err) {
  1928. switch (err) {
  1929. case LIBUSB_ERROR_ACCESS:
  1930. applog(LOG_ERR,
  1931. "USB init, open device failed, err %d, "
  1932. "you don't have privilege to access %s",
  1933. err, devstr);
  1934. applog(LOG_ERR, "See README file included for help");
  1935. break;
  1936. #ifdef WIN32
  1937. // Windows specific message
  1938. case LIBUSB_ERROR_NOT_SUPPORTED:
  1939. applog(LOG_ERR, "USB init, open device failed, err %d, ", err);
  1940. applog(LOG_ERR, "You need to install a WinUSB driver for %s", devstr);
  1941. applog(LOG_ERR, "And associate %s with WinUSB using zadig", devstr);
  1942. applog(LOG_ERR, "See README.txt file included for help");
  1943. break;
  1944. #endif
  1945. default:
  1946. applog(LOG_DEBUG,
  1947. "USB init, open failed, err %d %s",
  1948. err, devstr);
  1949. }
  1950. goto dame;
  1951. }
  1952. #ifdef LINUX
  1953. for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++) {
  1954. if (libusb_kernel_driver_active(cgusb->handle, THISIF(found, ifinfo)) == 1) {
  1955. applog(LOG_DEBUG, "USB init, kernel attached ... %s", devstr);
  1956. err = libusb_detach_kernel_driver(cgusb->handle, THISIF(found, ifinfo));
  1957. if (err == 0) {
  1958. applog(LOG_DEBUG,
  1959. "USB init, kernel detached ifinfo %d interface %d"
  1960. " successfully %s",
  1961. ifinfo, THISIF(found, ifinfo), devstr);
  1962. } else {
  1963. applog(LOG_WARNING,
  1964. "USB init, kernel detach ifinfo %d interface %d failed,"
  1965. " err %d in use? %s",
  1966. ifinfo, THISIF(found, ifinfo), err, devstr);
  1967. goto nokernel;
  1968. }
  1969. }
  1970. }
  1971. #endif
  1972. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  1973. cgusb->descriptor->iManufacturer,
  1974. man, STRBUFLEN);
  1975. if (err < 0) {
  1976. applog(LOG_DEBUG,
  1977. "USB init, failed to get iManufacturer, err %d %s",
  1978. err, devstr);
  1979. goto cldame;
  1980. }
  1981. if (found->iManufacturer) {
  1982. if (strcasecmp((char *)man, found->iManufacturer)) {
  1983. applog(LOG_DEBUG, "USB init, iManufacturer mismatch %s",
  1984. devstr);
  1985. applog(LOG_DEBUG, "Found %s vs %s", man, found->iManufacturer);
  1986. bad = USB_INIT_IGNORE;
  1987. goto cldame;
  1988. }
  1989. } else {
  1990. for (i = 0; find_dev[i].drv != DRIVER_MAX; i++) {
  1991. const char *iManufacturer = find_dev[i].iManufacturer;
  1992. /* If other drivers has an iManufacturer set that match,
  1993. * don't try to claim this device. */
  1994. if (!iManufacturer)
  1995. continue;
  1996. if (!strcasecmp((char *)man, iManufacturer)) {
  1997. applog(LOG_DEBUG, "USB init, alternative iManufacturer match %s",
  1998. devstr);
  1999. applog(LOG_DEBUG, "Found %s", iManufacturer);
  2000. bad = USB_INIT_IGNORE;
  2001. goto cldame;
  2002. }
  2003. }
  2004. }
  2005. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  2006. cgusb->descriptor->iProduct,
  2007. prod, STRBUFLEN);
  2008. if (err < 0) {
  2009. applog(LOG_DEBUG,
  2010. "USB init, failed to get iProduct, err %d %s",
  2011. err, devstr);
  2012. goto cldame;
  2013. }
  2014. if (found->iProduct) {
  2015. if (strcasecmp((char *)prod, found->iProduct)) {
  2016. applog(LOG_DEBUG, "USB init, iProduct mismatch %s",
  2017. devstr);
  2018. applog(LOG_DEBUG, "Found %s vs %s", prod, found->iProduct);
  2019. bad = USB_INIT_IGNORE;
  2020. goto cldame;
  2021. }
  2022. } else {
  2023. for (i = 0; find_dev[i].drv != DRIVER_MAX; i++) {
  2024. const char *iProduct = find_dev[i].iProduct;
  2025. /* Do same for iProduct as iManufacturer above */
  2026. if (!iProduct)
  2027. continue;
  2028. if (!strcasecmp((char *)prod, iProduct)) {
  2029. applog(LOG_DEBUG, "USB init, alternative iProduct match %s",
  2030. devstr);
  2031. applog(LOG_DEBUG, "Found %s", iProduct);
  2032. bad = USB_INIT_IGNORE;
  2033. goto cldame;
  2034. }
  2035. }
  2036. }
  2037. cfg = -1;
  2038. err = libusb_get_configuration(cgusb->handle, &cfg);
  2039. if (err)
  2040. cfg = -1;
  2041. // Try to set it if we can't read it or it's different
  2042. if (cfg != found->config) {
  2043. err = libusb_set_configuration(cgusb->handle, found->config);
  2044. if (err) {
  2045. switch(err) {
  2046. case LIBUSB_ERROR_BUSY:
  2047. applog(LOG_WARNING,
  2048. "USB init, set config %d in use %s",
  2049. found->config, devstr);
  2050. break;
  2051. default:
  2052. applog(LOG_DEBUG,
  2053. "USB init, failed to set config to %d, err %d %s",
  2054. found->config, err, devstr);
  2055. }
  2056. goto cldame;
  2057. }
  2058. }
  2059. err = libusb_get_active_config_descriptor(dev, &config);
  2060. if (err) {
  2061. applog(LOG_DEBUG,
  2062. "USB init, failed to get config descriptor, err %d %s",
  2063. err, devstr);
  2064. goto cldame;
  2065. }
  2066. int imax = -1;
  2067. for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++)
  2068. if (found->intinfos[ifinfo].interface > imax)
  2069. imax = found->intinfos[ifinfo].interface;
  2070. if ((int)(config->bNumInterfaces) <= imax) {
  2071. applog(LOG_DEBUG, "USB init bNumInterfaces %d <= interface max %d for %s",
  2072. (int)(config->bNumInterfaces), imax, devstr);
  2073. goto cldame;
  2074. }
  2075. for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++)
  2076. for (epinfo = 0; epinfo < found->intinfos[ifinfo].epinfo_count; epinfo++)
  2077. found->intinfos[ifinfo].epinfos[epinfo].found = false;
  2078. for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++) {
  2079. int interface = found->intinfos[ifinfo].interface;
  2080. for (alt = 0; alt < config->interface[interface].num_altsetting; alt++) {
  2081. idesc = &(config->interface[interface].altsetting[alt]);
  2082. for (epnum = 0; epnum < (int)(idesc->bNumEndpoints); epnum++) {
  2083. struct usb_epinfo *epinfos = found->intinfos[ifinfo].epinfos;
  2084. epdesc = &(idesc->endpoint[epnum]);
  2085. for (epinfo = 0; epinfo < found->intinfos[ifinfo].epinfo_count; epinfo++) {
  2086. if (!epinfos[epinfo].found) {
  2087. if (epdesc->bmAttributes == epinfos[epinfo].att
  2088. && epdesc->wMaxPacketSize >= epinfos[epinfo].size
  2089. && epdesc->bEndpointAddress == epinfos[epinfo].ep) {
  2090. epinfos[epinfo].found = true;
  2091. epinfos[epinfo].wMaxPacketSize = epdesc->wMaxPacketSize;
  2092. break;
  2093. }
  2094. }
  2095. }
  2096. }
  2097. }
  2098. }
  2099. for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++)
  2100. for (epinfo = 0; epinfo < found->intinfos[ifinfo].epinfo_count; epinfo++)
  2101. if (found->intinfos[ifinfo].epinfos[epinfo].found == false) {
  2102. applog(LOG_DEBUG, "USB init found (%d,%d) == false %s",
  2103. ifinfo, epinfo, devstr);
  2104. goto cldame;
  2105. }
  2106. claimed = 0;
  2107. for (ifinfo = 0; ifinfo < found->intinfo_count; ifinfo++) {
  2108. err = libusb_claim_interface(cgusb->handle, THISIF(found, ifinfo));
  2109. if (err == 0)
  2110. claimed++;
  2111. else {
  2112. switch(err) {
  2113. case LIBUSB_ERROR_BUSY:
  2114. applog(LOG_WARNING,
  2115. "USB init, claim ifinfo %d interface %d in use %s",
  2116. ifinfo, THISIF(found, ifinfo), devstr);
  2117. break;
  2118. default:
  2119. applog(LOG_DEBUG,
  2120. "USB init, claim ifinfo %d interface %d failed,"
  2121. " err %d %s",
  2122. ifinfo, THISIF(found, ifinfo), err, devstr);
  2123. }
  2124. goto reldame;
  2125. }
  2126. }
  2127. cfg = -1;
  2128. err = libusb_get_configuration(cgusb->handle, &cfg);
  2129. if (err)
  2130. cfg = -1;
  2131. if (cfg != found->config) {
  2132. applog(LOG_WARNING,
  2133. "USB init, incorrect config (%d!=%d) after claim of %s",
  2134. cfg, found->config, devstr);
  2135. goto reldame;
  2136. }
  2137. cgusb->usbver = cgusb->descriptor->bcdUSB;
  2138. if (cgusb->usbver < 0x0200) {
  2139. cgusb->usb11 = true;
  2140. cgusb->tt = true;
  2141. }
  2142. // TODO: allow this with the right version of the libusb include and running library
  2143. // cgusb->speed = libusb_get_device_speed(dev);
  2144. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  2145. cgusb->descriptor->iProduct, strbuf, STRBUFLEN);
  2146. if (err > 0)
  2147. cgusb->prod_string = strdup((char *)strbuf);
  2148. else
  2149. cgusb->prod_string = (char *)BLANK;
  2150. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  2151. cgusb->descriptor->iManufacturer, strbuf, STRBUFLEN);
  2152. if (err > 0)
  2153. cgusb->manuf_string = strdup((char *)strbuf);
  2154. else
  2155. cgusb->manuf_string = (char *)BLANK;
  2156. err = libusb_get_string_descriptor_ascii(cgusb->handle,
  2157. cgusb->descriptor->iSerialNumber, strbuf, STRBUFLEN);
  2158. if (err > 0)
  2159. cgusb->serial_string = strdup((char *)strbuf);
  2160. else
  2161. cgusb->serial_string = (char *)BLANK;
  2162. // TODO: ?
  2163. // cgusb->fwVersion <- for temp1/temp2 decision? or serial? (driver-modminer.c)
  2164. // cgusb->interfaceVersion
  2165. applog(LOG_DEBUG,
  2166. "USB init %s usbver=%04x prod='%s' manuf='%s' serial='%s'",
  2167. devstr, cgusb->usbver, cgusb->prod_string,
  2168. cgusb->manuf_string, cgusb->serial_string);
  2169. cgpu->usbdev = cgusb;
  2170. cgpu->usbinfo.nodev = false;
  2171. libusb_free_config_descriptor(config);
  2172. // Allow a name change based on the idVendor+idProduct
  2173. // N.B. must be done before calling add_cgpu()
  2174. if (strcasecmp(cgpu->drv->name, found->name)) {
  2175. if (!cgpu->drv->copy)
  2176. cgpu->drv = copy_drv(cgpu->drv);
  2177. cgpu->drv->name = (char *)(found->name);
  2178. }
  2179. bad = USB_INIT_OK;
  2180. goto out_unlock;
  2181. reldame:
  2182. ifinfo = claimed;
  2183. while (ifinfo-- > 0)
  2184. libusb_release_interface(cgusb->handle, THISIF(found, ifinfo));
  2185. cldame:
  2186. #ifdef LINUX
  2187. libusb_attach_kernel_driver(cgusb->handle, THISIF(found, ifinfo));
  2188. nokernel:
  2189. #endif
  2190. cg_wlock(&cgusb_fd_lock);
  2191. libusb_close(cgusb->handle);
  2192. cgusb->handle = NULL;
  2193. cg_wunlock(&cgusb_fd_lock);
  2194. dame:
  2195. if (config)
  2196. libusb_free_config_descriptor(config);
  2197. cgusb = free_cgusb(cgusb);
  2198. out_unlock:
  2199. DEVWUNLOCK(cgpu, pstate);
  2200. return bad;
  2201. }
  2202. bool usb_init(struct cgpu_info *cgpu, struct libusb_device *dev, struct usb_find_devices *found_match)
  2203. {
  2204. struct usb_find_devices *found_use = NULL;
  2205. int uninitialised_var(ret);
  2206. int i;
  2207. for (i = 0; find_dev[i].drv != DRIVER_MAX; i++) {
  2208. if (find_dev[i].drv == found_match->drv &&
  2209. find_dev[i].idVendor == found_match->idVendor &&
  2210. find_dev[i].idProduct == found_match->idProduct) {
  2211. found_use = malloc(sizeof(*found_use));
  2212. if (unlikely(!found_use))
  2213. quit(1, "USB failed to malloc found_use");
  2214. cg_memcpy(found_use, &(find_dev[i]), sizeof(*found_use));
  2215. ret = _usb_init(cgpu, dev, found_use);
  2216. if (ret != USB_INIT_IGNORE)
  2217. break;
  2218. }
  2219. }
  2220. if (ret == USB_INIT_FAIL)
  2221. applog(LOG_ERR, "%s detect (%d:%d) failed to initialise (incorrect device?)",
  2222. cgpu->drv->dname,
  2223. (int)(cgpu->usbinfo.bus_number),
  2224. (int)(cgpu->usbinfo.device_address));
  2225. return (ret == USB_INIT_OK);
  2226. }
  2227. static bool usb_check_device(struct device_drv *drv, struct libusb_device *dev, struct usb_find_devices *look)
  2228. {
  2229. struct libusb_device_descriptor desc;
  2230. int bus_number, device_address;
  2231. int err, i;
  2232. bool ok;
  2233. err = libusb_get_device_descriptor(dev, &desc);
  2234. if (err) {
  2235. applog(LOG_DEBUG, "USB check device: Failed to get descriptor, err %d", err);
  2236. return false;
  2237. }
  2238. if (desc.idVendor != look->idVendor || desc.idProduct != look->idProduct) {
  2239. applog(LOG_DEBUG, "%s looking for %s %04x:%04x but found %04x:%04x instead",
  2240. drv->name, look->name, look->idVendor, look->idProduct, desc.idVendor, desc.idProduct);
  2241. return false;
  2242. }
  2243. if (busdev_count > 0) {
  2244. bus_number = (int)libusb_get_bus_number(dev);
  2245. device_address = (int)libusb_get_device_address(dev);
  2246. ok = false;
  2247. for (i = 0; i < busdev_count; i++) {
  2248. if (bus_number == busdev[i].bus_number) {
  2249. if (busdev[i].device_address == -1 ||
  2250. device_address == busdev[i].device_address) {
  2251. ok = true;
  2252. break;
  2253. }
  2254. }
  2255. }
  2256. if (!ok) {
  2257. applog(LOG_DEBUG, "%s rejected %s %04x:%04x with bus:dev (%d:%d)",
  2258. drv->name, look->name, look->idVendor, look->idProduct,
  2259. bus_number, device_address);
  2260. return false;
  2261. }
  2262. }
  2263. applog(LOG_DEBUG, "%s looking for and found %s %04x:%04x",
  2264. drv->name, look->name, look->idVendor, look->idProduct);
  2265. return true;
  2266. }
  2267. static struct usb_find_devices *usb_check_each(int drvnum, struct device_drv *drv, struct libusb_device *dev)
  2268. {
  2269. struct usb_find_devices *found;
  2270. int i;
  2271. for (i = 0; find_dev[i].drv != DRIVER_MAX; i++)
  2272. if (find_dev[i].drv == drvnum) {
  2273. if (usb_check_device(drv, dev, &(find_dev[i]))) {
  2274. found = malloc(sizeof(*found));
  2275. if (unlikely(!found))
  2276. quit(1, "USB failed to malloc found");
  2277. cg_memcpy(found, &(find_dev[i]), sizeof(*found));
  2278. return found;
  2279. }
  2280. }
  2281. return NULL;
  2282. }
  2283. #define DRIVER_USB_CHECK_EACH(X) if (drv->drv_id == DRIVER_##X) \
  2284. return usb_check_each(DRIVER_##X, drv, dev);
  2285. static struct usb_find_devices *usb_check(__maybe_unused struct device_drv *drv, __maybe_unused struct libusb_device *dev)
  2286. {
  2287. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  2288. applog(LOG_DEBUG,
  2289. "USB scan devices3: %s limit %d reached",
  2290. drv->dname, drv_count[drv->drv_id].limit);
  2291. return NULL;
  2292. }
  2293. DRIVER_PARSE_COMMANDS(DRIVER_USB_CHECK_EACH)
  2294. return NULL;
  2295. }
  2296. void __usb_detect(struct device_drv *drv, struct cgpu_info *(*device_detect)(struct libusb_device *, struct usb_find_devices *),
  2297. bool single)
  2298. {
  2299. libusb_device **list;
  2300. ssize_t count, i;
  2301. struct usb_find_devices *found;
  2302. struct cgpu_info *cgpu;
  2303. applog(LOG_DEBUG, "USB scan devices: checking for %s devices", drv->name);
  2304. if (total_count >= total_limit) {
  2305. applog(LOG_DEBUG, "USB scan devices: total limit %d reached", total_limit);
  2306. return;
  2307. }
  2308. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  2309. applog(LOG_DEBUG,
  2310. "USB scan devices: %s limit %d reached",
  2311. drv->dname, drv_count[drv->drv_id].limit);
  2312. return;
  2313. }
  2314. count = libusb_get_device_list(NULL, &list);
  2315. if (count < 0) {
  2316. applog(LOG_DEBUG, "USB scan devices: failed, err %d", (int)count);
  2317. return;
  2318. }
  2319. if (count == 0)
  2320. applog(LOG_DEBUG, "USB scan devices: found no devices");
  2321. else
  2322. cgsleep_ms(166);
  2323. for (i = 0; i < count; i++) {
  2324. if (total_count >= total_limit) {
  2325. applog(LOG_DEBUG, "USB scan devices2: total limit %d reached", total_limit);
  2326. break;
  2327. }
  2328. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  2329. applog(LOG_DEBUG,
  2330. "USB scan devices2: %s limit %d reached",
  2331. drv->dname, drv_count[drv->drv_id].limit);
  2332. break;
  2333. }
  2334. found = usb_check(drv, list[i]);
  2335. if (found != NULL) {
  2336. bool new_dev = false;
  2337. if (is_in_use(list[i]) || cgminer_usb_lock(drv, list[i]) == false)
  2338. free(found);
  2339. else {
  2340. cgpu = device_detect(list[i], found);
  2341. if (!cgpu)
  2342. cgminer_usb_unlock(drv, list[i]);
  2343. else {
  2344. new_dev = true;
  2345. cgpu->usbinfo.initialised = true;
  2346. total_count++;
  2347. drv_count[drv->drv_id].count++;
  2348. }
  2349. free(found);
  2350. }
  2351. if (single && new_dev)
  2352. break;
  2353. }
  2354. }
  2355. libusb_free_device_list(list, 1);
  2356. }
  2357. #if DO_USB_STATS
  2358. static void modes_str(char *buf, uint32_t modes)
  2359. {
  2360. bool first;
  2361. *buf = '\0';
  2362. if (modes == MODE_NONE)
  2363. strcpy(buf, MODE_NONE_STR);
  2364. else {
  2365. first = true;
  2366. if (modes & MODE_CTRL_READ) {
  2367. strcpy(buf, MODE_CTRL_READ_STR);
  2368. first = false;
  2369. }
  2370. if (modes & MODE_CTRL_WRITE) {
  2371. if (!first)
  2372. strcat(buf, MODE_SEP_STR);
  2373. strcat(buf, MODE_CTRL_WRITE_STR);
  2374. first = false;
  2375. }
  2376. if (modes & MODE_BULK_READ) {
  2377. if (!first)
  2378. strcat(buf, MODE_SEP_STR);
  2379. strcat(buf, MODE_BULK_READ_STR);
  2380. first = false;
  2381. }
  2382. if (modes & MODE_BULK_WRITE) {
  2383. if (!first)
  2384. strcat(buf, MODE_SEP_STR);
  2385. strcat(buf, MODE_BULK_WRITE_STR);
  2386. first = false;
  2387. }
  2388. }
  2389. }
  2390. #endif
  2391. // The stat data can be spurious due to not locking it before copying it -
  2392. // however that would require the stat() function to also lock and release
  2393. // a mutex every time a usb read or write is called which would slow
  2394. // things down more
  2395. struct api_data *api_usb_stats(__maybe_unused int *count)
  2396. {
  2397. #if DO_USB_STATS
  2398. struct cg_usb_stats_details *details;
  2399. struct cg_usb_stats *sta;
  2400. struct api_data *root = NULL;
  2401. int device;
  2402. int cmdseq;
  2403. char modes_s[32];
  2404. if (next_stat == USB_NOSTAT)
  2405. return NULL;
  2406. while (*count < next_stat * C_MAX * 2) {
  2407. device = *count / (C_MAX * 2);
  2408. cmdseq = *count % (C_MAX * 2);
  2409. (*count)++;
  2410. sta = &(usb_stats[device]);
  2411. details = &(sta->details[cmdseq]);
  2412. // Only show stats that have results
  2413. if (details->item[CMD_CMD].count == 0 &&
  2414. details->item[CMD_TIMEOUT].count == 0 &&
  2415. details->item[CMD_ERROR].count == 0)
  2416. continue;
  2417. root = api_add_string(root, "Name", sta->name, false);
  2418. root = api_add_int(root, "ID", &(sta->device_id), false);
  2419. root = api_add_const(root, "Stat", usb_commands[cmdseq/2], false);
  2420. root = api_add_int(root, "Seq", &(details->seq), true);
  2421. modes_str(modes_s, details->modes);
  2422. root = api_add_string(root, "Modes", modes_s, true);
  2423. root = api_add_uint64(root, "Count",
  2424. &(details->item[CMD_CMD].count), true);
  2425. root = api_add_double(root, "Total Delay",
  2426. &(details->item[CMD_CMD].total_delay), true);
  2427. root = api_add_double(root, "Min Delay",
  2428. &(details->item[CMD_CMD].min_delay), true);
  2429. root = api_add_double(root, "Max Delay",
  2430. &(details->item[CMD_CMD].max_delay), true);
  2431. root = api_add_uint64(root, "Timeout Count",
  2432. &(details->item[CMD_TIMEOUT].count), true);
  2433. root = api_add_double(root, "Timeout Total Delay",
  2434. &(details->item[CMD_TIMEOUT].total_delay), true);
  2435. root = api_add_double(root, "Timeout Min Delay",
  2436. &(details->item[CMD_TIMEOUT].min_delay), true);
  2437. root = api_add_double(root, "Timeout Max Delay",
  2438. &(details->item[CMD_TIMEOUT].max_delay), true);
  2439. root = api_add_uint64(root, "Error Count",
  2440. &(details->item[CMD_ERROR].count), true);
  2441. root = api_add_double(root, "Error Total Delay",
  2442. &(details->item[CMD_ERROR].total_delay), true);
  2443. root = api_add_double(root, "Error Min Delay",
  2444. &(details->item[CMD_ERROR].min_delay), true);
  2445. root = api_add_double(root, "Error Max Delay",
  2446. &(details->item[CMD_ERROR].max_delay), true);
  2447. root = api_add_timeval(root, "First Command",
  2448. &(details->item[CMD_CMD].first), true);
  2449. root = api_add_timeval(root, "Last Command",
  2450. &(details->item[CMD_CMD].last), true);
  2451. root = api_add_timeval(root, "First Timeout",
  2452. &(details->item[CMD_TIMEOUT].first), true);
  2453. root = api_add_timeval(root, "Last Timeout",
  2454. &(details->item[CMD_TIMEOUT].last), true);
  2455. root = api_add_timeval(root, "First Error",
  2456. &(details->item[CMD_ERROR].first), true);
  2457. root = api_add_timeval(root, "Last Error",
  2458. &(details->item[CMD_ERROR].last), true);
  2459. return root;
  2460. }
  2461. #endif
  2462. return NULL;
  2463. }
  2464. #if DO_USB_STATS
  2465. static void newstats(struct cgpu_info *cgpu)
  2466. {
  2467. int i;
  2468. mutex_lock(&cgusb_lock);
  2469. cgpu->usbinfo.usbstat = next_stat + 1;
  2470. usb_stats = realloc(usb_stats, sizeof(*usb_stats) * (next_stat+1));
  2471. if (unlikely(!usb_stats))
  2472. quit(1, "USB failed to realloc usb_stats %d", next_stat+1);
  2473. usb_stats[next_stat].name = cgpu->drv->name;
  2474. usb_stats[next_stat].device_id = -1;
  2475. usb_stats[next_stat].details = calloc(2, sizeof(struct cg_usb_stats_details) * (C_MAX + 1));
  2476. if (unlikely(!usb_stats[next_stat].details))
  2477. quit(1, "USB failed to calloc details for %d", next_stat+1);
  2478. for (i = 1; i < C_MAX * 2; i += 2)
  2479. usb_stats[next_stat].details[i].seq = 1;
  2480. next_stat++;
  2481. mutex_unlock(&cgusb_lock);
  2482. }
  2483. #endif
  2484. void update_usb_stats(__maybe_unused struct cgpu_info *cgpu)
  2485. {
  2486. #if DO_USB_STATS
  2487. if (cgpu->usbinfo.usbstat < 1)
  2488. newstats(cgpu);
  2489. // we don't know the device_id until after add_cgpu()
  2490. usb_stats[cgpu->usbinfo.usbstat - 1].device_id = cgpu->device_id;
  2491. #endif
  2492. }
  2493. #if DO_USB_STATS
  2494. 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)
  2495. {
  2496. struct cg_usb_stats_details *details;
  2497. double diff;
  2498. int item, extrams;
  2499. if (cgpu->usbinfo.usbstat < 1)
  2500. newstats(cgpu);
  2501. cgpu->usbinfo.tmo_count++;
  2502. // timeout checks are only done when stats are enabled
  2503. extrams = SECTOMS(tdiff(tv_finish, tv_start)) - timeout;
  2504. if (extrams >= USB_TMO_0) {
  2505. uint32_t totms = (uint32_t)(timeout + extrams);
  2506. int offset = 0;
  2507. if (extrams >= USB_TMO_2) {
  2508. applog(LOG_INFO, "%s%i: TIMEOUT %s took %dms but was %dms",
  2509. cgpu->drv->name, cgpu->device_id,
  2510. usb_cmdname(cmd), totms, timeout) ;
  2511. offset = 2;
  2512. } else if (extrams >= USB_TMO_1)
  2513. offset = 1;
  2514. cgpu->usbinfo.usb_tmo[offset].count++;
  2515. cgpu->usbinfo.usb_tmo[offset].total_over += extrams;
  2516. cgpu->usbinfo.usb_tmo[offset].total_tmo += timeout;
  2517. if (cgpu->usbinfo.usb_tmo[offset].min_tmo == 0) {
  2518. cgpu->usbinfo.usb_tmo[offset].min_tmo = totms;
  2519. cgpu->usbinfo.usb_tmo[offset].max_tmo = totms;
  2520. } else {
  2521. if (cgpu->usbinfo.usb_tmo[offset].min_tmo > totms)
  2522. cgpu->usbinfo.usb_tmo[offset].min_tmo = totms;
  2523. if (cgpu->usbinfo.usb_tmo[offset].max_tmo < totms)
  2524. cgpu->usbinfo.usb_tmo[offset].max_tmo = totms;
  2525. }
  2526. }
  2527. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[cmd * 2 + seq]);
  2528. details->modes |= mode;
  2529. diff = tdiff(tv_finish, tv_start);
  2530. switch (err) {
  2531. case LIBUSB_SUCCESS:
  2532. item = CMD_CMD;
  2533. break;
  2534. case LIBUSB_ERROR_TIMEOUT:
  2535. item = CMD_TIMEOUT;
  2536. break;
  2537. default:
  2538. item = CMD_ERROR;
  2539. break;
  2540. }
  2541. if (details->item[item].count == 0) {
  2542. details->item[item].min_delay = diff;
  2543. cg_memcpy(&(details->item[item].first), tv_start, sizeof(*tv_start));
  2544. } else if (diff < details->item[item].min_delay)
  2545. details->item[item].min_delay = diff;
  2546. if (diff > details->item[item].max_delay)
  2547. details->item[item].max_delay = diff;
  2548. details->item[item].total_delay += diff;
  2549. cg_memcpy(&(details->item[item].last), tv_start, sizeof(*tv_start));
  2550. details->item[item].count++;
  2551. }
  2552. static void rejected_inc(struct cgpu_info *cgpu, uint32_t mode)
  2553. {
  2554. struct cg_usb_stats_details *details;
  2555. int item = CMD_ERROR;
  2556. if (cgpu->usbinfo.usbstat < 1)
  2557. newstats(cgpu);
  2558. details = &(usb_stats[cgpu->usbinfo.usbstat - 1].details[C_REJECTED * 2 + 0]);
  2559. details->modes |= mode;
  2560. details->item[item].count++;
  2561. }
  2562. #endif
  2563. #define USB_RETRY_MAX 5
  2564. struct usb_transfer {
  2565. cgsem_t cgsem;
  2566. struct libusb_transfer *transfer;
  2567. bool cancellable;
  2568. struct list_head list;
  2569. };
  2570. bool async_usb_transfers(void)
  2571. {
  2572. bool ret;
  2573. cg_rlock(&cgusb_fd_lock);
  2574. ret = !list_empty(&ut_list);
  2575. cg_runlock(&cgusb_fd_lock);
  2576. return ret;
  2577. }
  2578. /* Cancellable transfers should only be labelled as such if it is safe for them
  2579. * to effectively mimic timing out early. This flag is usually used to signify
  2580. * a read is waiting on a non-critical response that takes a long time and the
  2581. * driver wishes it be aborted if work restart message has been sent. */
  2582. void cancel_usb_transfers(void)
  2583. {
  2584. struct usb_transfer *ut;
  2585. int cancellations = 0;
  2586. cg_wlock(&cgusb_fd_lock);
  2587. list_for_each_entry(ut, &ut_list, list) {
  2588. if (ut->cancellable) {
  2589. ut->cancellable = false;
  2590. libusb_cancel_transfer(ut->transfer);
  2591. cancellations++;
  2592. }
  2593. }
  2594. cg_wunlock(&cgusb_fd_lock);
  2595. if (cancellations)
  2596. applog(LOG_DEBUG, "Cancelled %d USB transfers", cancellations);
  2597. }
  2598. static void init_usb_transfer(struct usb_transfer *ut)
  2599. {
  2600. cgsem_init(&ut->cgsem);
  2601. ut->transfer = libusb_alloc_transfer(0);
  2602. if (unlikely(!ut->transfer))
  2603. quit(1, "Failed to libusb_alloc_transfer");
  2604. ut->transfer->user_data = ut;
  2605. ut->cancellable = false;
  2606. }
  2607. static void complete_usb_transfer(struct usb_transfer *ut)
  2608. {
  2609. cg_wlock(&cgusb_fd_lock);
  2610. list_del(&ut->list);
  2611. cg_wunlock(&cgusb_fd_lock);
  2612. cgsem_destroy(&ut->cgsem);
  2613. libusb_free_transfer(ut->transfer);
  2614. }
  2615. static void LIBUSB_CALL transfer_callback(struct libusb_transfer *transfer)
  2616. {
  2617. struct usb_transfer *ut = transfer->user_data;
  2618. ut->cancellable = false;
  2619. cgsem_post(&ut->cgsem);
  2620. }
  2621. static int usb_transfer_toerr(int ret)
  2622. {
  2623. if (ret <= 0)
  2624. return ret;
  2625. switch (ret) {
  2626. default:
  2627. case LIBUSB_TRANSFER_COMPLETED:
  2628. ret = LIBUSB_SUCCESS;
  2629. break;
  2630. case LIBUSB_TRANSFER_ERROR:
  2631. ret = LIBUSB_ERROR_IO;
  2632. break;
  2633. case LIBUSB_TRANSFER_TIMED_OUT:
  2634. case LIBUSB_TRANSFER_CANCELLED:
  2635. ret = LIBUSB_ERROR_TIMEOUT;
  2636. break;
  2637. case LIBUSB_TRANSFER_STALL:
  2638. ret = LIBUSB_ERROR_PIPE;
  2639. break;
  2640. case LIBUSB_TRANSFER_NO_DEVICE:
  2641. ret = LIBUSB_ERROR_NO_DEVICE;
  2642. break;
  2643. case LIBUSB_TRANSFER_OVERFLOW:
  2644. ret = LIBUSB_ERROR_OVERFLOW;
  2645. break;
  2646. }
  2647. return ret;
  2648. }
  2649. /* Wait for callback function to tell us it has finished the USB transfer, but
  2650. * use our own timer to cancel the request if we go beyond the timeout. */
  2651. static int callback_wait(struct usb_transfer *ut, int *transferred, unsigned int timeout)
  2652. {
  2653. struct libusb_transfer *transfer= ut->transfer;
  2654. int ret;
  2655. ret = cgsem_mswait(&ut->cgsem, timeout);
  2656. if (ret == ETIMEDOUT) {
  2657. /* We are emulating a timeout ourself here */
  2658. libusb_cancel_transfer(transfer);
  2659. /* Now wait for the callback function to be invoked. */
  2660. cgsem_wait(&ut->cgsem);
  2661. }
  2662. ret = transfer->status;
  2663. ret = usb_transfer_toerr(ret);
  2664. /* No need to sort out mutexes here since they won't be reused */
  2665. *transferred = transfer->actual_length;
  2666. return ret;
  2667. }
  2668. static int usb_submit_transfer(struct usb_transfer *ut, struct libusb_transfer *transfer,
  2669. bool cancellable, bool tt)
  2670. {
  2671. int err;
  2672. INIT_LIST_HEAD(&ut->list);
  2673. cg_wlock(&cgusb_fd_lock);
  2674. /* Imitate a transaction translator for writes to usb1.1 devices */
  2675. if (tt)
  2676. cgsleep_ms_r(&usb11_cgt, 1);
  2677. err = libusb_submit_transfer(transfer);
  2678. if (likely(!err))
  2679. ut->cancellable = cancellable;
  2680. list_add(&ut->list, &ut_list);
  2681. if (tt)
  2682. cgtimer_time(&usb11_cgt);
  2683. cg_wunlock(&cgusb_fd_lock);
  2684. return err;
  2685. }
  2686. static int
  2687. usb_perform_transfer(struct cgpu_info *cgpu, struct cg_usb_device *usbdev, int intinfo,
  2688. int epinfo, unsigned char *data, int length, int *transferred,
  2689. unsigned int timeout, __maybe_unused int mode, enum usb_cmds cmd,
  2690. __maybe_unused int seq, bool cancellable, bool tt)
  2691. {
  2692. int bulk_timeout, callback_timeout = timeout, err_retries = 0;
  2693. struct libusb_device_handle *dev_handle = usbdev->handle;
  2694. struct usb_epinfo *usb_epinfo;
  2695. struct usb_transfer ut;
  2696. unsigned char endpoint;
  2697. bool interrupt;
  2698. int err, errn;
  2699. #if DO_USB_STATS
  2700. struct timeval tv_start, tv_finish;
  2701. #endif
  2702. unsigned char buf[512];
  2703. #ifdef WIN32
  2704. /* On windows the callback_timeout is a safety mechanism only. */
  2705. bulk_timeout = timeout;
  2706. callback_timeout += WIN_CALLBACK_EXTRA;
  2707. #else
  2708. /* We give the transfer no timeout since we manage timeouts ourself on
  2709. * non windows. */
  2710. bulk_timeout = 0;
  2711. #endif
  2712. usb_epinfo = &(usbdev->found->intinfos[intinfo].epinfos[epinfo]);
  2713. interrupt = usb_epinfo->att == LIBUSB_TRANSFER_TYPE_INTERRUPT;
  2714. endpoint = usb_epinfo->ep;
  2715. if (unlikely(!data)) {
  2716. applog(LOG_ERR, "USB error: usb_perform_transfer sent NULL data (%s,intinfo=%d,epinfo=%d,length=%d,timeout=%u,mode=%d,cmd=%s,seq=%d) endpoint=%d",
  2717. cgpu->drv->name, intinfo, epinfo, length, timeout, mode, usb_cmdname(cmd), seq, (int)endpoint);
  2718. err = LIBUSB_ERROR_IO;
  2719. goto out_fail;
  2720. }
  2721. /* Avoid any async transfers during shutdown to allow the polling
  2722. * thread to be shut down after all existing transfers are complete */
  2723. if (opt_lowmem || cgpu->shutdown)
  2724. return libusb_bulk_transfer(dev_handle, endpoint, data, length, transferred, timeout);
  2725. err_retry:
  2726. init_usb_transfer(&ut);
  2727. if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) {
  2728. cg_memcpy(buf, data, length);
  2729. #ifndef HAVE_LIBUSB
  2730. /* Older versions may not have this feature so only enable it
  2731. * when we know we're compiling with included static libusb. We
  2732. * only do this for bulk transfer, not interrupt. */
  2733. if (!cgpu->nozlp && !interrupt)
  2734. ut.transfer->flags |= LIBUSB_TRANSFER_ADD_ZERO_PACKET;
  2735. #endif
  2736. #ifdef WIN32
  2737. /* Writes on windows really don't like to be cancelled, but
  2738. * are prone to timeouts under heavy USB traffic, so make this
  2739. * a last resort cancellation delayed long after the write
  2740. * would have timed out on its own. */
  2741. callback_timeout += WIN_WRITE_CBEXTRA;
  2742. #endif
  2743. }
  2744. USBDEBUG("USB debug: @usb_perform_transfer(%s (nodev=%s),intinfo=%d,epinfo=%d,data=%p,length=%d,timeout=%u,mode=%d,cmd=%s,seq=%d) endpoint=%d", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), intinfo, epinfo, data, length, timeout, mode, usb_cmdname(cmd), seq, (int)endpoint);
  2745. if (interrupt) {
  2746. libusb_fill_interrupt_transfer(ut.transfer, dev_handle, endpoint,
  2747. buf, length, transfer_callback, &ut,
  2748. bulk_timeout);
  2749. } else {
  2750. libusb_fill_bulk_transfer(ut.transfer, dev_handle, endpoint, buf,
  2751. length, transfer_callback, &ut, bulk_timeout);
  2752. }
  2753. STATS_TIMEVAL(&tv_start);
  2754. err = usb_submit_transfer(&ut, ut.transfer, cancellable, tt);
  2755. errn = errno;
  2756. if (!err)
  2757. err = callback_wait(&ut, transferred, callback_timeout);
  2758. else
  2759. err = usb_transfer_toerr(err);
  2760. complete_usb_transfer(&ut);
  2761. STATS_TIMEVAL(&tv_finish);
  2762. USB_STATS(cgpu, &tv_start, &tv_finish, err, mode, cmd, seq, timeout);
  2763. if (err < 0) {
  2764. applog(LOG_DEBUG, "%s%i: %s (amt=%d err=%d ern=%d)",
  2765. cgpu->drv->name, cgpu->device_id,
  2766. usb_cmdname(cmd), *transferred, err, errn);
  2767. }
  2768. if (err == LIBUSB_ERROR_PIPE) {
  2769. int pipeerr, retries = 0;
  2770. do {
  2771. cgpu->usbinfo.last_pipe = time(NULL);
  2772. cgpu->usbinfo.pipe_count++;
  2773. applog(LOG_INFO, "%s%i: libusb pipe error, trying to clear",
  2774. cgpu->drv->name, cgpu->device_id);
  2775. pipeerr = libusb_clear_halt(dev_handle, endpoint);
  2776. applog(LOG_DEBUG, "%s%i: libusb pipe error%scleared",
  2777. cgpu->drv->name, cgpu->device_id, err ? " not " : " ");
  2778. if (pipeerr)
  2779. cgpu->usbinfo.clear_fail_count++;
  2780. } while (pipeerr && ++retries < USB_RETRY_MAX);
  2781. if (!pipeerr && ++err_retries < USB_RETRY_MAX)
  2782. goto err_retry;
  2783. }
  2784. if (err == LIBUSB_ERROR_IO && ++err_retries < USB_RETRY_MAX)
  2785. goto err_retry;
  2786. out_fail:
  2787. if (NODEV(err))
  2788. *transferred = 0;
  2789. else if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN && *transferred)
  2790. cg_memcpy(data, buf, *transferred);
  2791. return err;
  2792. }
  2793. void usb_reset(struct cgpu_info *cgpu)
  2794. {
  2795. int pstate, err = 0;
  2796. DEVRLOCK(cgpu, pstate);
  2797. if (!cgpu->usbinfo.nodev) {
  2798. err = libusb_reset_device(cgpu->usbdev->handle);
  2799. applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
  2800. cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
  2801. }
  2802. if (NODEV(err)) {
  2803. cg_ruwlock(&cgpu->usbinfo.devlock);
  2804. release_cgpu(cgpu);
  2805. DEVWUNLOCK(cgpu, pstate);
  2806. } else
  2807. DEVRUNLOCK(cgpu, pstate);
  2808. }
  2809. int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz,
  2810. int *processed, int timeout, const char *end, enum usb_cmds cmd, bool readonce, bool cancellable)
  2811. {
  2812. unsigned char *ptr, usbbuf[USB_READ_BUFSIZE];
  2813. struct timeval read_start, tv_finish;
  2814. int bufleft, err, got, tot, pstate, tried_reset;
  2815. struct cg_usb_device *usbdev;
  2816. unsigned int initial_timeout;
  2817. bool first = true;
  2818. size_t usbbufread;
  2819. int endlen = 0;
  2820. char *eom = NULL;
  2821. double done;
  2822. bool ftdi;
  2823. memset(usbbuf, 0, USB_READ_BUFSIZE);
  2824. memset(buf, 0, bufsiz);
  2825. if (end)
  2826. endlen = strlen(end);
  2827. DEVRLOCK(cgpu, pstate);
  2828. if (cgpu->usbinfo.nodev) {
  2829. *processed = 0;
  2830. USB_REJECT(cgpu, MODE_BULK_READ);
  2831. err = LIBUSB_ERROR_NO_DEVICE;
  2832. goto out_noerrmsg;
  2833. }
  2834. usbdev = cgpu->usbdev;
  2835. /* Interrupt transfers are guaranteed to be of an expected size (we hope) */
  2836. if (usbdev->found->intinfos[intinfo].epinfos[epinfo].att == LIBUSB_TRANSFER_TYPE_INTERRUPT)
  2837. usbbufread = bufsiz;
  2838. else
  2839. usbbufread = 512;
  2840. ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  2841. USBDEBUG("USB debug: _usb_read(%s (nodev=%s),intinfo=%d,epinfo=%d,buf=%p,bufsiz=%d,proc=%p,timeout=%u,end=%s,cmd=%s,ftdi=%s,readonce=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), intinfo, epinfo, buf, (int)bufsiz, processed, timeout, end ? (char *)str_text((char *)end) : "NULL", usb_cmdname(cmd), bool_str(ftdi), bool_str(readonce));
  2842. if (bufsiz > USB_MAX_READ)
  2843. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, (int)bufsiz, USB_MAX_READ);
  2844. if (timeout == DEVTIMEOUT)
  2845. timeout = usbdev->found->timeout;
  2846. tot = usbdev->bufamt;
  2847. bufleft = bufsiz - tot;
  2848. if (tot)
  2849. cg_memcpy(usbbuf, usbdev->buffer, tot);
  2850. ptr = usbbuf + tot;
  2851. usbdev->bufamt = 0;
  2852. err = LIBUSB_SUCCESS;
  2853. if (end != NULL)
  2854. eom = strstr((const char *)usbbuf, end);
  2855. initial_timeout = timeout;
  2856. cgtime(&read_start);
  2857. tried_reset = 0;
  2858. while (bufleft > 0 && !eom) {
  2859. err = usb_perform_transfer(cgpu, usbdev, intinfo, epinfo, ptr, usbbufread,
  2860. &got, timeout, MODE_BULK_READ, cmd,
  2861. first ? SEQ0 : SEQ1, cancellable, false);
  2862. cgtime(&tv_finish);
  2863. ptr[got] = '\0';
  2864. USBDEBUG("USB debug: @_usb_read(%s (nodev=%s)) first=%s err=%d%s got=%d ptr='%s' usbbufread=%d", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), bool_str(first), err, isnodev(err), got, (char *)str_text((char *)ptr), (int)usbbufread);
  2865. if (ftdi) {
  2866. // first 2 bytes returned are an FTDI status
  2867. if (got > 2) {
  2868. got -= 2;
  2869. memmove(ptr, ptr+2, got+1);
  2870. } else {
  2871. got = 0;
  2872. *ptr = '\0';
  2873. }
  2874. }
  2875. tot += got;
  2876. if (end != NULL)
  2877. eom = strstr((const char *)usbbuf, end);
  2878. /* Attempt a usb reset for an error that will otherwise cause
  2879. * this device to drop out provided we know the device still
  2880. * might exist. */
  2881. if (err && err != LIBUSB_ERROR_TIMEOUT) {
  2882. applog(LOG_WARNING, "%s %i %s usb read err:(%d) %s", cgpu->drv->name,
  2883. cgpu->device_id, usb_cmdname(cmd), err, libusb_error_name(err));
  2884. if (err != LIBUSB_ERROR_NO_DEVICE && !tried_reset) {
  2885. err = libusb_reset_device(usbdev->handle);
  2886. tried_reset = 1; // don't call reset twice in a row
  2887. applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
  2888. cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
  2889. }
  2890. } else {
  2891. tried_reset = 0;
  2892. }
  2893. ptr += got;
  2894. bufleft -= got;
  2895. if (bufleft < 1)
  2896. err = LIBUSB_SUCCESS;
  2897. if (err || readonce)
  2898. break;
  2899. first = false;
  2900. done = tdiff(&tv_finish, &read_start);
  2901. // N.B. this is: return last err with whatever size has already been read
  2902. timeout = initial_timeout - (done * 1000);
  2903. if (timeout <= 0)
  2904. break;
  2905. }
  2906. /* If we found the end of message marker, just use that data and
  2907. * return success. */
  2908. if (eom) {
  2909. size_t eomlen = (void *)eom - (void *)usbbuf + endlen;
  2910. if (eomlen < bufsiz) {
  2911. bufsiz = eomlen;
  2912. err = LIBUSB_SUCCESS;
  2913. }
  2914. }
  2915. // N.B. usbdev->buffer was emptied before the while() loop
  2916. if (tot > (int)bufsiz) {
  2917. usbdev->bufamt = tot - bufsiz;
  2918. cg_memcpy(usbdev->buffer, usbbuf + bufsiz, usbdev->bufamt);
  2919. tot -= usbdev->bufamt;
  2920. usbbuf[tot] = '\0';
  2921. applog(LOG_DEBUG, "USB: %s%i read1 buffering %d extra bytes",
  2922. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2923. }
  2924. *processed = tot;
  2925. cg_memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2926. out_noerrmsg:
  2927. if (NODEV(err)) {
  2928. cg_ruwlock(&cgpu->usbinfo.devlock);
  2929. release_cgpu(cgpu);
  2930. DEVWUNLOCK(cgpu, pstate);
  2931. } else
  2932. DEVRUNLOCK(cgpu, pstate);
  2933. return err;
  2934. }
  2935. int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, int timeout, enum usb_cmds cmd)
  2936. {
  2937. struct timeval write_start, tv_finish;
  2938. struct cg_usb_device *usbdev;
  2939. unsigned int initial_timeout;
  2940. int err, sent, tot, pstate, tried_reset;
  2941. bool first = true;
  2942. double done;
  2943. DEVRLOCK(cgpu, pstate);
  2944. USBDEBUG("USB debug: _usb_write(%s (nodev=%s),intinfo=%d,epinfo=%d,buf='%s',bufsiz=%d,proc=%p,timeout=%u,cmd=%s)", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), intinfo, epinfo, (char *)str_text(buf), (int)bufsiz, processed, timeout, usb_cmdname(cmd));
  2945. *processed = 0;
  2946. if (cgpu->usbinfo.nodev) {
  2947. USB_REJECT(cgpu, MODE_BULK_WRITE);
  2948. err = LIBUSB_ERROR_NO_DEVICE;
  2949. goto out_noerrmsg;
  2950. }
  2951. usbdev = cgpu->usbdev;
  2952. if (timeout == DEVTIMEOUT)
  2953. timeout = usbdev->found->timeout;
  2954. tot = 0;
  2955. err = LIBUSB_SUCCESS;
  2956. initial_timeout = timeout;
  2957. cgtime(&write_start);
  2958. tried_reset = 0;
  2959. while (bufsiz > 0) {
  2960. int tosend = bufsiz;
  2961. /* USB 1.1 devices don't handle zero packets well so split them
  2962. * up to not have the final transfer equal to the wMaxPacketSize
  2963. * or they will stall waiting for more data. */
  2964. if (usbdev->usb11) {
  2965. struct usb_epinfo *ue = &usbdev->found->intinfos[intinfo].epinfos[epinfo];
  2966. if (tosend == ue->wMaxPacketSize) {
  2967. tosend >>= 1;
  2968. if (unlikely(!tosend))
  2969. tosend = 1;
  2970. }
  2971. }
  2972. err = usb_perform_transfer(cgpu, usbdev, intinfo, epinfo, (unsigned char *)buf,
  2973. tosend, &sent, timeout, MODE_BULK_WRITE,
  2974. cmd, first ? SEQ0 : SEQ1, false, usbdev->tt);
  2975. cgtime(&tv_finish);
  2976. 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);
  2977. tot += sent;
  2978. /* Unlike reads, even a timeout error is unrecoverable on
  2979. * writes. */
  2980. if (err) {
  2981. applog(LOG_WARNING, "%s %i %s usb write err:(%d) %s", cgpu->drv->name,
  2982. cgpu->device_id, usb_cmdname(cmd), err, libusb_error_name(err));
  2983. if (err != LIBUSB_ERROR_NO_DEVICE && !tried_reset) {
  2984. err = libusb_reset_device(usbdev->handle);
  2985. tried_reset = 1; // don't try reset twice in a row
  2986. applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
  2987. cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
  2988. }
  2989. } else {
  2990. tried_reset = 0;
  2991. }
  2992. if (err)
  2993. break;
  2994. buf += sent;
  2995. bufsiz -= sent;
  2996. first = false;
  2997. done = tdiff(&tv_finish, &write_start);
  2998. // N.B. this is: return last err with whatever size was written
  2999. timeout = initial_timeout - (done * 1000);
  3000. if (timeout <= 0)
  3001. break;
  3002. }
  3003. *processed = tot;
  3004. out_noerrmsg:
  3005. if (NODEV(err)) {
  3006. cg_ruwlock(&cgpu->usbinfo.devlock);
  3007. release_cgpu(cgpu);
  3008. DEVWUNLOCK(cgpu, pstate);
  3009. } else
  3010. DEVRUNLOCK(cgpu, pstate);
  3011. return err;
  3012. }
  3013. /* As we do for bulk reads, emulate a sync function for control transfers using
  3014. * our own timeouts that takes the same parameters as libusb_control_transfer.
  3015. */
  3016. static int usb_control_transfer(struct cgpu_info *cgpu, libusb_device_handle *dev_handle, uint8_t bmRequestType,
  3017. uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
  3018. unsigned char *buffer, uint16_t wLength, unsigned int timeout)
  3019. {
  3020. struct usb_transfer ut;
  3021. unsigned char buf[70];
  3022. int err, transferred;
  3023. bool tt = false;
  3024. if (unlikely(cgpu->shutdown))
  3025. return libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, buffer, wLength, timeout);
  3026. init_usb_transfer(&ut);
  3027. libusb_fill_control_setup(buf, bmRequestType, bRequest, wValue,
  3028. wIndex, wLength);
  3029. if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) {
  3030. if (wLength)
  3031. cg_memcpy(buf + LIBUSB_CONTROL_SETUP_SIZE, buffer, wLength);
  3032. if (cgpu->usbdev->descriptor->bcdUSB < 0x0200)
  3033. tt = true;
  3034. }
  3035. libusb_fill_control_transfer(ut.transfer, dev_handle, buf, transfer_callback,
  3036. &ut, 0);
  3037. err = usb_submit_transfer(&ut, ut.transfer, false, tt);
  3038. if (!err)
  3039. err = callback_wait(&ut, &transferred, timeout);
  3040. if (err == LIBUSB_SUCCESS && transferred) {
  3041. if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
  3042. cg_memcpy(buffer, libusb_control_transfer_get_data(ut.transfer),
  3043. transferred);
  3044. err = transferred;
  3045. goto out;
  3046. }
  3047. err = usb_transfer_toerr(err);
  3048. out:
  3049. complete_usb_transfer(&ut);
  3050. return err;
  3051. }
  3052. 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)
  3053. {
  3054. struct cg_usb_device *usbdev;
  3055. #if DO_USB_STATS
  3056. struct timeval tv_start, tv_finish;
  3057. #endif
  3058. unsigned char buf[64];
  3059. uint32_t *buf32 = (uint32_t *)buf;
  3060. int err, i, bufsiz;
  3061. 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));
  3062. if (cgpu->usbinfo.nodev) {
  3063. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  3064. err = LIBUSB_ERROR_NO_DEVICE;
  3065. goto out_;
  3066. }
  3067. usbdev = cgpu->usbdev;
  3068. if (timeout == DEVTIMEOUT)
  3069. timeout = usbdev->found->timeout;
  3070. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  3071. if (siz > 0) {
  3072. bufsiz = siz - 1;
  3073. bufsiz >>= 2;
  3074. bufsiz++;
  3075. for (i = 0; i < bufsiz; i++)
  3076. buf32[i] = htole32(data[i]);
  3077. }
  3078. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex(buf, (size_t)siz));
  3079. STATS_TIMEVAL(&tv_start);
  3080. err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
  3081. wValue, wIndex, buf, (uint16_t)siz, timeout);
  3082. STATS_TIMEVAL(&tv_finish);
  3083. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0, timeout);
  3084. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  3085. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  3086. applog(LOG_WARNING, "%s %i usb transfer err:(%d) %s", cgpu->drv->name, cgpu->device_id,
  3087. err, libusb_error_name(err));
  3088. }
  3089. out_:
  3090. return err;
  3091. }
  3092. /* We use the write devlock for control transfers since some control transfers
  3093. * are rare but may be changing settings within the device causing problems
  3094. * if concurrent transfers are happening. Using the write lock serialises
  3095. * any transfers. */
  3096. 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)
  3097. {
  3098. int pstate, err;
  3099. DEVWLOCK(cgpu, pstate);
  3100. err = __usb_transfer(cgpu, request_type, bRequest, wValue, wIndex, data, siz, timeout, cmd);
  3101. if (NOCONTROLDEV(err))
  3102. release_cgpu(cgpu);
  3103. DEVWUNLOCK(cgpu, pstate);
  3104. return err;
  3105. }
  3106. 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)
  3107. {
  3108. struct cg_usb_device *usbdev;
  3109. #if DO_USB_STATS
  3110. struct timeval tv_start, tv_finish;
  3111. #endif
  3112. unsigned char tbuf[64];
  3113. int err, pstate;
  3114. DEVWLOCK(cgpu, pstate);
  3115. 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));
  3116. if (cgpu->usbinfo.nodev) {
  3117. USB_REJECT(cgpu, MODE_CTRL_READ);
  3118. err = LIBUSB_ERROR_NO_DEVICE;
  3119. goto out_noerrmsg;
  3120. }
  3121. usbdev = cgpu->usbdev;
  3122. if (timeout == DEVTIMEOUT)
  3123. timeout = usbdev->found->timeout;
  3124. *amount = 0;
  3125. memset(tbuf, 0, 64);
  3126. STATS_TIMEVAL(&tv_start);
  3127. err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
  3128. wValue, wIndex, tbuf, (uint16_t)bufsiz, timeout);
  3129. STATS_TIMEVAL(&tv_finish);
  3130. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0, timeout);
  3131. cg_memcpy(buf, tbuf, bufsiz);
  3132. 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);
  3133. if (err > 0) {
  3134. *amount = err;
  3135. err = 0;
  3136. }
  3137. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  3138. applog(LOG_WARNING, "%s %i usb transfer read err:(%d) %s", cgpu->drv->name, cgpu->device_id,
  3139. err, libusb_error_name(err));
  3140. }
  3141. out_noerrmsg:
  3142. if (NOCONTROLDEV(err))
  3143. release_cgpu(cgpu);
  3144. DEVWUNLOCK(cgpu, pstate);
  3145. return err;
  3146. }
  3147. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  3148. #define FTDI_RS0_CTS (1 << 4)
  3149. #define FTDI_RS0_DSR (1 << 5)
  3150. #define FTDI_RS0_RI (1 << 6)
  3151. #define FTDI_RS0_RLSD (1 << 7)
  3152. /* Clear to send for FTDI */
  3153. int usb_ftdi_cts(struct cgpu_info *cgpu)
  3154. {
  3155. char buf[2], ret;
  3156. int err, amount;
  3157. err = _usb_transfer_read(cgpu, (uint8_t)FTDI_TYPE_IN, (uint8_t)5,
  3158. (uint16_t)0, (uint16_t)0, buf, 2,
  3159. &amount, DEVTIMEOUT, C_FTDI_STATUS);
  3160. /* We return true in case drivers are waiting indefinitely to try and
  3161. * write to something that's not there. */
  3162. if (err)
  3163. return true;
  3164. ret = buf[0] & FTDI_STATUS_B0_MASK;
  3165. return (ret & FTDI_RS0_CTS);
  3166. }
  3167. int _usb_ftdi_set_latency(struct cgpu_info *cgpu, int intinfo)
  3168. {
  3169. int err = 0;
  3170. int pstate;
  3171. DEVWLOCK(cgpu, pstate);
  3172. if (cgpu->usbdev) {
  3173. if (cgpu->usbdev->usb_type != USB_TYPE_FTDI) {
  3174. applog(LOG_ERR, "%s: cgid %d latency request on non-FTDI device",
  3175. cgpu->drv->name, cgpu->cgminer_id);
  3176. err = LIBUSB_ERROR_NOT_SUPPORTED;
  3177. } else if (cgpu->usbdev->found->latency == LATENCY_UNUSED) {
  3178. applog(LOG_ERR, "%s: cgid %d invalid latency (UNUSED)",
  3179. cgpu->drv->name, cgpu->cgminer_id);
  3180. err = LIBUSB_ERROR_NOT_SUPPORTED;
  3181. }
  3182. if (!err)
  3183. err = __usb_transfer(cgpu, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
  3184. cgpu->usbdev->found->latency,
  3185. USBIF(cgpu->usbdev, intinfo),
  3186. NULL, 0, DEVTIMEOUT, C_LATENCY);
  3187. }
  3188. DEVWUNLOCK(cgpu, pstate);
  3189. applog(LOG_DEBUG, "%s: cgid %d %s got err %d",
  3190. cgpu->drv->name, cgpu->cgminer_id,
  3191. usb_cmdname(C_LATENCY), err);
  3192. return err;
  3193. }
  3194. void usb_buffer_clear(struct cgpu_info *cgpu)
  3195. {
  3196. int pstate;
  3197. DEVWLOCK(cgpu, pstate);
  3198. if (cgpu->usbdev)
  3199. cgpu->usbdev->bufamt = 0;
  3200. DEVWUNLOCK(cgpu, pstate);
  3201. }
  3202. uint32_t usb_buffer_size(struct cgpu_info *cgpu)
  3203. {
  3204. uint32_t ret = 0;
  3205. int pstate;
  3206. DEVRLOCK(cgpu, pstate);
  3207. if (cgpu->usbdev)
  3208. ret = cgpu->usbdev->bufamt;
  3209. DEVRUNLOCK(cgpu, pstate);
  3210. return ret;
  3211. }
  3212. /*
  3213. * The value returned (0) when usbdev is NULL
  3214. * doesn't matter since it also means the next call to
  3215. * any usbutils function will fail with a nodev
  3216. * N.B. this is to get the interface number to use in a control_transfer
  3217. * which for some devices isn't actually the interface number
  3218. */
  3219. int _usb_interface(struct cgpu_info *cgpu, int intinfo)
  3220. {
  3221. int interface = 0;
  3222. int pstate;
  3223. DEVRLOCK(cgpu, pstate);
  3224. if (cgpu->usbdev)
  3225. interface = cgpu->usbdev->found->intinfos[intinfo].ctrl_transfer;
  3226. DEVRUNLOCK(cgpu, pstate);
  3227. return interface;
  3228. }
  3229. enum sub_ident usb_ident(struct cgpu_info *cgpu)
  3230. {
  3231. enum sub_ident ident = IDENT_UNK;
  3232. int pstate;
  3233. DEVRLOCK(cgpu, pstate);
  3234. if (cgpu->usbdev)
  3235. ident = cgpu->usbdev->ident;
  3236. DEVRUNLOCK(cgpu, pstate);
  3237. return ident;
  3238. }
  3239. // Need to set all devices with matching usbdev
  3240. void usb_set_dev_start(struct cgpu_info *cgpu)
  3241. {
  3242. struct cg_usb_device *cgusb;
  3243. struct cgpu_info *cgpu2;
  3244. struct timeval now;
  3245. int pstate;
  3246. DEVWLOCK(cgpu, pstate);
  3247. cgusb = cgpu->usbdev;
  3248. // If the device wasn't dropped
  3249. if (cgusb != NULL) {
  3250. int i;
  3251. cgtime(&now);
  3252. for (i = 0; i < total_devices; i++) {
  3253. cgpu2 = get_devices(i);
  3254. if (cgpu2->usbdev == cgusb)
  3255. copy_time(&(cgpu2->dev_start_tv), &now);
  3256. }
  3257. }
  3258. DEVWUNLOCK(cgpu, pstate);
  3259. }
  3260. void usb_cleanup(void)
  3261. {
  3262. struct cgpu_info *cgpu;
  3263. int count, pstate;
  3264. int i;
  3265. hotplug_time = 0;
  3266. cgsleep_ms(10);
  3267. count = 0;
  3268. for (i = 0; i < total_devices; i++) {
  3269. cgpu = devices[i];
  3270. switch (cgpu->drv->drv_id) {
  3271. case DRIVER_bflsc:
  3272. case DRIVER_bitforce:
  3273. case DRIVER_bitfury:
  3274. case DRIVER_cointerra:
  3275. case DRIVER_drillbit:
  3276. case DRIVER_modminer:
  3277. case DRIVER_icarus:
  3278. case DRIVER_avalon:
  3279. case DRIVER_avalon2:
  3280. case DRIVER_avalon4:
  3281. case DRIVER_bitmain:
  3282. case DRIVER_bmsc:
  3283. case DRIVER_klondike:
  3284. case DRIVER_hashfast:
  3285. DEVWLOCK(cgpu, pstate);
  3286. release_cgpu(cgpu);
  3287. DEVWUNLOCK(cgpu, pstate);
  3288. count++;
  3289. break;
  3290. default:
  3291. break;
  3292. }
  3293. }
  3294. /*
  3295. * Must attempt to wait for the resource thread to release coz
  3296. * during a restart it won't automatically release them in linux
  3297. */
  3298. if (count) {
  3299. struct timeval start, now;
  3300. cgtime(&start);
  3301. while (42) {
  3302. cgsleep_ms(50);
  3303. mutex_lock(&cgusbres_lock);
  3304. if (!res_work_head)
  3305. break;
  3306. cgtime(&now);
  3307. if (tdiff(&now, &start) > 0.366) {
  3308. applog(LOG_WARNING,
  3309. "usb_cleanup gave up waiting for resource thread");
  3310. break;
  3311. }
  3312. mutex_unlock(&cgusbres_lock);
  3313. }
  3314. mutex_unlock(&cgusbres_lock);
  3315. }
  3316. cgsem_destroy(&usb_resource_sem);
  3317. }
  3318. #define DRIVER_COUNT_FOUND(X) if (X##_drv.name && strcasecmp(ptr, X##_drv.name) == 0) { \
  3319. drv_count[X##_drv.drv_id].limit = lim; \
  3320. found = true; \
  3321. }
  3322. void usb_initialise(void)
  3323. {
  3324. char *fre, *ptr, *comma, *colon;
  3325. int bus, dev, lim, i;
  3326. bool found;
  3327. INIT_LIST_HEAD(&ut_list);
  3328. for (i = 0; i < DRIVER_MAX; i++) {
  3329. drv_count[i].count = 0;
  3330. drv_count[i].limit = 999999;
  3331. }
  3332. cgusb_check_init();
  3333. if (opt_usb_select && *opt_usb_select) {
  3334. // Absolute device limit
  3335. if (*opt_usb_select == ':') {
  3336. total_limit = atoi(opt_usb_select+1);
  3337. if (total_limit < 0)
  3338. quit(1, "Invalid --usb total limit");
  3339. // Comma list of bus:dev devices to match
  3340. } else if (isdigit(*opt_usb_select)) {
  3341. fre = ptr = strdup(opt_usb_select);
  3342. do {
  3343. comma = strchr(ptr, ',');
  3344. if (comma)
  3345. *(comma++) = '\0';
  3346. colon = strchr(ptr, ':');
  3347. if (!colon)
  3348. quit(1, "Invalid --usb bus:dev missing ':'");
  3349. *(colon++) = '\0';
  3350. if (!isdigit(*ptr))
  3351. quit(1, "Invalid --usb bus:dev - bus must be a number");
  3352. if (!isdigit(*colon) && *colon != '*')
  3353. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  3354. bus = atoi(ptr);
  3355. if (bus <= 0)
  3356. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  3357. if (*colon == '*')
  3358. dev = -1;
  3359. else {
  3360. dev = atoi(colon);
  3361. if (dev <= 0)
  3362. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  3363. }
  3364. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  3365. if (unlikely(!busdev))
  3366. quit(1, "USB failed to realloc busdev");
  3367. busdev[busdev_count-1].bus_number = bus;
  3368. busdev[busdev_count-1].device_address = dev;
  3369. ptr = comma;
  3370. } while (ptr);
  3371. free(fre);
  3372. // Comma list of DRV:limit
  3373. } else {
  3374. fre = ptr = strdup(opt_usb_select);
  3375. do {
  3376. comma = strchr(ptr, ',');
  3377. if (comma)
  3378. *(comma++) = '\0';
  3379. colon = strchr(ptr, ':');
  3380. if (!colon)
  3381. quit(1, "Invalid --usb DRV:limit missing ':'");
  3382. *(colon++) = '\0';
  3383. if (!isdigit(*colon))
  3384. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  3385. lim = atoi(colon);
  3386. if (lim < 0)
  3387. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  3388. found = false;
  3389. /* Use the DRIVER_PARSE_COMMANDS macro to iterate
  3390. * over all the drivers. */
  3391. DRIVER_PARSE_COMMANDS(DRIVER_COUNT_FOUND)
  3392. if (!found)
  3393. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  3394. ptr = comma;
  3395. } while (ptr);
  3396. free(fre);
  3397. }
  3398. }
  3399. }
  3400. #ifndef WIN32
  3401. #include <errno.h>
  3402. #include <unistd.h>
  3403. #include <sys/stat.h>
  3404. #include <sys/file.h>
  3405. #include <fcntl.h>
  3406. #ifndef __APPLE__
  3407. union semun {
  3408. int val;
  3409. struct semid_ds *buf;
  3410. unsigned short *array;
  3411. struct seminfo *__buf;
  3412. };
  3413. #endif
  3414. #else
  3415. static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
  3416. {
  3417. FreeSid(((PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor))->Group);
  3418. free(sec->lpSecurityDescriptor);
  3419. free(sec);
  3420. return NULL;
  3421. }
  3422. static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
  3423. {
  3424. SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
  3425. PSID gsid = NULL;
  3426. LPSECURITY_ATTRIBUTES sec_att = NULL;
  3427. PSECURITY_DESCRIPTOR sec_des = NULL;
  3428. sec_des = malloc(sizeof(*sec_des));
  3429. if (unlikely(!sec_des))
  3430. quit(1, "MTX: Failed to malloc LPSECURITY_DESCRIPTOR");
  3431. if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
  3432. applog(LOG_ERR,
  3433. "MTX: %s (%d:%d) USB failed to init secdes err (%d)",
  3434. dname, (int)bus_number, (int)device_address,
  3435. (int)GetLastError());
  3436. free(sec_des);
  3437. return NULL;
  3438. }
  3439. if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
  3440. applog(LOG_ERR,
  3441. "MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
  3442. dname, (int)bus_number, (int)device_address,
  3443. (int)GetLastError());
  3444. free(sec_des);
  3445. return NULL;
  3446. }
  3447. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
  3448. applog(LOG_ERR,
  3449. "MTX: %s (%d:%d) USB failed to create gsid err (%d)",
  3450. dname, (int)bus_number, (int)device_address,
  3451. (int)GetLastError());
  3452. free(sec_des);
  3453. return NULL;
  3454. }
  3455. if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
  3456. applog(LOG_ERR,
  3457. "MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
  3458. dname, (int)bus_number, (int)device_address,
  3459. (int)GetLastError());
  3460. FreeSid(gsid);
  3461. free(sec_des);
  3462. return NULL;
  3463. }
  3464. sec_att = malloc(sizeof(*sec_att));
  3465. if (unlikely(!sec_att))
  3466. quit(1, "MTX: Failed to malloc LPSECURITY_ATTRIBUTES");
  3467. sec_att->nLength = sizeof(*sec_att);
  3468. sec_att->lpSecurityDescriptor = sec_des;
  3469. sec_att->bInheritHandle = FALSE;
  3470. return sec_att;
  3471. }
  3472. #endif
  3473. // Any errors should always be printed since they will rarely if ever occur
  3474. // and thus it is best to always display them
  3475. static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
  3476. {
  3477. applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
  3478. #ifdef WIN32
  3479. struct cgpu_info *cgpu;
  3480. LPSECURITY_ATTRIBUTES sec;
  3481. HANDLE usbMutex;
  3482. char name[64];
  3483. DWORD res;
  3484. int i;
  3485. if (is_in_use_bd(bus_number, device_address))
  3486. return false;
  3487. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  3488. sec = mksec(dname, bus_number, device_address);
  3489. if (!sec)
  3490. return false;
  3491. usbMutex = CreateMutex(sec, FALSE, name);
  3492. if (usbMutex == NULL) {
  3493. applog(LOG_ERR,
  3494. "MTX: %s USB failed to get '%s' err (%d)",
  3495. dname, name, (int)GetLastError());
  3496. sec = unsec(sec);
  3497. return false;
  3498. }
  3499. res = WaitForSingleObject(usbMutex, 0);
  3500. switch(res) {
  3501. case WAIT_OBJECT_0:
  3502. case WAIT_ABANDONED:
  3503. // Am I using it already?
  3504. for (i = 0; i < total_devices; i++) {
  3505. cgpu = get_devices(i);
  3506. if (cgpu->usbinfo.bus_number == bus_number &&
  3507. cgpu->usbinfo.device_address == device_address &&
  3508. cgpu->usbinfo.nodev == false) {
  3509. if (ReleaseMutex(usbMutex)) {
  3510. applog(LOG_WARNING,
  3511. "MTX: %s USB can't get '%s' - device in use",
  3512. dname, name);
  3513. goto fail;
  3514. }
  3515. applog(LOG_ERR,
  3516. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  3517. dname, name, (int)GetLastError());
  3518. goto fail;
  3519. }
  3520. }
  3521. break;
  3522. case WAIT_TIMEOUT:
  3523. if (!hotplug_mode)
  3524. applog(LOG_WARNING,
  3525. "MTX: %s USB failed to get '%s' - device in use",
  3526. dname, name);
  3527. goto fail;
  3528. case WAIT_FAILED:
  3529. applog(LOG_ERR,
  3530. "MTX: %s USB failed to get '%s' err (%d)",
  3531. dname, name, (int)GetLastError());
  3532. goto fail;
  3533. default:
  3534. applog(LOG_ERR,
  3535. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  3536. dname, name, (int)res);
  3537. goto fail;
  3538. }
  3539. add_in_use(bus_number, device_address, false);
  3540. in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
  3541. return true;
  3542. fail:
  3543. CloseHandle(usbMutex);
  3544. sec = unsec(sec);
  3545. return false;
  3546. #else
  3547. char name[64];
  3548. int fd;
  3549. if (is_in_use_bd(bus_number, device_address))
  3550. return false;
  3551. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  3552. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  3553. if (fd == -1) {
  3554. applog(LOG_ERR, "%s USB open failed '%s' err (%d) %s",
  3555. dname, name, errno, strerror(errno));
  3556. return false;
  3557. }
  3558. if (flock(fd, LOCK_EX | LOCK_NB)) {
  3559. applog(LOG_INFO, "%s USB failed to get '%s' - device in use",
  3560. dname, name);
  3561. close(fd);
  3562. return false;
  3563. }
  3564. add_in_use(bus_number, device_address, false);
  3565. in_use_store_fd(bus_number, device_address, fd);
  3566. return true;
  3567. #endif
  3568. }
  3569. // Any errors should always be printed since they will rarely if ever occur
  3570. // and thus it is best to always display them
  3571. static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
  3572. {
  3573. applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
  3574. #ifdef WIN32
  3575. LPSECURITY_ATTRIBUTES sec = NULL;
  3576. HANDLE usbMutex = NULL;
  3577. char name[64];
  3578. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  3579. in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
  3580. if (!usbMutex || !sec)
  3581. goto fila;
  3582. if (!ReleaseMutex(usbMutex))
  3583. applog(LOG_ERR,
  3584. "MTX: %s USB failed to release '%s' err (%d)",
  3585. dname, name, (int)GetLastError());
  3586. fila:
  3587. if (usbMutex)
  3588. CloseHandle(usbMutex);
  3589. if (sec)
  3590. unsec(sec);
  3591. remove_in_use(bus_number, device_address);
  3592. return;
  3593. #else
  3594. char name[64];
  3595. int fd;
  3596. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  3597. fd = in_use_get_fd(bus_number, device_address);
  3598. if (fd < 0)
  3599. return;
  3600. remove_in_use(bus_number, device_address);
  3601. close(fd);
  3602. unlink(name);
  3603. return;
  3604. #endif
  3605. }
  3606. static void resource_process()
  3607. {
  3608. struct resource_work *res_work = NULL;
  3609. struct resource_reply *res_reply = NULL;
  3610. bool ok;
  3611. applog(LOG_DEBUG, "RES: %s (%d:%d) lock=%d",
  3612. res_work_head->dname,
  3613. (int)res_work_head->bus_number,
  3614. (int)res_work_head->device_address,
  3615. res_work_head->lock);
  3616. if (res_work_head->lock) {
  3617. ok = resource_lock(res_work_head->dname,
  3618. res_work_head->bus_number,
  3619. res_work_head->device_address);
  3620. applog(LOG_DEBUG, "RES: %s (%d:%d) lock ok=%d",
  3621. res_work_head->dname,
  3622. (int)res_work_head->bus_number,
  3623. (int)res_work_head->device_address,
  3624. ok);
  3625. res_reply = calloc(1, sizeof(*res_reply));
  3626. if (unlikely(!res_reply))
  3627. quit(1, "USB failed to calloc res_reply");
  3628. res_reply->bus_number = res_work_head->bus_number;
  3629. res_reply->device_address = res_work_head->device_address;
  3630. res_reply->got = ok;
  3631. res_reply->next = res_reply_head;
  3632. res_reply_head = res_reply;
  3633. }
  3634. else
  3635. resource_unlock(res_work_head->dname,
  3636. res_work_head->bus_number,
  3637. res_work_head->device_address);
  3638. res_work = res_work_head;
  3639. res_work_head = res_work_head->next;
  3640. free(res_work);
  3641. }
  3642. void *usb_resource_thread(void __maybe_unused *userdata)
  3643. {
  3644. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3645. RenameThread("USBResource");
  3646. applog(LOG_DEBUG, "RES: thread starting");
  3647. while (42) {
  3648. /* Wait to be told we have work to do */
  3649. cgsem_wait(&usb_resource_sem);
  3650. mutex_lock(&cgusbres_lock);
  3651. while (res_work_head)
  3652. resource_process();
  3653. mutex_unlock(&cgusbres_lock);
  3654. }
  3655. return NULL;
  3656. }
  3657. void initialise_usblocks(void)
  3658. {
  3659. mutex_init(&cgusb_lock);
  3660. mutex_init(&cgusbres_lock);
  3661. cglock_init(&cgusb_fd_lock);
  3662. }
  3663. #ifdef USE_BITMAIN
  3664. struct cgpu_info *btm_alloc_cgpu(struct device_drv *drv, int threads)
  3665. {
  3666. struct cgpu_info *cgpu = calloc(1, sizeof(*cgpu));
  3667. if (unlikely(!cgpu))
  3668. quit(1, "Failed to calloc cgpu for %s in usb_alloc_cgpu", drv->dname);
  3669. cgpu->drv = drv;
  3670. cgpu->deven = DEV_ENABLED;
  3671. cgpu->threads = threads;
  3672. cgpu->usbinfo.nodev = true;
  3673. cgpu->device_fd = -1;
  3674. cglock_init(&cgpu->usbinfo.devlock);
  3675. return cgpu;
  3676. }
  3677. struct cgpu_info *btm_free_cgpu(struct cgpu_info *cgpu)
  3678. {
  3679. if (cgpu->drv->copy)
  3680. free(cgpu->drv);
  3681. if(cgpu->device_path) {
  3682. free(cgpu->device_path);
  3683. }
  3684. free(cgpu);
  3685. return NULL;
  3686. }
  3687. bool btm_init(struct cgpu_info *cgpu, const char * devpath)
  3688. {
  3689. #ifdef WIN32
  3690. int fd = -1;
  3691. signed short timeout = 1;
  3692. unsigned long baud = 115200;
  3693. bool purge = true;
  3694. HANDLE hSerial = NULL;
  3695. applog(LOG_DEBUG, "btm_init cgpu->device_fd=%d", cgpu->device_fd);
  3696. if(cgpu->device_fd >= 0) {
  3697. return false;
  3698. }
  3699. hSerial = CreateFile(devpath, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
  3700. if (unlikely(hSerial == INVALID_HANDLE_VALUE))
  3701. {
  3702. DWORD e = GetLastError();
  3703. switch (e) {
  3704. case ERROR_ACCESS_DENIED:
  3705. applog(LOG_DEBUG, "Do not have user privileges required to open %s", devpath);
  3706. break;
  3707. case ERROR_SHARING_VIOLATION:
  3708. applog(LOG_DEBUG, "%s is already in use by another process", devpath);
  3709. break;
  3710. default:
  3711. applog(LOG_DEBUG, "Open %s failed, GetLastError:%d", devpath, (int)e);
  3712. break;
  3713. }
  3714. } else {
  3715. // thanks to af_newbie for pointers about this
  3716. COMMCONFIG comCfg = {0};
  3717. comCfg.dwSize = sizeof(COMMCONFIG);
  3718. comCfg.wVersion = 1;
  3719. comCfg.dcb.DCBlength = sizeof(DCB);
  3720. comCfg.dcb.BaudRate = baud;
  3721. comCfg.dcb.fBinary = 1;
  3722. comCfg.dcb.fDtrControl = DTR_CONTROL_ENABLE;
  3723. comCfg.dcb.fRtsControl = RTS_CONTROL_ENABLE;
  3724. comCfg.dcb.ByteSize = 8;
  3725. SetCommConfig(hSerial, &comCfg, sizeof(comCfg));
  3726. // Code must specify a valid timeout value (0 means don't timeout)
  3727. const DWORD ctoms = (timeout * 100);
  3728. COMMTIMEOUTS cto = {ctoms, 0, ctoms, 0, ctoms};
  3729. SetCommTimeouts(hSerial, &cto);
  3730. if (purge) {
  3731. PurgeComm(hSerial, PURGE_RXABORT);
  3732. PurgeComm(hSerial, PURGE_TXABORT);
  3733. PurgeComm(hSerial, PURGE_RXCLEAR);
  3734. PurgeComm(hSerial, PURGE_TXCLEAR);
  3735. }
  3736. fd = _open_osfhandle((intptr_t)hSerial, 0);
  3737. }
  3738. #else
  3739. int fd = -1;
  3740. if(cgpu->device_fd >= 0) {
  3741. return false;
  3742. }
  3743. fd = open(devpath, O_RDWR|O_EXCL|O_NONBLOCK);
  3744. #endif
  3745. if(fd == -1) {
  3746. applog(LOG_DEBUG, "%s open %s error %d",
  3747. cgpu->drv->dname, devpath, errno);
  3748. return false;
  3749. }
  3750. cgpu->device_path = strdup(devpath);
  3751. cgpu->device_fd = fd;
  3752. cgpu->usbinfo.nodev = false;
  3753. applog(LOG_DEBUG, "btm_init open device fd = %d", cgpu->device_fd);
  3754. return true;
  3755. }
  3756. void btm_uninit(struct cgpu_info *cgpu)
  3757. {
  3758. applog(LOG_DEBUG, "BTM uninit %s%i", cgpu->drv->name, cgpu->device_fd);
  3759. // May have happened already during a failed initialisation
  3760. // if release_cgpu() was called due to a USB NODEV(err)
  3761. close(cgpu->device_fd);
  3762. if(cgpu->device_path) {
  3763. free(cgpu->device_path);
  3764. cgpu->device_path = NULL;
  3765. }
  3766. }
  3767. void btm_detect(struct device_drv *drv, bool (*device_detect)(const char*))
  3768. {
  3769. ssize_t count, i;
  3770. applog(LOG_DEBUG, "BTM scan devices: checking for %s devices", drv->name);
  3771. if (total_count >= total_limit) {
  3772. applog(LOG_DEBUG, "BTM scan devices: total limit %d reached", total_limit);
  3773. return;
  3774. }
  3775. if (drv_count[drv->drv_id].count >= drv_count[drv->drv_id].limit) {
  3776. applog(LOG_DEBUG,
  3777. "BTM scan devices: %s limit %d reached",
  3778. drv->dname, drv_count[drv->drv_id].limit);
  3779. return;
  3780. }
  3781. device_detect("asic");
  3782. }
  3783. int btm_read(struct cgpu_info *cgpu, char *buf, size_t bufsize)
  3784. {
  3785. int err = 0;
  3786. //applog(LOG_DEBUG, "btm_read ----- %d -----", bufsize);
  3787. err = read(cgpu->device_fd, buf, bufsize);
  3788. return err;
  3789. }
  3790. int btm_write(struct cgpu_info *cgpu, char *buf, size_t bufsize)
  3791. {
  3792. int err = 0;
  3793. //applog(LOG_DEBUG, "btm_write ----- %d -----", bufsize);
  3794. err = write(cgpu->device_fd, buf, bufsize);
  3795. return err;
  3796. }
  3797. #endif