usbutils.c 107 KB

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