usbutils.c 96 KB

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