usbutils.c 98 KB

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