usbutils.c 98 KB

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