usbutils.c 97 KB

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