usbutils.c 96 KB

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