i915_perf.c 112 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508
  1. /*
  2. * Copyright © 2015-2016 Intel Corporation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice (including the next
  12. * paragraph) shall be included in all copies or substantial portions of the
  13. * Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  18. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21. * IN THE SOFTWARE.
  22. *
  23. * Authors:
  24. * Robert Bragg <robert@sixbynine.org>
  25. */
  26. /**
  27. * DOC: i915 Perf Overview
  28. *
  29. * Gen graphics supports a large number of performance counters that can help
  30. * driver and application developers understand and optimize their use of the
  31. * GPU.
  32. *
  33. * This i915 perf interface enables userspace to configure and open a file
  34. * descriptor representing a stream of GPU metrics which can then be read() as
  35. * a stream of sample records.
  36. *
  37. * The interface is particularly suited to exposing buffered metrics that are
  38. * captured by DMA from the GPU, unsynchronized with and unrelated to the CPU.
  39. *
  40. * Streams representing a single context are accessible to applications with a
  41. * corresponding drm file descriptor, such that OpenGL can use the interface
  42. * without special privileges. Access to system-wide metrics requires root
  43. * privileges by default, unless changed via the dev.i915.perf_event_paranoid
  44. * sysctl option.
  45. *
  46. */
  47. /**
  48. * DOC: i915 Perf History and Comparison with Core Perf
  49. *
  50. * The interface was initially inspired by the core Perf infrastructure but
  51. * some notable differences are:
  52. *
  53. * i915 perf file descriptors represent a "stream" instead of an "event"; where
  54. * a perf event primarily corresponds to a single 64bit value, while a stream
  55. * might sample sets of tightly-coupled counters, depending on the
  56. * configuration. For example the Gen OA unit isn't designed to support
  57. * orthogonal configurations of individual counters; it's configured for a set
  58. * of related counters. Samples for an i915 perf stream capturing OA metrics
  59. * will include a set of counter values packed in a compact HW specific format.
  60. * The OA unit supports a number of different packing formats which can be
  61. * selected by the user opening the stream. Perf has support for grouping
  62. * events, but each event in the group is configured, validated and
  63. * authenticated individually with separate system calls.
  64. *
  65. * i915 perf stream configurations are provided as an array of u64 (key,value)
  66. * pairs, instead of a fixed struct with multiple miscellaneous config members,
  67. * interleaved with event-type specific members.
  68. *
  69. * i915 perf doesn't support exposing metrics via an mmap'd circular buffer.
  70. * The supported metrics are being written to memory by the GPU unsynchronized
  71. * with the CPU, using HW specific packing formats for counter sets. Sometimes
  72. * the constraints on HW configuration require reports to be filtered before it
  73. * would be acceptable to expose them to unprivileged applications - to hide
  74. * the metrics of other processes/contexts. For these use cases a read() based
  75. * interface is a good fit, and provides an opportunity to filter data as it
  76. * gets copied from the GPU mapped buffers to userspace buffers.
  77. *
  78. *
  79. * Issues hit with first prototype based on Core Perf
  80. * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  81. *
  82. * The first prototype of this driver was based on the core perf
  83. * infrastructure, and while we did make that mostly work, with some changes to
  84. * perf, we found we were breaking or working around too many assumptions baked
  85. * into perf's currently cpu centric design.
  86. *
  87. * In the end we didn't see a clear benefit to making perf's implementation and
  88. * interface more complex by changing design assumptions while we knew we still
  89. * wouldn't be able to use any existing perf based userspace tools.
  90. *
  91. * Also considering the Gen specific nature of the Observability hardware and
  92. * how userspace will sometimes need to combine i915 perf OA metrics with
  93. * side-band OA data captured via MI_REPORT_PERF_COUNT commands; we're
  94. * expecting the interface to be used by a platform specific userspace such as
  95. * OpenGL or tools. This is to say; we aren't inherently missing out on having
  96. * a standard vendor/architecture agnostic interface by not using perf.
  97. *
  98. *
  99. * For posterity, in case we might re-visit trying to adapt core perf to be
  100. * better suited to exposing i915 metrics these were the main pain points we
  101. * hit:
  102. *
  103. * - The perf based OA PMU driver broke some significant design assumptions:
  104. *
  105. * Existing perf pmus are used for profiling work on a cpu and we were
  106. * introducing the idea of _IS_DEVICE pmus with different security
  107. * implications, the need to fake cpu-related data (such as user/kernel
  108. * registers) to fit with perf's current design, and adding _DEVICE records
  109. * as a way to forward device-specific status records.
  110. *
  111. * The OA unit writes reports of counters into a circular buffer, without
  112. * involvement from the CPU, making our PMU driver the first of a kind.
  113. *
  114. * Given the way we were periodically forward data from the GPU-mapped, OA
  115. * buffer to perf's buffer, those bursts of sample writes looked to perf like
  116. * we were sampling too fast and so we had to subvert its throttling checks.
  117. *
  118. * Perf supports groups of counters and allows those to be read via
  119. * transactions internally but transactions currently seem designed to be
  120. * explicitly initiated from the cpu (say in response to a userspace read())
  121. * and while we could pull a report out of the OA buffer we can't
  122. * trigger a report from the cpu on demand.
  123. *
  124. * Related to being report based; the OA counters are configured in HW as a
  125. * set while perf generally expects counter configurations to be orthogonal.
  126. * Although counters can be associated with a group leader as they are
  127. * opened, there's no clear precedent for being able to provide group-wide
  128. * configuration attributes (for example we want to let userspace choose the
  129. * OA unit report format used to capture all counters in a set, or specify a
  130. * GPU context to filter metrics on). We avoided using perf's grouping
  131. * feature and forwarded OA reports to userspace via perf's 'raw' sample
  132. * field. This suited our userspace well considering how coupled the counters
  133. * are when dealing with normalizing. It would be inconvenient to split
  134. * counters up into separate events, only to require userspace to recombine
  135. * them. For Mesa it's also convenient to be forwarded raw, periodic reports
  136. * for combining with the side-band raw reports it captures using
  137. * MI_REPORT_PERF_COUNT commands.
  138. *
  139. * - As a side note on perf's grouping feature; there was also some concern
  140. * that using PERF_FORMAT_GROUP as a way to pack together counter values
  141. * would quite drastically inflate our sample sizes, which would likely
  142. * lower the effective sampling resolutions we could use when the available
  143. * memory bandwidth is limited.
  144. *
  145. * With the OA unit's report formats, counters are packed together as 32
  146. * or 40bit values, with the largest report size being 256 bytes.
  147. *
  148. * PERF_FORMAT_GROUP values are 64bit, but there doesn't appear to be a
  149. * documented ordering to the values, implying PERF_FORMAT_ID must also be
  150. * used to add a 64bit ID before each value; giving 16 bytes per counter.
  151. *
  152. * Related to counter orthogonality; we can't time share the OA unit, while
  153. * event scheduling is a central design idea within perf for allowing
  154. * userspace to open + enable more events than can be configured in HW at any
  155. * one time. The OA unit is not designed to allow re-configuration while in
  156. * use. We can't reconfigure the OA unit without losing internal OA unit
  157. * state which we can't access explicitly to save and restore. Reconfiguring
  158. * the OA unit is also relatively slow, involving ~100 register writes. From
  159. * userspace Mesa also depends on a stable OA configuration when emitting
  160. * MI_REPORT_PERF_COUNT commands and importantly the OA unit can't be
  161. * disabled while there are outstanding MI_RPC commands lest we hang the
  162. * command streamer.
  163. *
  164. * The contents of sample records aren't extensible by device drivers (i.e.
  165. * the sample_type bits). As an example; Sourab Gupta had been looking to
  166. * attach GPU timestamps to our OA samples. We were shoehorning OA reports
  167. * into sample records by using the 'raw' field, but it's tricky to pack more
  168. * than one thing into this field because events/core.c currently only lets a
  169. * pmu give a single raw data pointer plus len which will be copied into the
  170. * ring buffer. To include more than the OA report we'd have to copy the
  171. * report into an intermediate larger buffer. I'd been considering allowing a
  172. * vector of data+len values to be specified for copying the raw data, but
  173. * it felt like a kludge to being using the raw field for this purpose.
  174. *
  175. * - It felt like our perf based PMU was making some technical compromises
  176. * just for the sake of using perf:
  177. *
  178. * perf_event_open() requires events to either relate to a pid or a specific
  179. * cpu core, while our device pmu related to neither. Events opened with a
  180. * pid will be automatically enabled/disabled according to the scheduling of
  181. * that process - so not appropriate for us. When an event is related to a
  182. * cpu id, perf ensures pmu methods will be invoked via an inter process
  183. * interrupt on that core. To avoid invasive changes our userspace opened OA
  184. * perf events for a specific cpu. This was workable but it meant the
  185. * majority of the OA driver ran in atomic context, including all OA report
  186. * forwarding, which wasn't really necessary in our case and seems to make
  187. * our locking requirements somewhat complex as we handled the interaction
  188. * with the rest of the i915 driver.
  189. */
  190. #include <linux/anon_inodes.h>
  191. #include <linux/sizes.h>
  192. #include <linux/uuid.h>
  193. #include "i915_drv.h"
  194. #include "i915_oa_hsw.h"
  195. #include "i915_oa_bdw.h"
  196. #include "i915_oa_chv.h"
  197. #include "i915_oa_sklgt2.h"
  198. #include "i915_oa_sklgt3.h"
  199. #include "i915_oa_sklgt4.h"
  200. #include "i915_oa_bxt.h"
  201. #include "i915_oa_kblgt2.h"
  202. #include "i915_oa_kblgt3.h"
  203. #include "i915_oa_glk.h"
  204. #include "i915_oa_cflgt2.h"
  205. #include "i915_oa_cflgt3.h"
  206. #include "i915_oa_cnl.h"
  207. #include "i915_oa_icl.h"
  208. #include "intel_lrc_reg.h"
  209. /* HW requires this to be a power of two, between 128k and 16M, though driver
  210. * is currently generally designed assuming the largest 16M size is used such
  211. * that the overflow cases are unlikely in normal operation.
  212. */
  213. #define OA_BUFFER_SIZE SZ_16M
  214. #define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
  215. /**
  216. * DOC: OA Tail Pointer Race
  217. *
  218. * There's a HW race condition between OA unit tail pointer register updates and
  219. * writes to memory whereby the tail pointer can sometimes get ahead of what's
  220. * been written out to the OA buffer so far (in terms of what's visible to the
  221. * CPU).
  222. *
  223. * Although this can be observed explicitly while copying reports to userspace
  224. * by checking for a zeroed report-id field in tail reports, we want to account
  225. * for this earlier, as part of the oa_buffer_check to avoid lots of redundant
  226. * read() attempts.
  227. *
  228. * In effect we define a tail pointer for reading that lags the real tail
  229. * pointer by at least %OA_TAIL_MARGIN_NSEC nanoseconds, which gives enough
  230. * time for the corresponding reports to become visible to the CPU.
  231. *
  232. * To manage this we actually track two tail pointers:
  233. * 1) An 'aging' tail with an associated timestamp that is tracked until we
  234. * can trust the corresponding data is visible to the CPU; at which point
  235. * it is considered 'aged'.
  236. * 2) An 'aged' tail that can be used for read()ing.
  237. *
  238. * The two separate pointers let us decouple read()s from tail pointer aging.
  239. *
  240. * The tail pointers are checked and updated at a limited rate within a hrtimer
  241. * callback (the same callback that is used for delivering EPOLLIN events)
  242. *
  243. * Initially the tails are marked invalid with %INVALID_TAIL_PTR which
  244. * indicates that an updated tail pointer is needed.
  245. *
  246. * Most of the implementation details for this workaround are in
  247. * oa_buffer_check_unlocked() and _append_oa_reports()
  248. *
  249. * Note for posterity: previously the driver used to define an effective tail
  250. * pointer that lagged the real pointer by a 'tail margin' measured in bytes
  251. * derived from %OA_TAIL_MARGIN_NSEC and the configured sampling frequency.
  252. * This was flawed considering that the OA unit may also automatically generate
  253. * non-periodic reports (such as on context switch) or the OA unit may be
  254. * enabled without any periodic sampling.
  255. */
  256. #define OA_TAIL_MARGIN_NSEC 100000ULL
  257. #define INVALID_TAIL_PTR 0xffffffff
  258. /* frequency for checking whether the OA unit has written new reports to the
  259. * circular OA buffer...
  260. */
  261. #define POLL_FREQUENCY 200
  262. #define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
  263. /* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
  264. static int zero;
  265. static int one = 1;
  266. static u32 i915_perf_stream_paranoid = true;
  267. /* The maximum exponent the hardware accepts is 63 (essentially it selects one
  268. * of the 64bit timestamp bits to trigger reports from) but there's currently
  269. * no known use case for sampling as infrequently as once per 47 thousand years.
  270. *
  271. * Since the timestamps included in OA reports are only 32bits it seems
  272. * reasonable to limit the OA exponent where it's still possible to account for
  273. * overflow in OA report timestamps.
  274. */
  275. #define OA_EXPONENT_MAX 31
  276. #define INVALID_CTX_ID 0xffffffff
  277. /* On Gen8+ automatically triggered OA reports include a 'reason' field... */
  278. #define OAREPORT_REASON_MASK 0x3f
  279. #define OAREPORT_REASON_SHIFT 19
  280. #define OAREPORT_REASON_TIMER (1<<0)
  281. #define OAREPORT_REASON_CTX_SWITCH (1<<3)
  282. #define OAREPORT_REASON_CLK_RATIO (1<<5)
  283. /* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
  284. *
  285. * The highest sampling frequency we can theoretically program the OA unit
  286. * with is always half the timestamp frequency: E.g. 6.25Mhz for Haswell.
  287. *
  288. * Initialized just before we register the sysctl parameter.
  289. */
  290. static int oa_sample_rate_hard_limit;
  291. /* Theoretically we can program the OA unit to sample every 160ns but don't
  292. * allow that by default unless root...
  293. *
  294. * The default threshold of 100000Hz is based on perf's similar
  295. * kernel.perf_event_max_sample_rate sysctl parameter.
  296. */
  297. static u32 i915_oa_max_sample_rate = 100000;
  298. /* XXX: beware if future OA HW adds new report formats that the current
  299. * code assumes all reports have a power-of-two size and ~(size - 1) can
  300. * be used as a mask to align the OA tail pointer.
  301. */
  302. static const struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
  303. [I915_OA_FORMAT_A13] = { 0, 64 },
  304. [I915_OA_FORMAT_A29] = { 1, 128 },
  305. [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
  306. /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
  307. [I915_OA_FORMAT_B4_C8] = { 4, 64 },
  308. [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
  309. [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
  310. [I915_OA_FORMAT_C4_B8] = { 7, 64 },
  311. };
  312. static const struct i915_oa_format gen8_plus_oa_formats[I915_OA_FORMAT_MAX] = {
  313. [I915_OA_FORMAT_A12] = { 0, 64 },
  314. [I915_OA_FORMAT_A12_B8_C8] = { 2, 128 },
  315. [I915_OA_FORMAT_A32u40_A4u32_B8_C8] = { 5, 256 },
  316. [I915_OA_FORMAT_C4_B8] = { 7, 64 },
  317. };
  318. #define SAMPLE_OA_REPORT (1<<0)
  319. /**
  320. * struct perf_open_properties - for validated properties given to open a stream
  321. * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
  322. * @single_context: Whether a single or all gpu contexts should be monitored
  323. * @ctx_handle: A gem ctx handle for use with @single_context
  324. * @metrics_set: An ID for an OA unit metric set advertised via sysfs
  325. * @oa_format: An OA unit HW report format
  326. * @oa_periodic: Whether to enable periodic OA unit sampling
  327. * @oa_period_exponent: The OA unit sampling period is derived from this
  328. *
  329. * As read_properties_unlocked() enumerates and validates the properties given
  330. * to open a stream of metrics the configuration is built up in the structure
  331. * which starts out zero initialized.
  332. */
  333. struct perf_open_properties {
  334. u32 sample_flags;
  335. u64 single_context:1;
  336. u64 ctx_handle;
  337. /* OA sampling state */
  338. int metrics_set;
  339. int oa_format;
  340. bool oa_periodic;
  341. int oa_period_exponent;
  342. };
  343. static void free_oa_config(struct drm_i915_private *dev_priv,
  344. struct i915_oa_config *oa_config)
  345. {
  346. if (!PTR_ERR(oa_config->flex_regs))
  347. kfree(oa_config->flex_regs);
  348. if (!PTR_ERR(oa_config->b_counter_regs))
  349. kfree(oa_config->b_counter_regs);
  350. if (!PTR_ERR(oa_config->mux_regs))
  351. kfree(oa_config->mux_regs);
  352. kfree(oa_config);
  353. }
  354. static void put_oa_config(struct drm_i915_private *dev_priv,
  355. struct i915_oa_config *oa_config)
  356. {
  357. if (!atomic_dec_and_test(&oa_config->ref_count))
  358. return;
  359. free_oa_config(dev_priv, oa_config);
  360. }
  361. static int get_oa_config(struct drm_i915_private *dev_priv,
  362. int metrics_set,
  363. struct i915_oa_config **out_config)
  364. {
  365. int ret;
  366. if (metrics_set == 1) {
  367. *out_config = &dev_priv->perf.oa.test_config;
  368. atomic_inc(&dev_priv->perf.oa.test_config.ref_count);
  369. return 0;
  370. }
  371. ret = mutex_lock_interruptible(&dev_priv->perf.metrics_lock);
  372. if (ret)
  373. return ret;
  374. *out_config = idr_find(&dev_priv->perf.metrics_idr, metrics_set);
  375. if (!*out_config)
  376. ret = -EINVAL;
  377. else
  378. atomic_inc(&(*out_config)->ref_count);
  379. mutex_unlock(&dev_priv->perf.metrics_lock);
  380. return ret;
  381. }
  382. static u32 gen8_oa_hw_tail_read(struct drm_i915_private *dev_priv)
  383. {
  384. return I915_READ(GEN8_OATAILPTR) & GEN8_OATAILPTR_MASK;
  385. }
  386. static u32 gen7_oa_hw_tail_read(struct drm_i915_private *dev_priv)
  387. {
  388. u32 oastatus1 = I915_READ(GEN7_OASTATUS1);
  389. return oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
  390. }
  391. /**
  392. * oa_buffer_check_unlocked - check for data and update tail ptr state
  393. * @dev_priv: i915 device instance
  394. *
  395. * This is either called via fops (for blocking reads in user ctx) or the poll
  396. * check hrtimer (atomic ctx) to check the OA buffer tail pointer and check
  397. * if there is data available for userspace to read.
  398. *
  399. * This function is central to providing a workaround for the OA unit tail
  400. * pointer having a race with respect to what data is visible to the CPU.
  401. * It is responsible for reading tail pointers from the hardware and giving
  402. * the pointers time to 'age' before they are made available for reading.
  403. * (See description of OA_TAIL_MARGIN_NSEC above for further details.)
  404. *
  405. * Besides returning true when there is data available to read() this function
  406. * also has the side effect of updating the oa_buffer.tails[], .aging_timestamp
  407. * and .aged_tail_idx state used for reading.
  408. *
  409. * Note: It's safe to read OA config state here unlocked, assuming that this is
  410. * only called while the stream is enabled, while the global OA configuration
  411. * can't be modified.
  412. *
  413. * Returns: %true if the OA buffer contains data, else %false
  414. */
  415. static bool oa_buffer_check_unlocked(struct drm_i915_private *dev_priv)
  416. {
  417. int report_size = dev_priv->perf.oa.oa_buffer.format_size;
  418. unsigned long flags;
  419. unsigned int aged_idx;
  420. u32 head, hw_tail, aged_tail, aging_tail;
  421. u64 now;
  422. /* We have to consider the (unlikely) possibility that read() errors
  423. * could result in an OA buffer reset which might reset the head,
  424. * tails[] and aged_tail state.
  425. */
  426. spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  427. /* NB: The head we observe here might effectively be a little out of
  428. * date (between head and tails[aged_idx].offset if there is currently
  429. * a read() in progress.
  430. */
  431. head = dev_priv->perf.oa.oa_buffer.head;
  432. aged_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
  433. aged_tail = dev_priv->perf.oa.oa_buffer.tails[aged_idx].offset;
  434. aging_tail = dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset;
  435. hw_tail = dev_priv->perf.oa.ops.oa_hw_tail_read(dev_priv);
  436. /* The tail pointer increases in 64 byte increments,
  437. * not in report_size steps...
  438. */
  439. hw_tail &= ~(report_size - 1);
  440. now = ktime_get_mono_fast_ns();
  441. /* Update the aged tail
  442. *
  443. * Flip the tail pointer available for read()s once the aging tail is
  444. * old enough to trust that the corresponding data will be visible to
  445. * the CPU...
  446. *
  447. * Do this before updating the aging pointer in case we may be able to
  448. * immediately start aging a new pointer too (if new data has become
  449. * available) without needing to wait for a later hrtimer callback.
  450. */
  451. if (aging_tail != INVALID_TAIL_PTR &&
  452. ((now - dev_priv->perf.oa.oa_buffer.aging_timestamp) >
  453. OA_TAIL_MARGIN_NSEC)) {
  454. aged_idx ^= 1;
  455. dev_priv->perf.oa.oa_buffer.aged_tail_idx = aged_idx;
  456. aged_tail = aging_tail;
  457. /* Mark that we need a new pointer to start aging... */
  458. dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset = INVALID_TAIL_PTR;
  459. aging_tail = INVALID_TAIL_PTR;
  460. }
  461. /* Update the aging tail
  462. *
  463. * We throttle aging tail updates until we have a new tail that
  464. * represents >= one report more data than is already available for
  465. * reading. This ensures there will be enough data for a successful
  466. * read once this new pointer has aged and ensures we will give the new
  467. * pointer time to age.
  468. */
  469. if (aging_tail == INVALID_TAIL_PTR &&
  470. (aged_tail == INVALID_TAIL_PTR ||
  471. OA_TAKEN(hw_tail, aged_tail) >= report_size)) {
  472. struct i915_vma *vma = dev_priv->perf.oa.oa_buffer.vma;
  473. u32 gtt_offset = i915_ggtt_offset(vma);
  474. /* Be paranoid and do a bounds check on the pointer read back
  475. * from hardware, just in case some spurious hardware condition
  476. * could put the tail out of bounds...
  477. */
  478. if (hw_tail >= gtt_offset &&
  479. hw_tail < (gtt_offset + OA_BUFFER_SIZE)) {
  480. dev_priv->perf.oa.oa_buffer.tails[!aged_idx].offset =
  481. aging_tail = hw_tail;
  482. dev_priv->perf.oa.oa_buffer.aging_timestamp = now;
  483. } else {
  484. DRM_ERROR("Ignoring spurious out of range OA buffer tail pointer = %u\n",
  485. hw_tail);
  486. }
  487. }
  488. spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  489. return aged_tail == INVALID_TAIL_PTR ?
  490. false : OA_TAKEN(aged_tail, head) >= report_size;
  491. }
  492. /**
  493. * append_oa_status - Appends a status record to a userspace read() buffer.
  494. * @stream: An i915-perf stream opened for OA metrics
  495. * @buf: destination buffer given by userspace
  496. * @count: the number of bytes userspace wants to read
  497. * @offset: (inout): the current position for writing into @buf
  498. * @type: The kind of status to report to userspace
  499. *
  500. * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
  501. * into the userspace read() buffer.
  502. *
  503. * The @buf @offset will only be updated on success.
  504. *
  505. * Returns: 0 on success, negative error code on failure.
  506. */
  507. static int append_oa_status(struct i915_perf_stream *stream,
  508. char __user *buf,
  509. size_t count,
  510. size_t *offset,
  511. enum drm_i915_perf_record_type type)
  512. {
  513. struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
  514. if ((count - *offset) < header.size)
  515. return -ENOSPC;
  516. if (copy_to_user(buf + *offset, &header, sizeof(header)))
  517. return -EFAULT;
  518. (*offset) += header.size;
  519. return 0;
  520. }
  521. /**
  522. * append_oa_sample - Copies single OA report into userspace read() buffer.
  523. * @stream: An i915-perf stream opened for OA metrics
  524. * @buf: destination buffer given by userspace
  525. * @count: the number of bytes userspace wants to read
  526. * @offset: (inout): the current position for writing into @buf
  527. * @report: A single OA report to (optionally) include as part of the sample
  528. *
  529. * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
  530. * properties when opening a stream, tracked as `stream->sample_flags`. This
  531. * function copies the requested components of a single sample to the given
  532. * read() @buf.
  533. *
  534. * The @buf @offset will only be updated on success.
  535. *
  536. * Returns: 0 on success, negative error code on failure.
  537. */
  538. static int append_oa_sample(struct i915_perf_stream *stream,
  539. char __user *buf,
  540. size_t count,
  541. size_t *offset,
  542. const u8 *report)
  543. {
  544. struct drm_i915_private *dev_priv = stream->dev_priv;
  545. int report_size = dev_priv->perf.oa.oa_buffer.format_size;
  546. struct drm_i915_perf_record_header header;
  547. u32 sample_flags = stream->sample_flags;
  548. header.type = DRM_I915_PERF_RECORD_SAMPLE;
  549. header.pad = 0;
  550. header.size = stream->sample_size;
  551. if ((count - *offset) < header.size)
  552. return -ENOSPC;
  553. buf += *offset;
  554. if (copy_to_user(buf, &header, sizeof(header)))
  555. return -EFAULT;
  556. buf += sizeof(header);
  557. if (sample_flags & SAMPLE_OA_REPORT) {
  558. if (copy_to_user(buf, report, report_size))
  559. return -EFAULT;
  560. }
  561. (*offset) += header.size;
  562. return 0;
  563. }
  564. /**
  565. * Copies all buffered OA reports into userspace read() buffer.
  566. * @stream: An i915-perf stream opened for OA metrics
  567. * @buf: destination buffer given by userspace
  568. * @count: the number of bytes userspace wants to read
  569. * @offset: (inout): the current position for writing into @buf
  570. *
  571. * Notably any error condition resulting in a short read (-%ENOSPC or
  572. * -%EFAULT) will be returned even though one or more records may
  573. * have been successfully copied. In this case it's up to the caller
  574. * to decide if the error should be squashed before returning to
  575. * userspace.
  576. *
  577. * Note: reports are consumed from the head, and appended to the
  578. * tail, so the tail chases the head?... If you think that's mad
  579. * and back-to-front you're not alone, but this follows the
  580. * Gen PRM naming convention.
  581. *
  582. * Returns: 0 on success, negative error code on failure.
  583. */
  584. static int gen8_append_oa_reports(struct i915_perf_stream *stream,
  585. char __user *buf,
  586. size_t count,
  587. size_t *offset)
  588. {
  589. struct drm_i915_private *dev_priv = stream->dev_priv;
  590. int report_size = dev_priv->perf.oa.oa_buffer.format_size;
  591. u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
  592. u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
  593. u32 mask = (OA_BUFFER_SIZE - 1);
  594. size_t start_offset = *offset;
  595. unsigned long flags;
  596. unsigned int aged_tail_idx;
  597. u32 head, tail;
  598. u32 taken;
  599. int ret = 0;
  600. if (WARN_ON(!stream->enabled))
  601. return -EIO;
  602. spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  603. head = dev_priv->perf.oa.oa_buffer.head;
  604. aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
  605. tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
  606. spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  607. /*
  608. * An invalid tail pointer here means we're still waiting for the poll
  609. * hrtimer callback to give us a pointer
  610. */
  611. if (tail == INVALID_TAIL_PTR)
  612. return -EAGAIN;
  613. /*
  614. * NB: oa_buffer.head/tail include the gtt_offset which we don't want
  615. * while indexing relative to oa_buf_base.
  616. */
  617. head -= gtt_offset;
  618. tail -= gtt_offset;
  619. /*
  620. * An out of bounds or misaligned head or tail pointer implies a driver
  621. * bug since we validate + align the tail pointers we read from the
  622. * hardware and we are in full control of the head pointer which should
  623. * only be incremented by multiples of the report size (notably also
  624. * all a power of two).
  625. */
  626. if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
  627. tail > OA_BUFFER_SIZE || tail % report_size,
  628. "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
  629. head, tail))
  630. return -EIO;
  631. for (/* none */;
  632. (taken = OA_TAKEN(tail, head));
  633. head = (head + report_size) & mask) {
  634. u8 *report = oa_buf_base + head;
  635. u32 *report32 = (void *)report;
  636. u32 ctx_id;
  637. u32 reason;
  638. /*
  639. * All the report sizes factor neatly into the buffer
  640. * size so we never expect to see a report split
  641. * between the beginning and end of the buffer.
  642. *
  643. * Given the initial alignment check a misalignment
  644. * here would imply a driver bug that would result
  645. * in an overrun.
  646. */
  647. if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
  648. DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
  649. break;
  650. }
  651. /*
  652. * The reason field includes flags identifying what
  653. * triggered this specific report (mostly timer
  654. * triggered or e.g. due to a context switch).
  655. *
  656. * This field is never expected to be zero so we can
  657. * check that the report isn't invalid before copying
  658. * it to userspace...
  659. */
  660. reason = ((report32[0] >> OAREPORT_REASON_SHIFT) &
  661. OAREPORT_REASON_MASK);
  662. if (reason == 0) {
  663. if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
  664. DRM_NOTE("Skipping spurious, invalid OA report\n");
  665. continue;
  666. }
  667. ctx_id = report32[2] & dev_priv->perf.oa.specific_ctx_id_mask;
  668. /*
  669. * Squash whatever is in the CTX_ID field if it's marked as
  670. * invalid to be sure we avoid false-positive, single-context
  671. * filtering below...
  672. *
  673. * Note: that we don't clear the valid_ctx_bit so userspace can
  674. * understand that the ID has been squashed by the kernel.
  675. */
  676. if (!(report32[0] & dev_priv->perf.oa.gen8_valid_ctx_bit))
  677. ctx_id = report32[2] = INVALID_CTX_ID;
  678. /*
  679. * NB: For Gen 8 the OA unit no longer supports clock gating
  680. * off for a specific context and the kernel can't securely
  681. * stop the counters from updating as system-wide / global
  682. * values.
  683. *
  684. * Automatic reports now include a context ID so reports can be
  685. * filtered on the cpu but it's not worth trying to
  686. * automatically subtract/hide counter progress for other
  687. * contexts while filtering since we can't stop userspace
  688. * issuing MI_REPORT_PERF_COUNT commands which would still
  689. * provide a side-band view of the real values.
  690. *
  691. * To allow userspace (such as Mesa/GL_INTEL_performance_query)
  692. * to normalize counters for a single filtered context then it
  693. * needs be forwarded bookend context-switch reports so that it
  694. * can track switches in between MI_REPORT_PERF_COUNT commands
  695. * and can itself subtract/ignore the progress of counters
  696. * associated with other contexts. Note that the hardware
  697. * automatically triggers reports when switching to a new
  698. * context which are tagged with the ID of the newly active
  699. * context. To avoid the complexity (and likely fragility) of
  700. * reading ahead while parsing reports to try and minimize
  701. * forwarding redundant context switch reports (i.e. between
  702. * other, unrelated contexts) we simply elect to forward them
  703. * all.
  704. *
  705. * We don't rely solely on the reason field to identify context
  706. * switches since it's not-uncommon for periodic samples to
  707. * identify a switch before any 'context switch' report.
  708. */
  709. if (!dev_priv->perf.oa.exclusive_stream->ctx ||
  710. dev_priv->perf.oa.specific_ctx_id == ctx_id ||
  711. (dev_priv->perf.oa.oa_buffer.last_ctx_id ==
  712. dev_priv->perf.oa.specific_ctx_id) ||
  713. reason & OAREPORT_REASON_CTX_SWITCH) {
  714. /*
  715. * While filtering for a single context we avoid
  716. * leaking the IDs of other contexts.
  717. */
  718. if (dev_priv->perf.oa.exclusive_stream->ctx &&
  719. dev_priv->perf.oa.specific_ctx_id != ctx_id) {
  720. report32[2] = INVALID_CTX_ID;
  721. }
  722. ret = append_oa_sample(stream, buf, count, offset,
  723. report);
  724. if (ret)
  725. break;
  726. dev_priv->perf.oa.oa_buffer.last_ctx_id = ctx_id;
  727. }
  728. /*
  729. * The above reason field sanity check is based on
  730. * the assumption that the OA buffer is initially
  731. * zeroed and we reset the field after copying so the
  732. * check is still meaningful once old reports start
  733. * being overwritten.
  734. */
  735. report32[0] = 0;
  736. }
  737. if (start_offset != *offset) {
  738. spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  739. /*
  740. * We removed the gtt_offset for the copy loop above, indexing
  741. * relative to oa_buf_base so put back here...
  742. */
  743. head += gtt_offset;
  744. I915_WRITE(GEN8_OAHEADPTR, head & GEN8_OAHEADPTR_MASK);
  745. dev_priv->perf.oa.oa_buffer.head = head;
  746. spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  747. }
  748. return ret;
  749. }
  750. /**
  751. * gen8_oa_read - copy status records then buffered OA reports
  752. * @stream: An i915-perf stream opened for OA metrics
  753. * @buf: destination buffer given by userspace
  754. * @count: the number of bytes userspace wants to read
  755. * @offset: (inout): the current position for writing into @buf
  756. *
  757. * Checks OA unit status registers and if necessary appends corresponding
  758. * status records for userspace (such as for a buffer full condition) and then
  759. * initiate appending any buffered OA reports.
  760. *
  761. * Updates @offset according to the number of bytes successfully copied into
  762. * the userspace buffer.
  763. *
  764. * NB: some data may be successfully copied to the userspace buffer
  765. * even if an error is returned, and this is reflected in the
  766. * updated @offset.
  767. *
  768. * Returns: zero on success or a negative error code
  769. */
  770. static int gen8_oa_read(struct i915_perf_stream *stream,
  771. char __user *buf,
  772. size_t count,
  773. size_t *offset)
  774. {
  775. struct drm_i915_private *dev_priv = stream->dev_priv;
  776. u32 oastatus;
  777. int ret;
  778. if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
  779. return -EIO;
  780. oastatus = I915_READ(GEN8_OASTATUS);
  781. /*
  782. * We treat OABUFFER_OVERFLOW as a significant error:
  783. *
  784. * Although theoretically we could handle this more gracefully
  785. * sometimes, some Gens don't correctly suppress certain
  786. * automatically triggered reports in this condition and so we
  787. * have to assume that old reports are now being trampled
  788. * over.
  789. *
  790. * Considering how we don't currently give userspace control
  791. * over the OA buffer size and always configure a large 16MB
  792. * buffer, then a buffer overflow does anyway likely indicate
  793. * that something has gone quite badly wrong.
  794. */
  795. if (oastatus & GEN8_OASTATUS_OABUFFER_OVERFLOW) {
  796. ret = append_oa_status(stream, buf, count, offset,
  797. DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
  798. if (ret)
  799. return ret;
  800. DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
  801. dev_priv->perf.oa.period_exponent);
  802. dev_priv->perf.oa.ops.oa_disable(dev_priv);
  803. dev_priv->perf.oa.ops.oa_enable(dev_priv);
  804. /*
  805. * Note: .oa_enable() is expected to re-init the oabuffer and
  806. * reset GEN8_OASTATUS for us
  807. */
  808. oastatus = I915_READ(GEN8_OASTATUS);
  809. }
  810. if (oastatus & GEN8_OASTATUS_REPORT_LOST) {
  811. ret = append_oa_status(stream, buf, count, offset,
  812. DRM_I915_PERF_RECORD_OA_REPORT_LOST);
  813. if (ret)
  814. return ret;
  815. I915_WRITE(GEN8_OASTATUS,
  816. oastatus & ~GEN8_OASTATUS_REPORT_LOST);
  817. }
  818. return gen8_append_oa_reports(stream, buf, count, offset);
  819. }
  820. /**
  821. * Copies all buffered OA reports into userspace read() buffer.
  822. * @stream: An i915-perf stream opened for OA metrics
  823. * @buf: destination buffer given by userspace
  824. * @count: the number of bytes userspace wants to read
  825. * @offset: (inout): the current position for writing into @buf
  826. *
  827. * Notably any error condition resulting in a short read (-%ENOSPC or
  828. * -%EFAULT) will be returned even though one or more records may
  829. * have been successfully copied. In this case it's up to the caller
  830. * to decide if the error should be squashed before returning to
  831. * userspace.
  832. *
  833. * Note: reports are consumed from the head, and appended to the
  834. * tail, so the tail chases the head?... If you think that's mad
  835. * and back-to-front you're not alone, but this follows the
  836. * Gen PRM naming convention.
  837. *
  838. * Returns: 0 on success, negative error code on failure.
  839. */
  840. static int gen7_append_oa_reports(struct i915_perf_stream *stream,
  841. char __user *buf,
  842. size_t count,
  843. size_t *offset)
  844. {
  845. struct drm_i915_private *dev_priv = stream->dev_priv;
  846. int report_size = dev_priv->perf.oa.oa_buffer.format_size;
  847. u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
  848. u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
  849. u32 mask = (OA_BUFFER_SIZE - 1);
  850. size_t start_offset = *offset;
  851. unsigned long flags;
  852. unsigned int aged_tail_idx;
  853. u32 head, tail;
  854. u32 taken;
  855. int ret = 0;
  856. if (WARN_ON(!stream->enabled))
  857. return -EIO;
  858. spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  859. head = dev_priv->perf.oa.oa_buffer.head;
  860. aged_tail_idx = dev_priv->perf.oa.oa_buffer.aged_tail_idx;
  861. tail = dev_priv->perf.oa.oa_buffer.tails[aged_tail_idx].offset;
  862. spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  863. /* An invalid tail pointer here means we're still waiting for the poll
  864. * hrtimer callback to give us a pointer
  865. */
  866. if (tail == INVALID_TAIL_PTR)
  867. return -EAGAIN;
  868. /* NB: oa_buffer.head/tail include the gtt_offset which we don't want
  869. * while indexing relative to oa_buf_base.
  870. */
  871. head -= gtt_offset;
  872. tail -= gtt_offset;
  873. /* An out of bounds or misaligned head or tail pointer implies a driver
  874. * bug since we validate + align the tail pointers we read from the
  875. * hardware and we are in full control of the head pointer which should
  876. * only be incremented by multiples of the report size (notably also
  877. * all a power of two).
  878. */
  879. if (WARN_ONCE(head > OA_BUFFER_SIZE || head % report_size ||
  880. tail > OA_BUFFER_SIZE || tail % report_size,
  881. "Inconsistent OA buffer pointers: head = %u, tail = %u\n",
  882. head, tail))
  883. return -EIO;
  884. for (/* none */;
  885. (taken = OA_TAKEN(tail, head));
  886. head = (head + report_size) & mask) {
  887. u8 *report = oa_buf_base + head;
  888. u32 *report32 = (void *)report;
  889. /* All the report sizes factor neatly into the buffer
  890. * size so we never expect to see a report split
  891. * between the beginning and end of the buffer.
  892. *
  893. * Given the initial alignment check a misalignment
  894. * here would imply a driver bug that would result
  895. * in an overrun.
  896. */
  897. if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
  898. DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
  899. break;
  900. }
  901. /* The report-ID field for periodic samples includes
  902. * some undocumented flags related to what triggered
  903. * the report and is never expected to be zero so we
  904. * can check that the report isn't invalid before
  905. * copying it to userspace...
  906. */
  907. if (report32[0] == 0) {
  908. if (__ratelimit(&dev_priv->perf.oa.spurious_report_rs))
  909. DRM_NOTE("Skipping spurious, invalid OA report\n");
  910. continue;
  911. }
  912. ret = append_oa_sample(stream, buf, count, offset, report);
  913. if (ret)
  914. break;
  915. /* The above report-id field sanity check is based on
  916. * the assumption that the OA buffer is initially
  917. * zeroed and we reset the field after copying so the
  918. * check is still meaningful once old reports start
  919. * being overwritten.
  920. */
  921. report32[0] = 0;
  922. }
  923. if (start_offset != *offset) {
  924. spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  925. /* We removed the gtt_offset for the copy loop above, indexing
  926. * relative to oa_buf_base so put back here...
  927. */
  928. head += gtt_offset;
  929. I915_WRITE(GEN7_OASTATUS2,
  930. ((head & GEN7_OASTATUS2_HEAD_MASK) |
  931. GEN7_OASTATUS2_MEM_SELECT_GGTT));
  932. dev_priv->perf.oa.oa_buffer.head = head;
  933. spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  934. }
  935. return ret;
  936. }
  937. /**
  938. * gen7_oa_read - copy status records then buffered OA reports
  939. * @stream: An i915-perf stream opened for OA metrics
  940. * @buf: destination buffer given by userspace
  941. * @count: the number of bytes userspace wants to read
  942. * @offset: (inout): the current position for writing into @buf
  943. *
  944. * Checks Gen 7 specific OA unit status registers and if necessary appends
  945. * corresponding status records for userspace (such as for a buffer full
  946. * condition) and then initiate appending any buffered OA reports.
  947. *
  948. * Updates @offset according to the number of bytes successfully copied into
  949. * the userspace buffer.
  950. *
  951. * Returns: zero on success or a negative error code
  952. */
  953. static int gen7_oa_read(struct i915_perf_stream *stream,
  954. char __user *buf,
  955. size_t count,
  956. size_t *offset)
  957. {
  958. struct drm_i915_private *dev_priv = stream->dev_priv;
  959. u32 oastatus1;
  960. int ret;
  961. if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
  962. return -EIO;
  963. oastatus1 = I915_READ(GEN7_OASTATUS1);
  964. /* XXX: On Haswell we don't have a safe way to clear oastatus1
  965. * bits while the OA unit is enabled (while the tail pointer
  966. * may be updated asynchronously) so we ignore status bits
  967. * that have already been reported to userspace.
  968. */
  969. oastatus1 &= ~dev_priv->perf.oa.gen7_latched_oastatus1;
  970. /* We treat OABUFFER_OVERFLOW as a significant error:
  971. *
  972. * - The status can be interpreted to mean that the buffer is
  973. * currently full (with a higher precedence than OA_TAKEN()
  974. * which will start to report a near-empty buffer after an
  975. * overflow) but it's awkward that we can't clear the status
  976. * on Haswell, so without a reset we won't be able to catch
  977. * the state again.
  978. *
  979. * - Since it also implies the HW has started overwriting old
  980. * reports it may also affect our sanity checks for invalid
  981. * reports when copying to userspace that assume new reports
  982. * are being written to cleared memory.
  983. *
  984. * - In the future we may want to introduce a flight recorder
  985. * mode where the driver will automatically maintain a safe
  986. * guard band between head/tail, avoiding this overflow
  987. * condition, but we avoid the added driver complexity for
  988. * now.
  989. */
  990. if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
  991. ret = append_oa_status(stream, buf, count, offset,
  992. DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
  993. if (ret)
  994. return ret;
  995. DRM_DEBUG("OA buffer overflow (exponent = %d): force restart\n",
  996. dev_priv->perf.oa.period_exponent);
  997. dev_priv->perf.oa.ops.oa_disable(dev_priv);
  998. dev_priv->perf.oa.ops.oa_enable(dev_priv);
  999. oastatus1 = I915_READ(GEN7_OASTATUS1);
  1000. }
  1001. if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
  1002. ret = append_oa_status(stream, buf, count, offset,
  1003. DRM_I915_PERF_RECORD_OA_REPORT_LOST);
  1004. if (ret)
  1005. return ret;
  1006. dev_priv->perf.oa.gen7_latched_oastatus1 |=
  1007. GEN7_OASTATUS1_REPORT_LOST;
  1008. }
  1009. return gen7_append_oa_reports(stream, buf, count, offset);
  1010. }
  1011. /**
  1012. * i915_oa_wait_unlocked - handles blocking IO until OA data available
  1013. * @stream: An i915-perf stream opened for OA metrics
  1014. *
  1015. * Called when userspace tries to read() from a blocking stream FD opened
  1016. * for OA metrics. It waits until the hrtimer callback finds a non-empty
  1017. * OA buffer and wakes us.
  1018. *
  1019. * Note: it's acceptable to have this return with some false positives
  1020. * since any subsequent read handling will return -EAGAIN if there isn't
  1021. * really data ready for userspace yet.
  1022. *
  1023. * Returns: zero on success or a negative error code
  1024. */
  1025. static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
  1026. {
  1027. struct drm_i915_private *dev_priv = stream->dev_priv;
  1028. /* We would wait indefinitely if periodic sampling is not enabled */
  1029. if (!dev_priv->perf.oa.periodic)
  1030. return -EIO;
  1031. return wait_event_interruptible(dev_priv->perf.oa.poll_wq,
  1032. oa_buffer_check_unlocked(dev_priv));
  1033. }
  1034. /**
  1035. * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
  1036. * @stream: An i915-perf stream opened for OA metrics
  1037. * @file: An i915 perf stream file
  1038. * @wait: poll() state table
  1039. *
  1040. * For handling userspace polling on an i915 perf stream opened for OA metrics,
  1041. * this starts a poll_wait with the wait queue that our hrtimer callback wakes
  1042. * when it sees data ready to read in the circular OA buffer.
  1043. */
  1044. static void i915_oa_poll_wait(struct i915_perf_stream *stream,
  1045. struct file *file,
  1046. poll_table *wait)
  1047. {
  1048. struct drm_i915_private *dev_priv = stream->dev_priv;
  1049. poll_wait(file, &dev_priv->perf.oa.poll_wq, wait);
  1050. }
  1051. /**
  1052. * i915_oa_read - just calls through to &i915_oa_ops->read
  1053. * @stream: An i915-perf stream opened for OA metrics
  1054. * @buf: destination buffer given by userspace
  1055. * @count: the number of bytes userspace wants to read
  1056. * @offset: (inout): the current position for writing into @buf
  1057. *
  1058. * Updates @offset according to the number of bytes successfully copied into
  1059. * the userspace buffer.
  1060. *
  1061. * Returns: zero on success or a negative error code
  1062. */
  1063. static int i915_oa_read(struct i915_perf_stream *stream,
  1064. char __user *buf,
  1065. size_t count,
  1066. size_t *offset)
  1067. {
  1068. struct drm_i915_private *dev_priv = stream->dev_priv;
  1069. return dev_priv->perf.oa.ops.read(stream, buf, count, offset);
  1070. }
  1071. static struct intel_context *oa_pin_context(struct drm_i915_private *i915,
  1072. struct i915_gem_context *ctx)
  1073. {
  1074. struct intel_engine_cs *engine = i915->engine[RCS];
  1075. struct intel_context *ce;
  1076. int ret;
  1077. ret = i915_mutex_lock_interruptible(&i915->drm);
  1078. if (ret)
  1079. return ERR_PTR(ret);
  1080. /*
  1081. * As the ID is the gtt offset of the context's vma we
  1082. * pin the vma to ensure the ID remains fixed.
  1083. *
  1084. * NB: implied RCS engine...
  1085. */
  1086. ce = intel_context_pin(ctx, engine);
  1087. mutex_unlock(&i915->drm.struct_mutex);
  1088. if (IS_ERR(ce))
  1089. return ce;
  1090. i915->perf.oa.pinned_ctx = ce;
  1091. return ce;
  1092. }
  1093. /**
  1094. * oa_get_render_ctx_id - determine and hold ctx hw id
  1095. * @stream: An i915-perf stream opened for OA metrics
  1096. *
  1097. * Determine the render context hw id, and ensure it remains fixed for the
  1098. * lifetime of the stream. This ensures that we don't have to worry about
  1099. * updating the context ID in OACONTROL on the fly.
  1100. *
  1101. * Returns: zero on success or a negative error code
  1102. */
  1103. static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
  1104. {
  1105. struct drm_i915_private *i915 = stream->dev_priv;
  1106. struct intel_context *ce;
  1107. ce = oa_pin_context(i915, stream->ctx);
  1108. if (IS_ERR(ce))
  1109. return PTR_ERR(ce);
  1110. switch (INTEL_GEN(i915)) {
  1111. case 7: {
  1112. /*
  1113. * On Haswell we don't do any post processing of the reports
  1114. * and don't need to use the mask.
  1115. */
  1116. i915->perf.oa.specific_ctx_id = i915_ggtt_offset(ce->state);
  1117. i915->perf.oa.specific_ctx_id_mask = 0;
  1118. break;
  1119. }
  1120. case 8:
  1121. case 9:
  1122. case 10:
  1123. if (USES_GUC_SUBMISSION(i915)) {
  1124. /*
  1125. * When using GuC, the context descriptor we write in
  1126. * i915 is read by GuC and rewritten before it's
  1127. * actually written into the hardware. The LRCA is
  1128. * what is put into the context id field of the
  1129. * context descriptor by GuC. Because it's aligned to
  1130. * a page, the lower 12bits are always at 0 and
  1131. * dropped by GuC. They won't be part of the context
  1132. * ID in the OA reports, so squash those lower bits.
  1133. */
  1134. i915->perf.oa.specific_ctx_id =
  1135. lower_32_bits(ce->lrc_desc) >> 12;
  1136. /*
  1137. * GuC uses the top bit to signal proxy submission, so
  1138. * ignore that bit.
  1139. */
  1140. i915->perf.oa.specific_ctx_id_mask =
  1141. (1U << (GEN8_CTX_ID_WIDTH - 1)) - 1;
  1142. } else {
  1143. i915->perf.oa.specific_ctx_id_mask =
  1144. (1U << GEN8_CTX_ID_WIDTH) - 1;
  1145. i915->perf.oa.specific_ctx_id =
  1146. upper_32_bits(ce->lrc_desc);
  1147. i915->perf.oa.specific_ctx_id &=
  1148. i915->perf.oa.specific_ctx_id_mask;
  1149. }
  1150. break;
  1151. case 11: {
  1152. i915->perf.oa.specific_ctx_id_mask =
  1153. ((1U << GEN11_SW_CTX_ID_WIDTH) - 1) << (GEN11_SW_CTX_ID_SHIFT - 32) |
  1154. ((1U << GEN11_ENGINE_INSTANCE_WIDTH) - 1) << (GEN11_ENGINE_INSTANCE_SHIFT - 32) |
  1155. ((1 << GEN11_ENGINE_CLASS_WIDTH) - 1) << (GEN11_ENGINE_CLASS_SHIFT - 32);
  1156. i915->perf.oa.specific_ctx_id = upper_32_bits(ce->lrc_desc);
  1157. i915->perf.oa.specific_ctx_id &=
  1158. i915->perf.oa.specific_ctx_id_mask;
  1159. break;
  1160. }
  1161. default:
  1162. MISSING_CASE(INTEL_GEN(i915));
  1163. }
  1164. DRM_DEBUG_DRIVER("filtering on ctx_id=0x%x ctx_id_mask=0x%x\n",
  1165. i915->perf.oa.specific_ctx_id,
  1166. i915->perf.oa.specific_ctx_id_mask);
  1167. return 0;
  1168. }
  1169. /**
  1170. * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
  1171. * @stream: An i915-perf stream opened for OA metrics
  1172. *
  1173. * In case anything needed doing to ensure the context HW ID would remain valid
  1174. * for the lifetime of the stream, then that can be undone here.
  1175. */
  1176. static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
  1177. {
  1178. struct drm_i915_private *dev_priv = stream->dev_priv;
  1179. struct intel_context *ce;
  1180. dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
  1181. dev_priv->perf.oa.specific_ctx_id_mask = 0;
  1182. ce = fetch_and_zero(&dev_priv->perf.oa.pinned_ctx);
  1183. if (ce) {
  1184. mutex_lock(&dev_priv->drm.struct_mutex);
  1185. intel_context_unpin(ce);
  1186. mutex_unlock(&dev_priv->drm.struct_mutex);
  1187. }
  1188. }
  1189. static void
  1190. free_oa_buffer(struct drm_i915_private *i915)
  1191. {
  1192. mutex_lock(&i915->drm.struct_mutex);
  1193. i915_vma_unpin_and_release(&i915->perf.oa.oa_buffer.vma,
  1194. I915_VMA_RELEASE_MAP);
  1195. mutex_unlock(&i915->drm.struct_mutex);
  1196. i915->perf.oa.oa_buffer.vaddr = NULL;
  1197. }
  1198. static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
  1199. {
  1200. struct drm_i915_private *dev_priv = stream->dev_priv;
  1201. BUG_ON(stream != dev_priv->perf.oa.exclusive_stream);
  1202. /*
  1203. * Unset exclusive_stream first, it will be checked while disabling
  1204. * the metric set on gen8+.
  1205. */
  1206. mutex_lock(&dev_priv->drm.struct_mutex);
  1207. dev_priv->perf.oa.exclusive_stream = NULL;
  1208. dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
  1209. mutex_unlock(&dev_priv->drm.struct_mutex);
  1210. free_oa_buffer(dev_priv);
  1211. intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
  1212. intel_runtime_pm_put(dev_priv);
  1213. if (stream->ctx)
  1214. oa_put_render_ctx_id(stream);
  1215. put_oa_config(dev_priv, stream->oa_config);
  1216. if (dev_priv->perf.oa.spurious_report_rs.missed) {
  1217. DRM_NOTE("%d spurious OA report notices suppressed due to ratelimiting\n",
  1218. dev_priv->perf.oa.spurious_report_rs.missed);
  1219. }
  1220. }
  1221. static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv)
  1222. {
  1223. u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
  1224. unsigned long flags;
  1225. spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  1226. /* Pre-DevBDW: OABUFFER must be set with counters off,
  1227. * before OASTATUS1, but after OASTATUS2
  1228. */
  1229. I915_WRITE(GEN7_OASTATUS2,
  1230. gtt_offset | GEN7_OASTATUS2_MEM_SELECT_GGTT); /* head */
  1231. dev_priv->perf.oa.oa_buffer.head = gtt_offset;
  1232. I915_WRITE(GEN7_OABUFFER, gtt_offset);
  1233. I915_WRITE(GEN7_OASTATUS1, gtt_offset | OABUFFER_SIZE_16M); /* tail */
  1234. /* Mark that we need updated tail pointers to read from... */
  1235. dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
  1236. dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
  1237. spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  1238. /* On Haswell we have to track which OASTATUS1 flags we've
  1239. * already seen since they can't be cleared while periodic
  1240. * sampling is enabled.
  1241. */
  1242. dev_priv->perf.oa.gen7_latched_oastatus1 = 0;
  1243. /* NB: although the OA buffer will initially be allocated
  1244. * zeroed via shmfs (and so this memset is redundant when
  1245. * first allocating), we may re-init the OA buffer, either
  1246. * when re-enabling a stream or in error/reset paths.
  1247. *
  1248. * The reason we clear the buffer for each re-init is for the
  1249. * sanity check in gen7_append_oa_reports() that looks at the
  1250. * report-id field to make sure it's non-zero which relies on
  1251. * the assumption that new reports are being written to zeroed
  1252. * memory...
  1253. */
  1254. memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
  1255. /* Maybe make ->pollin per-stream state if we support multiple
  1256. * concurrent streams in the future.
  1257. */
  1258. dev_priv->perf.oa.pollin = false;
  1259. }
  1260. static void gen8_init_oa_buffer(struct drm_i915_private *dev_priv)
  1261. {
  1262. u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
  1263. unsigned long flags;
  1264. spin_lock_irqsave(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  1265. I915_WRITE(GEN8_OASTATUS, 0);
  1266. I915_WRITE(GEN8_OAHEADPTR, gtt_offset);
  1267. dev_priv->perf.oa.oa_buffer.head = gtt_offset;
  1268. I915_WRITE(GEN8_OABUFFER_UDW, 0);
  1269. /*
  1270. * PRM says:
  1271. *
  1272. * "This MMIO must be set before the OATAILPTR
  1273. * register and after the OAHEADPTR register. This is
  1274. * to enable proper functionality of the overflow
  1275. * bit."
  1276. */
  1277. I915_WRITE(GEN8_OABUFFER, gtt_offset |
  1278. OABUFFER_SIZE_16M | GEN8_OABUFFER_MEM_SELECT_GGTT);
  1279. I915_WRITE(GEN8_OATAILPTR, gtt_offset & GEN8_OATAILPTR_MASK);
  1280. /* Mark that we need updated tail pointers to read from... */
  1281. dev_priv->perf.oa.oa_buffer.tails[0].offset = INVALID_TAIL_PTR;
  1282. dev_priv->perf.oa.oa_buffer.tails[1].offset = INVALID_TAIL_PTR;
  1283. /*
  1284. * Reset state used to recognise context switches, affecting which
  1285. * reports we will forward to userspace while filtering for a single
  1286. * context.
  1287. */
  1288. dev_priv->perf.oa.oa_buffer.last_ctx_id = INVALID_CTX_ID;
  1289. spin_unlock_irqrestore(&dev_priv->perf.oa.oa_buffer.ptr_lock, flags);
  1290. /*
  1291. * NB: although the OA buffer will initially be allocated
  1292. * zeroed via shmfs (and so this memset is redundant when
  1293. * first allocating), we may re-init the OA buffer, either
  1294. * when re-enabling a stream or in error/reset paths.
  1295. *
  1296. * The reason we clear the buffer for each re-init is for the
  1297. * sanity check in gen8_append_oa_reports() that looks at the
  1298. * reason field to make sure it's non-zero which relies on
  1299. * the assumption that new reports are being written to zeroed
  1300. * memory...
  1301. */
  1302. memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
  1303. /*
  1304. * Maybe make ->pollin per-stream state if we support multiple
  1305. * concurrent streams in the future.
  1306. */
  1307. dev_priv->perf.oa.pollin = false;
  1308. }
  1309. static int alloc_oa_buffer(struct drm_i915_private *dev_priv)
  1310. {
  1311. struct drm_i915_gem_object *bo;
  1312. struct i915_vma *vma;
  1313. int ret;
  1314. if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma))
  1315. return -ENODEV;
  1316. ret = i915_mutex_lock_interruptible(&dev_priv->drm);
  1317. if (ret)
  1318. return ret;
  1319. BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
  1320. BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
  1321. bo = i915_gem_object_create(dev_priv, OA_BUFFER_SIZE);
  1322. if (IS_ERR(bo)) {
  1323. DRM_ERROR("Failed to allocate OA buffer\n");
  1324. ret = PTR_ERR(bo);
  1325. goto unlock;
  1326. }
  1327. ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC);
  1328. if (ret)
  1329. goto err_unref;
  1330. /* PreHSW required 512K alignment, HSW requires 16M */
  1331. vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
  1332. if (IS_ERR(vma)) {
  1333. ret = PTR_ERR(vma);
  1334. goto err_unref;
  1335. }
  1336. dev_priv->perf.oa.oa_buffer.vma = vma;
  1337. dev_priv->perf.oa.oa_buffer.vaddr =
  1338. i915_gem_object_pin_map(bo, I915_MAP_WB);
  1339. if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) {
  1340. ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr);
  1341. goto err_unpin;
  1342. }
  1343. dev_priv->perf.oa.ops.init_oa_buffer(dev_priv);
  1344. DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p\n",
  1345. i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma),
  1346. dev_priv->perf.oa.oa_buffer.vaddr);
  1347. goto unlock;
  1348. err_unpin:
  1349. __i915_vma_unpin(vma);
  1350. err_unref:
  1351. i915_gem_object_put(bo);
  1352. dev_priv->perf.oa.oa_buffer.vaddr = NULL;
  1353. dev_priv->perf.oa.oa_buffer.vma = NULL;
  1354. unlock:
  1355. mutex_unlock(&dev_priv->drm.struct_mutex);
  1356. return ret;
  1357. }
  1358. static void config_oa_regs(struct drm_i915_private *dev_priv,
  1359. const struct i915_oa_reg *regs,
  1360. u32 n_regs)
  1361. {
  1362. u32 i;
  1363. for (i = 0; i < n_regs; i++) {
  1364. const struct i915_oa_reg *reg = regs + i;
  1365. I915_WRITE(reg->addr, reg->value);
  1366. }
  1367. }
  1368. static int hsw_enable_metric_set(struct drm_i915_private *dev_priv,
  1369. const struct i915_oa_config *oa_config)
  1370. {
  1371. /* PRM:
  1372. *
  1373. * OA unit is using “crclk” for its functionality. When trunk
  1374. * level clock gating takes place, OA clock would be gated,
  1375. * unable to count the events from non-render clock domain.
  1376. * Render clock gating must be disabled when OA is enabled to
  1377. * count the events from non-render domain. Unit level clock
  1378. * gating for RCS should also be disabled.
  1379. */
  1380. I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
  1381. ~GEN7_DOP_CLOCK_GATE_ENABLE));
  1382. I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
  1383. GEN6_CSUNIT_CLOCK_GATE_DISABLE));
  1384. config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len);
  1385. /* It apparently takes a fairly long time for a new MUX
  1386. * configuration to be be applied after these register writes.
  1387. * This delay duration was derived empirically based on the
  1388. * render_basic config but hopefully it covers the maximum
  1389. * configuration latency.
  1390. *
  1391. * As a fallback, the checks in _append_oa_reports() to skip
  1392. * invalid OA reports do also seem to work to discard reports
  1393. * generated before this config has completed - albeit not
  1394. * silently.
  1395. *
  1396. * Unfortunately this is essentially a magic number, since we
  1397. * don't currently know of a reliable mechanism for predicting
  1398. * how long the MUX config will take to apply and besides
  1399. * seeing invalid reports we don't know of a reliable way to
  1400. * explicitly check that the MUX config has landed.
  1401. *
  1402. * It's even possible we've miss characterized the underlying
  1403. * problem - it just seems like the simplest explanation why
  1404. * a delay at this location would mitigate any invalid reports.
  1405. */
  1406. usleep_range(15000, 20000);
  1407. config_oa_regs(dev_priv, oa_config->b_counter_regs,
  1408. oa_config->b_counter_regs_len);
  1409. return 0;
  1410. }
  1411. static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
  1412. {
  1413. I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
  1414. ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
  1415. I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
  1416. GEN7_DOP_CLOCK_GATE_ENABLE));
  1417. I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
  1418. ~GT_NOA_ENABLE));
  1419. }
  1420. /*
  1421. * NB: It must always remain pointer safe to run this even if the OA unit
  1422. * has been disabled.
  1423. *
  1424. * It's fine to put out-of-date values into these per-context registers
  1425. * in the case that the OA unit has been disabled.
  1426. */
  1427. static void gen8_update_reg_state_unlocked(struct i915_gem_context *ctx,
  1428. u32 *reg_state,
  1429. const struct i915_oa_config *oa_config)
  1430. {
  1431. struct drm_i915_private *dev_priv = ctx->i915;
  1432. u32 ctx_oactxctrl = dev_priv->perf.oa.ctx_oactxctrl_offset;
  1433. u32 ctx_flexeu0 = dev_priv->perf.oa.ctx_flexeu0_offset;
  1434. /* The MMIO offsets for Flex EU registers aren't contiguous */
  1435. i915_reg_t flex_regs[] = {
  1436. EU_PERF_CNTL0,
  1437. EU_PERF_CNTL1,
  1438. EU_PERF_CNTL2,
  1439. EU_PERF_CNTL3,
  1440. EU_PERF_CNTL4,
  1441. EU_PERF_CNTL5,
  1442. EU_PERF_CNTL6,
  1443. };
  1444. int i;
  1445. CTX_REG(reg_state, ctx_oactxctrl, GEN8_OACTXCONTROL,
  1446. (dev_priv->perf.oa.period_exponent << GEN8_OA_TIMER_PERIOD_SHIFT) |
  1447. (dev_priv->perf.oa.periodic ? GEN8_OA_TIMER_ENABLE : 0) |
  1448. GEN8_OA_COUNTER_RESUME);
  1449. for (i = 0; i < ARRAY_SIZE(flex_regs); i++) {
  1450. u32 state_offset = ctx_flexeu0 + i * 2;
  1451. u32 mmio = i915_mmio_reg_offset(flex_regs[i]);
  1452. /*
  1453. * This arbitrary default will select the 'EU FPU0 Pipeline
  1454. * Active' event. In the future it's anticipated that there
  1455. * will be an explicit 'No Event' we can select, but not yet...
  1456. */
  1457. u32 value = 0;
  1458. if (oa_config) {
  1459. u32 j;
  1460. for (j = 0; j < oa_config->flex_regs_len; j++) {
  1461. if (i915_mmio_reg_offset(oa_config->flex_regs[j].addr) == mmio) {
  1462. value = oa_config->flex_regs[j].value;
  1463. break;
  1464. }
  1465. }
  1466. }
  1467. CTX_REG(reg_state, state_offset, flex_regs[i], value);
  1468. }
  1469. }
  1470. /*
  1471. * Manages updating the per-context aspects of the OA stream
  1472. * configuration across all contexts.
  1473. *
  1474. * The awkward consideration here is that OACTXCONTROL controls the
  1475. * exponent for periodic sampling which is primarily used for system
  1476. * wide profiling where we'd like a consistent sampling period even in
  1477. * the face of context switches.
  1478. *
  1479. * Our approach of updating the register state context (as opposed to
  1480. * say using a workaround batch buffer) ensures that the hardware
  1481. * won't automatically reload an out-of-date timer exponent even
  1482. * transiently before a WA BB could be parsed.
  1483. *
  1484. * This function needs to:
  1485. * - Ensure the currently running context's per-context OA state is
  1486. * updated
  1487. * - Ensure that all existing contexts will have the correct per-context
  1488. * OA state if they are scheduled for use.
  1489. * - Ensure any new contexts will be initialized with the correct
  1490. * per-context OA state.
  1491. *
  1492. * Note: it's only the RCS/Render context that has any OA state.
  1493. */
  1494. static int gen8_configure_all_contexts(struct drm_i915_private *dev_priv,
  1495. const struct i915_oa_config *oa_config)
  1496. {
  1497. struct intel_engine_cs *engine = dev_priv->engine[RCS];
  1498. unsigned int map_type = i915_coherent_map_type(dev_priv);
  1499. struct i915_gem_context *ctx;
  1500. struct i915_request *rq;
  1501. int ret;
  1502. lockdep_assert_held(&dev_priv->drm.struct_mutex);
  1503. /*
  1504. * The OA register config is setup through the context image. This image
  1505. * might be written to by the GPU on context switch (in particular on
  1506. * lite-restore). This means we can't safely update a context's image,
  1507. * if this context is scheduled/submitted to run on the GPU.
  1508. *
  1509. * We could emit the OA register config through the batch buffer but
  1510. * this might leave small interval of time where the OA unit is
  1511. * configured at an invalid sampling period.
  1512. *
  1513. * So far the best way to work around this issue seems to be draining
  1514. * the GPU from any submitted work.
  1515. */
  1516. ret = i915_gem_wait_for_idle(dev_priv,
  1517. I915_WAIT_LOCKED,
  1518. MAX_SCHEDULE_TIMEOUT);
  1519. if (ret)
  1520. return ret;
  1521. /* Update all contexts now that we've stalled the submission. */
  1522. list_for_each_entry(ctx, &dev_priv->contexts.list, link) {
  1523. struct intel_context *ce = to_intel_context(ctx, engine);
  1524. u32 *regs;
  1525. /* OA settings will be set upon first use */
  1526. if (!ce->state)
  1527. continue;
  1528. regs = i915_gem_object_pin_map(ce->state->obj, map_type);
  1529. if (IS_ERR(regs))
  1530. return PTR_ERR(regs);
  1531. ce->state->obj->mm.dirty = true;
  1532. regs += LRC_STATE_PN * PAGE_SIZE / sizeof(*regs);
  1533. gen8_update_reg_state_unlocked(ctx, regs, oa_config);
  1534. i915_gem_object_unpin_map(ce->state->obj);
  1535. }
  1536. /*
  1537. * Apply the configuration by doing one context restore of the edited
  1538. * context image.
  1539. */
  1540. rq = i915_request_alloc(engine, dev_priv->kernel_context);
  1541. if (IS_ERR(rq))
  1542. return PTR_ERR(rq);
  1543. i915_request_add(rq);
  1544. return 0;
  1545. }
  1546. static int gen8_enable_metric_set(struct drm_i915_private *dev_priv,
  1547. const struct i915_oa_config *oa_config)
  1548. {
  1549. int ret;
  1550. /*
  1551. * We disable slice/unslice clock ratio change reports on SKL since
  1552. * they are too noisy. The HW generates a lot of redundant reports
  1553. * where the ratio hasn't really changed causing a lot of redundant
  1554. * work to processes and increasing the chances we'll hit buffer
  1555. * overruns.
  1556. *
  1557. * Although we don't currently use the 'disable overrun' OABUFFER
  1558. * feature it's worth noting that clock ratio reports have to be
  1559. * disabled before considering to use that feature since the HW doesn't
  1560. * correctly block these reports.
  1561. *
  1562. * Currently none of the high-level metrics we have depend on knowing
  1563. * this ratio to normalize.
  1564. *
  1565. * Note: This register is not power context saved and restored, but
  1566. * that's OK considering that we disable RC6 while the OA unit is
  1567. * enabled.
  1568. *
  1569. * The _INCLUDE_CLK_RATIO bit allows the slice/unslice frequency to
  1570. * be read back from automatically triggered reports, as part of the
  1571. * RPT_ID field.
  1572. */
  1573. if (IS_GEN(dev_priv, 9, 11)) {
  1574. I915_WRITE(GEN8_OA_DEBUG,
  1575. _MASKED_BIT_ENABLE(GEN9_OA_DEBUG_DISABLE_CLK_RATIO_REPORTS |
  1576. GEN9_OA_DEBUG_INCLUDE_CLK_RATIO));
  1577. }
  1578. /*
  1579. * Update all contexts prior writing the mux configurations as we need
  1580. * to make sure all slices/subslices are ON before writing to NOA
  1581. * registers.
  1582. */
  1583. ret = gen8_configure_all_contexts(dev_priv, oa_config);
  1584. if (ret)
  1585. return ret;
  1586. config_oa_regs(dev_priv, oa_config->mux_regs, oa_config->mux_regs_len);
  1587. config_oa_regs(dev_priv, oa_config->b_counter_regs,
  1588. oa_config->b_counter_regs_len);
  1589. return 0;
  1590. }
  1591. static void gen8_disable_metric_set(struct drm_i915_private *dev_priv)
  1592. {
  1593. /* Reset all contexts' slices/subslices configurations. */
  1594. gen8_configure_all_contexts(dev_priv, NULL);
  1595. I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
  1596. ~GT_NOA_ENABLE));
  1597. }
  1598. static void gen10_disable_metric_set(struct drm_i915_private *dev_priv)
  1599. {
  1600. /* Reset all contexts' slices/subslices configurations. */
  1601. gen8_configure_all_contexts(dev_priv, NULL);
  1602. /* Make sure we disable noa to save power. */
  1603. I915_WRITE(RPM_CONFIG1,
  1604. I915_READ(RPM_CONFIG1) & ~GEN10_GT_NOA_ENABLE);
  1605. }
  1606. static void gen7_oa_enable(struct drm_i915_private *dev_priv)
  1607. {
  1608. struct i915_gem_context *ctx =
  1609. dev_priv->perf.oa.exclusive_stream->ctx;
  1610. u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
  1611. bool periodic = dev_priv->perf.oa.periodic;
  1612. u32 period_exponent = dev_priv->perf.oa.period_exponent;
  1613. u32 report_format = dev_priv->perf.oa.oa_buffer.format;
  1614. /*
  1615. * Reset buf pointers so we don't forward reports from before now.
  1616. *
  1617. * Think carefully if considering trying to avoid this, since it
  1618. * also ensures status flags and the buffer itself are cleared
  1619. * in error paths, and we have checks for invalid reports based
  1620. * on the assumption that certain fields are written to zeroed
  1621. * memory which this helps maintains.
  1622. */
  1623. gen7_init_oa_buffer(dev_priv);
  1624. I915_WRITE(GEN7_OACONTROL,
  1625. (ctx_id & GEN7_OACONTROL_CTX_MASK) |
  1626. (period_exponent <<
  1627. GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
  1628. (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
  1629. (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
  1630. (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
  1631. GEN7_OACONTROL_ENABLE);
  1632. }
  1633. static void gen8_oa_enable(struct drm_i915_private *dev_priv)
  1634. {
  1635. u32 report_format = dev_priv->perf.oa.oa_buffer.format;
  1636. /*
  1637. * Reset buf pointers so we don't forward reports from before now.
  1638. *
  1639. * Think carefully if considering trying to avoid this, since it
  1640. * also ensures status flags and the buffer itself are cleared
  1641. * in error paths, and we have checks for invalid reports based
  1642. * on the assumption that certain fields are written to zeroed
  1643. * memory which this helps maintains.
  1644. */
  1645. gen8_init_oa_buffer(dev_priv);
  1646. /*
  1647. * Note: we don't rely on the hardware to perform single context
  1648. * filtering and instead filter on the cpu based on the context-id
  1649. * field of reports
  1650. */
  1651. I915_WRITE(GEN8_OACONTROL, (report_format <<
  1652. GEN8_OA_REPORT_FORMAT_SHIFT) |
  1653. GEN8_OA_COUNTER_ENABLE);
  1654. }
  1655. /**
  1656. * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
  1657. * @stream: An i915 perf stream opened for OA metrics
  1658. *
  1659. * [Re]enables hardware periodic sampling according to the period configured
  1660. * when opening the stream. This also starts a hrtimer that will periodically
  1661. * check for data in the circular OA buffer for notifying userspace (e.g.
  1662. * during a read() or poll()).
  1663. */
  1664. static void i915_oa_stream_enable(struct i915_perf_stream *stream)
  1665. {
  1666. struct drm_i915_private *dev_priv = stream->dev_priv;
  1667. dev_priv->perf.oa.ops.oa_enable(dev_priv);
  1668. if (dev_priv->perf.oa.periodic)
  1669. hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
  1670. ns_to_ktime(POLL_PERIOD),
  1671. HRTIMER_MODE_REL_PINNED);
  1672. }
  1673. static void gen7_oa_disable(struct drm_i915_private *dev_priv)
  1674. {
  1675. I915_WRITE(GEN7_OACONTROL, 0);
  1676. if (intel_wait_for_register(dev_priv,
  1677. GEN7_OACONTROL, GEN7_OACONTROL_ENABLE, 0,
  1678. 50))
  1679. DRM_ERROR("wait for OA to be disabled timed out\n");
  1680. }
  1681. static void gen8_oa_disable(struct drm_i915_private *dev_priv)
  1682. {
  1683. I915_WRITE(GEN8_OACONTROL, 0);
  1684. if (intel_wait_for_register(dev_priv,
  1685. GEN8_OACONTROL, GEN8_OA_COUNTER_ENABLE, 0,
  1686. 50))
  1687. DRM_ERROR("wait for OA to be disabled timed out\n");
  1688. }
  1689. /**
  1690. * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
  1691. * @stream: An i915 perf stream opened for OA metrics
  1692. *
  1693. * Stops the OA unit from periodically writing counter reports into the
  1694. * circular OA buffer. This also stops the hrtimer that periodically checks for
  1695. * data in the circular OA buffer, for notifying userspace.
  1696. */
  1697. static void i915_oa_stream_disable(struct i915_perf_stream *stream)
  1698. {
  1699. struct drm_i915_private *dev_priv = stream->dev_priv;
  1700. dev_priv->perf.oa.ops.oa_disable(dev_priv);
  1701. if (dev_priv->perf.oa.periodic)
  1702. hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
  1703. }
  1704. static const struct i915_perf_stream_ops i915_oa_stream_ops = {
  1705. .destroy = i915_oa_stream_destroy,
  1706. .enable = i915_oa_stream_enable,
  1707. .disable = i915_oa_stream_disable,
  1708. .wait_unlocked = i915_oa_wait_unlocked,
  1709. .poll_wait = i915_oa_poll_wait,
  1710. .read = i915_oa_read,
  1711. };
  1712. /**
  1713. * i915_oa_stream_init - validate combined props for OA stream and init
  1714. * @stream: An i915 perf stream
  1715. * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
  1716. * @props: The property state that configures stream (individually validated)
  1717. *
  1718. * While read_properties_unlocked() validates properties in isolation it
  1719. * doesn't ensure that the combination necessarily makes sense.
  1720. *
  1721. * At this point it has been determined that userspace wants a stream of
  1722. * OA metrics, but still we need to further validate the combined
  1723. * properties are OK.
  1724. *
  1725. * If the configuration makes sense then we can allocate memory for
  1726. * a circular OA buffer and apply the requested metric set configuration.
  1727. *
  1728. * Returns: zero on success or a negative error code.
  1729. */
  1730. static int i915_oa_stream_init(struct i915_perf_stream *stream,
  1731. struct drm_i915_perf_open_param *param,
  1732. struct perf_open_properties *props)
  1733. {
  1734. struct drm_i915_private *dev_priv = stream->dev_priv;
  1735. int format_size;
  1736. int ret;
  1737. /* If the sysfs metrics/ directory wasn't registered for some
  1738. * reason then don't let userspace try their luck with config
  1739. * IDs
  1740. */
  1741. if (!dev_priv->perf.metrics_kobj) {
  1742. DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
  1743. return -EINVAL;
  1744. }
  1745. if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
  1746. DRM_DEBUG("Only OA report sampling supported\n");
  1747. return -EINVAL;
  1748. }
  1749. if (!dev_priv->perf.oa.ops.init_oa_buffer) {
  1750. DRM_DEBUG("OA unit not supported\n");
  1751. return -ENODEV;
  1752. }
  1753. /* To avoid the complexity of having to accurately filter
  1754. * counter reports and marshal to the appropriate client
  1755. * we currently only allow exclusive access
  1756. */
  1757. if (dev_priv->perf.oa.exclusive_stream) {
  1758. DRM_DEBUG("OA unit already in use\n");
  1759. return -EBUSY;
  1760. }
  1761. if (!props->oa_format) {
  1762. DRM_DEBUG("OA report format not specified\n");
  1763. return -EINVAL;
  1764. }
  1765. /* We set up some ratelimit state to potentially throttle any _NOTES
  1766. * about spurious, invalid OA reports which we don't forward to
  1767. * userspace.
  1768. *
  1769. * The initialization is associated with opening the stream (not driver
  1770. * init) considering we print a _NOTE about any throttling when closing
  1771. * the stream instead of waiting until driver _fini which no one would
  1772. * ever see.
  1773. *
  1774. * Using the same limiting factors as printk_ratelimit()
  1775. */
  1776. ratelimit_state_init(&dev_priv->perf.oa.spurious_report_rs,
  1777. 5 * HZ, 10);
  1778. /* Since we use a DRM_NOTE for spurious reports it would be
  1779. * inconsistent to let __ratelimit() automatically print a warning for
  1780. * throttling.
  1781. */
  1782. ratelimit_set_flags(&dev_priv->perf.oa.spurious_report_rs,
  1783. RATELIMIT_MSG_ON_RELEASE);
  1784. stream->sample_size = sizeof(struct drm_i915_perf_record_header);
  1785. format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
  1786. stream->sample_flags |= SAMPLE_OA_REPORT;
  1787. stream->sample_size += format_size;
  1788. dev_priv->perf.oa.oa_buffer.format_size = format_size;
  1789. if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
  1790. return -EINVAL;
  1791. dev_priv->perf.oa.oa_buffer.format =
  1792. dev_priv->perf.oa.oa_formats[props->oa_format].format;
  1793. dev_priv->perf.oa.periodic = props->oa_periodic;
  1794. if (dev_priv->perf.oa.periodic)
  1795. dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
  1796. if (stream->ctx) {
  1797. ret = oa_get_render_ctx_id(stream);
  1798. if (ret) {
  1799. DRM_DEBUG("Invalid context id to filter with\n");
  1800. return ret;
  1801. }
  1802. }
  1803. ret = get_oa_config(dev_priv, props->metrics_set, &stream->oa_config);
  1804. if (ret) {
  1805. DRM_DEBUG("Invalid OA config id=%i\n", props->metrics_set);
  1806. goto err_config;
  1807. }
  1808. /* PRM - observability performance counters:
  1809. *
  1810. * OACONTROL, performance counter enable, note:
  1811. *
  1812. * "When this bit is set, in order to have coherent counts,
  1813. * RC6 power state and trunk clock gating must be disabled.
  1814. * This can be achieved by programming MMIO registers as
  1815. * 0xA094=0 and 0xA090[31]=1"
  1816. *
  1817. * In our case we are expecting that taking pm + FORCEWAKE
  1818. * references will effectively disable RC6.
  1819. */
  1820. intel_runtime_pm_get(dev_priv);
  1821. intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
  1822. ret = alloc_oa_buffer(dev_priv);
  1823. if (ret)
  1824. goto err_oa_buf_alloc;
  1825. ret = i915_mutex_lock_interruptible(&dev_priv->drm);
  1826. if (ret)
  1827. goto err_lock;
  1828. ret = dev_priv->perf.oa.ops.enable_metric_set(dev_priv,
  1829. stream->oa_config);
  1830. if (ret) {
  1831. DRM_DEBUG("Unable to enable metric set\n");
  1832. goto err_enable;
  1833. }
  1834. stream->ops = &i915_oa_stream_ops;
  1835. dev_priv->perf.oa.exclusive_stream = stream;
  1836. mutex_unlock(&dev_priv->drm.struct_mutex);
  1837. return 0;
  1838. err_enable:
  1839. dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
  1840. mutex_unlock(&dev_priv->drm.struct_mutex);
  1841. err_lock:
  1842. free_oa_buffer(dev_priv);
  1843. err_oa_buf_alloc:
  1844. put_oa_config(dev_priv, stream->oa_config);
  1845. intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
  1846. intel_runtime_pm_put(dev_priv);
  1847. err_config:
  1848. if (stream->ctx)
  1849. oa_put_render_ctx_id(stream);
  1850. return ret;
  1851. }
  1852. void i915_oa_init_reg_state(struct intel_engine_cs *engine,
  1853. struct i915_gem_context *ctx,
  1854. u32 *reg_state)
  1855. {
  1856. struct i915_perf_stream *stream;
  1857. if (engine->id != RCS)
  1858. return;
  1859. stream = engine->i915->perf.oa.exclusive_stream;
  1860. if (stream)
  1861. gen8_update_reg_state_unlocked(ctx, reg_state, stream->oa_config);
  1862. }
  1863. /**
  1864. * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
  1865. * @stream: An i915 perf stream
  1866. * @file: An i915 perf stream file
  1867. * @buf: destination buffer given by userspace
  1868. * @count: the number of bytes userspace wants to read
  1869. * @ppos: (inout) file seek position (unused)
  1870. *
  1871. * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
  1872. * ensure that if we've successfully copied any data then reporting that takes
  1873. * precedence over any internal error status, so the data isn't lost.
  1874. *
  1875. * For example ret will be -ENOSPC whenever there is more buffered data than
  1876. * can be copied to userspace, but that's only interesting if we weren't able
  1877. * to copy some data because it implies the userspace buffer is too small to
  1878. * receive a single record (and we never split records).
  1879. *
  1880. * Another case with ret == -EFAULT is more of a grey area since it would seem
  1881. * like bad form for userspace to ask us to overrun its buffer, but the user
  1882. * knows best:
  1883. *
  1884. * http://yarchive.net/comp/linux/partial_reads_writes.html
  1885. *
  1886. * Returns: The number of bytes copied or a negative error code on failure.
  1887. */
  1888. static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
  1889. struct file *file,
  1890. char __user *buf,
  1891. size_t count,
  1892. loff_t *ppos)
  1893. {
  1894. /* Note we keep the offset (aka bytes read) separate from any
  1895. * error status so that the final check for whether we return
  1896. * the bytes read with a higher precedence than any error (see
  1897. * comment below) doesn't need to be handled/duplicated in
  1898. * stream->ops->read() implementations.
  1899. */
  1900. size_t offset = 0;
  1901. int ret = stream->ops->read(stream, buf, count, &offset);
  1902. return offset ?: (ret ?: -EAGAIN);
  1903. }
  1904. /**
  1905. * i915_perf_read - handles read() FOP for i915 perf stream FDs
  1906. * @file: An i915 perf stream file
  1907. * @buf: destination buffer given by userspace
  1908. * @count: the number of bytes userspace wants to read
  1909. * @ppos: (inout) file seek position (unused)
  1910. *
  1911. * The entry point for handling a read() on a stream file descriptor from
  1912. * userspace. Most of the work is left to the i915_perf_read_locked() and
  1913. * &i915_perf_stream_ops->read but to save having stream implementations (of
  1914. * which we might have multiple later) we handle blocking read here.
  1915. *
  1916. * We can also consistently treat trying to read from a disabled stream
  1917. * as an IO error so implementations can assume the stream is enabled
  1918. * while reading.
  1919. *
  1920. * Returns: The number of bytes copied or a negative error code on failure.
  1921. */
  1922. static ssize_t i915_perf_read(struct file *file,
  1923. char __user *buf,
  1924. size_t count,
  1925. loff_t *ppos)
  1926. {
  1927. struct i915_perf_stream *stream = file->private_data;
  1928. struct drm_i915_private *dev_priv = stream->dev_priv;
  1929. ssize_t ret;
  1930. /* To ensure it's handled consistently we simply treat all reads of a
  1931. * disabled stream as an error. In particular it might otherwise lead
  1932. * to a deadlock for blocking file descriptors...
  1933. */
  1934. if (!stream->enabled)
  1935. return -EIO;
  1936. if (!(file->f_flags & O_NONBLOCK)) {
  1937. /* There's the small chance of false positives from
  1938. * stream->ops->wait_unlocked.
  1939. *
  1940. * E.g. with single context filtering since we only wait until
  1941. * oabuffer has >= 1 report we don't immediately know whether
  1942. * any reports really belong to the current context
  1943. */
  1944. do {
  1945. ret = stream->ops->wait_unlocked(stream);
  1946. if (ret)
  1947. return ret;
  1948. mutex_lock(&dev_priv->perf.lock);
  1949. ret = i915_perf_read_locked(stream, file,
  1950. buf, count, ppos);
  1951. mutex_unlock(&dev_priv->perf.lock);
  1952. } while (ret == -EAGAIN);
  1953. } else {
  1954. mutex_lock(&dev_priv->perf.lock);
  1955. ret = i915_perf_read_locked(stream, file, buf, count, ppos);
  1956. mutex_unlock(&dev_priv->perf.lock);
  1957. }
  1958. /* We allow the poll checking to sometimes report false positive EPOLLIN
  1959. * events where we might actually report EAGAIN on read() if there's
  1960. * not really any data available. In this situation though we don't
  1961. * want to enter a busy loop between poll() reporting a EPOLLIN event
  1962. * and read() returning -EAGAIN. Clearing the oa.pollin state here
  1963. * effectively ensures we back off until the next hrtimer callback
  1964. * before reporting another EPOLLIN event.
  1965. */
  1966. if (ret >= 0 || ret == -EAGAIN) {
  1967. /* Maybe make ->pollin per-stream state if we support multiple
  1968. * concurrent streams in the future.
  1969. */
  1970. dev_priv->perf.oa.pollin = false;
  1971. }
  1972. return ret;
  1973. }
  1974. static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
  1975. {
  1976. struct drm_i915_private *dev_priv =
  1977. container_of(hrtimer, typeof(*dev_priv),
  1978. perf.oa.poll_check_timer);
  1979. if (oa_buffer_check_unlocked(dev_priv)) {
  1980. dev_priv->perf.oa.pollin = true;
  1981. wake_up(&dev_priv->perf.oa.poll_wq);
  1982. }
  1983. hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
  1984. return HRTIMER_RESTART;
  1985. }
  1986. /**
  1987. * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
  1988. * @dev_priv: i915 device instance
  1989. * @stream: An i915 perf stream
  1990. * @file: An i915 perf stream file
  1991. * @wait: poll() state table
  1992. *
  1993. * For handling userspace polling on an i915 perf stream, this calls through to
  1994. * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
  1995. * will be woken for new stream data.
  1996. *
  1997. * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
  1998. * with any non-file-operation driver hooks.
  1999. *
  2000. * Returns: any poll events that are ready without sleeping
  2001. */
  2002. static __poll_t i915_perf_poll_locked(struct drm_i915_private *dev_priv,
  2003. struct i915_perf_stream *stream,
  2004. struct file *file,
  2005. poll_table *wait)
  2006. {
  2007. __poll_t events = 0;
  2008. stream->ops->poll_wait(stream, file, wait);
  2009. /* Note: we don't explicitly check whether there's something to read
  2010. * here since this path may be very hot depending on what else
  2011. * userspace is polling, or on the timeout in use. We rely solely on
  2012. * the hrtimer/oa_poll_check_timer_cb to notify us when there are
  2013. * samples to read.
  2014. */
  2015. if (dev_priv->perf.oa.pollin)
  2016. events |= EPOLLIN;
  2017. return events;
  2018. }
  2019. /**
  2020. * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
  2021. * @file: An i915 perf stream file
  2022. * @wait: poll() state table
  2023. *
  2024. * For handling userspace polling on an i915 perf stream, this ensures
  2025. * poll_wait() gets called with a wait queue that will be woken for new stream
  2026. * data.
  2027. *
  2028. * Note: Implementation deferred to i915_perf_poll_locked()
  2029. *
  2030. * Returns: any poll events that are ready without sleeping
  2031. */
  2032. static __poll_t i915_perf_poll(struct file *file, poll_table *wait)
  2033. {
  2034. struct i915_perf_stream *stream = file->private_data;
  2035. struct drm_i915_private *dev_priv = stream->dev_priv;
  2036. __poll_t ret;
  2037. mutex_lock(&dev_priv->perf.lock);
  2038. ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
  2039. mutex_unlock(&dev_priv->perf.lock);
  2040. return ret;
  2041. }
  2042. /**
  2043. * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
  2044. * @stream: A disabled i915 perf stream
  2045. *
  2046. * [Re]enables the associated capture of data for this stream.
  2047. *
  2048. * If a stream was previously enabled then there's currently no intention
  2049. * to provide userspace any guarantee about the preservation of previously
  2050. * buffered data.
  2051. */
  2052. static void i915_perf_enable_locked(struct i915_perf_stream *stream)
  2053. {
  2054. if (stream->enabled)
  2055. return;
  2056. /* Allow stream->ops->enable() to refer to this */
  2057. stream->enabled = true;
  2058. if (stream->ops->enable)
  2059. stream->ops->enable(stream);
  2060. }
  2061. /**
  2062. * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
  2063. * @stream: An enabled i915 perf stream
  2064. *
  2065. * Disables the associated capture of data for this stream.
  2066. *
  2067. * The intention is that disabling an re-enabling a stream will ideally be
  2068. * cheaper than destroying and re-opening a stream with the same configuration,
  2069. * though there are no formal guarantees about what state or buffered data
  2070. * must be retained between disabling and re-enabling a stream.
  2071. *
  2072. * Note: while a stream is disabled it's considered an error for userspace
  2073. * to attempt to read from the stream (-EIO).
  2074. */
  2075. static void i915_perf_disable_locked(struct i915_perf_stream *stream)
  2076. {
  2077. if (!stream->enabled)
  2078. return;
  2079. /* Allow stream->ops->disable() to refer to this */
  2080. stream->enabled = false;
  2081. if (stream->ops->disable)
  2082. stream->ops->disable(stream);
  2083. }
  2084. /**
  2085. * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
  2086. * @stream: An i915 perf stream
  2087. * @cmd: the ioctl request
  2088. * @arg: the ioctl data
  2089. *
  2090. * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
  2091. * with any non-file-operation driver hooks.
  2092. *
  2093. * Returns: zero on success or a negative error code. Returns -EINVAL for
  2094. * an unknown ioctl request.
  2095. */
  2096. static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
  2097. unsigned int cmd,
  2098. unsigned long arg)
  2099. {
  2100. switch (cmd) {
  2101. case I915_PERF_IOCTL_ENABLE:
  2102. i915_perf_enable_locked(stream);
  2103. return 0;
  2104. case I915_PERF_IOCTL_DISABLE:
  2105. i915_perf_disable_locked(stream);
  2106. return 0;
  2107. }
  2108. return -EINVAL;
  2109. }
  2110. /**
  2111. * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
  2112. * @file: An i915 perf stream file
  2113. * @cmd: the ioctl request
  2114. * @arg: the ioctl data
  2115. *
  2116. * Implementation deferred to i915_perf_ioctl_locked().
  2117. *
  2118. * Returns: zero on success or a negative error code. Returns -EINVAL for
  2119. * an unknown ioctl request.
  2120. */
  2121. static long i915_perf_ioctl(struct file *file,
  2122. unsigned int cmd,
  2123. unsigned long arg)
  2124. {
  2125. struct i915_perf_stream *stream = file->private_data;
  2126. struct drm_i915_private *dev_priv = stream->dev_priv;
  2127. long ret;
  2128. mutex_lock(&dev_priv->perf.lock);
  2129. ret = i915_perf_ioctl_locked(stream, cmd, arg);
  2130. mutex_unlock(&dev_priv->perf.lock);
  2131. return ret;
  2132. }
  2133. /**
  2134. * i915_perf_destroy_locked - destroy an i915 perf stream
  2135. * @stream: An i915 perf stream
  2136. *
  2137. * Frees all resources associated with the given i915 perf @stream, disabling
  2138. * any associated data capture in the process.
  2139. *
  2140. * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
  2141. * with any non-file-operation driver hooks.
  2142. */
  2143. static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
  2144. {
  2145. if (stream->enabled)
  2146. i915_perf_disable_locked(stream);
  2147. if (stream->ops->destroy)
  2148. stream->ops->destroy(stream);
  2149. list_del(&stream->link);
  2150. if (stream->ctx)
  2151. i915_gem_context_put(stream->ctx);
  2152. kfree(stream);
  2153. }
  2154. /**
  2155. * i915_perf_release - handles userspace close() of a stream file
  2156. * @inode: anonymous inode associated with file
  2157. * @file: An i915 perf stream file
  2158. *
  2159. * Cleans up any resources associated with an open i915 perf stream file.
  2160. *
  2161. * NB: close() can't really fail from the userspace point of view.
  2162. *
  2163. * Returns: zero on success or a negative error code.
  2164. */
  2165. static int i915_perf_release(struct inode *inode, struct file *file)
  2166. {
  2167. struct i915_perf_stream *stream = file->private_data;
  2168. struct drm_i915_private *dev_priv = stream->dev_priv;
  2169. mutex_lock(&dev_priv->perf.lock);
  2170. i915_perf_destroy_locked(stream);
  2171. mutex_unlock(&dev_priv->perf.lock);
  2172. return 0;
  2173. }
  2174. static const struct file_operations fops = {
  2175. .owner = THIS_MODULE,
  2176. .llseek = no_llseek,
  2177. .release = i915_perf_release,
  2178. .poll = i915_perf_poll,
  2179. .read = i915_perf_read,
  2180. .unlocked_ioctl = i915_perf_ioctl,
  2181. /* Our ioctl have no arguments, so it's safe to use the same function
  2182. * to handle 32bits compatibility.
  2183. */
  2184. .compat_ioctl = i915_perf_ioctl,
  2185. };
  2186. /**
  2187. * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
  2188. * @dev_priv: i915 device instance
  2189. * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
  2190. * @props: individually validated u64 property value pairs
  2191. * @file: drm file
  2192. *
  2193. * See i915_perf_ioctl_open() for interface details.
  2194. *
  2195. * Implements further stream config validation and stream initialization on
  2196. * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
  2197. * taken to serialize with any non-file-operation driver hooks.
  2198. *
  2199. * Note: at this point the @props have only been validated in isolation and
  2200. * it's still necessary to validate that the combination of properties makes
  2201. * sense.
  2202. *
  2203. * In the case where userspace is interested in OA unit metrics then further
  2204. * config validation and stream initialization details will be handled by
  2205. * i915_oa_stream_init(). The code here should only validate config state that
  2206. * will be relevant to all stream types / backends.
  2207. *
  2208. * Returns: zero on success or a negative error code.
  2209. */
  2210. static int
  2211. i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
  2212. struct drm_i915_perf_open_param *param,
  2213. struct perf_open_properties *props,
  2214. struct drm_file *file)
  2215. {
  2216. struct i915_gem_context *specific_ctx = NULL;
  2217. struct i915_perf_stream *stream = NULL;
  2218. unsigned long f_flags = 0;
  2219. bool privileged_op = true;
  2220. int stream_fd;
  2221. int ret;
  2222. if (props->single_context) {
  2223. u32 ctx_handle = props->ctx_handle;
  2224. struct drm_i915_file_private *file_priv = file->driver_priv;
  2225. specific_ctx = i915_gem_context_lookup(file_priv, ctx_handle);
  2226. if (!specific_ctx) {
  2227. DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
  2228. ctx_handle);
  2229. ret = -ENOENT;
  2230. goto err;
  2231. }
  2232. }
  2233. /*
  2234. * On Haswell the OA unit supports clock gating off for a specific
  2235. * context and in this mode there's no visibility of metrics for the
  2236. * rest of the system, which we consider acceptable for a
  2237. * non-privileged client.
  2238. *
  2239. * For Gen8+ the OA unit no longer supports clock gating off for a
  2240. * specific context and the kernel can't securely stop the counters
  2241. * from updating as system-wide / global values. Even though we can
  2242. * filter reports based on the included context ID we can't block
  2243. * clients from seeing the raw / global counter values via
  2244. * MI_REPORT_PERF_COUNT commands and so consider it a privileged op to
  2245. * enable the OA unit by default.
  2246. */
  2247. if (IS_HASWELL(dev_priv) && specific_ctx)
  2248. privileged_op = false;
  2249. /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
  2250. * we check a dev.i915.perf_stream_paranoid sysctl option
  2251. * to determine if it's ok to access system wide OA counters
  2252. * without CAP_SYS_ADMIN privileges.
  2253. */
  2254. if (privileged_op &&
  2255. i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
  2256. DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
  2257. ret = -EACCES;
  2258. goto err_ctx;
  2259. }
  2260. stream = kzalloc(sizeof(*stream), GFP_KERNEL);
  2261. if (!stream) {
  2262. ret = -ENOMEM;
  2263. goto err_ctx;
  2264. }
  2265. stream->dev_priv = dev_priv;
  2266. stream->ctx = specific_ctx;
  2267. ret = i915_oa_stream_init(stream, param, props);
  2268. if (ret)
  2269. goto err_alloc;
  2270. /* we avoid simply assigning stream->sample_flags = props->sample_flags
  2271. * to have _stream_init check the combination of sample flags more
  2272. * thoroughly, but still this is the expected result at this point.
  2273. */
  2274. if (WARN_ON(stream->sample_flags != props->sample_flags)) {
  2275. ret = -ENODEV;
  2276. goto err_flags;
  2277. }
  2278. list_add(&stream->link, &dev_priv->perf.streams);
  2279. if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
  2280. f_flags |= O_CLOEXEC;
  2281. if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
  2282. f_flags |= O_NONBLOCK;
  2283. stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
  2284. if (stream_fd < 0) {
  2285. ret = stream_fd;
  2286. goto err_open;
  2287. }
  2288. if (!(param->flags & I915_PERF_FLAG_DISABLED))
  2289. i915_perf_enable_locked(stream);
  2290. return stream_fd;
  2291. err_open:
  2292. list_del(&stream->link);
  2293. err_flags:
  2294. if (stream->ops->destroy)
  2295. stream->ops->destroy(stream);
  2296. err_alloc:
  2297. kfree(stream);
  2298. err_ctx:
  2299. if (specific_ctx)
  2300. i915_gem_context_put(specific_ctx);
  2301. err:
  2302. return ret;
  2303. }
  2304. static u64 oa_exponent_to_ns(struct drm_i915_private *dev_priv, int exponent)
  2305. {
  2306. return div64_u64(1000000000ULL * (2ULL << exponent),
  2307. 1000ULL * INTEL_INFO(dev_priv)->cs_timestamp_frequency_khz);
  2308. }
  2309. /**
  2310. * read_properties_unlocked - validate + copy userspace stream open properties
  2311. * @dev_priv: i915 device instance
  2312. * @uprops: The array of u64 key value pairs given by userspace
  2313. * @n_props: The number of key value pairs expected in @uprops
  2314. * @props: The stream configuration built up while validating properties
  2315. *
  2316. * Note this function only validates properties in isolation it doesn't
  2317. * validate that the combination of properties makes sense or that all
  2318. * properties necessary for a particular kind of stream have been set.
  2319. *
  2320. * Note that there currently aren't any ordering requirements for properties so
  2321. * we shouldn't validate or assume anything about ordering here. This doesn't
  2322. * rule out defining new properties with ordering requirements in the future.
  2323. */
  2324. static int read_properties_unlocked(struct drm_i915_private *dev_priv,
  2325. u64 __user *uprops,
  2326. u32 n_props,
  2327. struct perf_open_properties *props)
  2328. {
  2329. u64 __user *uprop = uprops;
  2330. u32 i;
  2331. memset(props, 0, sizeof(struct perf_open_properties));
  2332. if (!n_props) {
  2333. DRM_DEBUG("No i915 perf properties given\n");
  2334. return -EINVAL;
  2335. }
  2336. /* Considering that ID = 0 is reserved and assuming that we don't
  2337. * (currently) expect any configurations to ever specify duplicate
  2338. * values for a particular property ID then the last _PROP_MAX value is
  2339. * one greater than the maximum number of properties we expect to get
  2340. * from userspace.
  2341. */
  2342. if (n_props >= DRM_I915_PERF_PROP_MAX) {
  2343. DRM_DEBUG("More i915 perf properties specified than exist\n");
  2344. return -EINVAL;
  2345. }
  2346. for (i = 0; i < n_props; i++) {
  2347. u64 oa_period, oa_freq_hz;
  2348. u64 id, value;
  2349. int ret;
  2350. ret = get_user(id, uprop);
  2351. if (ret)
  2352. return ret;
  2353. ret = get_user(value, uprop + 1);
  2354. if (ret)
  2355. return ret;
  2356. if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
  2357. DRM_DEBUG("Unknown i915 perf property ID\n");
  2358. return -EINVAL;
  2359. }
  2360. switch ((enum drm_i915_perf_property_id)id) {
  2361. case DRM_I915_PERF_PROP_CTX_HANDLE:
  2362. props->single_context = 1;
  2363. props->ctx_handle = value;
  2364. break;
  2365. case DRM_I915_PERF_PROP_SAMPLE_OA:
  2366. if (value)
  2367. props->sample_flags |= SAMPLE_OA_REPORT;
  2368. break;
  2369. case DRM_I915_PERF_PROP_OA_METRICS_SET:
  2370. if (value == 0) {
  2371. DRM_DEBUG("Unknown OA metric set ID\n");
  2372. return -EINVAL;
  2373. }
  2374. props->metrics_set = value;
  2375. break;
  2376. case DRM_I915_PERF_PROP_OA_FORMAT:
  2377. if (value == 0 || value >= I915_OA_FORMAT_MAX) {
  2378. DRM_DEBUG("Out-of-range OA report format %llu\n",
  2379. value);
  2380. return -EINVAL;
  2381. }
  2382. if (!dev_priv->perf.oa.oa_formats[value].size) {
  2383. DRM_DEBUG("Unsupported OA report format %llu\n",
  2384. value);
  2385. return -EINVAL;
  2386. }
  2387. props->oa_format = value;
  2388. break;
  2389. case DRM_I915_PERF_PROP_OA_EXPONENT:
  2390. if (value > OA_EXPONENT_MAX) {
  2391. DRM_DEBUG("OA timer exponent too high (> %u)\n",
  2392. OA_EXPONENT_MAX);
  2393. return -EINVAL;
  2394. }
  2395. /* Theoretically we can program the OA unit to sample
  2396. * e.g. every 160ns for HSW, 167ns for BDW/SKL or 104ns
  2397. * for BXT. We don't allow such high sampling
  2398. * frequencies by default unless root.
  2399. */
  2400. BUILD_BUG_ON(sizeof(oa_period) != 8);
  2401. oa_period = oa_exponent_to_ns(dev_priv, value);
  2402. /* This check is primarily to ensure that oa_period <=
  2403. * UINT32_MAX (before passing to do_div which only
  2404. * accepts a u32 denominator), but we can also skip
  2405. * checking anything < 1Hz which implicitly can't be
  2406. * limited via an integer oa_max_sample_rate.
  2407. */
  2408. if (oa_period <= NSEC_PER_SEC) {
  2409. u64 tmp = NSEC_PER_SEC;
  2410. do_div(tmp, oa_period);
  2411. oa_freq_hz = tmp;
  2412. } else
  2413. oa_freq_hz = 0;
  2414. if (oa_freq_hz > i915_oa_max_sample_rate &&
  2415. !capable(CAP_SYS_ADMIN)) {
  2416. DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n",
  2417. i915_oa_max_sample_rate);
  2418. return -EACCES;
  2419. }
  2420. props->oa_periodic = true;
  2421. props->oa_period_exponent = value;
  2422. break;
  2423. case DRM_I915_PERF_PROP_MAX:
  2424. MISSING_CASE(id);
  2425. return -EINVAL;
  2426. }
  2427. uprop += 2;
  2428. }
  2429. return 0;
  2430. }
  2431. /**
  2432. * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
  2433. * @dev: drm device
  2434. * @data: ioctl data copied from userspace (unvalidated)
  2435. * @file: drm file
  2436. *
  2437. * Validates the stream open parameters given by userspace including flags
  2438. * and an array of u64 key, value pair properties.
  2439. *
  2440. * Very little is assumed up front about the nature of the stream being
  2441. * opened (for instance we don't assume it's for periodic OA unit metrics). An
  2442. * i915-perf stream is expected to be a suitable interface for other forms of
  2443. * buffered data written by the GPU besides periodic OA metrics.
  2444. *
  2445. * Note we copy the properties from userspace outside of the i915 perf
  2446. * mutex to avoid an awkward lockdep with mmap_sem.
  2447. *
  2448. * Most of the implementation details are handled by
  2449. * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
  2450. * mutex for serializing with any non-file-operation driver hooks.
  2451. *
  2452. * Return: A newly opened i915 Perf stream file descriptor or negative
  2453. * error code on failure.
  2454. */
  2455. int i915_perf_open_ioctl(struct drm_device *dev, void *data,
  2456. struct drm_file *file)
  2457. {
  2458. struct drm_i915_private *dev_priv = dev->dev_private;
  2459. struct drm_i915_perf_open_param *param = data;
  2460. struct perf_open_properties props;
  2461. u32 known_open_flags;
  2462. int ret;
  2463. if (!dev_priv->perf.initialized) {
  2464. DRM_DEBUG("i915 perf interface not available for this system\n");
  2465. return -ENOTSUPP;
  2466. }
  2467. known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
  2468. I915_PERF_FLAG_FD_NONBLOCK |
  2469. I915_PERF_FLAG_DISABLED;
  2470. if (param->flags & ~known_open_flags) {
  2471. DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
  2472. return -EINVAL;
  2473. }
  2474. ret = read_properties_unlocked(dev_priv,
  2475. u64_to_user_ptr(param->properties_ptr),
  2476. param->num_properties,
  2477. &props);
  2478. if (ret)
  2479. return ret;
  2480. mutex_lock(&dev_priv->perf.lock);
  2481. ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
  2482. mutex_unlock(&dev_priv->perf.lock);
  2483. return ret;
  2484. }
  2485. /**
  2486. * i915_perf_register - exposes i915-perf to userspace
  2487. * @dev_priv: i915 device instance
  2488. *
  2489. * In particular OA metric sets are advertised under a sysfs metrics/
  2490. * directory allowing userspace to enumerate valid IDs that can be
  2491. * used to open an i915-perf stream.
  2492. */
  2493. void i915_perf_register(struct drm_i915_private *dev_priv)
  2494. {
  2495. int ret;
  2496. if (!dev_priv->perf.initialized)
  2497. return;
  2498. /* To be sure we're synchronized with an attempted
  2499. * i915_perf_open_ioctl(); considering that we register after
  2500. * being exposed to userspace.
  2501. */
  2502. mutex_lock(&dev_priv->perf.lock);
  2503. dev_priv->perf.metrics_kobj =
  2504. kobject_create_and_add("metrics",
  2505. &dev_priv->drm.primary->kdev->kobj);
  2506. if (!dev_priv->perf.metrics_kobj)
  2507. goto exit;
  2508. sysfs_attr_init(&dev_priv->perf.oa.test_config.sysfs_metric_id.attr);
  2509. if (IS_HASWELL(dev_priv)) {
  2510. i915_perf_load_test_config_hsw(dev_priv);
  2511. } else if (IS_BROADWELL(dev_priv)) {
  2512. i915_perf_load_test_config_bdw(dev_priv);
  2513. } else if (IS_CHERRYVIEW(dev_priv)) {
  2514. i915_perf_load_test_config_chv(dev_priv);
  2515. } else if (IS_SKYLAKE(dev_priv)) {
  2516. if (IS_SKL_GT2(dev_priv))
  2517. i915_perf_load_test_config_sklgt2(dev_priv);
  2518. else if (IS_SKL_GT3(dev_priv))
  2519. i915_perf_load_test_config_sklgt3(dev_priv);
  2520. else if (IS_SKL_GT4(dev_priv))
  2521. i915_perf_load_test_config_sklgt4(dev_priv);
  2522. } else if (IS_BROXTON(dev_priv)) {
  2523. i915_perf_load_test_config_bxt(dev_priv);
  2524. } else if (IS_KABYLAKE(dev_priv)) {
  2525. if (IS_KBL_GT2(dev_priv))
  2526. i915_perf_load_test_config_kblgt2(dev_priv);
  2527. else if (IS_KBL_GT3(dev_priv))
  2528. i915_perf_load_test_config_kblgt3(dev_priv);
  2529. } else if (IS_GEMINILAKE(dev_priv)) {
  2530. i915_perf_load_test_config_glk(dev_priv);
  2531. } else if (IS_COFFEELAKE(dev_priv)) {
  2532. if (IS_CFL_GT2(dev_priv))
  2533. i915_perf_load_test_config_cflgt2(dev_priv);
  2534. if (IS_CFL_GT3(dev_priv))
  2535. i915_perf_load_test_config_cflgt3(dev_priv);
  2536. } else if (IS_CANNONLAKE(dev_priv)) {
  2537. i915_perf_load_test_config_cnl(dev_priv);
  2538. } else if (IS_ICELAKE(dev_priv)) {
  2539. i915_perf_load_test_config_icl(dev_priv);
  2540. }
  2541. if (dev_priv->perf.oa.test_config.id == 0)
  2542. goto sysfs_error;
  2543. ret = sysfs_create_group(dev_priv->perf.metrics_kobj,
  2544. &dev_priv->perf.oa.test_config.sysfs_metric);
  2545. if (ret)
  2546. goto sysfs_error;
  2547. atomic_set(&dev_priv->perf.oa.test_config.ref_count, 1);
  2548. goto exit;
  2549. sysfs_error:
  2550. kobject_put(dev_priv->perf.metrics_kobj);
  2551. dev_priv->perf.metrics_kobj = NULL;
  2552. exit:
  2553. mutex_unlock(&dev_priv->perf.lock);
  2554. }
  2555. /**
  2556. * i915_perf_unregister - hide i915-perf from userspace
  2557. * @dev_priv: i915 device instance
  2558. *
  2559. * i915-perf state cleanup is split up into an 'unregister' and
  2560. * 'deinit' phase where the interface is first hidden from
  2561. * userspace by i915_perf_unregister() before cleaning up
  2562. * remaining state in i915_perf_fini().
  2563. */
  2564. void i915_perf_unregister(struct drm_i915_private *dev_priv)
  2565. {
  2566. if (!dev_priv->perf.metrics_kobj)
  2567. return;
  2568. sysfs_remove_group(dev_priv->perf.metrics_kobj,
  2569. &dev_priv->perf.oa.test_config.sysfs_metric);
  2570. kobject_put(dev_priv->perf.metrics_kobj);
  2571. dev_priv->perf.metrics_kobj = NULL;
  2572. }
  2573. static bool gen8_is_valid_flex_addr(struct drm_i915_private *dev_priv, u32 addr)
  2574. {
  2575. static const i915_reg_t flex_eu_regs[] = {
  2576. EU_PERF_CNTL0,
  2577. EU_PERF_CNTL1,
  2578. EU_PERF_CNTL2,
  2579. EU_PERF_CNTL3,
  2580. EU_PERF_CNTL4,
  2581. EU_PERF_CNTL5,
  2582. EU_PERF_CNTL6,
  2583. };
  2584. int i;
  2585. for (i = 0; i < ARRAY_SIZE(flex_eu_regs); i++) {
  2586. if (i915_mmio_reg_offset(flex_eu_regs[i]) == addr)
  2587. return true;
  2588. }
  2589. return false;
  2590. }
  2591. static bool gen7_is_valid_b_counter_addr(struct drm_i915_private *dev_priv, u32 addr)
  2592. {
  2593. return (addr >= i915_mmio_reg_offset(OASTARTTRIG1) &&
  2594. addr <= i915_mmio_reg_offset(OASTARTTRIG8)) ||
  2595. (addr >= i915_mmio_reg_offset(OAREPORTTRIG1) &&
  2596. addr <= i915_mmio_reg_offset(OAREPORTTRIG8)) ||
  2597. (addr >= i915_mmio_reg_offset(OACEC0_0) &&
  2598. addr <= i915_mmio_reg_offset(OACEC7_1));
  2599. }
  2600. static bool gen7_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
  2601. {
  2602. return addr == i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) ||
  2603. (addr >= i915_mmio_reg_offset(MICRO_BP0_0) &&
  2604. addr <= i915_mmio_reg_offset(NOA_WRITE)) ||
  2605. (addr >= i915_mmio_reg_offset(OA_PERFCNT1_LO) &&
  2606. addr <= i915_mmio_reg_offset(OA_PERFCNT2_HI)) ||
  2607. (addr >= i915_mmio_reg_offset(OA_PERFMATRIX_LO) &&
  2608. addr <= i915_mmio_reg_offset(OA_PERFMATRIX_HI));
  2609. }
  2610. static bool gen8_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
  2611. {
  2612. return gen7_is_valid_mux_addr(dev_priv, addr) ||
  2613. addr == i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) ||
  2614. (addr >= i915_mmio_reg_offset(RPM_CONFIG0) &&
  2615. addr <= i915_mmio_reg_offset(NOA_CONFIG(8)));
  2616. }
  2617. static bool gen10_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
  2618. {
  2619. return gen8_is_valid_mux_addr(dev_priv, addr) ||
  2620. (addr >= i915_mmio_reg_offset(OA_PERFCNT3_LO) &&
  2621. addr <= i915_mmio_reg_offset(OA_PERFCNT4_HI));
  2622. }
  2623. static bool hsw_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
  2624. {
  2625. return gen7_is_valid_mux_addr(dev_priv, addr) ||
  2626. (addr >= 0x25100 && addr <= 0x2FF90) ||
  2627. (addr >= i915_mmio_reg_offset(HSW_MBVID2_NOA0) &&
  2628. addr <= i915_mmio_reg_offset(HSW_MBVID2_NOA9)) ||
  2629. addr == i915_mmio_reg_offset(HSW_MBVID2_MISR0);
  2630. }
  2631. static bool chv_is_valid_mux_addr(struct drm_i915_private *dev_priv, u32 addr)
  2632. {
  2633. return gen7_is_valid_mux_addr(dev_priv, addr) ||
  2634. (addr >= 0x182300 && addr <= 0x1823A4);
  2635. }
  2636. static uint32_t mask_reg_value(u32 reg, u32 val)
  2637. {
  2638. /* HALF_SLICE_CHICKEN2 is programmed with a the
  2639. * WaDisableSTUnitPowerOptimization workaround. Make sure the value
  2640. * programmed by userspace doesn't change this.
  2641. */
  2642. if (i915_mmio_reg_offset(HALF_SLICE_CHICKEN2) == reg)
  2643. val = val & ~_MASKED_BIT_ENABLE(GEN8_ST_PO_DISABLE);
  2644. /* WAIT_FOR_RC6_EXIT has only one bit fullfilling the function
  2645. * indicated by its name and a bunch of selection fields used by OA
  2646. * configs.
  2647. */
  2648. if (i915_mmio_reg_offset(WAIT_FOR_RC6_EXIT) == reg)
  2649. val = val & ~_MASKED_BIT_ENABLE(HSW_WAIT_FOR_RC6_EXIT_ENABLE);
  2650. return val;
  2651. }
  2652. static struct i915_oa_reg *alloc_oa_regs(struct drm_i915_private *dev_priv,
  2653. bool (*is_valid)(struct drm_i915_private *dev_priv, u32 addr),
  2654. u32 __user *regs,
  2655. u32 n_regs)
  2656. {
  2657. struct i915_oa_reg *oa_regs;
  2658. int err;
  2659. u32 i;
  2660. if (!n_regs)
  2661. return NULL;
  2662. if (!access_ok(VERIFY_READ, regs, n_regs * sizeof(u32) * 2))
  2663. return ERR_PTR(-EFAULT);
  2664. /* No is_valid function means we're not allowing any register to be programmed. */
  2665. GEM_BUG_ON(!is_valid);
  2666. if (!is_valid)
  2667. return ERR_PTR(-EINVAL);
  2668. oa_regs = kmalloc_array(n_regs, sizeof(*oa_regs), GFP_KERNEL);
  2669. if (!oa_regs)
  2670. return ERR_PTR(-ENOMEM);
  2671. for (i = 0; i < n_regs; i++) {
  2672. u32 addr, value;
  2673. err = get_user(addr, regs);
  2674. if (err)
  2675. goto addr_err;
  2676. if (!is_valid(dev_priv, addr)) {
  2677. DRM_DEBUG("Invalid oa_reg address: %X\n", addr);
  2678. err = -EINVAL;
  2679. goto addr_err;
  2680. }
  2681. err = get_user(value, regs + 1);
  2682. if (err)
  2683. goto addr_err;
  2684. oa_regs[i].addr = _MMIO(addr);
  2685. oa_regs[i].value = mask_reg_value(addr, value);
  2686. regs += 2;
  2687. }
  2688. return oa_regs;
  2689. addr_err:
  2690. kfree(oa_regs);
  2691. return ERR_PTR(err);
  2692. }
  2693. static ssize_t show_dynamic_id(struct device *dev,
  2694. struct device_attribute *attr,
  2695. char *buf)
  2696. {
  2697. struct i915_oa_config *oa_config =
  2698. container_of(attr, typeof(*oa_config), sysfs_metric_id);
  2699. return sprintf(buf, "%d\n", oa_config->id);
  2700. }
  2701. static int create_dynamic_oa_sysfs_entry(struct drm_i915_private *dev_priv,
  2702. struct i915_oa_config *oa_config)
  2703. {
  2704. sysfs_attr_init(&oa_config->sysfs_metric_id.attr);
  2705. oa_config->sysfs_metric_id.attr.name = "id";
  2706. oa_config->sysfs_metric_id.attr.mode = S_IRUGO;
  2707. oa_config->sysfs_metric_id.show = show_dynamic_id;
  2708. oa_config->sysfs_metric_id.store = NULL;
  2709. oa_config->attrs[0] = &oa_config->sysfs_metric_id.attr;
  2710. oa_config->attrs[1] = NULL;
  2711. oa_config->sysfs_metric.name = oa_config->uuid;
  2712. oa_config->sysfs_metric.attrs = oa_config->attrs;
  2713. return sysfs_create_group(dev_priv->perf.metrics_kobj,
  2714. &oa_config->sysfs_metric);
  2715. }
  2716. /**
  2717. * i915_perf_add_config_ioctl - DRM ioctl() for userspace to add a new OA config
  2718. * @dev: drm device
  2719. * @data: ioctl data (pointer to struct drm_i915_perf_oa_config) copied from
  2720. * userspace (unvalidated)
  2721. * @file: drm file
  2722. *
  2723. * Validates the submitted OA register to be saved into a new OA config that
  2724. * can then be used for programming the OA unit and its NOA network.
  2725. *
  2726. * Returns: A new allocated config number to be used with the perf open ioctl
  2727. * or a negative error code on failure.
  2728. */
  2729. int i915_perf_add_config_ioctl(struct drm_device *dev, void *data,
  2730. struct drm_file *file)
  2731. {
  2732. struct drm_i915_private *dev_priv = dev->dev_private;
  2733. struct drm_i915_perf_oa_config *args = data;
  2734. struct i915_oa_config *oa_config, *tmp;
  2735. int err, id;
  2736. if (!dev_priv->perf.initialized) {
  2737. DRM_DEBUG("i915 perf interface not available for this system\n");
  2738. return -ENOTSUPP;
  2739. }
  2740. if (!dev_priv->perf.metrics_kobj) {
  2741. DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
  2742. return -EINVAL;
  2743. }
  2744. if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
  2745. DRM_DEBUG("Insufficient privileges to add i915 OA config\n");
  2746. return -EACCES;
  2747. }
  2748. if ((!args->mux_regs_ptr || !args->n_mux_regs) &&
  2749. (!args->boolean_regs_ptr || !args->n_boolean_regs) &&
  2750. (!args->flex_regs_ptr || !args->n_flex_regs)) {
  2751. DRM_DEBUG("No OA registers given\n");
  2752. return -EINVAL;
  2753. }
  2754. oa_config = kzalloc(sizeof(*oa_config), GFP_KERNEL);
  2755. if (!oa_config) {
  2756. DRM_DEBUG("Failed to allocate memory for the OA config\n");
  2757. return -ENOMEM;
  2758. }
  2759. atomic_set(&oa_config->ref_count, 1);
  2760. if (!uuid_is_valid(args->uuid)) {
  2761. DRM_DEBUG("Invalid uuid format for OA config\n");
  2762. err = -EINVAL;
  2763. goto reg_err;
  2764. }
  2765. /* Last character in oa_config->uuid will be 0 because oa_config is
  2766. * kzalloc.
  2767. */
  2768. memcpy(oa_config->uuid, args->uuid, sizeof(args->uuid));
  2769. oa_config->mux_regs_len = args->n_mux_regs;
  2770. oa_config->mux_regs =
  2771. alloc_oa_regs(dev_priv,
  2772. dev_priv->perf.oa.ops.is_valid_mux_reg,
  2773. u64_to_user_ptr(args->mux_regs_ptr),
  2774. args->n_mux_regs);
  2775. if (IS_ERR(oa_config->mux_regs)) {
  2776. DRM_DEBUG("Failed to create OA config for mux_regs\n");
  2777. err = PTR_ERR(oa_config->mux_regs);
  2778. goto reg_err;
  2779. }
  2780. oa_config->b_counter_regs_len = args->n_boolean_regs;
  2781. oa_config->b_counter_regs =
  2782. alloc_oa_regs(dev_priv,
  2783. dev_priv->perf.oa.ops.is_valid_b_counter_reg,
  2784. u64_to_user_ptr(args->boolean_regs_ptr),
  2785. args->n_boolean_regs);
  2786. if (IS_ERR(oa_config->b_counter_regs)) {
  2787. DRM_DEBUG("Failed to create OA config for b_counter_regs\n");
  2788. err = PTR_ERR(oa_config->b_counter_regs);
  2789. goto reg_err;
  2790. }
  2791. if (INTEL_GEN(dev_priv) < 8) {
  2792. if (args->n_flex_regs != 0) {
  2793. err = -EINVAL;
  2794. goto reg_err;
  2795. }
  2796. } else {
  2797. oa_config->flex_regs_len = args->n_flex_regs;
  2798. oa_config->flex_regs =
  2799. alloc_oa_regs(dev_priv,
  2800. dev_priv->perf.oa.ops.is_valid_flex_reg,
  2801. u64_to_user_ptr(args->flex_regs_ptr),
  2802. args->n_flex_regs);
  2803. if (IS_ERR(oa_config->flex_regs)) {
  2804. DRM_DEBUG("Failed to create OA config for flex_regs\n");
  2805. err = PTR_ERR(oa_config->flex_regs);
  2806. goto reg_err;
  2807. }
  2808. }
  2809. err = mutex_lock_interruptible(&dev_priv->perf.metrics_lock);
  2810. if (err)
  2811. goto reg_err;
  2812. /* We shouldn't have too many configs, so this iteration shouldn't be
  2813. * too costly.
  2814. */
  2815. idr_for_each_entry(&dev_priv->perf.metrics_idr, tmp, id) {
  2816. if (!strcmp(tmp->uuid, oa_config->uuid)) {
  2817. DRM_DEBUG("OA config already exists with this uuid\n");
  2818. err = -EADDRINUSE;
  2819. goto sysfs_err;
  2820. }
  2821. }
  2822. err = create_dynamic_oa_sysfs_entry(dev_priv, oa_config);
  2823. if (err) {
  2824. DRM_DEBUG("Failed to create sysfs entry for OA config\n");
  2825. goto sysfs_err;
  2826. }
  2827. /* Config id 0 is invalid, id 1 for kernel stored test config. */
  2828. oa_config->id = idr_alloc(&dev_priv->perf.metrics_idr,
  2829. oa_config, 2,
  2830. 0, GFP_KERNEL);
  2831. if (oa_config->id < 0) {
  2832. DRM_DEBUG("Failed to create sysfs entry for OA config\n");
  2833. err = oa_config->id;
  2834. goto sysfs_err;
  2835. }
  2836. mutex_unlock(&dev_priv->perf.metrics_lock);
  2837. DRM_DEBUG("Added config %s id=%i\n", oa_config->uuid, oa_config->id);
  2838. return oa_config->id;
  2839. sysfs_err:
  2840. mutex_unlock(&dev_priv->perf.metrics_lock);
  2841. reg_err:
  2842. put_oa_config(dev_priv, oa_config);
  2843. DRM_DEBUG("Failed to add new OA config\n");
  2844. return err;
  2845. }
  2846. /**
  2847. * i915_perf_remove_config_ioctl - DRM ioctl() for userspace to remove an OA config
  2848. * @dev: drm device
  2849. * @data: ioctl data (pointer to u64 integer) copied from userspace
  2850. * @file: drm file
  2851. *
  2852. * Configs can be removed while being used, the will stop appearing in sysfs
  2853. * and their content will be freed when the stream using the config is closed.
  2854. *
  2855. * Returns: 0 on success or a negative error code on failure.
  2856. */
  2857. int i915_perf_remove_config_ioctl(struct drm_device *dev, void *data,
  2858. struct drm_file *file)
  2859. {
  2860. struct drm_i915_private *dev_priv = dev->dev_private;
  2861. u64 *arg = data;
  2862. struct i915_oa_config *oa_config;
  2863. int ret;
  2864. if (!dev_priv->perf.initialized) {
  2865. DRM_DEBUG("i915 perf interface not available for this system\n");
  2866. return -ENOTSUPP;
  2867. }
  2868. if (i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
  2869. DRM_DEBUG("Insufficient privileges to remove i915 OA config\n");
  2870. return -EACCES;
  2871. }
  2872. ret = mutex_lock_interruptible(&dev_priv->perf.metrics_lock);
  2873. if (ret)
  2874. goto lock_err;
  2875. oa_config = idr_find(&dev_priv->perf.metrics_idr, *arg);
  2876. if (!oa_config) {
  2877. DRM_DEBUG("Failed to remove unknown OA config\n");
  2878. ret = -ENOENT;
  2879. goto config_err;
  2880. }
  2881. GEM_BUG_ON(*arg != oa_config->id);
  2882. sysfs_remove_group(dev_priv->perf.metrics_kobj,
  2883. &oa_config->sysfs_metric);
  2884. idr_remove(&dev_priv->perf.metrics_idr, *arg);
  2885. DRM_DEBUG("Removed config %s id=%i\n", oa_config->uuid, oa_config->id);
  2886. put_oa_config(dev_priv, oa_config);
  2887. config_err:
  2888. mutex_unlock(&dev_priv->perf.metrics_lock);
  2889. lock_err:
  2890. return ret;
  2891. }
  2892. static struct ctl_table oa_table[] = {
  2893. {
  2894. .procname = "perf_stream_paranoid",
  2895. .data = &i915_perf_stream_paranoid,
  2896. .maxlen = sizeof(i915_perf_stream_paranoid),
  2897. .mode = 0644,
  2898. .proc_handler = proc_dointvec_minmax,
  2899. .extra1 = &zero,
  2900. .extra2 = &one,
  2901. },
  2902. {
  2903. .procname = "oa_max_sample_rate",
  2904. .data = &i915_oa_max_sample_rate,
  2905. .maxlen = sizeof(i915_oa_max_sample_rate),
  2906. .mode = 0644,
  2907. .proc_handler = proc_dointvec_minmax,
  2908. .extra1 = &zero,
  2909. .extra2 = &oa_sample_rate_hard_limit,
  2910. },
  2911. {}
  2912. };
  2913. static struct ctl_table i915_root[] = {
  2914. {
  2915. .procname = "i915",
  2916. .maxlen = 0,
  2917. .mode = 0555,
  2918. .child = oa_table,
  2919. },
  2920. {}
  2921. };
  2922. static struct ctl_table dev_root[] = {
  2923. {
  2924. .procname = "dev",
  2925. .maxlen = 0,
  2926. .mode = 0555,
  2927. .child = i915_root,
  2928. },
  2929. {}
  2930. };
  2931. /**
  2932. * i915_perf_init - initialize i915-perf state on module load
  2933. * @dev_priv: i915 device instance
  2934. *
  2935. * Initializes i915-perf state without exposing anything to userspace.
  2936. *
  2937. * Note: i915-perf initialization is split into an 'init' and 'register'
  2938. * phase with the i915_perf_register() exposing state to userspace.
  2939. */
  2940. void i915_perf_init(struct drm_i915_private *dev_priv)
  2941. {
  2942. if (IS_HASWELL(dev_priv)) {
  2943. dev_priv->perf.oa.ops.is_valid_b_counter_reg =
  2944. gen7_is_valid_b_counter_addr;
  2945. dev_priv->perf.oa.ops.is_valid_mux_reg =
  2946. hsw_is_valid_mux_addr;
  2947. dev_priv->perf.oa.ops.is_valid_flex_reg = NULL;
  2948. dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
  2949. dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
  2950. dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
  2951. dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
  2952. dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
  2953. dev_priv->perf.oa.ops.read = gen7_oa_read;
  2954. dev_priv->perf.oa.ops.oa_hw_tail_read =
  2955. gen7_oa_hw_tail_read;
  2956. dev_priv->perf.oa.oa_formats = hsw_oa_formats;
  2957. } else if (HAS_LOGICAL_RING_CONTEXTS(dev_priv)) {
  2958. /* Note: that although we could theoretically also support the
  2959. * legacy ringbuffer mode on BDW (and earlier iterations of
  2960. * this driver, before upstreaming did this) it didn't seem
  2961. * worth the complexity to maintain now that BDW+ enable
  2962. * execlist mode by default.
  2963. */
  2964. dev_priv->perf.oa.oa_formats = gen8_plus_oa_formats;
  2965. dev_priv->perf.oa.ops.init_oa_buffer = gen8_init_oa_buffer;
  2966. dev_priv->perf.oa.ops.oa_enable = gen8_oa_enable;
  2967. dev_priv->perf.oa.ops.oa_disable = gen8_oa_disable;
  2968. dev_priv->perf.oa.ops.read = gen8_oa_read;
  2969. dev_priv->perf.oa.ops.oa_hw_tail_read = gen8_oa_hw_tail_read;
  2970. if (IS_GEN8(dev_priv) || IS_GEN9(dev_priv)) {
  2971. dev_priv->perf.oa.ops.is_valid_b_counter_reg =
  2972. gen7_is_valid_b_counter_addr;
  2973. dev_priv->perf.oa.ops.is_valid_mux_reg =
  2974. gen8_is_valid_mux_addr;
  2975. dev_priv->perf.oa.ops.is_valid_flex_reg =
  2976. gen8_is_valid_flex_addr;
  2977. if (IS_CHERRYVIEW(dev_priv)) {
  2978. dev_priv->perf.oa.ops.is_valid_mux_reg =
  2979. chv_is_valid_mux_addr;
  2980. }
  2981. dev_priv->perf.oa.ops.enable_metric_set = gen8_enable_metric_set;
  2982. dev_priv->perf.oa.ops.disable_metric_set = gen8_disable_metric_set;
  2983. if (IS_GEN8(dev_priv)) {
  2984. dev_priv->perf.oa.ctx_oactxctrl_offset = 0x120;
  2985. dev_priv->perf.oa.ctx_flexeu0_offset = 0x2ce;
  2986. dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<25);
  2987. } else {
  2988. dev_priv->perf.oa.ctx_oactxctrl_offset = 0x128;
  2989. dev_priv->perf.oa.ctx_flexeu0_offset = 0x3de;
  2990. dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<16);
  2991. }
  2992. } else if (IS_GEN(dev_priv, 10, 11)) {
  2993. dev_priv->perf.oa.ops.is_valid_b_counter_reg =
  2994. gen7_is_valid_b_counter_addr;
  2995. dev_priv->perf.oa.ops.is_valid_mux_reg =
  2996. gen10_is_valid_mux_addr;
  2997. dev_priv->perf.oa.ops.is_valid_flex_reg =
  2998. gen8_is_valid_flex_addr;
  2999. dev_priv->perf.oa.ops.enable_metric_set = gen8_enable_metric_set;
  3000. dev_priv->perf.oa.ops.disable_metric_set = gen10_disable_metric_set;
  3001. dev_priv->perf.oa.ctx_oactxctrl_offset = 0x128;
  3002. dev_priv->perf.oa.ctx_flexeu0_offset = 0x3de;
  3003. dev_priv->perf.oa.gen8_valid_ctx_bit = (1<<16);
  3004. }
  3005. }
  3006. if (dev_priv->perf.oa.ops.enable_metric_set) {
  3007. hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
  3008. CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  3009. dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
  3010. init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
  3011. INIT_LIST_HEAD(&dev_priv->perf.streams);
  3012. mutex_init(&dev_priv->perf.lock);
  3013. spin_lock_init(&dev_priv->perf.oa.oa_buffer.ptr_lock);
  3014. oa_sample_rate_hard_limit = 1000 *
  3015. (INTEL_INFO(dev_priv)->cs_timestamp_frequency_khz / 2);
  3016. dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
  3017. mutex_init(&dev_priv->perf.metrics_lock);
  3018. idr_init(&dev_priv->perf.metrics_idr);
  3019. dev_priv->perf.initialized = true;
  3020. }
  3021. }
  3022. static int destroy_config(int id, void *p, void *data)
  3023. {
  3024. struct drm_i915_private *dev_priv = data;
  3025. struct i915_oa_config *oa_config = p;
  3026. put_oa_config(dev_priv, oa_config);
  3027. return 0;
  3028. }
  3029. /**
  3030. * i915_perf_fini - Counter part to i915_perf_init()
  3031. * @dev_priv: i915 device instance
  3032. */
  3033. void i915_perf_fini(struct drm_i915_private *dev_priv)
  3034. {
  3035. if (!dev_priv->perf.initialized)
  3036. return;
  3037. idr_for_each(&dev_priv->perf.metrics_idr, destroy_config, dev_priv);
  3038. idr_destroy(&dev_priv->perf.metrics_idr);
  3039. unregister_sysctl_table(dev_priv->perf.sysctl_header);
  3040. memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
  3041. dev_priv->perf.initialized = false;
  3042. }