usbutils.c 97 KB

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