usbutils.c 92 KB

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