usbutils.c 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808
  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)
  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. }
  1886. static void complete_usb_transfer(struct usb_transfer *ut)
  1887. {
  1888. cgsem_destroy(&ut->cgsem);
  1889. libusb_free_transfer(ut->transfer);
  1890. cg_wlock(&cgusb_fd_lock);
  1891. cgusb_transfers--;
  1892. if (ut->cancellable)
  1893. list_del(&ut->ct.list);
  1894. cg_wunlock(&cgusb_fd_lock);
  1895. }
  1896. static void LIBUSB_CALL transfer_callback(struct libusb_transfer *transfer)
  1897. {
  1898. struct usb_transfer *ut = transfer->user_data;
  1899. cgsem_post(&ut->cgsem);
  1900. }
  1901. static int usb_transfer_toerr(int ret)
  1902. {
  1903. switch (ret) {
  1904. default:
  1905. case LIBUSB_TRANSFER_COMPLETED:
  1906. ret = LIBUSB_SUCCESS;
  1907. break;
  1908. case LIBUSB_TRANSFER_ERROR:
  1909. ret = LIBUSB_ERROR_IO;
  1910. break;
  1911. case LIBUSB_TRANSFER_TIMED_OUT:
  1912. case LIBUSB_TRANSFER_CANCELLED:
  1913. ret = LIBUSB_ERROR_TIMEOUT;
  1914. break;
  1915. case LIBUSB_TRANSFER_STALL:
  1916. ret = LIBUSB_ERROR_PIPE;
  1917. break;
  1918. case LIBUSB_TRANSFER_NO_DEVICE:
  1919. ret = LIBUSB_ERROR_NO_DEVICE;
  1920. break;
  1921. case LIBUSB_TRANSFER_OVERFLOW:
  1922. ret = LIBUSB_ERROR_OVERFLOW;
  1923. break;
  1924. }
  1925. return ret;
  1926. }
  1927. /* Wait for callback function to tell us it has finished the USB transfer, but
  1928. * use our own timer to cancel the request if we go beyond the timeout. */
  1929. static int callback_wait(struct usb_transfer *ut, int *transferred, unsigned int timeout)
  1930. {
  1931. struct libusb_transfer *transfer= ut->transfer;
  1932. int ret;
  1933. ret = cgsem_mswait(&ut->cgsem, timeout);
  1934. if (ret == ETIMEDOUT) {
  1935. /* We are emulating a timeout ourself here */
  1936. libusb_cancel_transfer(transfer);
  1937. /* Now wait for the callback function to be invoked. */
  1938. cgsem_wait(&ut->cgsem);
  1939. }
  1940. ret = transfer->status;
  1941. ret = usb_transfer_toerr(ret);
  1942. /* No need to sort out mutexes here since they won't be reused */
  1943. *transferred = transfer->actual_length;
  1944. return ret;
  1945. }
  1946. static int usb_submit_transfer(struct usb_transfer *ut, struct libusb_transfer *transfer,
  1947. bool cancellable)
  1948. {
  1949. int err;
  1950. cg_wlock(&cgusb_fd_lock);
  1951. err = libusb_submit_transfer(transfer);
  1952. cgusb_transfers++;
  1953. if (cancellable) {
  1954. ut->cancellable = true;
  1955. INIT_LIST_HEAD(&ut->ct.list);
  1956. list_add(&ct_list, &ut->ct.list);
  1957. }
  1958. cg_wunlock(&cgusb_fd_lock);
  1959. return err;
  1960. }
  1961. static int
  1962. usb_bulk_transfer(struct libusb_device_handle *dev_handle, int intinfo,
  1963. int epinfo, unsigned char *data, int length,
  1964. int *transferred, unsigned int timeout,
  1965. struct cgpu_info *cgpu, __maybe_unused int mode,
  1966. enum usb_cmds cmd, __maybe_unused int seq, bool cancellable)
  1967. {
  1968. struct usb_epinfo *usb_epinfo;
  1969. struct usb_transfer ut;
  1970. unsigned char endpoint;
  1971. uint16_t MaxPacketSize;
  1972. int err, errn;
  1973. #if DO_USB_STATS
  1974. struct timeval tv_start, tv_finish;
  1975. #endif
  1976. unsigned char buf[512];
  1977. usb_epinfo = &(cgpu->usbdev->found->intinfos[intinfo].epinfos[epinfo]);
  1978. endpoint = usb_epinfo->ep;
  1979. /* Avoid any async transfers during shutdown to allow the polling
  1980. * thread to be shut down after all existing transfers are complete */
  1981. if (unlikely(cgpu->shutdown))
  1982. return libusb_bulk_transfer(dev_handle, endpoint, data, length, transferred, timeout);
  1983. /* Limit length of transfer to the largest this descriptor supports
  1984. * and leave the higher level functions to transfer more if needed. */
  1985. if (usb_epinfo->PrefPacketSize)
  1986. MaxPacketSize = usb_epinfo->PrefPacketSize;
  1987. else
  1988. MaxPacketSize = usb_epinfo->wMaxPacketSize;
  1989. if (length > MaxPacketSize)
  1990. length = MaxPacketSize;
  1991. if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)
  1992. memcpy(buf, data, length);
  1993. 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);
  1994. init_usb_transfer(&ut);
  1995. /* We give the transfer no timeout since we manage timeouts ourself */
  1996. libusb_fill_bulk_transfer(ut.transfer, dev_handle, endpoint, buf, length,
  1997. transfer_callback, &ut, 0);
  1998. STATS_TIMEVAL(&tv_start);
  1999. err = usb_submit_transfer(&ut, ut.transfer, cancellable);
  2000. errn = errno;
  2001. if (!err)
  2002. err = callback_wait(&ut, transferred, timeout);
  2003. complete_usb_transfer(&ut);
  2004. STATS_TIMEVAL(&tv_finish);
  2005. USB_STATS(cgpu, &tv_start, &tv_finish, err, mode, cmd, seq, timeout);
  2006. if (err < 0)
  2007. applog(LOG_DEBUG, "%s%i: %s (amt=%d err=%d ern=%d)",
  2008. cgpu->drv->name, cgpu->device_id,
  2009. usb_cmdname(cmd), *transferred, err, errn);
  2010. if (err == LIBUSB_ERROR_PIPE) {
  2011. int retries = 0;
  2012. do {
  2013. cgpu->usbinfo.last_pipe = time(NULL);
  2014. cgpu->usbinfo.pipe_count++;
  2015. applog(LOG_INFO, "%s%i: libusb pipe error, trying to clear",
  2016. cgpu->drv->name, cgpu->device_id);
  2017. err = libusb_clear_halt(dev_handle, endpoint);
  2018. applog(LOG_DEBUG, "%s%i: libusb pipe error%scleared",
  2019. cgpu->drv->name, cgpu->device_id, err ? " not " : " ");
  2020. if (err)
  2021. cgpu->usbinfo.clear_fail_count++;
  2022. } while (err && ++retries < USB_RETRY_MAX);
  2023. }
  2024. if ((endpoint & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
  2025. memcpy(data, buf, length);
  2026. return err;
  2027. }
  2028. 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, bool cancellable)
  2029. {
  2030. struct cg_usb_device *usbdev;
  2031. bool ftdi;
  2032. struct timeval read_start, tv_finish;
  2033. unsigned int initial_timeout;
  2034. double max, done;
  2035. int bufleft, err, got, tot, pstate;
  2036. bool first = true;
  2037. char *search;
  2038. int endlen;
  2039. unsigned char *ptr, *usbbuf = cgpu->usbinfo.bulkbuf;
  2040. size_t usbbufread;
  2041. DEVRLOCK(cgpu, pstate);
  2042. if (cgpu->usbinfo.nodev) {
  2043. *buf = '\0';
  2044. *processed = 0;
  2045. USB_REJECT(cgpu, MODE_BULK_READ);
  2046. err = LIBUSB_ERROR_NO_DEVICE;
  2047. goto out_noerrmsg;
  2048. }
  2049. usbdev = cgpu->usbdev;
  2050. ftdi = (usbdev->usb_type == USB_TYPE_FTDI);
  2051. 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));
  2052. if (bufsiz > USB_MAX_READ)
  2053. quit(1, "%s USB read request %d too large (max=%d)", cgpu->drv->name, (int)bufsiz, USB_MAX_READ);
  2054. if (timeout == DEVTIMEOUT)
  2055. timeout = usbdev->found->timeout;
  2056. if (end == NULL) {
  2057. if (usbdev->buffer && usbdev->bufamt) {
  2058. tot = usbdev->bufamt;
  2059. bufleft = bufsiz - tot;
  2060. memcpy(usbbuf, usbdev->buffer, tot);
  2061. ptr = usbbuf + tot;
  2062. usbdev->bufamt = 0;
  2063. } else {
  2064. tot = 0;
  2065. bufleft = bufsiz;
  2066. ptr = usbbuf;
  2067. }
  2068. err = LIBUSB_SUCCESS;
  2069. initial_timeout = timeout;
  2070. max = ((double)timeout) / 1000.0;
  2071. cgtime(&read_start);
  2072. while (bufleft > 0) {
  2073. // TODO: use (USB_MAX_READ - tot) always?
  2074. if (usbdev->buffer)
  2075. usbbufread = USB_MAX_READ - tot;
  2076. else {
  2077. if (ftdi)
  2078. usbbufread = bufleft + 2;
  2079. else
  2080. usbbufread = bufleft;
  2081. }
  2082. got = 0;
  2083. if (first && usbdev->usecps && usbdev->last_write_siz) {
  2084. cgtimer_t now, already_done;
  2085. double sleep_estimate;
  2086. double write_time = (double)(usbdev->last_write_siz) /
  2087. (double)(usbdev->cps);
  2088. cgtimer_time(&now);
  2089. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2090. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2091. if (sleep_estimate > 0.0) {
  2092. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2093. cgpu->usbinfo.read_delay_count++;
  2094. cgpu->usbinfo.total_read_delay += sleep_estimate;
  2095. }
  2096. }
  2097. err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
  2098. ptr, usbbufread, &got, timeout,
  2099. cgpu, MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1,
  2100. cancellable);
  2101. cgtime(&tv_finish);
  2102. ptr[got] = '\0';
  2103. 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);
  2104. IOERR_CHECK(cgpu, err);
  2105. if (ftdi) {
  2106. // first 2 bytes returned are an FTDI status
  2107. if (got > 2) {
  2108. got -= 2;
  2109. memmove(ptr, ptr+2, got+1);
  2110. } else {
  2111. got = 0;
  2112. *ptr = '\0';
  2113. }
  2114. }
  2115. tot += got;
  2116. if (err || readonce)
  2117. break;
  2118. ptr += got;
  2119. bufleft -= got;
  2120. first = false;
  2121. done = tdiff(&tv_finish, &read_start);
  2122. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  2123. if (unlikely(done >= max))
  2124. break;
  2125. timeout = initial_timeout - (done * 1000);
  2126. if (!timeout)
  2127. break;
  2128. }
  2129. // N.B. usbdev->buffer was emptied before the while() loop
  2130. if (usbdev->buffer && tot > (int)bufsiz) {
  2131. usbdev->bufamt = tot - bufsiz;
  2132. memcpy(usbdev->buffer, usbbuf + bufsiz, usbdev->bufamt);
  2133. tot -= usbdev->bufamt;
  2134. usbbuf[tot] = '\0';
  2135. applog(LOG_DEBUG, "USB: %s%i read1 buffering %d extra bytes",
  2136. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2137. }
  2138. *processed = tot;
  2139. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2140. goto out_unlock;
  2141. }
  2142. if (usbdev->buffer && usbdev->bufamt) {
  2143. tot = usbdev->bufamt;
  2144. bufleft = bufsiz - tot;
  2145. memcpy(usbbuf, usbdev->buffer, tot);
  2146. ptr = usbbuf + tot;
  2147. usbdev->bufamt = 0;
  2148. } else {
  2149. tot = 0;
  2150. bufleft = bufsiz;
  2151. ptr = usbbuf;
  2152. }
  2153. endlen = strlen(end);
  2154. err = LIBUSB_SUCCESS;
  2155. initial_timeout = timeout;
  2156. max = ((double)timeout) / 1000.0;
  2157. cgtime(&read_start);
  2158. while (bufleft > 0) {
  2159. // TODO: use (USB_MAX_READ - tot) always?
  2160. if (usbdev->buffer)
  2161. usbbufread = USB_MAX_READ - tot;
  2162. else {
  2163. if (ftdi)
  2164. usbbufread = bufleft + 2;
  2165. else
  2166. usbbufread = bufleft;
  2167. }
  2168. got = 0;
  2169. if (first && usbdev->usecps && usbdev->last_write_siz) {
  2170. cgtimer_t now, already_done;
  2171. double sleep_estimate;
  2172. double write_time = (double)(usbdev->last_write_siz) /
  2173. (double)(usbdev->cps);
  2174. cgtimer_time(&now);
  2175. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2176. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2177. if (sleep_estimate > 0.0) {
  2178. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2179. cgpu->usbinfo.read_delay_count++;
  2180. cgpu->usbinfo.total_read_delay += sleep_estimate;
  2181. }
  2182. }
  2183. err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
  2184. ptr, usbbufread, &got, timeout,
  2185. cgpu, MODE_BULK_READ, cmd, first ? SEQ0 : SEQ1,
  2186. cancellable);
  2187. cgtime(&tv_finish);
  2188. ptr[got] = '\0';
  2189. 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);
  2190. IOERR_CHECK(cgpu, err);
  2191. if (ftdi) {
  2192. // first 2 bytes returned are an FTDI status
  2193. if (got > 2) {
  2194. got -= 2;
  2195. memmove(ptr, ptr+2, got+1);
  2196. } else {
  2197. got = 0;
  2198. *ptr = '\0';
  2199. }
  2200. }
  2201. tot += got;
  2202. if (err || readonce)
  2203. break;
  2204. if (find_end(usbbuf, ptr, got, tot, (char *)end, endlen, first))
  2205. break;
  2206. ptr += got;
  2207. bufleft -= got;
  2208. first = false;
  2209. done = tdiff(&tv_finish, &read_start);
  2210. // N.B. this is: return LIBUSB_SUCCESS with whatever size has already been read
  2211. if (unlikely(done >= max))
  2212. break;
  2213. timeout = initial_timeout - (done * 1000);
  2214. if (!timeout)
  2215. break;
  2216. }
  2217. if (usbdev->buffer) {
  2218. bool dobuffer = false;
  2219. if ((search = find_end(usbbuf, usbbuf, tot, tot, (char *)end, endlen, true))) {
  2220. // end finishes after bufsiz
  2221. if ((search + endlen - (char *)usbbuf) > (int)bufsiz) {
  2222. usbdev->bufamt = tot - bufsiz;
  2223. dobuffer = true;
  2224. } else {
  2225. // extra data after end
  2226. if (*(search + endlen)) {
  2227. usbdev->bufamt = tot - (search + endlen - (char *)usbbuf);
  2228. dobuffer = true;
  2229. }
  2230. }
  2231. } else {
  2232. // no end, but still bigger than bufsiz
  2233. if (tot > (int)bufsiz) {
  2234. usbdev->bufamt = tot - bufsiz;
  2235. dobuffer = true;
  2236. }
  2237. }
  2238. if (dobuffer) {
  2239. tot -= usbdev->bufamt;
  2240. memcpy(usbdev->buffer, usbbuf + tot, usbdev->bufamt);
  2241. usbbuf[tot] = '\0';
  2242. applog(LOG_DEBUG, "USB: %s%i read2 buffering %d extra bytes",
  2243. cgpu->drv->name, cgpu->device_id, usbdev->bufamt);
  2244. }
  2245. }
  2246. *processed = tot;
  2247. memcpy((char *)buf, (const char *)usbbuf, (tot < (int)bufsiz) ? tot + 1 : (int)bufsiz);
  2248. out_unlock:
  2249. if (err && err != LIBUSB_ERROR_TIMEOUT) {
  2250. applog(LOG_WARNING, "%s %i %s usb read err:(%d) %s", cgpu->drv->name, cgpu->device_id, usb_cmdname(cmd),
  2251. err, libusb_error_name(err));
  2252. if (cgpu->usbinfo.continuous_ioerr_count > USB_RETRY_MAX)
  2253. err = LIBUSB_ERROR_OTHER;
  2254. }
  2255. out_noerrmsg:
  2256. if (NODEV(err)) {
  2257. cg_ruwlock(&cgpu->usbinfo.devlock);
  2258. release_cgpu(cgpu);
  2259. DEVWUNLOCK(cgpu, pstate);
  2260. } else
  2261. DEVRUNLOCK(cgpu, pstate);
  2262. return err;
  2263. }
  2264. 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)
  2265. {
  2266. struct cg_usb_device *usbdev;
  2267. struct timeval read_start, tv_finish;
  2268. unsigned int initial_timeout;
  2269. double max, done;
  2270. __maybe_unused bool first = true;
  2271. int err, sent, tot, pstate;
  2272. DEVRLOCK(cgpu, pstate);
  2273. 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));
  2274. *processed = 0;
  2275. if (cgpu->usbinfo.nodev) {
  2276. USB_REJECT(cgpu, MODE_BULK_WRITE);
  2277. err = LIBUSB_ERROR_NO_DEVICE;
  2278. goto out_noerrmsg;
  2279. }
  2280. usbdev = cgpu->usbdev;
  2281. if (timeout == DEVTIMEOUT)
  2282. timeout = usbdev->found->timeout;
  2283. tot = 0;
  2284. err = LIBUSB_SUCCESS;
  2285. initial_timeout = timeout;
  2286. max = ((double)timeout) / 1000.0;
  2287. cgtime(&read_start);
  2288. while (bufsiz > 0) {
  2289. sent = 0;
  2290. if (usbdev->usecps) {
  2291. if (usbdev->last_write_siz) {
  2292. cgtimer_t now, already_done;
  2293. double sleep_estimate;
  2294. double write_time = (double)(usbdev->last_write_siz) /
  2295. (double)(usbdev->cps);
  2296. cgtimer_time(&now);
  2297. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2298. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2299. if (sleep_estimate > 0.0) {
  2300. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2301. cgpu->usbinfo.write_delay_count++;
  2302. cgpu->usbinfo.total_write_delay += sleep_estimate;
  2303. }
  2304. }
  2305. cgsleep_prepare_r(&usbdev->cgt_last_write);
  2306. usbdev->last_write_siz = bufsiz;
  2307. }
  2308. err = usb_bulk_transfer(usbdev->handle, intinfo, epinfo,
  2309. (unsigned char *)buf, bufsiz, &sent, timeout,
  2310. cgpu, MODE_BULK_WRITE, cmd, first ? SEQ0 : SEQ1,
  2311. false);
  2312. cgtime(&tv_finish);
  2313. 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);
  2314. IOERR_CHECK(cgpu, err);
  2315. tot += sent;
  2316. if (err)
  2317. break;
  2318. buf += sent;
  2319. bufsiz -= sent;
  2320. first = false;
  2321. done = tdiff(&tv_finish, &read_start);
  2322. // N.B. this is: return LIBUSB_SUCCESS with whatever size was written
  2323. if (unlikely(done >= max))
  2324. break;
  2325. timeout = initial_timeout - (done * 1000);
  2326. if (!timeout)
  2327. break;
  2328. }
  2329. *processed = tot;
  2330. if (err) {
  2331. applog(LOG_WARNING, "%s %i %s usb write err:(%d) %s", cgpu->drv->name, cgpu->device_id, usb_cmdname(cmd),
  2332. err, libusb_error_name(err));
  2333. if (cgpu->usbinfo.continuous_ioerr_count > USB_RETRY_MAX)
  2334. err = LIBUSB_ERROR_OTHER;
  2335. }
  2336. out_noerrmsg:
  2337. if (NODEV(err)) {
  2338. cg_ruwlock(&cgpu->usbinfo.devlock);
  2339. release_cgpu(cgpu);
  2340. DEVWUNLOCK(cgpu, pstate);
  2341. } else
  2342. DEVRUNLOCK(cgpu, pstate);
  2343. return err;
  2344. }
  2345. /* As we do for bulk reads, emulate a sync function for control transfers using
  2346. * our own timeouts that takes the same parameters as libusb_control_transfer.
  2347. */
  2348. static int usb_control_transfer(struct cgpu_info *cgpu, libusb_device_handle *dev_handle, uint8_t bmRequestType,
  2349. uint8_t bRequest, uint16_t wValue, uint16_t wIndex,
  2350. unsigned char *buffer, uint16_t wLength, unsigned int timeout)
  2351. {
  2352. struct usb_transfer ut;
  2353. unsigned char buf[70];
  2354. int err, transferred;
  2355. if (unlikely(cgpu->shutdown))
  2356. return libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, buffer, wLength, timeout);
  2357. init_usb_transfer(&ut);
  2358. libusb_fill_control_setup(buf, bmRequestType, bRequest, wValue,
  2359. wIndex, wLength);
  2360. if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_OUT)
  2361. memcpy(buf + LIBUSB_CONTROL_SETUP_SIZE, buffer, wLength);
  2362. libusb_fill_control_transfer(ut.transfer, dev_handle, buf, transfer_callback,
  2363. &ut, 0);
  2364. err = usb_submit_transfer(&ut, ut.transfer, false);
  2365. if (!err)
  2366. err = callback_wait(&ut, &transferred, timeout);
  2367. if (err == LIBUSB_SUCCESS && transferred) {
  2368. if ((bmRequestType & LIBUSB_ENDPOINT_DIR_MASK) == LIBUSB_ENDPOINT_IN)
  2369. memcpy(buffer, libusb_control_transfer_get_data(ut.transfer),
  2370. transferred);
  2371. err = transferred;
  2372. goto out;
  2373. }
  2374. err = usb_transfer_toerr(err);
  2375. out:
  2376. complete_usb_transfer(&ut);
  2377. return err;
  2378. }
  2379. 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)
  2380. {
  2381. struct cg_usb_device *usbdev;
  2382. #if DO_USB_STATS
  2383. struct timeval tv_start, tv_finish;
  2384. #endif
  2385. unsigned char buf[64];
  2386. uint32_t *buf32 = (uint32_t *)buf;
  2387. int err, i, bufsiz;
  2388. 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));
  2389. if (cgpu->usbinfo.nodev) {
  2390. USB_REJECT(cgpu, MODE_CTRL_WRITE);
  2391. err = LIBUSB_ERROR_NO_DEVICE;
  2392. goto out_;
  2393. }
  2394. usbdev = cgpu->usbdev;
  2395. if (timeout == DEVTIMEOUT)
  2396. timeout = usbdev->found->timeout;
  2397. USBDEBUG("USB debug: @_usb_transfer() data=%s", bin2hex((unsigned char *)data, (size_t)siz));
  2398. if (siz > 0) {
  2399. bufsiz = siz - 1;
  2400. bufsiz >>= 2;
  2401. bufsiz++;
  2402. for (i = 0; i < bufsiz; i++)
  2403. buf32[i] = htole32(data[i]);
  2404. }
  2405. USBDEBUG("USB debug: @_usb_transfer() buf=%s", bin2hex(buf, (size_t)siz));
  2406. if (usbdev->usecps) {
  2407. if (usbdev->last_write_siz) {
  2408. cgtimer_t now, already_done;
  2409. double sleep_estimate;
  2410. double write_time = (double)(usbdev->last_write_siz) /
  2411. (double)(usbdev->cps);
  2412. cgtimer_time(&now);
  2413. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2414. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2415. if (sleep_estimate > 0.0) {
  2416. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2417. cgpu->usbinfo.write_delay_count++;
  2418. cgpu->usbinfo.total_write_delay += sleep_estimate;
  2419. }
  2420. }
  2421. cgsleep_prepare_r(&usbdev->cgt_last_write);
  2422. usbdev->last_write_siz = siz;
  2423. }
  2424. STATS_TIMEVAL(&tv_start);
  2425. err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
  2426. wValue, wIndex, buf, (uint16_t)siz, timeout);
  2427. STATS_TIMEVAL(&tv_finish);
  2428. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_WRITE, cmd, SEQ0, timeout);
  2429. USBDEBUG("USB debug: @_usb_transfer(%s (nodev=%s)) err=%d%s", cgpu->drv->name, bool_str(cgpu->usbinfo.nodev), err, isnodev(err));
  2430. IOERR_CHECK(cgpu, err);
  2431. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  2432. applog(LOG_WARNING, "%s %i usb transfer err:(%d) %s", cgpu->drv->name, cgpu->device_id,
  2433. err, libusb_error_name(err));
  2434. }
  2435. out_:
  2436. return err;
  2437. }
  2438. /* We use the write devlock for control transfers since some control transfers
  2439. * are rare but may be changing settings within the device causing problems
  2440. * if concurrent transfers are happening. Using the write lock serialises
  2441. * any transfers. */
  2442. 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)
  2443. {
  2444. int pstate, err;
  2445. DEVWLOCK(cgpu, pstate);
  2446. err = __usb_transfer(cgpu, request_type, bRequest, wValue, wIndex, data, siz, timeout, cmd);
  2447. if (NOCONTROLDEV(err))
  2448. release_cgpu(cgpu);
  2449. DEVWUNLOCK(cgpu, pstate);
  2450. return err;
  2451. }
  2452. 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)
  2453. {
  2454. struct cg_usb_device *usbdev;
  2455. #if DO_USB_STATS
  2456. struct timeval tv_start, tv_finish;
  2457. #endif
  2458. unsigned char tbuf[64];
  2459. int err, pstate;
  2460. DEVWLOCK(cgpu, pstate);
  2461. 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));
  2462. if (cgpu->usbinfo.nodev) {
  2463. USB_REJECT(cgpu, MODE_CTRL_READ);
  2464. err = LIBUSB_ERROR_NO_DEVICE;
  2465. goto out_noerrmsg;
  2466. }
  2467. usbdev = cgpu->usbdev;
  2468. if (timeout == DEVTIMEOUT)
  2469. timeout = usbdev->found->timeout;
  2470. *amount = 0;
  2471. if (usbdev->usecps && usbdev->last_write_siz) {
  2472. cgtimer_t now, already_done;
  2473. double sleep_estimate;
  2474. double write_time = (double)(usbdev->last_write_siz) /
  2475. (double)(usbdev->cps);
  2476. cgtimer_time(&now);
  2477. cgtimer_sub(&now, &usbdev->cgt_last_write, &already_done);
  2478. sleep_estimate = write_time - cgtimer_to_ms(&already_done);
  2479. if (sleep_estimate > 0.0) {
  2480. cgsleep_ms_r(&usbdev->cgt_last_write, write_time * 1000.0);
  2481. cgpu->usbinfo.read_delay_count++;
  2482. cgpu->usbinfo.total_read_delay += sleep_estimate;
  2483. }
  2484. }
  2485. memset(tbuf, 0, 64);
  2486. STATS_TIMEVAL(&tv_start);
  2487. cg_rlock(&cgusb_fd_lock);
  2488. err = usb_control_transfer(cgpu, usbdev->handle, request_type, bRequest,
  2489. wValue, wIndex, tbuf, (uint16_t)bufsiz, timeout);
  2490. cg_runlock(&cgusb_fd_lock);
  2491. STATS_TIMEVAL(&tv_finish);
  2492. USB_STATS(cgpu, &tv_start, &tv_finish, err, MODE_CTRL_READ, cmd, SEQ0, timeout);
  2493. memcpy(buf, tbuf, bufsiz);
  2494. 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);
  2495. IOERR_CHECK(cgpu, err);
  2496. if (err > 0) {
  2497. *amount = err;
  2498. err = 0;
  2499. }
  2500. if (err < 0 && err != LIBUSB_ERROR_TIMEOUT) {
  2501. applog(LOG_WARNING, "%s %i usb transfer read err:(%d) %s", cgpu->drv->name, cgpu->device_id,
  2502. err, libusb_error_name(err));
  2503. }
  2504. out_noerrmsg:
  2505. if (NOCONTROLDEV(err))
  2506. release_cgpu(cgpu);
  2507. DEVWUNLOCK(cgpu, pstate);
  2508. return err;
  2509. }
  2510. #define FTDI_STATUS_B0_MASK (FTDI_RS0_CTS | FTDI_RS0_DSR | FTDI_RS0_RI | FTDI_RS0_RLSD)
  2511. #define FTDI_RS0_CTS (1 << 4)
  2512. #define FTDI_RS0_DSR (1 << 5)
  2513. #define FTDI_RS0_RI (1 << 6)
  2514. #define FTDI_RS0_RLSD (1 << 7)
  2515. /* Clear to send for FTDI */
  2516. int usb_ftdi_cts(struct cgpu_info *cgpu)
  2517. {
  2518. char buf[2], ret;
  2519. int err, amount;
  2520. err = _usb_transfer_read(cgpu, (uint8_t)FTDI_TYPE_IN, (uint8_t)5,
  2521. (uint16_t)0, (uint16_t)0, buf, 2,
  2522. &amount, DEVTIMEOUT, C_FTDI_STATUS);
  2523. /* We return true in case drivers are waiting indefinitely to try and
  2524. * write to something that's not there. */
  2525. if (err)
  2526. return true;
  2527. ret = buf[0] & FTDI_STATUS_B0_MASK;
  2528. return (ret & FTDI_RS0_CTS);
  2529. }
  2530. int _usb_ftdi_set_latency(struct cgpu_info *cgpu, int intinfo)
  2531. {
  2532. int err = 0;
  2533. int pstate;
  2534. DEVWLOCK(cgpu, pstate);
  2535. if (cgpu->usbdev) {
  2536. if (cgpu->usbdev->usb_type != USB_TYPE_FTDI) {
  2537. applog(LOG_ERR, "%s: cgid %d latency request on non-FTDI device",
  2538. cgpu->drv->name, cgpu->cgminer_id);
  2539. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2540. } else if (cgpu->usbdev->found->latency == LATENCY_UNUSED) {
  2541. applog(LOG_ERR, "%s: cgid %d invalid latency (UNUSED)",
  2542. cgpu->drv->name, cgpu->cgminer_id);
  2543. err = LIBUSB_ERROR_NOT_SUPPORTED;
  2544. }
  2545. if (!err)
  2546. err = __usb_transfer(cgpu, FTDI_TYPE_OUT, FTDI_REQUEST_LATENCY,
  2547. cgpu->usbdev->found->latency,
  2548. USBIF(cgpu->usbdev, intinfo),
  2549. NULL, 0, DEVTIMEOUT, C_LATENCY);
  2550. }
  2551. DEVWUNLOCK(cgpu, pstate);
  2552. applog(LOG_DEBUG, "%s: cgid %d %s got err %d",
  2553. cgpu->drv->name, cgpu->cgminer_id,
  2554. usb_cmdname(C_LATENCY), err);
  2555. return err;
  2556. }
  2557. void usb_buffer_enable(struct cgpu_info *cgpu)
  2558. {
  2559. struct cg_usb_device *cgusb;
  2560. int pstate;
  2561. DEVWLOCK(cgpu, pstate);
  2562. cgusb = cgpu->usbdev;
  2563. if (cgusb && !cgusb->buffer) {
  2564. cgusb->bufamt = 0;
  2565. cgusb->buffer = malloc(USB_MAX_READ+1);
  2566. if (!cgusb->buffer)
  2567. quit(1, "Failed to malloc buffer for USB %s%i",
  2568. cgpu->drv->name, cgpu->device_id);
  2569. cgusb->bufsiz = USB_MAX_READ;
  2570. }
  2571. DEVWUNLOCK(cgpu, pstate);
  2572. }
  2573. void usb_buffer_disable(struct cgpu_info *cgpu)
  2574. {
  2575. struct cg_usb_device *cgusb;
  2576. int pstate;
  2577. DEVWLOCK(cgpu, pstate);
  2578. cgusb = cgpu->usbdev;
  2579. if (cgusb && cgusb->buffer) {
  2580. cgusb->bufamt = 0;
  2581. cgusb->bufsiz = 0;
  2582. free(cgusb->buffer);
  2583. cgusb->buffer = NULL;
  2584. }
  2585. DEVWUNLOCK(cgpu, pstate);
  2586. }
  2587. void usb_buffer_clear(struct cgpu_info *cgpu)
  2588. {
  2589. int pstate;
  2590. DEVWLOCK(cgpu, pstate);
  2591. if (cgpu->usbdev)
  2592. cgpu->usbdev->bufamt = 0;
  2593. DEVWUNLOCK(cgpu, pstate);
  2594. }
  2595. uint32_t usb_buffer_size(struct cgpu_info *cgpu)
  2596. {
  2597. uint32_t ret = 0;
  2598. int pstate;
  2599. DEVRLOCK(cgpu, pstate);
  2600. if (cgpu->usbdev)
  2601. ret = cgpu->usbdev->bufamt;
  2602. DEVRUNLOCK(cgpu, pstate);
  2603. return ret;
  2604. }
  2605. void usb_set_cps(struct cgpu_info *cgpu, int cps)
  2606. {
  2607. int pstate;
  2608. DEVWLOCK(cgpu, pstate);
  2609. if (cgpu->usbdev)
  2610. cgpu->usbdev->cps = cps;
  2611. DEVWUNLOCK(cgpu, pstate);
  2612. }
  2613. void usb_enable_cps(struct cgpu_info *cgpu)
  2614. {
  2615. int pstate;
  2616. DEVWLOCK(cgpu, pstate);
  2617. if (cgpu->usbdev)
  2618. cgpu->usbdev->usecps = true;
  2619. DEVWUNLOCK(cgpu, pstate);
  2620. }
  2621. void usb_disable_cps(struct cgpu_info *cgpu)
  2622. {
  2623. int pstate;
  2624. DEVWLOCK(cgpu, pstate);
  2625. if (cgpu->usbdev)
  2626. cgpu->usbdev->usecps = false;
  2627. DEVWUNLOCK(cgpu, pstate);
  2628. }
  2629. /*
  2630. * The value returned (0) when usbdev is NULL
  2631. * doesn't matter since it also means the next call to
  2632. * any usbutils function will fail with a nodev
  2633. * N.B. this is to get the interface number to use in a control_transfer
  2634. * which for some devices isn't actually the interface number
  2635. */
  2636. int _usb_interface(struct cgpu_info *cgpu, int intinfo)
  2637. {
  2638. int interface = 0;
  2639. int pstate;
  2640. DEVRLOCK(cgpu, pstate);
  2641. if (cgpu->usbdev)
  2642. interface = cgpu->usbdev->found->intinfos[intinfo].ctrl_transfer;
  2643. DEVRUNLOCK(cgpu, pstate);
  2644. return interface;
  2645. }
  2646. enum sub_ident usb_ident(struct cgpu_info *cgpu)
  2647. {
  2648. enum sub_ident ident = IDENT_UNK;
  2649. int pstate;
  2650. DEVRLOCK(cgpu, pstate);
  2651. if (cgpu->usbdev)
  2652. ident = cgpu->usbdev->ident;
  2653. DEVRUNLOCK(cgpu, pstate);
  2654. return ident;
  2655. }
  2656. /*
  2657. * If you pass both intinfo and epinfo as <0 then it will set all
  2658. * endpoints to PrefPacketSize
  2659. * If intinfo >=0 but epinfo <0 then it will set all endpoints
  2660. * for the given one intinfo to PrefPacketSize
  2661. * If both are >=0 then it will set only the specified single
  2662. * endpoint (intinfo,epinfo) to PrefPacketSize
  2663. */
  2664. void _usb_set_pps(struct cgpu_info *cgpu, int intinfo, int epinfo, uint16_t PrefPacketSize)
  2665. {
  2666. struct usb_find_devices *found;
  2667. int pstate;
  2668. DEVWLOCK(cgpu, pstate);
  2669. if (cgpu->usbdev) {
  2670. found = cgpu->usbdev->found;
  2671. if (intinfo >= 0 && epinfo >= 0)
  2672. found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
  2673. else {
  2674. if (intinfo >= 0) {
  2675. for (epinfo = 0; epinfo < found->intinfos[intinfo].epinfo_count; epinfo++)
  2676. found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
  2677. } else {
  2678. for (intinfo = 0; intinfo < found->intinfo_count ; intinfo++)
  2679. for (epinfo = 0; epinfo < found->intinfos[intinfo].epinfo_count; epinfo++)
  2680. found->intinfos[intinfo].epinfos[epinfo].PrefPacketSize = PrefPacketSize;
  2681. }
  2682. }
  2683. }
  2684. DEVWUNLOCK(cgpu, pstate);
  2685. }
  2686. // Need to set all devices with matching usbdev
  2687. void usb_set_dev_start(struct cgpu_info *cgpu)
  2688. {
  2689. struct cg_usb_device *cgusb;
  2690. struct cgpu_info *cgpu2;
  2691. struct timeval now;
  2692. int pstate;
  2693. DEVWLOCK(cgpu, pstate);
  2694. cgusb = cgpu->usbdev;
  2695. // If the device wasn't dropped
  2696. if (cgusb != NULL) {
  2697. int i;
  2698. cgtime(&now);
  2699. for (i = 0; i < total_devices; i++) {
  2700. cgpu2 = get_devices(i);
  2701. if (cgpu2->usbdev == cgusb)
  2702. copy_time(&(cgpu2->dev_start_tv), &now);
  2703. }
  2704. }
  2705. DEVWUNLOCK(cgpu, pstate);
  2706. }
  2707. void usb_cleanup(void)
  2708. {
  2709. struct cgpu_info *cgpu;
  2710. int count, pstate;
  2711. int i;
  2712. hotplug_time = 0;
  2713. cgsleep_ms(10);
  2714. count = 0;
  2715. for (i = 0; i < total_devices; i++) {
  2716. cgpu = devices[i];
  2717. switch (cgpu->drv->drv_id) {
  2718. case DRIVER_bflsc:
  2719. case DRIVER_bitforce:
  2720. case DRIVER_bitfury:
  2721. case DRIVER_modminer:
  2722. case DRIVER_icarus:
  2723. case DRIVER_avalon:
  2724. case DRIVER_klondike:
  2725. DEVWLOCK(cgpu, pstate);
  2726. release_cgpu(cgpu);
  2727. DEVWUNLOCK(cgpu, pstate);
  2728. count++;
  2729. break;
  2730. default:
  2731. break;
  2732. }
  2733. }
  2734. /*
  2735. * Must attempt to wait for the resource thread to release coz
  2736. * during a restart it won't automatically release them in linux
  2737. */
  2738. if (count) {
  2739. struct timeval start, now;
  2740. cgtime(&start);
  2741. while (42) {
  2742. cgsleep_ms(50);
  2743. mutex_lock(&cgusbres_lock);
  2744. if (!res_work_head)
  2745. break;
  2746. cgtime(&now);
  2747. if (tdiff(&now, &start) > 0.366) {
  2748. applog(LOG_WARNING,
  2749. "usb_cleanup gave up waiting for resource thread");
  2750. break;
  2751. }
  2752. mutex_unlock(&cgusbres_lock);
  2753. }
  2754. mutex_unlock(&cgusbres_lock);
  2755. }
  2756. cgsem_destroy(&usb_resource_sem);
  2757. }
  2758. #define DRIVER_COUNT_FOUND(X) if (X##_drv.name && strcasecmp(ptr, X##_drv.name) == 0) { \
  2759. drv_count[X##_drv.drv_id].limit = lim; \
  2760. found = true; \
  2761. }
  2762. void usb_initialise(void)
  2763. {
  2764. char *fre, *ptr, *comma, *colon;
  2765. int bus, dev, lim, i;
  2766. bool found;
  2767. INIT_LIST_HEAD(&ct_list);
  2768. for (i = 0; i < DRIVER_MAX; i++) {
  2769. drv_count[i].count = 0;
  2770. drv_count[i].limit = 999999;
  2771. }
  2772. cgusb_check_init();
  2773. if (opt_usb_select && *opt_usb_select) {
  2774. // Absolute device limit
  2775. if (*opt_usb_select == ':') {
  2776. total_limit = atoi(opt_usb_select+1);
  2777. if (total_limit < 0)
  2778. quit(1, "Invalid --usb total limit");
  2779. // Comma list of bus:dev devices to match
  2780. } else if (isdigit(*opt_usb_select)) {
  2781. fre = ptr = strdup(opt_usb_select);
  2782. do {
  2783. comma = strchr(ptr, ',');
  2784. if (comma)
  2785. *(comma++) = '\0';
  2786. colon = strchr(ptr, ':');
  2787. if (!colon)
  2788. quit(1, "Invalid --usb bus:dev missing ':'");
  2789. *(colon++) = '\0';
  2790. if (!isdigit(*ptr))
  2791. quit(1, "Invalid --usb bus:dev - bus must be a number");
  2792. if (!isdigit(*colon) && *colon != '*')
  2793. quit(1, "Invalid --usb bus:dev - dev must be a number or '*'");
  2794. bus = atoi(ptr);
  2795. if (bus <= 0)
  2796. quit(1, "Invalid --usb bus:dev - bus must be > 0");
  2797. if (*colon == '*')
  2798. dev = -1;
  2799. else {
  2800. dev = atoi(colon);
  2801. if (dev <= 0)
  2802. quit(1, "Invalid --usb bus:dev - dev must be > 0 or '*'");
  2803. }
  2804. busdev = realloc(busdev, sizeof(*busdev) * (++busdev_count));
  2805. if (unlikely(!busdev))
  2806. quit(1, "USB failed to realloc busdev");
  2807. busdev[busdev_count-1].bus_number = bus;
  2808. busdev[busdev_count-1].device_address = dev;
  2809. ptr = comma;
  2810. } while (ptr);
  2811. free(fre);
  2812. // Comma list of DRV:limit
  2813. } else {
  2814. fre = ptr = strdup(opt_usb_select);
  2815. do {
  2816. comma = strchr(ptr, ',');
  2817. if (comma)
  2818. *(comma++) = '\0';
  2819. colon = strchr(ptr, ':');
  2820. if (!colon)
  2821. quit(1, "Invalid --usb DRV:limit missing ':'");
  2822. *(colon++) = '\0';
  2823. if (!isdigit(*colon))
  2824. quit(1, "Invalid --usb DRV:limit - limit must be a number");
  2825. lim = atoi(colon);
  2826. if (lim < 0)
  2827. quit(1, "Invalid --usb DRV:limit - limit must be >= 0");
  2828. found = false;
  2829. /* Use the DRIVER_PARSE_COMMANDS macro to iterate
  2830. * over all the drivers. */
  2831. DRIVER_PARSE_COMMANDS(DRIVER_COUNT_FOUND)
  2832. if (!found)
  2833. quit(1, "Invalid --usb DRV:limit - unknown DRV='%s'", ptr);
  2834. ptr = comma;
  2835. } while (ptr);
  2836. free(fre);
  2837. }
  2838. }
  2839. }
  2840. #ifndef WIN32
  2841. #include <errno.h>
  2842. #include <unistd.h>
  2843. #include <sys/types.h>
  2844. #include <sys/ipc.h>
  2845. #include <sys/sem.h>
  2846. #include <sys/stat.h>
  2847. #include <fcntl.h>
  2848. #ifndef __APPLE__
  2849. union semun {
  2850. int val;
  2851. struct semid_ds *buf;
  2852. unsigned short *array;
  2853. struct seminfo *__buf;
  2854. };
  2855. #endif
  2856. #else
  2857. static LPSECURITY_ATTRIBUTES unsec(LPSECURITY_ATTRIBUTES sec)
  2858. {
  2859. FreeSid(((PSECURITY_DESCRIPTOR)(sec->lpSecurityDescriptor))->Group);
  2860. free(sec->lpSecurityDescriptor);
  2861. free(sec);
  2862. return NULL;
  2863. }
  2864. static LPSECURITY_ATTRIBUTES mksec(const char *dname, uint8_t bus_number, uint8_t device_address)
  2865. {
  2866. SID_IDENTIFIER_AUTHORITY SIDAuthWorld = {SECURITY_WORLD_SID_AUTHORITY};
  2867. PSID gsid = NULL;
  2868. LPSECURITY_ATTRIBUTES sec_att = NULL;
  2869. PSECURITY_DESCRIPTOR sec_des = NULL;
  2870. sec_des = malloc(sizeof(*sec_des));
  2871. if (unlikely(!sec_des))
  2872. quit(1, "MTX: Failed to malloc LPSECURITY_DESCRIPTOR");
  2873. if (!InitializeSecurityDescriptor(sec_des, SECURITY_DESCRIPTOR_REVISION)) {
  2874. applog(LOG_ERR,
  2875. "MTX: %s (%d:%d) USB failed to init secdes err (%d)",
  2876. dname, (int)bus_number, (int)device_address,
  2877. (int)GetLastError());
  2878. free(sec_des);
  2879. return NULL;
  2880. }
  2881. if (!SetSecurityDescriptorDacl(sec_des, TRUE, NULL, FALSE)) {
  2882. applog(LOG_ERR,
  2883. "MTX: %s (%d:%d) USB failed to secdes dacl err (%d)",
  2884. dname, (int)bus_number, (int)device_address,
  2885. (int)GetLastError());
  2886. free(sec_des);
  2887. return NULL;
  2888. }
  2889. if(!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &gsid)) {
  2890. applog(LOG_ERR,
  2891. "MTX: %s (%d:%d) USB failed to create gsid err (%d)",
  2892. dname, (int)bus_number, (int)device_address,
  2893. (int)GetLastError());
  2894. free(sec_des);
  2895. return NULL;
  2896. }
  2897. if (!SetSecurityDescriptorGroup(sec_des, gsid, FALSE)) {
  2898. applog(LOG_ERR,
  2899. "MTX: %s (%d:%d) USB failed to secdes grp err (%d)",
  2900. dname, (int)bus_number, (int)device_address,
  2901. (int)GetLastError());
  2902. FreeSid(gsid);
  2903. free(sec_des);
  2904. return NULL;
  2905. }
  2906. sec_att = malloc(sizeof(*sec_att));
  2907. if (unlikely(!sec_att))
  2908. quit(1, "MTX: Failed to malloc LPSECURITY_ATTRIBUTES");
  2909. sec_att->nLength = sizeof(*sec_att);
  2910. sec_att->lpSecurityDescriptor = sec_des;
  2911. sec_att->bInheritHandle = FALSE;
  2912. return sec_att;
  2913. }
  2914. #endif
  2915. // Any errors should always be printed since they will rarely if ever occur
  2916. // and thus it is best to always display them
  2917. static bool resource_lock(const char *dname, uint8_t bus_number, uint8_t device_address)
  2918. {
  2919. applog(LOG_DEBUG, "USB res lock %s %d-%d", dname, (int)bus_number, (int)device_address);
  2920. #ifdef WIN32
  2921. struct cgpu_info *cgpu;
  2922. LPSECURITY_ATTRIBUTES sec;
  2923. HANDLE usbMutex;
  2924. char name[64];
  2925. DWORD res;
  2926. int i;
  2927. if (is_in_use_bd(bus_number, device_address))
  2928. return false;
  2929. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  2930. sec = mksec(dname, bus_number, device_address);
  2931. if (!sec)
  2932. return false;
  2933. usbMutex = CreateMutex(sec, FALSE, name);
  2934. if (usbMutex == NULL) {
  2935. applog(LOG_ERR,
  2936. "MTX: %s USB failed to get '%s' err (%d)",
  2937. dname, name, (int)GetLastError());
  2938. sec = unsec(sec);
  2939. return false;
  2940. }
  2941. res = WaitForSingleObject(usbMutex, 0);
  2942. switch(res) {
  2943. case WAIT_OBJECT_0:
  2944. case WAIT_ABANDONED:
  2945. // Am I using it already?
  2946. for (i = 0; i < total_devices; i++) {
  2947. cgpu = get_devices(i);
  2948. if (cgpu->usbinfo.bus_number == bus_number &&
  2949. cgpu->usbinfo.device_address == device_address &&
  2950. cgpu->usbinfo.nodev == false) {
  2951. if (ReleaseMutex(usbMutex)) {
  2952. applog(LOG_WARNING,
  2953. "MTX: %s USB can't get '%s' - device in use",
  2954. dname, name);
  2955. goto fail;
  2956. }
  2957. applog(LOG_ERR,
  2958. "MTX: %s USB can't get '%s' - device in use - failure (%d)",
  2959. dname, name, (int)GetLastError());
  2960. goto fail;
  2961. }
  2962. }
  2963. break;
  2964. case WAIT_TIMEOUT:
  2965. if (!hotplug_mode)
  2966. applog(LOG_WARNING,
  2967. "MTX: %s USB failed to get '%s' - device in use",
  2968. dname, name);
  2969. goto fail;
  2970. case WAIT_FAILED:
  2971. applog(LOG_ERR,
  2972. "MTX: %s USB failed to get '%s' err (%d)",
  2973. dname, name, (int)GetLastError());
  2974. goto fail;
  2975. default:
  2976. applog(LOG_ERR,
  2977. "MTX: %s USB failed to get '%s' unknown reply (%d)",
  2978. dname, name, (int)res);
  2979. goto fail;
  2980. }
  2981. add_in_use(bus_number, device_address);
  2982. in_use_store_ress(bus_number, device_address, (void *)usbMutex, (void *)sec);
  2983. return true;
  2984. fail:
  2985. CloseHandle(usbMutex);
  2986. sec = unsec(sec);
  2987. return false;
  2988. #else
  2989. struct semid_ds seminfo;
  2990. union semun opt;
  2991. char name[64];
  2992. key_t *key;
  2993. int *sem;
  2994. int fd, count;
  2995. if (is_in_use_bd(bus_number, device_address))
  2996. return false;
  2997. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  2998. fd = open(name, O_CREAT|O_RDONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
  2999. if (fd == -1) {
  3000. applog(LOG_ERR,
  3001. "SEM: %s USB open failed '%s' err (%d) %s",
  3002. dname, name, errno, strerror(errno));
  3003. goto _out;
  3004. }
  3005. close(fd);
  3006. key = malloc(sizeof(*key));
  3007. if (unlikely(!key))
  3008. quit(1, "SEM: Failed to malloc key");
  3009. sem = malloc(sizeof(*sem));
  3010. if (unlikely(!sem))
  3011. quit(1, "SEM: Failed to malloc sem");
  3012. *key = ftok(name, 'K');
  3013. *sem = semget(*key, 1, IPC_CREAT | IPC_EXCL | 438);
  3014. if (*sem < 0) {
  3015. if (errno != EEXIST) {
  3016. applog(LOG_ERR,
  3017. "SEM: %s USB failed to get '%s' err (%d) %s",
  3018. dname, name, errno, strerror(errno));
  3019. goto free_out;
  3020. }
  3021. *sem = semget(*key, 1, 0);
  3022. if (*sem < 0) {
  3023. applog(LOG_ERR,
  3024. "SEM: %s USB failed to access '%s' err (%d) %s",
  3025. dname, name, errno, strerror(errno));
  3026. goto free_out;
  3027. }
  3028. opt.buf = &seminfo;
  3029. count = 0;
  3030. while (++count) {
  3031. // Should NEVER take 100ms
  3032. if (count > 99) {
  3033. applog(LOG_ERR,
  3034. "SEM: %s USB timeout waiting for (%d) '%s'",
  3035. dname, *sem, name);
  3036. goto free_out;
  3037. }
  3038. if (semctl(*sem, 0, IPC_STAT, opt) == -1) {
  3039. applog(LOG_ERR,
  3040. "SEM: %s USB failed to wait for (%d) '%s' count %d err (%d) %s",
  3041. dname, *sem, name, count, errno, strerror(errno));
  3042. goto free_out;
  3043. }
  3044. if (opt.buf->sem_otime != 0)
  3045. break;
  3046. cgsleep_ms(1);
  3047. }
  3048. }
  3049. struct sembuf sops[] = {
  3050. { 0, 0, IPC_NOWAIT | SEM_UNDO },
  3051. { 0, 1, IPC_NOWAIT | SEM_UNDO }
  3052. };
  3053. if (semop(*sem, sops, 2)) {
  3054. if (errno == EAGAIN) {
  3055. if (!hotplug_mode)
  3056. applog(LOG_WARNING,
  3057. "SEM: %s USB failed to get (%d) '%s' - device in use",
  3058. dname, *sem, name);
  3059. } else {
  3060. applog(LOG_DEBUG,
  3061. "SEM: %s USB failed to get (%d) '%s' err (%d) %s",
  3062. dname, *sem, name, errno, strerror(errno));
  3063. }
  3064. goto free_out;
  3065. }
  3066. add_in_use(bus_number, device_address);
  3067. in_use_store_ress(bus_number, device_address, (void *)key, (void *)sem);
  3068. return true;
  3069. free_out:
  3070. free(sem);
  3071. free(key);
  3072. _out:
  3073. return false;
  3074. #endif
  3075. }
  3076. // Any errors should always be printed since they will rarely if ever occur
  3077. // and thus it is best to always display them
  3078. static void resource_unlock(const char *dname, uint8_t bus_number, uint8_t device_address)
  3079. {
  3080. applog(LOG_DEBUG, "USB res unlock %s %d-%d", dname, (int)bus_number, (int)device_address);
  3081. #ifdef WIN32
  3082. LPSECURITY_ATTRIBUTES sec = NULL;
  3083. HANDLE usbMutex = NULL;
  3084. char name[64];
  3085. snprintf(name, sizeof(name), "cg-usb-%d-%d", (int)bus_number, (int)device_address);
  3086. in_use_get_ress(bus_number, device_address, (void **)(&usbMutex), (void **)(&sec));
  3087. if (!usbMutex || !sec)
  3088. goto fila;
  3089. if (!ReleaseMutex(usbMutex))
  3090. applog(LOG_ERR,
  3091. "MTX: %s USB failed to release '%s' err (%d)",
  3092. dname, name, (int)GetLastError());
  3093. fila:
  3094. if (usbMutex)
  3095. CloseHandle(usbMutex);
  3096. if (sec)
  3097. unsec(sec);
  3098. remove_in_use(bus_number, device_address);
  3099. return;
  3100. #else
  3101. char name[64];
  3102. key_t *key = NULL;
  3103. int *sem = NULL;
  3104. snprintf(name, sizeof(name), "/tmp/cgminer-usb-%d-%d", (int)bus_number, (int)device_address);
  3105. in_use_get_ress(bus_number, device_address, (void **)(&key), (void **)(&sem));
  3106. if (!key || !sem)
  3107. goto fila;
  3108. struct sembuf sops[] = {
  3109. { 0, -1, SEM_UNDO }
  3110. };
  3111. // Allow a 10ms timeout
  3112. // exceeding this timeout means it would probably never succeed anyway
  3113. struct timespec timeout = { 0, 10000000 };
  3114. if (semtimedop(*sem, sops, 1, &timeout)) {
  3115. applog(LOG_ERR,
  3116. "SEM: %s USB failed to release '%s' err (%d) %s",
  3117. dname, name, errno, strerror(errno));
  3118. }
  3119. if (semctl(*sem, 0, IPC_RMID)) {
  3120. applog(LOG_WARNING,
  3121. "SEM: %s USB failed to remove SEM '%s' err (%d) %s",
  3122. dname, name, errno, strerror(errno));
  3123. }
  3124. fila:
  3125. free(sem);
  3126. free(key);
  3127. remove_in_use(bus_number, device_address);
  3128. return;
  3129. #endif
  3130. }
  3131. static void resource_process()
  3132. {
  3133. struct resource_work *res_work = NULL;
  3134. struct resource_reply *res_reply = NULL;
  3135. bool ok;
  3136. applog(LOG_DEBUG, "RES: %s (%d:%d) lock=%d",
  3137. res_work_head->dname,
  3138. (int)res_work_head->bus_number,
  3139. (int)res_work_head->device_address,
  3140. res_work_head->lock);
  3141. if (res_work_head->lock) {
  3142. ok = resource_lock(res_work_head->dname,
  3143. res_work_head->bus_number,
  3144. res_work_head->device_address);
  3145. applog(LOG_DEBUG, "RES: %s (%d:%d) lock ok=%d",
  3146. res_work_head->dname,
  3147. (int)res_work_head->bus_number,
  3148. (int)res_work_head->device_address,
  3149. ok);
  3150. res_reply = calloc(1, sizeof(*res_reply));
  3151. if (unlikely(!res_reply))
  3152. quit(1, "USB failed to calloc res_reply");
  3153. res_reply->bus_number = res_work_head->bus_number;
  3154. res_reply->device_address = res_work_head->device_address;
  3155. res_reply->got = ok;
  3156. res_reply->next = res_reply_head;
  3157. res_reply_head = res_reply;
  3158. }
  3159. else
  3160. resource_unlock(res_work_head->dname,
  3161. res_work_head->bus_number,
  3162. res_work_head->device_address);
  3163. res_work = res_work_head;
  3164. res_work_head = res_work_head->next;
  3165. free(res_work);
  3166. }
  3167. void *usb_resource_thread(void __maybe_unused *userdata)
  3168. {
  3169. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3170. RenameThread("usbresource");
  3171. applog(LOG_DEBUG, "RES: thread starting");
  3172. while (42) {
  3173. /* Wait to be told we have work to do */
  3174. cgsem_wait(&usb_resource_sem);
  3175. mutex_lock(&cgusbres_lock);
  3176. while (res_work_head)
  3177. resource_process();
  3178. mutex_unlock(&cgusbres_lock);
  3179. }
  3180. return NULL;
  3181. }