usbutils.c 98 KB

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