usbutils.c 93 KB

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