usbutils.c 98 KB

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