usbutils.c 95 KB

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