usbutils.c 104 KB

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