usbutils.c 98 KB

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