usbutils.c 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300
  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. // There is no windows version
  51. #define ANT_S1_TIMEOUT_MS 200
  52. #define ANT_S2_TIMEOUT_MS 200
  53. #ifdef WIN32
  54. #define BFLSC_TIMEOUT_MS 999
  55. #define BITFORCE_TIMEOUT_MS 999
  56. #define MODMINER_TIMEOUT_MS 999
  57. #define AVALON_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. #define GRIDSEED_TIMEOUT_MS 999
  64. #define ZEUS_TIMEOUT_MS 999
  65. #define LKETC_TIMEOUT_MS 999
  66. /* The safety timeout we use, cancelling async transfers on windows that fail
  67. * to timeout on their own. */
  68. #define WIN_CALLBACK_EXTRA 40
  69. #define WIN_WRITE_CBEXTRA 5000
  70. #else
  71. #define BFLSC_TIMEOUT_MS 300
  72. #define BITFORCE_TIMEOUT_MS 200
  73. #define MODMINER_TIMEOUT_MS 100
  74. #define AVALON_TIMEOUT_MS 200
  75. #define KLONDIKE_TIMEOUT_MS 200
  76. #define COINTERRA_TIMEOUT_MS 200
  77. #define HASHFAST_TIMEOUT_MS 500
  78. #define HASHRATIO_TIMEOUT_MS 200
  79. #define BLOCKERUPTER_TIMEOUT_MS 300
  80. #define GRIDSEED_TIMEOUT_MS 200
  81. #define ZEUS_TIMEOUT_MS 200
  82. #define LKETC_TIMEOUT_MS 200
  83. #endif
  84. #define USB_EPS(_intx, _epinfosx) { \
  85. .interface = _intx, \
  86. .ctrl_transfer = _intx, \
  87. .epinfo_count = ARRAY_SIZE(_epinfosx), \
  88. .epinfos = _epinfosx \
  89. }
  90. #define USB_EPS_CTRL(_inty, _ctrlinty, _epinfosy) { \
  91. .interface = _inty, \
  92. .ctrl_transfer = _ctrlinty, \
  93. .epinfo_count = ARRAY_SIZE(_epinfosy), \
  94. .epinfos = _epinfosy \
  95. }
  96. /* Linked list of all async transfers in progress. Protected by cgusb_fd_lock.
  97. * This allows us to not stop the usb polling thread till all are complete, and
  98. * to find cancellable transfers. */
  99. static struct list_head ut_list;
  100. #ifdef USE_BFLSC
  101. static struct usb_epinfo bflsc_epinfos[] = {
  102. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPI(1), 0, 0 },
  103. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPO(2), 0, 0 }
  104. };
  105. static struct usb_intinfo bflsc_ints[] = {
  106. USB_EPS(0, bflsc_epinfos)
  107. };
  108. #endif
  109. #ifdef USE_BITFORCE
  110. // N.B. transfer size is 512 with USB2.0, but only 64 with USB1.1
  111. static struct usb_epinfo bfl_epinfos[] = {
  112. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  113. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  114. };
  115. static struct usb_intinfo bfl_ints[] = {
  116. USB_EPS(0, bfl_epinfos)
  117. };
  118. #endif
  119. #ifdef USE_BITFURY
  120. static struct usb_epinfo bfu0_epinfos[] = {
  121. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(2), 0, 0 }
  122. };
  123. static struct usb_epinfo bfu1_epinfos[] = {
  124. { LIBUSB_TRANSFER_TYPE_BULK, 16, EPI(3), 0, 0 },
  125. { LIBUSB_TRANSFER_TYPE_BULK, 16, EPO(4), 0, 0 }
  126. };
  127. /* Default to interface 1 */
  128. static struct usb_intinfo bfu_ints[] = {
  129. USB_EPS(1, bfu1_epinfos),
  130. USB_EPS(0, bfu0_epinfos)
  131. };
  132. static struct usb_epinfo bxf0_epinfos[] = {
  133. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(1), 0, 0 }
  134. };
  135. static struct usb_epinfo bxf1_epinfos[] = {
  136. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(2), 0, 0 },
  137. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  138. };
  139. static struct usb_intinfo bxf_ints[] = {
  140. USB_EPS(1, bxf1_epinfos),
  141. USB_EPS(0, bxf0_epinfos)
  142. };
  143. static struct usb_epinfo nfu_epinfos[] = {
  144. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 64, EPI(1), 0, 0 },
  145. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 64, EPO(1), 0, 0 },
  146. };
  147. static struct usb_intinfo nfu_ints[] = {
  148. USB_EPS(0, nfu_epinfos)
  149. };
  150. static struct usb_epinfo bxm_epinfos[] = {
  151. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPI(1), 0, 0 },
  152. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPO(2), 0, 0 }
  153. };
  154. static struct usb_intinfo bxm_ints[] = {
  155. USB_EPS(0, bxm_epinfos)
  156. };
  157. #endif
  158. #ifdef USE_BLOCKERUPTER
  159. // BlockErupter Device
  160. static struct usb_epinfo bet_epinfos[] = {
  161. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  162. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  163. };
  164. static struct usb_intinfo bet_ints[] = {
  165. USB_EPS(0, bet_epinfos)
  166. };
  167. #endif
  168. #ifdef USE_DRILLBIT
  169. // Drillbit Bitfury devices
  170. static struct usb_epinfo drillbit_int_epinfos[] = {
  171. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(3), 0, 0 }
  172. };
  173. static struct usb_epinfo drillbit_bulk_epinfos[] = {
  174. { LIBUSB_TRANSFER_TYPE_BULK, 16, EPI(1), 0, 0 },
  175. { LIBUSB_TRANSFER_TYPE_BULK, 16, EPO(2), 0, 0 },
  176. };
  177. /* Default to interface 1 */
  178. static struct usb_intinfo drillbit_ints[] = {
  179. USB_EPS(1, drillbit_bulk_epinfos),
  180. USB_EPS(0, drillbit_int_epinfos)
  181. };
  182. #endif
  183. #ifdef USE_HASHFAST
  184. #include "driver-hashfast.h"
  185. static struct usb_epinfo hfa0_epinfos[] = {
  186. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(3), 0, 0 }
  187. };
  188. static struct usb_epinfo hfa1_epinfos[] = {
  189. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  190. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  191. };
  192. /* Default to interface 1 */
  193. static struct usb_intinfo hfa_ints[] = {
  194. USB_EPS(1, hfa1_epinfos),
  195. USB_EPS(0, hfa0_epinfos)
  196. };
  197. #endif
  198. #ifdef USE_HASHRATIO
  199. static struct usb_epinfo hro_epinfos[] = {
  200. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  201. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  202. };
  203. static struct usb_intinfo hro_ints[] = {
  204. USB_EPS(0, hro_epinfos)
  205. };
  206. #endif
  207. #ifdef USE_MODMINER
  208. static struct usb_epinfo mmq_epinfos[] = {
  209. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  210. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0, 0 }
  211. };
  212. static struct usb_intinfo mmq_ints[] = {
  213. USB_EPS(1, mmq_epinfos)
  214. };
  215. #endif
  216. #ifdef USE_AVALON
  217. static struct usb_epinfo ava_epinfos[] = {
  218. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  219. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  220. };
  221. static struct usb_intinfo ava_ints[] = {
  222. USB_EPS(0, ava_epinfos)
  223. };
  224. #endif
  225. #ifdef USE_AVALON2
  226. static struct usb_epinfo ava2_epinfos[] = {
  227. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  228. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  229. };
  230. static struct usb_intinfo ava2_ints[] = {
  231. USB_EPS(0, ava2_epinfos)
  232. };
  233. #endif
  234. #ifdef USE_KLONDIKE
  235. static struct usb_epinfo kln_epinfos[] = {
  236. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  237. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  238. };
  239. static struct usb_intinfo kln_ints[] = {
  240. USB_EPS(0, kln_epinfos)
  241. };
  242. static struct usb_epinfo kli0_epinfos[] = {
  243. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(1), 0, 0 }
  244. };
  245. static struct usb_epinfo kli1_epinfos[] = {
  246. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(2), 0, 0 },
  247. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  248. };
  249. static struct usb_intinfo kli_ints[] = {
  250. USB_EPS(1, kli1_epinfos),
  251. USB_EPS(0, kli0_epinfos)
  252. };
  253. #endif
  254. #ifdef USE_ICARUS
  255. static struct usb_epinfo ica_epinfos[] = {
  256. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  257. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  258. };
  259. static struct usb_intinfo ica_ints[] = {
  260. USB_EPS(0, ica_epinfos)
  261. };
  262. static struct usb_epinfo ica1_epinfos0[] = {
  263. { LIBUSB_TRANSFER_TYPE_INTERRUPT, 16, EPI(0x82), 0, 0 }
  264. };
  265. static struct usb_epinfo ica1_epinfos1[] = {
  266. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(0x81), 0, 0 },
  267. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(0x01), 0, 0 }
  268. };
  269. static struct usb_intinfo ica1_ints[] = {
  270. USB_EPS(1, ica1_epinfos1),
  271. USB_EPS(0, ica1_epinfos0)
  272. };
  273. static struct usb_epinfo amu_epinfos[] = {
  274. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  275. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  276. };
  277. static struct usb_intinfo amu_ints[] = {
  278. USB_EPS(0, amu_epinfos)
  279. };
  280. static struct usb_epinfo llt_epinfos[] = {
  281. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  282. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  283. };
  284. static struct usb_intinfo llt_ints[] = {
  285. USB_EPS(0, llt_epinfos)
  286. };
  287. static struct usb_epinfo cmr1_epinfos[] = {
  288. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  289. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  290. };
  291. static struct usb_intinfo cmr1_ints[] = {
  292. USB_EPS(0, cmr1_epinfos)
  293. };
  294. static struct usb_epinfo cmr2_epinfos0[] = {
  295. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  296. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  297. };
  298. static struct usb_epinfo cmr2_epinfos1[] = {
  299. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  300. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(4), 0, 0 },
  301. };
  302. static struct usb_epinfo cmr2_epinfos2[] = {
  303. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(5), 0, 0 },
  304. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(6), 0, 0 },
  305. };
  306. static struct usb_epinfo cmr2_epinfos3[] = {
  307. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(7), 0, 0 },
  308. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(8), 0, 0 }
  309. };
  310. static struct usb_intinfo cmr2_ints[] = {
  311. USB_EPS_CTRL(0, 1, cmr2_epinfos0),
  312. USB_EPS_CTRL(1, 2, cmr2_epinfos1),
  313. USB_EPS_CTRL(2, 3, cmr2_epinfos2),
  314. USB_EPS_CTRL(3, 4, cmr2_epinfos3)
  315. };
  316. #endif
  317. #ifdef USE_COINTERRA
  318. static struct usb_epinfo cointerra_epinfos[] = {
  319. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  320. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  321. };
  322. static struct usb_intinfo cointerra_ints[] = {
  323. USB_EPS(0, cointerra_epinfos)
  324. };
  325. #endif
  326. #ifdef USE_ANT_S1
  327. static struct usb_epinfo ants1_epinfos[] = {
  328. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  329. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  330. };
  331. static struct usb_intinfo ants1_ints[] = {
  332. USB_EPS(0, ants1_epinfos)
  333. };
  334. #endif
  335. #ifdef USE_ANT_S2
  336. static struct usb_epinfo ants2_epinfos[] = {
  337. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  338. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  339. };
  340. static struct usb_intinfo ants2_ints[] = {
  341. USB_EPS(0, ants2_epinfos)
  342. };
  343. #endif
  344. #ifdef USE_GRIDSEED
  345. static struct usb_epinfo gsd_epinfos[] = {
  346. // { LIBUSB_TRANSFER_TYPE_INTERRUPT, 8, EPI(2), 0, 0 },
  347. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  348. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(3), 0, 0 }
  349. };
  350. static struct usb_intinfo gsd_ints[] = {
  351. USB_EPS(1, gsd_epinfos)
  352. };
  353. static struct usb_epinfo gsd1_epinfos[] = {
  354. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  355. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  356. };
  357. static struct usb_intinfo gsd1_ints[] = {
  358. USB_EPS(0, gsd1_epinfos)
  359. };
  360. static struct usb_epinfo gsd2_epinfos[] = {
  361. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPI(1), 0, 0 },
  362. { LIBUSB_TRANSFER_TYPE_BULK, 512, EPO(2), 0, 0 }
  363. };
  364. static struct usb_intinfo gsd2_ints[] = {
  365. USB_EPS(0, gsd2_epinfos)
  366. };
  367. static struct usb_epinfo gsd3_epinfos[] = {
  368. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(3), 0, 0 },
  369. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  370. };
  371. static struct usb_intinfo gsd3_ints[] = {
  372. USB_EPS(0, gsd3_epinfos)
  373. };
  374. #endif
  375. #ifdef USE_ZEUS
  376. static struct usb_epinfo zus_epinfos_cp2102[] = {
  377. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  378. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  379. };
  380. static struct usb_intinfo zus_ints_cp2102[] = {
  381. USB_EPS(0, zus_epinfos_cp2102)
  382. };
  383. static struct usb_epinfo zus_epinfos_ftdi[] = {
  384. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  385. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  386. };
  387. static struct usb_intinfo zus_ints_ftdi[] = {
  388. USB_EPS(0, zus_epinfos_ftdi)
  389. };
  390. #endif
  391. #ifdef USE_LKETC
  392. static struct usb_epinfo lke_epinfos_cp2102[] = {
  393. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  394. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(1), 0, 0 }
  395. };
  396. static struct usb_epinfo lke_epinfos_ftdi[] = {
  397. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPI(1), 0, 0 },
  398. { LIBUSB_TRANSFER_TYPE_BULK, 64, EPO(2), 0, 0 }
  399. };
  400. static struct usb_intinfo lke_ints_cp2102[] = {
  401. USB_EPS(0, lke_epinfos_cp2102)
  402. };
  403. #endif
  404. #define IDVENDOR_FTDI 0x0403
  405. #define INTINFO(_ints) \
  406. .intinfo_count = ARRAY_SIZE(_ints), \
  407. .intinfos = _ints
  408. #define USBEP(_usbdev, _intinfo, _epinfo) (_usbdev->found->intinfos[_intinfo].epinfos[_epinfo].ep)
  409. #define THISIF(_found, _this) (_found->intinfos[_this].interface)
  410. #define USBIF(_usbdev, _this) THISIF(_usbdev->found, _this)
  411. // TODO: Add support for (at least) Isochronous endpoints
  412. static struct usb_find_devices find_dev[] = {
  413. #ifdef USE_BFLSC
  414. {
  415. .drv = DRIVER_bflsc,
  416. .name = "BAS",
  417. .ident = IDENT_BAS,
  418. .idVendor = IDVENDOR_FTDI,
  419. .idProduct = 0x6014,
  420. //.iManufacturer = "Butterfly Labs",
  421. .iProduct = "BitFORCE SHA256 SC",
  422. .config = 1,
  423. .timeout = BFLSC_TIMEOUT_MS,
  424. .latency = LATENCY_STD,
  425. INTINFO(bflsc_ints) },
  426. {
  427. .drv = DRIVER_bflsc,
  428. .name = "BMA",
  429. .ident = IDENT_BMA,
  430. .idVendor = IDVENDOR_FTDI,
  431. .idProduct = 0x6014,
  432. //.iManufacturer = "BUTTERFLY LABS"
  433. .iProduct = "BitFORCE SC-28nm",
  434. .config = 1,
  435. .timeout = BFLSC_TIMEOUT_MS,
  436. .latency = LATENCY_STD,
  437. INTINFO(bflsc_ints) },
  438. {
  439. .drv = DRIVER_bflsc,
  440. .name = "BMA",
  441. .ident = IDENT_BMA,
  442. .idVendor = IDVENDOR_FTDI,
  443. .idProduct = 0x6014,
  444. .iManufacturer = "BUTTERFLY LABS",
  445. .iProduct = "BitFORCE SHA256",
  446. .config = 1,
  447. .timeout = BFLSC_TIMEOUT_MS,
  448. .latency = LATENCY_STD,
  449. INTINFO(bflsc_ints) },
  450. #endif
  451. #ifdef USE_BITFORCE
  452. {
  453. .drv = DRIVER_bitforce,
  454. .name = "BFL",
  455. .ident = IDENT_BFL,
  456. .idVendor = IDVENDOR_FTDI,
  457. .idProduct = 0x6014,
  458. .iManufacturer = "Butterfly Labs Inc.",
  459. .iProduct = "BitFORCE SHA256",
  460. .config = 1,
  461. .timeout = BITFORCE_TIMEOUT_MS,
  462. .latency = LATENCY_STD,
  463. INTINFO(bfl_ints) },
  464. #endif
  465. #ifdef USE_BITFURY
  466. {
  467. .drv = DRIVER_bitfury,
  468. .name = "BF1",
  469. .ident = IDENT_BF1,
  470. .idVendor = 0x03eb,
  471. .idProduct = 0x204b,
  472. .config = 1,
  473. .timeout = BITFURY_TIMEOUT_MS,
  474. .latency = LATENCY_UNUSED,
  475. //.iManufacturer = "BPMC",
  476. .iProduct = "Bitfury BF1",
  477. INTINFO(bfu_ints)
  478. },
  479. {
  480. .drv = DRIVER_bitfury,
  481. .name = "BXF",
  482. .ident = IDENT_BXF,
  483. .idVendor = 0x198c,
  484. .idProduct = 0xb1f1,
  485. .config = 1,
  486. .timeout = BITFURY_TIMEOUT_MS,
  487. .latency = LATENCY_UNUSED,
  488. .iManufacturer = "c-scape",
  489. .iProduct = "bi?fury",
  490. INTINFO(bxf_ints)
  491. },
  492. {
  493. .drv = DRIVER_bitfury,
  494. .name = "OSM",
  495. .ident = IDENT_OSM,
  496. .idVendor = 0x198c,
  497. .idProduct = 0xb1f1,
  498. .config = 1,
  499. .timeout = BITFURY_TIMEOUT_MS,
  500. .latency = LATENCY_UNUSED,
  501. .iManufacturer = "c-scape",
  502. .iProduct = "OneString",
  503. INTINFO(bxf_ints)
  504. },
  505. {
  506. .drv = DRIVER_bitfury,
  507. .name = "NFU",
  508. .ident = IDENT_NFU,
  509. .idVendor = 0x04d8,
  510. .idProduct = 0x00de,
  511. .config = 1,
  512. .timeout = BITFURY_TIMEOUT_MS,
  513. .latency = LATENCY_UNUSED,
  514. INTINFO(nfu_ints)
  515. },
  516. {
  517. .drv = DRIVER_bitfury,
  518. .name = "BXM",
  519. .ident = IDENT_BXM,
  520. .idVendor = 0x0403,
  521. .idProduct = 0x6014,
  522. .config = 1,
  523. .timeout = BITFURY_TIMEOUT_MS,
  524. .latency = LATENCY_UNUSED,
  525. INTINFO(bxm_ints)
  526. },
  527. #endif
  528. #ifdef USE_BLOCKERUPTER
  529. {
  530. .drv = DRIVER_blockerupter,
  531. .name = "BET",
  532. .ident = IDENT_BET,
  533. .idVendor = 0x10c4,
  534. .idProduct = 0xea60,
  535. .config = 1,
  536. .timeout = BLOCKERUPTER_TIMEOUT_MS,
  537. .latency = LATENCY_UNUSED,
  538. INTINFO(bet_ints) },
  539. #endif
  540. #ifdef USE_DRILLBIT
  541. {
  542. .drv = DRIVER_drillbit,
  543. .name = "DRB",
  544. .ident = IDENT_DRB,
  545. .idVendor = 0x03eb,
  546. .idProduct = 0x2404,
  547. .config = 1,
  548. .timeout = DRILLBIT_TIMEOUT_MS,
  549. .latency = LATENCY_UNUSED,
  550. .iManufacturer = "Drillbit Systems",
  551. .iProduct = NULL, /* Can be Thumb or Eight, same driver */
  552. INTINFO(drillbit_ints)
  553. },
  554. #endif
  555. #ifdef USE_MODMINER
  556. {
  557. .drv = DRIVER_modminer,
  558. .name = "MMQ",
  559. .ident = IDENT_MMQ,
  560. .idVendor = 0x1fc9,
  561. .idProduct = 0x0003,
  562. .config = 1,
  563. .timeout = MODMINER_TIMEOUT_MS,
  564. .latency = LATENCY_UNUSED,
  565. INTINFO(mmq_ints) },
  566. #endif
  567. #ifdef USE_AVALON
  568. {
  569. .drv = DRIVER_avalon,
  570. .name = "BTB",
  571. .ident = IDENT_BTB,
  572. .idVendor = IDVENDOR_FTDI,
  573. .idProduct = 0x6001,
  574. .iManufacturer = "Burnin Electronics",
  575. .iProduct = "BitBurner",
  576. .config = 1,
  577. .timeout = AVALON_TIMEOUT_MS,
  578. .latency = 10,
  579. INTINFO(ava_ints) },
  580. {
  581. .drv = DRIVER_avalon,
  582. .name = "BBF",
  583. .ident = IDENT_BBF,
  584. .idVendor = IDVENDOR_FTDI,
  585. .idProduct = 0x6001,
  586. .iManufacturer = "Burnin Electronics",
  587. .iProduct = "BitBurner Fury",
  588. .config = 1,
  589. .timeout = AVALON_TIMEOUT_MS,
  590. .latency = 10,
  591. INTINFO(ava_ints) },
  592. {
  593. .drv = DRIVER_avalon,
  594. .name = "AVA",
  595. .ident = IDENT_AVA,
  596. .idVendor = IDVENDOR_FTDI,
  597. .idProduct = 0x6001,
  598. .config = 1,
  599. .timeout = AVALON_TIMEOUT_MS,
  600. .latency = 10,
  601. INTINFO(ava_ints) },
  602. #endif
  603. #ifdef USE_AVALON2
  604. {
  605. .drv = DRIVER_avalon2,
  606. .name = "AV2",
  607. .ident = IDENT_AV2,
  608. .idVendor = 0x067b,
  609. .idProduct = 0x2303,
  610. .config = 1,
  611. .timeout = AVALON_TIMEOUT_MS,
  612. .latency = LATENCY_UNUSED,
  613. INTINFO(ava2_ints) },
  614. #endif
  615. #ifdef USE_HASHFAST
  616. {
  617. .drv = DRIVER_hashfast,
  618. .name = "HFA",
  619. .ident = IDENT_HFA,
  620. .idVendor = HF_USB_VENDOR_ID,
  621. .idProduct = HF_USB_PRODUCT_ID_G1,
  622. .iManufacturer = "HashFast LLC",
  623. .iProduct = "M1 Module",
  624. .config = 1,
  625. .timeout = HASHFAST_TIMEOUT_MS,
  626. .latency = LATENCY_UNUSED,
  627. INTINFO(hfa_ints) },
  628. #endif
  629. #ifdef USE_HASHRATIO
  630. {
  631. .drv = DRIVER_hashratio,
  632. .name = "HRO",
  633. .ident = IDENT_HRO,
  634. .idVendor = IDVENDOR_FTDI,
  635. .idProduct = 0x6001,
  636. .config = 1,
  637. .timeout = HASHRATIO_TIMEOUT_MS,
  638. .latency = LATENCY_UNUSED,
  639. INTINFO(hro_ints) },
  640. #endif
  641. #ifdef USE_KLONDIKE
  642. {
  643. .drv = DRIVER_klondike,
  644. .name = "KLN",
  645. .ident = IDENT_KLN,
  646. .idVendor = 0x04D8,
  647. .idProduct = 0xF60A,
  648. .config = 1,
  649. .timeout = KLONDIKE_TIMEOUT_MS,
  650. .latency = 10,
  651. INTINFO(kln_ints) },
  652. {
  653. .drv = DRIVER_klondike,
  654. .name = "KLI",
  655. .ident = IDENT_KLN,
  656. .idVendor = 0x04D8,
  657. .idProduct = 0xF60A,
  658. .config = 1,
  659. .timeout = KLONDIKE_TIMEOUT_MS,
  660. .latency = 10,
  661. INTINFO(kli_ints) },
  662. #endif
  663. #ifdef USE_ICARUS
  664. {
  665. .drv = DRIVER_icarus,
  666. .name = "ICA",
  667. .ident = IDENT_ICA,
  668. .idVendor = 0x067b,
  669. .idProduct = 0x2303,
  670. .config = 1,
  671. .timeout = ICARUS_TIMEOUT_MS,
  672. .latency = LATENCY_UNUSED,
  673. INTINFO(ica_ints) },
  674. {
  675. .drv = DRIVER_icarus,
  676. .name = "ICA",
  677. .ident = IDENT_AVA,
  678. .idVendor = 0x1fc9,
  679. .idProduct = 0x0083,
  680. .config = 1,
  681. .timeout = ICARUS_TIMEOUT_MS,
  682. .latency = LATENCY_UNUSED,
  683. INTINFO(ica1_ints) },
  684. {
  685. .drv = DRIVER_icarus,
  686. .name = "AMU",
  687. .ident = IDENT_AMU,
  688. .idVendor = 0x10c4,
  689. .idProduct = 0xea60,
  690. .config = 1,
  691. .timeout = ICARUS_TIMEOUT_MS,
  692. .latency = LATENCY_UNUSED,
  693. INTINFO(amu_ints) },
  694. {
  695. .drv = DRIVER_icarus,
  696. .name = "LIN",
  697. .ident = IDENT_LIN,
  698. .idVendor = 0x10c4,
  699. .idProduct = 0xea60,
  700. .config = 1,
  701. .timeout = ICARUS_TIMEOUT_MS,
  702. .latency = LATENCY_UNUSED,
  703. INTINFO(amu_ints) },
  704. {
  705. .drv = DRIVER_icarus,
  706. .name = "ANU",
  707. .ident = IDENT_ANU,
  708. .idVendor = 0x10c4,
  709. .idProduct = 0xea60,
  710. .config = 1,
  711. .timeout = ICARUS_TIMEOUT_MS,
  712. .latency = LATENCY_UNUSED,
  713. INTINFO(amu_ints) },
  714. {
  715. .drv = DRIVER_icarus,
  716. .name = "BLT",
  717. .ident = IDENT_BLT,
  718. .idVendor = IDVENDOR_FTDI,
  719. .idProduct = 0x6001,
  720. .iProduct = "FT232R USB UART",
  721. .config = 1,
  722. .timeout = ICARUS_TIMEOUT_MS,
  723. .latency = LATENCY_STD,
  724. INTINFO(llt_ints) },
  725. // For any that don't match the above "BLT"
  726. {
  727. .drv = DRIVER_icarus,
  728. .name = "LLT",
  729. .ident = IDENT_LLT,
  730. .idVendor = IDVENDOR_FTDI,
  731. .idProduct = 0x6001,
  732. .config = 1,
  733. .timeout = ICARUS_TIMEOUT_MS,
  734. .latency = LATENCY_STD,
  735. INTINFO(llt_ints) },
  736. {
  737. .drv = DRIVER_icarus,
  738. .name = "CMR",
  739. .ident = IDENT_CMR1,
  740. .idVendor = IDVENDOR_FTDI,
  741. .idProduct = 0x6014,
  742. .iProduct = "Cairnsmore1",
  743. .config = 1,
  744. .timeout = ICARUS_TIMEOUT_MS,
  745. .latency = LATENCY_STD,
  746. INTINFO(cmr1_ints) },
  747. {
  748. .drv = DRIVER_icarus,
  749. .name = "CMR",
  750. .ident = IDENT_CMR2,
  751. .idVendor = IDVENDOR_FTDI,
  752. .idProduct = 0x8350,
  753. .iProduct = "Cairnsmore1",
  754. .config = 1,
  755. .timeout = ICARUS_TIMEOUT_MS,
  756. .latency = LATENCY_STD,
  757. INTINFO(cmr2_ints) },
  758. #endif
  759. #ifdef USE_COINTERRA
  760. {
  761. .drv = DRIVER_cointerra,
  762. .name = "CTA",
  763. .ident = IDENT_CTA,
  764. .idVendor = 0x1cbe,
  765. .idProduct = 0x0003,
  766. .config = 1,
  767. .timeout = COINTERRA_TIMEOUT_MS,
  768. .latency = LATENCY_STD,
  769. INTINFO(cointerra_ints) },
  770. #endif
  771. #ifdef USE_ANT_S1
  772. {
  773. .drv = DRIVER_ants1,
  774. .name = "ANT",
  775. .ident = IDENT_ANT,
  776. .idVendor = 0x4254,
  777. .idProduct = 0x4153,
  778. .config = 1,
  779. .timeout = ANT_S1_TIMEOUT_MS,
  780. .latency = LATENCY_ANTS1,
  781. INTINFO(ants1_ints) },
  782. #endif
  783. #ifdef USE_ANT_S2
  784. {
  785. .drv = DRIVER_ants1,
  786. .name = "AS2",
  787. .ident = IDENT_AS2,
  788. .idVendor = 0x4254,
  789. .idProduct = 0x4153,
  790. .config = 1,
  791. .timeout = ANT_S2_TIMEOUT_MS,
  792. .latency = LATENCY_ANTS2,
  793. INTINFO(ants2_ints) },
  794. #endif
  795. #ifdef USE_GRIDSEED
  796. {
  797. .drv = DRIVER_gridseed,
  798. .name = "GSD",
  799. .ident = IDENT_GSD,
  800. .idVendor = 0x0483,
  801. .idProduct = 0x5740,
  802. .iManufacturer = "STMicroelectronics",
  803. .iProduct = "STM32 Virtual COM Port ",
  804. .config = 1,
  805. .timeout = GRIDSEED_TIMEOUT_MS,
  806. .latency = LATENCY_STD,
  807. INTINFO(gsd_ints) },
  808. {
  809. .drv = DRIVER_gridseed,
  810. .name = "GSD",
  811. .ident = IDENT_GSD1,
  812. .idVendor = 0x10c4,
  813. .idProduct = 0xea60,
  814. .iProduct = "CP2102 USB to UART Bridge Controller",
  815. .config = 1,
  816. .timeout = GRIDSEED_TIMEOUT_MS,
  817. .latency = LATENCY_STD,
  818. INTINFO(gsd1_ints) },
  819. {
  820. .drv = DRIVER_gridseed,
  821. .name = "GSD",
  822. .ident = IDENT_GSD2,
  823. .idVendor = IDVENDOR_FTDI,
  824. .idProduct = 0x6010,
  825. .iProduct = "Dual RS232-HS",
  826. .config = 1,
  827. .timeout = GRIDSEED_TIMEOUT_MS,
  828. .latency = LATENCY_STD,
  829. INTINFO(gsd2_ints) },
  830. {
  831. .drv = DRIVER_gridseed,
  832. .name = "GSD",
  833. .ident = IDENT_GSD3,
  834. .idVendor = 0x067b,
  835. .idProduct = 0x2303,
  836. .iProduct = "USB-Serial Controller",
  837. .config = 1,
  838. .timeout = GRIDSEED_TIMEOUT_MS,
  839. .latency = LATENCY_STD,
  840. INTINFO(gsd3_ints) },
  841. #endif
  842. #ifdef USE_ZEUS
  843. {
  844. .drv = DRIVER_zeus,
  845. .name = "ZUS",
  846. .ident = IDENT_ZUS1,
  847. .idVendor = 0x10c4,
  848. .idProduct = 0xea60,
  849. .iProduct = "CP2102 USB to UART Bridge Controller",
  850. .config = 1,
  851. .timeout = ZEUS_TIMEOUT_MS,
  852. .latency = LATENCY_STD,
  853. INTINFO(zus_ints_cp2102) },
  854. {
  855. .drv = DRIVER_zeus,
  856. .name = "ZUS",
  857. .ident = IDENT_ZUS2,
  858. .idVendor = IDVENDOR_FTDI,
  859. .idProduct = 0x6001,
  860. .iProduct = "FT232R USB UART",
  861. .config = 1,
  862. .timeout = ZEUS_TIMEOUT_MS,
  863. .latency = LATENCY_STD,
  864. INTINFO(zus_ints_ftdi) },
  865. #endif
  866. #ifdef USE_LKETC
  867. {
  868. .drv = DRIVER_lketc,
  869. .name = "LKE",
  870. .ident = IDENT_LKE,
  871. .idVendor = 0x10c4,
  872. .idProduct = 0xea60,
  873. .iProduct = "CP2103 USB to UART Bridge Controller",
  874. .config = 1,
  875. .timeout = LKETC_TIMEOUT_MS,
  876. .latency = LATENCY_STD,
  877. INTINFO(lke_ints_cp2102)
  878. },
  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 (strcmp((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 (!strcmp((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 (strcmp((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 (!strcmp((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 (strcmp(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. /* Avoid any async transfers during shutdown to allow the polling
  2716. * thread to be shut down after all existing transfers are complete */
  2717. if (opt_lowmem || cgpu->shutdown)
  2718. return libusb_bulk_transfer(dev_handle, endpoint, data, length, transferred, timeout);
  2719. err_retry:
  2720. init_usb_transfer(&ut);
  2721. if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) {
  2722. cg_memcpy(buf, data, length);
  2723. #ifndef HAVE_LIBUSB
  2724. /* Older versions may not have this feature so only enable it
  2725. * when we know we're compiling with included static libusb. We
  2726. * only do this for bulk transfer, not interrupt. */
  2727. if (!interrupt)
  2728. ut.transfer->flags |= LIBUSB_TRANSFER_ADD_ZERO_PACKET;
  2729. #endif
  2730. #ifdef WIN32
  2731. /* Writes on windows really don't like to be cancelled, but
  2732. * are prone to timeouts under heavy USB traffic, so make this
  2733. * a last resort cancellation delayed long after the write
  2734. * would have timed out on its own. */
  2735. callback_timeout += WIN_WRITE_CBEXTRA;
  2736. #endif
  2737. }
  2738. 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);
  2739. if (interrupt) {
  2740. libusb_fill_interrupt_transfer(ut.transfer, dev_handle, endpoint,
  2741. buf, length, transfer_callback, &ut,
  2742. bulk_timeout);
  2743. } else {
  2744. libusb_fill_bulk_transfer(ut.transfer, dev_handle, endpoint, buf,
  2745. length, transfer_callback, &ut, bulk_timeout);
  2746. }
  2747. STATS_TIMEVAL(&tv_start);
  2748. err = usb_submit_transfer(&ut, ut.transfer, cancellable, tt);
  2749. errn = errno;
  2750. if (!err)
  2751. err = callback_wait(&ut, transferred, callback_timeout);
  2752. else
  2753. err = usb_transfer_toerr(err);
  2754. complete_usb_transfer(&ut);
  2755. STATS_TIMEVAL(&tv_finish);
  2756. USB_STATS(cgpu, &tv_start, &tv_finish, err, mode, cmd, seq, timeout);
  2757. if (err < 0) {
  2758. applog(LOG_DEBUG, "%s%i: %s (amt=%d err=%d ern=%d)",
  2759. cgpu->drv->name, cgpu->device_id,
  2760. usb_cmdname(cmd), *transferred, err, errn);
  2761. }
  2762. if (err == LIBUSB_ERROR_PIPE) {
  2763. int pipeerr, retries = 0;
  2764. do {
  2765. cgpu->usbinfo.last_pipe = time(NULL);
  2766. cgpu->usbinfo.pipe_count++;
  2767. applog(LOG_INFO, "%s%i: libusb pipe error, trying to clear",
  2768. cgpu->drv->name, cgpu->device_id);
  2769. pipeerr = libusb_clear_halt(dev_handle, endpoint);
  2770. applog(LOG_DEBUG, "%s%i: libusb pipe error%scleared",
  2771. cgpu->drv->name, cgpu->device_id, err ? " not " : " ");
  2772. if (pipeerr)
  2773. cgpu->usbinfo.clear_fail_count++;
  2774. } while (pipeerr && ++retries < USB_RETRY_MAX);
  2775. if (!pipeerr && ++err_retries < USB_RETRY_MAX)
  2776. goto err_retry;
  2777. }
  2778. if (err == LIBUSB_ERROR_IO && ++err_retries < USB_RETRY_MAX)
  2779. goto err_retry;
  2780. if (NODEV(err))
  2781. *transferred = 0;
  2782. else if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN && *transferred)
  2783. cg_memcpy(data, buf, *transferred);
  2784. return err;
  2785. }
  2786. void usb_reset(struct cgpu_info *cgpu)
  2787. {
  2788. int pstate, err = 0;
  2789. DEVRLOCK(cgpu, pstate);
  2790. if (!cgpu->usbinfo.nodev) {
  2791. err = libusb_reset_device(cgpu->usbdev->handle);
  2792. applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
  2793. cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
  2794. }
  2795. if (NODEV(err)) {
  2796. cg_ruwlock(&cgpu->usbinfo.devlock);
  2797. release_cgpu(cgpu);
  2798. DEVWUNLOCK(cgpu, pstate);
  2799. } else
  2800. DEVRUNLOCK(cgpu, pstate);
  2801. }
  2802. int _usb_read(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz,
  2803. int *processed, int timeout, const char *end, enum usb_cmds cmd, bool readonce, bool cancellable)
  2804. {
  2805. unsigned char *ptr, usbbuf[USB_READ_BUFSIZE];
  2806. struct timeval read_start, tv_finish;
  2807. int bufleft, err, got, tot, pstate, tried_reset;
  2808. struct cg_usb_device *usbdev;
  2809. unsigned int initial_timeout;
  2810. bool first = true;
  2811. size_t usbbufread;
  2812. int endlen = 0;
  2813. char *eom = NULL;
  2814. double done;
  2815. bool ftdi;
  2816. memset(usbbuf, 0, USB_READ_BUFSIZE);
  2817. memset(buf, 0, bufsiz);
  2818. if (end)
  2819. endlen = strlen(end);
  2820. DEVRLOCK(cgpu, pstate);
  2821. if (cgpu->usbinfo.nodev) {
  2822. *processed = 0;
  2823. USB_REJECT(cgpu, MODE_BULK_READ);
  2824. err = LIBUSB_ERROR_NO_DEVICE;
  2825. goto out_noerrmsg;
  2826. }
  2827. usbdev = cgpu->usbdev;
  2828. /* Interrupt transfers are guaranteed to be of an expected size (we hope) */
  2829. if (usbdev->found->intinfos[intinfo].epinfos[epinfo].att == LIBUSB_TRANSFER_TYPE_INTERRUPT)
  2830. usbbufread = bufsiz;
  2831. else
  2832. usbbufread = 512;
  2833. ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  2834. 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));
  2835. if (bufsiz > USB_MAX_READ)
  2836. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, (int)bufsiz, USB_MAX_READ);
  2837. if (timeout == DEVTIMEOUT)
  2838. timeout = usbdev->found->timeout;
  2839. tot = usbdev->bufamt;
  2840. bufleft = bufsiz - tot;
  2841. if (tot)
  2842. cg_memcpy(usbbuf, usbdev->buffer, tot);
  2843. ptr = usbbuf + tot;
  2844. usbdev->bufamt = 0;
  2845. err = LIBUSB_SUCCESS;
  2846. if (end != NULL)
  2847. eom = strstr((const char *)usbbuf, end);
  2848. initial_timeout = timeout;
  2849. cgtime(&read_start);
  2850. tried_reset = 0;
  2851. while (bufleft > 0 && !eom) {
  2852. err = usb_perform_transfer(cgpu, usbdev, intinfo, epinfo, ptr, usbbufread,
  2853. &got, timeout, MODE_BULK_READ, cmd,
  2854. first ? SEQ0 : SEQ1, cancellable, false);
  2855. cgtime(&tv_finish);
  2856. ptr[got] = '\0';
  2857. 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);
  2858. if (ftdi) {
  2859. // first 2 bytes returned are an FTDI status
  2860. if (got > 2) {
  2861. got -= 2;
  2862. memmove(ptr, ptr+2, got+1);
  2863. } else {
  2864. got = 0;
  2865. *ptr = '\0';
  2866. }
  2867. }
  2868. tot += got;
  2869. if (end != NULL)
  2870. eom = strstr((const char *)usbbuf, end);
  2871. /* Attempt a usb reset for an error that will otherwise cause
  2872. * this device to drop out provided we know the device still
  2873. * might exist. */
  2874. if (err && err != LIBUSB_ERROR_TIMEOUT) {
  2875. applog(LOG_WARNING, "%s %i %s usb read err:(%d) %s", cgpu->drv->name,
  2876. cgpu->device_id, usb_cmdname(cmd), err, libusb_error_name(err));
  2877. if (err != LIBUSB_ERROR_NO_DEVICE && !tried_reset) {
  2878. err = libusb_reset_device(usbdev->handle);
  2879. tried_reset = 1; // don't call reset twice in a row
  2880. applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
  2881. cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
  2882. }
  2883. } else {
  2884. tried_reset = 0;
  2885. }
  2886. ptr += got;
  2887. bufleft -= got;
  2888. if (bufleft < 1)
  2889. err = LIBUSB_SUCCESS;
  2890. if (err || readonce)
  2891. break;
  2892. first = false;
  2893. done = tdiff(&tv_finish, &read_start);
  2894. // N.B. this is: return last err with whatever size has already been read
  2895. timeout = initial_timeout - (done * 1000);
  2896. if (timeout <= 0)
  2897. break;
  2898. }
  2899. /* If we found the end of message marker, just use that data and
  2900. * return success. */
  2901. if (eom) {
  2902. size_t eomlen = (void *)eom - (void *)usbbuf + endlen;
  2903. if (eomlen < bufsiz) {
  2904. bufsiz = eomlen;
  2905. err = LIBUSB_SUCCESS;
  2906. }
  2907. }
  2908. // N.B. usbdev->buffer was emptied before the while() loop
  2909. if (tot > (int)bufsiz) {
  2910. usbdev->bufamt = tot - bufsiz;
  2911. cg_memcpy(usbdev->buffer, usbbuf + bufsiz, usbdev->bufamt);
  2912. tot -= usbdev->bufamt;
  2913. usbbuf[tot] = '\0';
  2914. applog(LOG_DEBUG, "USB: %s%i read1 buffering %d extra bytes",
  2915. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2916. }
  2917. *processed = tot;
  2918. cg_memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2919. out_noerrmsg:
  2920. if (NODEV(err)) {
  2921. cg_ruwlock(&cgpu->usbinfo.devlock);
  2922. release_cgpu(cgpu);
  2923. DEVWUNLOCK(cgpu, pstate);
  2924. } else
  2925. DEVRUNLOCK(cgpu, pstate);
  2926. return err;
  2927. }
  2928. int _usb_write(struct cgpu_info *cgpu, int intinfo, int epinfo, char *buf, size_t bufsiz, int *processed, int timeout, enum usb_cmds cmd)
  2929. {
  2930. struct timeval write_start, tv_finish;
  2931. struct cg_usb_device *usbdev;
  2932. unsigned int initial_timeout;
  2933. int err, sent, tot, pstate, tried_reset;
  2934. bool first = true;
  2935. double done;
  2936. DEVRLOCK(cgpu, pstate);
  2937. 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));
  2938. *processed = 0;
  2939. if (cgpu->usbinfo.nodev) {
  2940. USB_REJECT(cgpu, MODE_BULK_WRITE);
  2941. err = LIBUSB_ERROR_NO_DEVICE;
  2942. goto out_noerrmsg;
  2943. }
  2944. usbdev = cgpu->usbdev;
  2945. if (timeout == DEVTIMEOUT)
  2946. timeout = usbdev->found->timeout;
  2947. tot = 0;
  2948. err = LIBUSB_SUCCESS;
  2949. initial_timeout = timeout;
  2950. cgtime(&write_start);
  2951. tried_reset = 0;
  2952. while (bufsiz > 0) {
  2953. int tosend = bufsiz;
  2954. /* USB 1.1 devices don't handle zero packets well so split them
  2955. * up to not have the final transfer equal to the wMaxPacketSize
  2956. * or they will stall waiting for more data. */
  2957. if (usbdev->usb11) {
  2958. struct usb_epinfo *ue = &usbdev->found->intinfos[intinfo].epinfos[epinfo];
  2959. if (tosend == ue->wMaxPacketSize) {
  2960. tosend >>= 1;
  2961. if (unlikely(!tosend))
  2962. tosend = 1;
  2963. }
  2964. }
  2965. err = usb_perform_transfer(cgpu, usbdev, intinfo, epinfo, (unsigned char *)buf,
  2966. tosend, &sent, timeout, MODE_BULK_WRITE,
  2967. cmd, first ? SEQ0 : SEQ1, false, usbdev->tt);
  2968. cgtime(&tv_finish);
  2969. 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);
  2970. tot += sent;
  2971. /* Unlike reads, even a timeout error is unrecoverable on
  2972. * writes. */
  2973. if (err) {
  2974. applog(LOG_WARNING, "%s %i %s usb write err:(%d) %s", cgpu->drv->name,
  2975. cgpu->device_id, usb_cmdname(cmd), err, libusb_error_name(err));
  2976. if (err != LIBUSB_ERROR_NO_DEVICE && !tried_reset) {
  2977. err = libusb_reset_device(usbdev->handle);
  2978. tried_reset = 1; // don't try reset twice in a row
  2979. applog(LOG_WARNING, "%s %i attempted reset got err:(%d) %s",
  2980. cgpu->drv->name, cgpu->device_id, err, libusb_error_name(err));
  2981. }
  2982. } else {
  2983. tried_reset = 0;
  2984. }
  2985. if (err)
  2986. break;
  2987. buf += sent;
  2988. bufsiz -= sent;
  2989. first = false;
  2990. done = tdiff(&tv_finish, &write_start);
  2991. // N.B. this is: return last err with whatever size was written
  2992. timeout = initial_timeout - (done * 1000);
  2993. if (timeout <= 0)
  2994. break;
  2995. }
  2996. *processed = tot;
  2997. out_noerrmsg:
  2998. if (NODEV(err)) {
  2999. cg_ruwlock(&cgpu->usbinfo.devlock);
  3000. release_cgpu(cgpu);
  3001. DEVWUNLOCK(cgpu, pstate);
  3002. } else
  3003. DEVRUNLOCK(cgpu, pstate);
  3004. return err;
  3005. }
  3006. /* As we do for bulk reads, emulate a sync function for control transfers using
  3007. * our own timeouts that takes the same parameters as libusb_control_transfer.
  3008. */
  3009. static int usb_control_transfer(struct cgpu_info *cgpu, libusb_device_handle *dev_handle, uint8_t bmRequestType,
  3010. uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
  3011. unsigned char *buffer, uint16_t wLength, unsigned int timeout)
  3012. {
  3013. struct usb_transfer ut;
  3014. unsigned char buf[70];
  3015. int err, transferred;
  3016. bool tt = false;
  3017. if (unlikely(cgpu->shutdown))
  3018. return libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, buffer, wLength, timeout);
  3019. init_usb_transfer(&ut);
  3020. libusb_fill_control_setup(buf, bmRequestType, bRequest, wValue,
  3021. wIndex, wLength);
  3022. if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT) {
  3023. if (wLength)
  3024. cg_memcpy(buf + LIBUSB_CONTROL_SETUP_SIZE, buffer, wLength);
  3025. if (cgpu->usbdev->descriptor->bcdUSB < 0x0200)
  3026. tt = true;
  3027. }
  3028. libusb_fill_control_transfer(ut.transfer, dev_handle, buf, transfer_callback,
  3029. &ut, 0);
  3030. err = usb_submit_transfer(&ut, ut.transfer, false, tt);
  3031. if (!err)
  3032. err = callback_wait(&ut, &transferred, timeout);
  3033. if (err == LIBUSB_SUCCESS && transferred) {
  3034. if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
  3035. cg_memcpy(buffer, libusb_control_transfer_get_data(ut.transfer),
  3036. transferred);
  3037. err = transferred;
  3038. goto out;
  3039. }
  3040. err = usb_transfer_toerr(err);
  3041. out:
  3042. complete_usb_transfer(&ut);
  3043. return err;
  3044. }
  3045. 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)
  3046. {
  3047. struct cg_usb_device *usbdev;
  3048. #if DO_USB_STATS
  3049. struct timeval tv_start, tv_finish;
  3050. #endif
  3051. unsigned char buf[64];
  3052. uint32_t *buf32 = (uint32_t *)buf;
  3053. int err, i, bufsiz;
  3054. 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));
  3055. if (cgpu->usbinfo.nodev) {
  3056. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  3057. err = LIBUSB_ERROR_NO_DEVICE;
  3058. goto out_;
  3059. }
  3060. usbdev = cgpu->usbdev;
  3061. if (timeout == DEVTIMEOUT)
  3062. timeout = usbdev->found->timeout;
  3063. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  3064. if (siz > 0) {
  3065. bufsiz = siz - 1;
  3066. bufsiz >>= 2;
  3067. bufsiz++;
  3068. for (i = 0; i < bufsiz; i++)
  3069. buf32[i] = htole32(data[i]);
  3070. }
  3071. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex(buf, (size_t)siz));
  3072. STATS_TIMEVAL(&tv_start);
  3073. err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
  3074. wValue, wIndex, buf, (uint16_t)siz, timeout);
  3075. STATS_TIMEVAL(&tv_finish);
  3076. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0, timeout);
  3077. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  3078. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  3079. applog(LOG_WARNING, "%s %i usb transfer err:(%d) %s", cgpu->drv->name, cgpu->device_id,
  3080. err, libusb_error_name(err));
  3081. }
  3082. out_:
  3083. return err;
  3084. }
  3085. /* We use the write devlock for control transfers since some control transfers
  3086. * are rare but may be changing settings within the device causing problems
  3087. * if concurrent transfers are happening. Using the write lock serialises
  3088. * any transfers. */
  3089. 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)
  3090. {
  3091. int pstate, err;
  3092. DEVWLOCK(cgpu, pstate);
  3093. err = __usb_transfer(cgpu, request_type, bRequest, wValue, wIndex, data, siz, timeout, cmd);
  3094. if (NOCONTROLDEV(err))
  3095. release_cgpu(cgpu);
  3096. DEVWUNLOCK(cgpu, pstate);
  3097. return err;
  3098. }
  3099. 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)
  3100. {
  3101. struct cg_usb_device *usbdev;
  3102. #if DO_USB_STATS
  3103. struct timeval tv_start, tv_finish;
  3104. #endif
  3105. unsigned char tbuf[64];
  3106. int err, pstate;
  3107. DEVWLOCK(cgpu, pstate);
  3108. 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));
  3109. if (cgpu->usbinfo.nodev) {
  3110. USB_REJECT(cgpu, MODE_CTRL_READ);
  3111. err = LIBUSB_ERROR_NO_DEVICE;
  3112. goto out_noerrmsg;
  3113. }
  3114. usbdev = cgpu->usbdev;
  3115. if (timeout == DEVTIMEOUT)
  3116. timeout = usbdev->found->timeout;
  3117. *amount = 0;
  3118. memset(tbuf, 0, 64);
  3119. STATS_TIMEVAL(&tv_start);
  3120. err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
  3121. wValue, wIndex, tbuf, (uint16_t)bufsiz, timeout);
  3122. STATS_TIMEVAL(&tv_finish);
  3123. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0, timeout);
  3124. cg_memcpy(buf, tbuf, bufsiz);
  3125. 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);
  3126. if (err > 0) {
  3127. *amount = err;
  3128. err = 0;
  3129. }
  3130. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  3131. applog(LOG_WARNING, "%s %i usb transfer read err:(%d) %s", cgpu->drv->name, cgpu->device_id,
  3132. err, libusb_error_name(err));
  3133. }
  3134. out_noerrmsg:
  3135. if (NOCONTROLDEV(err))
  3136. release_cgpu(cgpu);
  3137. DEVWUNLOCK(cgpu, pstate);
  3138. return err;
  3139. }
  3140. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  3141. #define FTDI_RS0_CTS (1 << 4)
  3142. #define FTDI_RS0_DSR (1 << 5)
  3143. #define FTDI_RS0_RI (1 << 6)
  3144. #define FTDI_RS0_RLSD (1 << 7)
  3145. /* Clear to send for FTDI */
  3146. int usb_ftdi_cts(struct cgpu_info *cgpu)
  3147. {
  3148. char buf[2], ret;
  3149. int err, amount;
  3150. err = _usb_transfer_read(cgpu, (uint8_t)FTDI_TYPE_IN, (uint8_t)5,
  3151. (uint16_t)0, (uint16_t)0, buf, 2,
  3152. &amount, DEVTIMEOUT, C_FTDI_STATUS);
  3153. /* We return true in case drivers are waiting indefinitely to try and
  3154. * write to something that's not there. */
  3155. if (err)
  3156. return true;
  3157. ret = buf[0] & FTDI_STATUS_B0_MASK;
  3158. return (ret & FTDI_RS0_CTS);
  3159. }
  3160. int _usb_ftdi_set_latency(struct cgpu_info *cgpu, int intinfo)
  3161. {
  3162. int err = 0;
  3163. int pstate;
  3164. DEVWLOCK(cgpu, pstate);
  3165. if (cgpu->usbdev) {
  3166. if (cgpu->usbdev->usb_type != USB_TYPE_FTDI) {
  3167. applog(LOG_ERR, "%s: cgid %d latency request on non-FTDI device",
  3168. cgpu->drv->name, cgpu->cgminer_id);
  3169. err = LIBUSB_ERROR_NOT_SUPPORTED;
  3170. } else if (cgpu->usbdev->found->latency == LATENCY_UNUSED) {
  3171. applog(LOG_ERR, "%s: cgid %d invalid latency (UNUSED)",
  3172. cgpu->drv->name, cgpu->cgminer_id);
  3173. err = LIBUSB_ERROR_NOT_SUPPORTED;
  3174. }
  3175. if (!err)
  3176. err = __usb_transfer(cgpu, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
  3177. cgpu->usbdev->found->latency,
  3178. USBIF(cgpu->usbdev, intinfo),
  3179. NULL, 0, DEVTIMEOUT, C_LATENCY);
  3180. }
  3181. DEVWUNLOCK(cgpu, pstate);
  3182. applog(LOG_DEBUG, "%s: cgid %d %s got err %d",
  3183. cgpu->drv->name, cgpu->cgminer_id,
  3184. usb_cmdname(C_LATENCY), err);
  3185. return err;
  3186. }
  3187. void usb_buffer_clear(struct cgpu_info *cgpu)
  3188. {
  3189. int pstate;
  3190. DEVWLOCK(cgpu, pstate);
  3191. if (cgpu->usbdev)
  3192. cgpu->usbdev->bufamt = 0;
  3193. DEVWUNLOCK(cgpu, pstate);
  3194. }
  3195. uint32_t usb_buffer_size(struct cgpu_info *cgpu)
  3196. {
  3197. uint32_t ret = 0;
  3198. int pstate;
  3199. DEVRLOCK(cgpu, pstate);
  3200. if (cgpu->usbdev)
  3201. ret = cgpu->usbdev->bufamt;
  3202. DEVRUNLOCK(cgpu, pstate);
  3203. return ret;
  3204. }
  3205. /*
  3206. * The value returned (0) when usbdev is NULL
  3207. * doesn't matter since it also means the next call to
  3208. * any usbutils function will fail with a nodev
  3209. * N.B. this is to get the interface number to use in a control_transfer
  3210. * which for some devices isn't actually the interface number
  3211. */
  3212. int _usb_interface(struct cgpu_info *cgpu, int intinfo)
  3213. {
  3214. int interface = 0;
  3215. int pstate;
  3216. DEVRLOCK(cgpu, pstate);
  3217. if (cgpu->usbdev)
  3218. interface = cgpu->usbdev->found->intinfos[intinfo].ctrl_transfer;
  3219. DEVRUNLOCK(cgpu, pstate);
  3220. return interface;
  3221. }
  3222. enum sub_ident usb_ident(struct cgpu_info *cgpu)
  3223. {
  3224. enum sub_ident ident = IDENT_UNK;
  3225. int pstate;
  3226. DEVRLOCK(cgpu, pstate);
  3227. if (cgpu->usbdev)
  3228. ident = cgpu->usbdev->ident;
  3229. DEVRUNLOCK(cgpu, pstate);
  3230. return ident;
  3231. }
  3232. // Need to set all devices with matching usbdev
  3233. void usb_set_dev_start(struct cgpu_info *cgpu)
  3234. {
  3235. struct cg_usb_device *cgusb;
  3236. struct cgpu_info *cgpu2;
  3237. struct timeval now;
  3238. int pstate;
  3239. DEVWLOCK(cgpu, pstate);
  3240. cgusb = cgpu->usbdev;
  3241. // If the device wasn't dropped
  3242. if (cgusb != NULL) {
  3243. int i;
  3244. cgtime(&now);
  3245. for (i = 0; i < total_devices; i++) {
  3246. cgpu2 = get_devices(i);
  3247. if (cgpu2->usbdev == cgusb)
  3248. copy_time(&(cgpu2->dev_start_tv), &now);
  3249. }
  3250. }
  3251. DEVWUNLOCK(cgpu, pstate);
  3252. }
  3253. void usb_cleanup(void)
  3254. {
  3255. struct cgpu_info *cgpu;
  3256. int count, pstate;
  3257. int i;
  3258. hotplug_time = 0;
  3259. cgsleep_ms(10);
  3260. count = 0;
  3261. for (i = 0; i < total_devices; i++) {
  3262. cgpu = devices[i];
  3263. switch (cgpu->drv->drv_id) {
  3264. case DRIVER_bflsc:
  3265. case DRIVER_bitforce:
  3266. case DRIVER_bitfury:
  3267. case DRIVER_cointerra:
  3268. case DRIVER_drillbit:
  3269. case DRIVER_modminer:
  3270. case DRIVER_icarus:
  3271. case DRIVER_avalon:
  3272. case DRIVER_klondike:
  3273. case DRIVER_hashfast:
  3274. case DRIVER_gridseed:
  3275. case DRIVER_zeus:
  3276. DEVWLOCK(cgpu, pstate);
  3277. release_cgpu(cgpu);
  3278. DEVWUNLOCK(cgpu, pstate);
  3279. count++;
  3280. break;
  3281. case DRIVER_lketc:
  3282. DEVWLOCK(cgpu, pstate);
  3283. release_cgpu(cgpu);
  3284. DEVWUNLOCK(cgpu, pstate);
  3285. count++;
  3286. default:
  3287. break;
  3288. }
  3289. }
  3290. /*
  3291. * Must attempt to wait for the resource thread to release coz
  3292. * during a restart it won't automatically release them in linux
  3293. */
  3294. if (count) {
  3295. struct timeval start, now;
  3296. cgtime(&start);
  3297. while (42) {
  3298. cgsleep_ms(50);
  3299. mutex_lock(&cgusbres_lock);
  3300. if (!res_work_head)
  3301. break;
  3302. cgtime(&now);
  3303. if (tdiff(&now, &start) > 0.366) {
  3304. applog(LOG_WARNING,
  3305. "usb_cleanup gave up waiting for resource thread");
  3306. break;
  3307. }
  3308. mutex_unlock(&cgusbres_lock);
  3309. }
  3310. mutex_unlock(&cgusbres_lock);
  3311. }
  3312. cgsem_destroy(&usb_resource_sem);
  3313. }
  3314. #define DRIVER_COUNT_FOUND(X) if (X##_drv.name && strcasecmp(ptr, X##_drv.name) == 0) { \
  3315. drv_count[X##_drv.drv_id].limit = lim; \
  3316. found = true; \
  3317. }
  3318. void usb_initialise(void)
  3319. {
  3320. char *fre, *ptr, *comma, *colon;
  3321. int bus, dev, lim, i;
  3322. bool found;
  3323. INIT_LIST_HEAD(&ut_list);
  3324. for (i = 0; i < DRIVER_MAX; i++) {
  3325. drv_count[i].count = 0;
  3326. drv_count[i].limit = 999999;
  3327. }
  3328. cgusb_check_init();
  3329. if (opt_usb_select && *opt_usb_select) {
  3330. // Absolute device limit
  3331. if (*opt_usb_select == ':') {
  3332. total_limit = atoi(opt_usb_select+1);
  3333. if (total_limit < 0)
  3334. quit(1, "Invalid --usb total limit");
  3335. // Comma list of bus:dev devices to match
  3336. } else if (isdigit(*opt_usb_select)) {
  3337. fre = ptr = strdup(opt_usb_select);
  3338. do {
  3339. comma = strchr(ptr, ',');
  3340. if (comma)
  3341. *(comma++) = '\0';
  3342. colon = strchr(ptr, ':');
  3343. if (!colon)
  3344. quit(1, "Invalid --usb bus:dev missing ':'");
  3345. *(colon++) = '\0';
  3346. if (!isdigit(*ptr))
  3347. quit(1, "Invalid --usb bus:dev - bus must be a number");
  3348. if (!isdigit(*colon) && *colon != '*')
  3349. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  3350. bus = atoi(ptr);
  3351. if (bus <= 0)
  3352. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  3353. if (*colon == '*')
  3354. dev = -1;
  3355. else {
  3356. dev = atoi(colon);
  3357. if (dev <= 0)
  3358. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  3359. }
  3360. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  3361. if (unlikely(!busdev))
  3362. quit(1, "USB failed to realloc busdev");
  3363. busdev[busdev_count-1].bus_number = bus;
  3364. busdev[busdev_count-1].device_address = dev;
  3365. ptr = comma;
  3366. } while (ptr);
  3367. free(fre);
  3368. // Comma list of DRV:limit
  3369. } else {
  3370. fre = ptr = strdup(opt_usb_select);
  3371. do {
  3372. comma = strchr(ptr, ',');
  3373. if (comma)
  3374. *(comma++) = '\0';
  3375. colon = strchr(ptr, ':');
  3376. if (!colon)
  3377. quit(1, "Invalid --usb DRV:limit missing ':'");
  3378. *(colon++) = '\0';
  3379. if (!isdigit(*colon))
  3380. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  3381. lim = atoi(colon);
  3382. if (lim < 0)
  3383. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  3384. found = false;
  3385. /* Use the DRIVER_PARSE_COMMANDS macro to iterate
  3386. * over all the drivers. */
  3387. DRIVER_PARSE_COMMANDS(DRIVER_COUNT_FOUND)
  3388. if (!found)
  3389. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  3390. ptr = comma;
  3391. } while (ptr);
  3392. free(fre);
  3393. }
  3394. }
  3395. }
  3396. #ifndef WIN32
  3397. #include <errno.h>
  3398. #include <unistd.h>
  3399. #include <sys/stat.h>
  3400. #include <sys/file.h>
  3401. #include <fcntl.h>
  3402. #ifndef __APPLE__
  3403. union semun {
  3404. int val;
  3405. struct semid_ds *buf;
  3406. unsigned short *array;
  3407. struct seminfo *__buf;
  3408. };
  3409. #endif
  3410. #else
  3411. static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
  3412. {
  3413. FreeSid(((PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor))->Group);
  3414. free(sec->lpSecurityDescriptor);
  3415. free(sec);
  3416. return NULL;
  3417. }
  3418. static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
  3419. {
  3420. SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
  3421. PSID gsid = NULL;
  3422. LPSECURITY_ATTRIBUTES sec_att = NULL;
  3423. PSECURITY_DESCRIPTOR sec_des = NULL;
  3424. sec_des = malloc(sizeof(*sec_des));
  3425. if (unlikely(!sec_des))
  3426. quit(1, "MTX: Failed to malloc LPSECURITY_DESCRIPTOR");
  3427. if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
  3428. applog(LOG_ERR,
  3429. "MTX: %s (%d:%d) USB failed to init secdes err (%d)",
  3430. dname, (int)bus_number, (int)device_address,
  3431. (int)GetLastError());
  3432. free(sec_des);
  3433. return NULL;
  3434. }
  3435. if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
  3436. applog(LOG_ERR,
  3437. "MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
  3438. dname, (int)bus_number, (int)device_address,
  3439. (int)GetLastError());
  3440. free(sec_des);
  3441. return NULL;
  3442. }
  3443. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
  3444. applog(LOG_ERR,
  3445. "MTX: %s (%d:%d) USB failed to create gsid err (%d)",
  3446. dname, (int)bus_number, (int)device_address,
  3447. (int)GetLastError());
  3448. free(sec_des);
  3449. return NULL;
  3450. }
  3451. if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
  3452. applog(LOG_ERR,
  3453. "MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
  3454. dname, (int)bus_number, (int)device_address,
  3455. (int)GetLastError());
  3456. FreeSid(gsid);
  3457. free(sec_des);
  3458. return NULL;
  3459. }
  3460. sec_att = malloc(sizeof(*sec_att));
  3461. if (unlikely(!sec_att))
  3462. quit(1, "MTX: Failed to malloc LPSECURITY_ATTRIBUTES");
  3463. sec_att->nLength = sizeof(*sec_att);
  3464. sec_att->lpSecurityDescriptor = sec_des;
  3465. sec_att->bInheritHandle = FALSE;
  3466. return sec_att;
  3467. }
  3468. #endif
  3469. // Any errors should always be printed since they will rarely if ever occur
  3470. // and thus it is best to always display them
  3471. static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
  3472. {
  3473. applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
  3474. #ifdef WIN32
  3475. struct cgpu_info *cgpu;
  3476. LPSECURITY_ATTRIBUTES sec;
  3477. HANDLE usbMutex;
  3478. char name[64];
  3479. DWORD res;
  3480. int i;
  3481. if (is_in_use_bd(bus_number, device_address))
  3482. return false;
  3483. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  3484. sec = mksec(dname, bus_number, device_address);
  3485. if (!sec)
  3486. return false;
  3487. usbMutex = CreateMutex(sec, FALSE, name);
  3488. if (usbMutex == NULL) {
  3489. applog(LOG_ERR,
  3490. "MTX: %s USB failed to get '%s' err (%d)",
  3491. dname, name, (int)GetLastError());
  3492. sec = unsec(sec);
  3493. return false;
  3494. }
  3495. res = WaitForSingleObject(usbMutex, 0);
  3496. switch(res) {
  3497. case WAIT_OBJECT_0:
  3498. case WAIT_ABANDONED:
  3499. // Am I using it already?
  3500. for (i = 0; i < total_devices; i++) {
  3501. cgpu = get_devices(i);
  3502. if (cgpu->usbinfo.bus_number == bus_number &&
  3503. cgpu->usbinfo.device_address == device_address &&
  3504. cgpu->usbinfo.nodev == false) {
  3505. if (ReleaseMutex(usbMutex)) {
  3506. applog(LOG_WARNING,
  3507. "MTX: %s USB can't get '%s' - device in use",
  3508. dname, name);
  3509. goto fail;
  3510. }
  3511. applog(LOG_ERR,
  3512. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  3513. dname, name, (int)GetLastError());
  3514. goto fail;
  3515. }
  3516. }
  3517. break;
  3518. case WAIT_TIMEOUT:
  3519. if (!hotplug_mode)
  3520. applog(LOG_WARNING,
  3521. "MTX: %s USB failed to get '%s' - device in use",
  3522. dname, name);
  3523. goto fail;
  3524. case WAIT_FAILED:
  3525. applog(LOG_ERR,
  3526. "MTX: %s USB failed to get '%s' err (%d)",
  3527. dname, name, (int)GetLastError());
  3528. goto fail;
  3529. default:
  3530. applog(LOG_ERR,
  3531. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  3532. dname, name, (int)res);
  3533. goto fail;
  3534. }
  3535. add_in_use(bus_number, device_address, false);
  3536. in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
  3537. return true;
  3538. fail:
  3539. CloseHandle(usbMutex);
  3540. sec = unsec(sec);
  3541. return false;
  3542. #else
  3543. char name[64];
  3544. int fd;
  3545. if (is_in_use_bd(bus_number, device_address))
  3546. return false;
  3547. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  3548. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  3549. if (fd == -1) {
  3550. applog(LOG_ERR, "%s USB open failed '%s' err (%d) %s",
  3551. dname, name, errno, strerror(errno));
  3552. return false;
  3553. }
  3554. if (flock(fd, LOCK_EX | LOCK_NB)) {
  3555. applog(LOG_INFO, "%s USB failed to get '%s' - device in use",
  3556. dname, name);
  3557. close(fd);
  3558. return false;
  3559. }
  3560. add_in_use(bus_number, device_address, false);
  3561. in_use_store_fd(bus_number, device_address, fd);
  3562. return true;
  3563. #endif
  3564. }
  3565. // Any errors should always be printed since they will rarely if ever occur
  3566. // and thus it is best to always display them
  3567. static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
  3568. {
  3569. applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
  3570. #ifdef WIN32
  3571. LPSECURITY_ATTRIBUTES sec = NULL;
  3572. HANDLE usbMutex = NULL;
  3573. char name[64];
  3574. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  3575. in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
  3576. if (!usbMutex || !sec)
  3577. goto fila;
  3578. if (!ReleaseMutex(usbMutex))
  3579. applog(LOG_ERR,
  3580. "MTX: %s USB failed to release '%s' err (%d)",
  3581. dname, name, (int)GetLastError());
  3582. fila:
  3583. if (usbMutex)
  3584. CloseHandle(usbMutex);
  3585. if (sec)
  3586. unsec(sec);
  3587. remove_in_use(bus_number, device_address);
  3588. return;
  3589. #else
  3590. char name[64];
  3591. int fd;
  3592. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  3593. fd = in_use_get_fd(bus_number, device_address);
  3594. if (fd < 0)
  3595. return;
  3596. remove_in_use(bus_number, device_address);
  3597. close(fd);
  3598. unlink(name);
  3599. return;
  3600. #endif
  3601. }
  3602. static void resource_process()
  3603. {
  3604. struct resource_work *res_work = NULL;
  3605. struct resource_reply *res_reply = NULL;
  3606. bool ok;
  3607. applog(LOG_DEBUG, "RES: %s (%d:%d) lock=%d",
  3608. res_work_head->dname,
  3609. (int)res_work_head->bus_number,
  3610. (int)res_work_head->device_address,
  3611. res_work_head->lock);
  3612. if (res_work_head->lock) {
  3613. ok = resource_lock(res_work_head->dname,
  3614. res_work_head->bus_number,
  3615. res_work_head->device_address);
  3616. applog(LOG_DEBUG, "RES: %s (%d:%d) lock ok=%d",
  3617. res_work_head->dname,
  3618. (int)res_work_head->bus_number,
  3619. (int)res_work_head->device_address,
  3620. ok);
  3621. res_reply = calloc(1, sizeof(*res_reply));
  3622. if (unlikely(!res_reply))
  3623. quit(1, "USB failed to calloc res_reply");
  3624. res_reply->bus_number = res_work_head->bus_number;
  3625. res_reply->device_address = res_work_head->device_address;
  3626. res_reply->got = ok;
  3627. res_reply->next = res_reply_head;
  3628. res_reply_head = res_reply;
  3629. }
  3630. else
  3631. resource_unlock(res_work_head->dname,
  3632. res_work_head->bus_number,
  3633. res_work_head->device_address);
  3634. res_work = res_work_head;
  3635. res_work_head = res_work_head->next;
  3636. free(res_work);
  3637. }
  3638. void *usb_resource_thread(void __maybe_unused *userdata)
  3639. {
  3640. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3641. RenameThread("USBResource");
  3642. applog(LOG_DEBUG, "RES: thread starting");
  3643. while (42) {
  3644. /* Wait to be told we have work to do */
  3645. cgsem_wait(&usb_resource_sem);
  3646. mutex_lock(&cgusbres_lock);
  3647. while (res_work_head)
  3648. resource_process();
  3649. mutex_unlock(&cgusbres_lock);
  3650. }
  3651. return NULL;
  3652. }
  3653. void initialise_usblocks(void)
  3654. {
  3655. mutex_init(&cgusb_lock);
  3656. mutex_init(&cgusbres_lock);
  3657. cglock_init(&cgusb_fd_lock);
  3658. }