usbutils.c 93 KB

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