usbutils.c 96 KB

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