i915_perf.c 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101
  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 "i915_drv.h"
  193. #include "i915_oa_hsw.h"
  194. /* HW requires this to be a power of two, between 128k and 16M, though driver
  195. * is currently generally designed assuming the largest 16M size is used such
  196. * that the overflow cases are unlikely in normal operation.
  197. */
  198. #define OA_BUFFER_SIZE SZ_16M
  199. #define OA_TAKEN(tail, head) ((tail - head) & (OA_BUFFER_SIZE - 1))
  200. /* There's a HW race condition between OA unit tail pointer register updates and
  201. * writes to memory whereby the tail pointer can sometimes get ahead of what's
  202. * been written out to the OA buffer so far.
  203. *
  204. * Although this can be observed explicitly by checking for a zeroed report-id
  205. * field in tail reports, it seems preferable to account for this earlier e.g.
  206. * as part of the _oa_buffer_is_empty checks to minimize -EAGAIN polling cycles
  207. * in this situation.
  208. *
  209. * To give time for the most recent reports to land before they may be copied to
  210. * userspace, the driver operates as if the tail pointer effectively lags behind
  211. * the HW tail pointer by 'tail_margin' bytes. The margin in bytes is calculated
  212. * based on this constant in nanoseconds, the current OA sampling exponent
  213. * and current report size.
  214. *
  215. * There is also a fallback check while reading to simply skip over reports with
  216. * a zeroed report-id.
  217. */
  218. #define OA_TAIL_MARGIN_NSEC 100000ULL
  219. /* frequency for checking whether the OA unit has written new reports to the
  220. * circular OA buffer...
  221. */
  222. #define POLL_FREQUENCY 200
  223. #define POLL_PERIOD (NSEC_PER_SEC / POLL_FREQUENCY)
  224. /* for sysctl proc_dointvec_minmax of dev.i915.perf_stream_paranoid */
  225. static int zero;
  226. static int one = 1;
  227. static u32 i915_perf_stream_paranoid = true;
  228. /* The maximum exponent the hardware accepts is 63 (essentially it selects one
  229. * of the 64bit timestamp bits to trigger reports from) but there's currently
  230. * no known use case for sampling as infrequently as once per 47 thousand years.
  231. *
  232. * Since the timestamps included in OA reports are only 32bits it seems
  233. * reasonable to limit the OA exponent where it's still possible to account for
  234. * overflow in OA report timestamps.
  235. */
  236. #define OA_EXPONENT_MAX 31
  237. #define INVALID_CTX_ID 0xffffffff
  238. /* For sysctl proc_dointvec_minmax of i915_oa_max_sample_rate
  239. *
  240. * 160ns is the smallest sampling period we can theoretically program the OA
  241. * unit with on Haswell, corresponding to 6.25MHz.
  242. */
  243. static int oa_sample_rate_hard_limit = 6250000;
  244. /* Theoretically we can program the OA unit to sample every 160ns but don't
  245. * allow that by default unless root...
  246. *
  247. * The default threshold of 100000Hz is based on perf's similar
  248. * kernel.perf_event_max_sample_rate sysctl parameter.
  249. */
  250. static u32 i915_oa_max_sample_rate = 100000;
  251. /* XXX: beware if future OA HW adds new report formats that the current
  252. * code assumes all reports have a power-of-two size and ~(size - 1) can
  253. * be used as a mask to align the OA tail pointer.
  254. */
  255. static struct i915_oa_format hsw_oa_formats[I915_OA_FORMAT_MAX] = {
  256. [I915_OA_FORMAT_A13] = { 0, 64 },
  257. [I915_OA_FORMAT_A29] = { 1, 128 },
  258. [I915_OA_FORMAT_A13_B8_C8] = { 2, 128 },
  259. /* A29_B8_C8 Disallowed as 192 bytes doesn't factor into buffer size */
  260. [I915_OA_FORMAT_B4_C8] = { 4, 64 },
  261. [I915_OA_FORMAT_A45_B8_C8] = { 5, 256 },
  262. [I915_OA_FORMAT_B4_C8_A16] = { 6, 128 },
  263. [I915_OA_FORMAT_C4_B8] = { 7, 64 },
  264. };
  265. #define SAMPLE_OA_REPORT (1<<0)
  266. /**
  267. * struct perf_open_properties - for validated properties given to open a stream
  268. * @sample_flags: `DRM_I915_PERF_PROP_SAMPLE_*` properties are tracked as flags
  269. * @single_context: Whether a single or all gpu contexts should be monitored
  270. * @ctx_handle: A gem ctx handle for use with @single_context
  271. * @metrics_set: An ID for an OA unit metric set advertised via sysfs
  272. * @oa_format: An OA unit HW report format
  273. * @oa_periodic: Whether to enable periodic OA unit sampling
  274. * @oa_period_exponent: The OA unit sampling period is derived from this
  275. *
  276. * As read_properties_unlocked() enumerates and validates the properties given
  277. * to open a stream of metrics the configuration is built up in the structure
  278. * which starts out zero initialized.
  279. */
  280. struct perf_open_properties {
  281. u32 sample_flags;
  282. u64 single_context:1;
  283. u64 ctx_handle;
  284. /* OA sampling state */
  285. int metrics_set;
  286. int oa_format;
  287. bool oa_periodic;
  288. int oa_period_exponent;
  289. };
  290. /* NB: This is either called via fops or the poll check hrtimer (atomic ctx)
  291. *
  292. * It's safe to read OA config state here unlocked, assuming that this is only
  293. * called while the stream is enabled, while the global OA configuration can't
  294. * be modified.
  295. *
  296. * Note: we don't lock around the head/tail reads even though there's the slim
  297. * possibility of read() fop errors forcing a re-init of the OA buffer
  298. * pointers. A race here could result in a false positive !empty status which
  299. * is acceptable.
  300. */
  301. static bool gen7_oa_buffer_is_empty_fop_unlocked(struct drm_i915_private *dev_priv)
  302. {
  303. int report_size = dev_priv->perf.oa.oa_buffer.format_size;
  304. u32 oastatus2 = I915_READ(GEN7_OASTATUS2);
  305. u32 oastatus1 = I915_READ(GEN7_OASTATUS1);
  306. u32 head = oastatus2 & GEN7_OASTATUS2_HEAD_MASK;
  307. u32 tail = oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
  308. return OA_TAKEN(tail, head) <
  309. dev_priv->perf.oa.tail_margin + report_size;
  310. }
  311. /**
  312. * append_oa_status - Appends a status record to a userspace read() buffer.
  313. * @stream: An i915-perf stream opened for OA metrics
  314. * @buf: destination buffer given by userspace
  315. * @count: the number of bytes userspace wants to read
  316. * @offset: (inout): the current position for writing into @buf
  317. * @type: The kind of status to report to userspace
  318. *
  319. * Writes a status record (such as `DRM_I915_PERF_RECORD_OA_REPORT_LOST`)
  320. * into the userspace read() buffer.
  321. *
  322. * The @buf @offset will only be updated on success.
  323. *
  324. * Returns: 0 on success, negative error code on failure.
  325. */
  326. static int append_oa_status(struct i915_perf_stream *stream,
  327. char __user *buf,
  328. size_t count,
  329. size_t *offset,
  330. enum drm_i915_perf_record_type type)
  331. {
  332. struct drm_i915_perf_record_header header = { type, 0, sizeof(header) };
  333. if ((count - *offset) < header.size)
  334. return -ENOSPC;
  335. if (copy_to_user(buf + *offset, &header, sizeof(header)))
  336. return -EFAULT;
  337. (*offset) += header.size;
  338. return 0;
  339. }
  340. /**
  341. * append_oa_sample - Copies single OA report into userspace read() buffer.
  342. * @stream: An i915-perf stream opened for OA metrics
  343. * @buf: destination buffer given by userspace
  344. * @count: the number of bytes userspace wants to read
  345. * @offset: (inout): the current position for writing into @buf
  346. * @report: A single OA report to (optionally) include as part of the sample
  347. *
  348. * The contents of a sample are configured through `DRM_I915_PERF_PROP_SAMPLE_*`
  349. * properties when opening a stream, tracked as `stream->sample_flags`. This
  350. * function copies the requested components of a single sample to the given
  351. * read() @buf.
  352. *
  353. * The @buf @offset will only be updated on success.
  354. *
  355. * Returns: 0 on success, negative error code on failure.
  356. */
  357. static int append_oa_sample(struct i915_perf_stream *stream,
  358. char __user *buf,
  359. size_t count,
  360. size_t *offset,
  361. const u8 *report)
  362. {
  363. struct drm_i915_private *dev_priv = stream->dev_priv;
  364. int report_size = dev_priv->perf.oa.oa_buffer.format_size;
  365. struct drm_i915_perf_record_header header;
  366. u32 sample_flags = stream->sample_flags;
  367. header.type = DRM_I915_PERF_RECORD_SAMPLE;
  368. header.pad = 0;
  369. header.size = stream->sample_size;
  370. if ((count - *offset) < header.size)
  371. return -ENOSPC;
  372. buf += *offset;
  373. if (copy_to_user(buf, &header, sizeof(header)))
  374. return -EFAULT;
  375. buf += sizeof(header);
  376. if (sample_flags & SAMPLE_OA_REPORT) {
  377. if (copy_to_user(buf, report, report_size))
  378. return -EFAULT;
  379. }
  380. (*offset) += header.size;
  381. return 0;
  382. }
  383. /**
  384. * Copies all buffered OA reports into userspace read() buffer.
  385. * @stream: An i915-perf stream opened for OA metrics
  386. * @buf: destination buffer given by userspace
  387. * @count: the number of bytes userspace wants to read
  388. * @offset: (inout): the current position for writing into @buf
  389. * @head_ptr: (inout): the current oa buffer cpu read position
  390. * @tail: the current oa buffer gpu write position
  391. *
  392. * Notably any error condition resulting in a short read (-%ENOSPC or
  393. * -%EFAULT) will be returned even though one or more records may
  394. * have been successfully copied. In this case it's up to the caller
  395. * to decide if the error should be squashed before returning to
  396. * userspace.
  397. *
  398. * Note: reports are consumed from the head, and appended to the
  399. * tail, so the head chases the tail?... If you think that's mad
  400. * and back-to-front you're not alone, but this follows the
  401. * Gen PRM naming convention.
  402. *
  403. * Returns: 0 on success, negative error code on failure.
  404. */
  405. static int gen7_append_oa_reports(struct i915_perf_stream *stream,
  406. char __user *buf,
  407. size_t count,
  408. size_t *offset,
  409. u32 *head_ptr,
  410. u32 tail)
  411. {
  412. struct drm_i915_private *dev_priv = stream->dev_priv;
  413. int report_size = dev_priv->perf.oa.oa_buffer.format_size;
  414. u8 *oa_buf_base = dev_priv->perf.oa.oa_buffer.vaddr;
  415. int tail_margin = dev_priv->perf.oa.tail_margin;
  416. u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
  417. u32 mask = (OA_BUFFER_SIZE - 1);
  418. u32 head;
  419. u32 taken;
  420. int ret = 0;
  421. if (WARN_ON(!stream->enabled))
  422. return -EIO;
  423. head = *head_ptr - gtt_offset;
  424. tail -= gtt_offset;
  425. /* The OA unit is expected to wrap the tail pointer according to the OA
  426. * buffer size and since we should never write a misaligned head
  427. * pointer we don't expect to read one back either...
  428. */
  429. if (tail > OA_BUFFER_SIZE || head > OA_BUFFER_SIZE ||
  430. head % report_size) {
  431. DRM_ERROR("Inconsistent OA buffer pointer (head = %u, tail = %u): force restart\n",
  432. head, tail);
  433. dev_priv->perf.oa.ops.oa_disable(dev_priv);
  434. dev_priv->perf.oa.ops.oa_enable(dev_priv);
  435. *head_ptr = I915_READ(GEN7_OASTATUS2) &
  436. GEN7_OASTATUS2_HEAD_MASK;
  437. return -EIO;
  438. }
  439. /* The tail pointer increases in 64 byte increments, not in report_size
  440. * steps...
  441. */
  442. tail &= ~(report_size - 1);
  443. /* Move the tail pointer back by the current tail_margin to account for
  444. * the possibility that the latest reports may not have really landed
  445. * in memory yet...
  446. */
  447. if (OA_TAKEN(tail, head) < report_size + tail_margin)
  448. return -EAGAIN;
  449. tail -= tail_margin;
  450. tail &= mask;
  451. for (/* none */;
  452. (taken = OA_TAKEN(tail, head));
  453. head = (head + report_size) & mask) {
  454. u8 *report = oa_buf_base + head;
  455. u32 *report32 = (void *)report;
  456. /* All the report sizes factor neatly into the buffer
  457. * size so we never expect to see a report split
  458. * between the beginning and end of the buffer.
  459. *
  460. * Given the initial alignment check a misalignment
  461. * here would imply a driver bug that would result
  462. * in an overrun.
  463. */
  464. if (WARN_ON((OA_BUFFER_SIZE - head) < report_size)) {
  465. DRM_ERROR("Spurious OA head ptr: non-integral report offset\n");
  466. break;
  467. }
  468. /* The report-ID field for periodic samples includes
  469. * some undocumented flags related to what triggered
  470. * the report and is never expected to be zero so we
  471. * can check that the report isn't invalid before
  472. * copying it to userspace...
  473. */
  474. if (report32[0] == 0) {
  475. DRM_NOTE("Skipping spurious, invalid OA report\n");
  476. continue;
  477. }
  478. ret = append_oa_sample(stream, buf, count, offset, report);
  479. if (ret)
  480. break;
  481. /* The above report-id field sanity check is based on
  482. * the assumption that the OA buffer is initially
  483. * zeroed and we reset the field after copying so the
  484. * check is still meaningful once old reports start
  485. * being overwritten.
  486. */
  487. report32[0] = 0;
  488. }
  489. *head_ptr = gtt_offset + head;
  490. return ret;
  491. }
  492. /**
  493. * gen7_oa_read - copy status records then buffered OA reports
  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. *
  499. * Checks Gen 7 specific OA unit status registers and if necessary appends
  500. * corresponding status records for userspace (such as for a buffer full
  501. * condition) and then initiate appending any buffered OA reports.
  502. *
  503. * Updates @offset according to the number of bytes successfully copied into
  504. * the userspace buffer.
  505. *
  506. * Returns: zero on success or a negative error code
  507. */
  508. static int gen7_oa_read(struct i915_perf_stream *stream,
  509. char __user *buf,
  510. size_t count,
  511. size_t *offset)
  512. {
  513. struct drm_i915_private *dev_priv = stream->dev_priv;
  514. int report_size = dev_priv->perf.oa.oa_buffer.format_size;
  515. u32 oastatus2;
  516. u32 oastatus1;
  517. u32 head;
  518. u32 tail;
  519. int ret;
  520. if (WARN_ON(!dev_priv->perf.oa.oa_buffer.vaddr))
  521. return -EIO;
  522. oastatus2 = I915_READ(GEN7_OASTATUS2);
  523. oastatus1 = I915_READ(GEN7_OASTATUS1);
  524. head = oastatus2 & GEN7_OASTATUS2_HEAD_MASK;
  525. tail = oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
  526. /* XXX: On Haswell we don't have a safe way to clear oastatus1
  527. * bits while the OA unit is enabled (while the tail pointer
  528. * may be updated asynchronously) so we ignore status bits
  529. * that have already been reported to userspace.
  530. */
  531. oastatus1 &= ~dev_priv->perf.oa.gen7_latched_oastatus1;
  532. /* We treat OABUFFER_OVERFLOW as a significant error:
  533. *
  534. * - The status can be interpreted to mean that the buffer is
  535. * currently full (with a higher precedence than OA_TAKEN()
  536. * which will start to report a near-empty buffer after an
  537. * overflow) but it's awkward that we can't clear the status
  538. * on Haswell, so without a reset we won't be able to catch
  539. * the state again.
  540. *
  541. * - Since it also implies the HW has started overwriting old
  542. * reports it may also affect our sanity checks for invalid
  543. * reports when copying to userspace that assume new reports
  544. * are being written to cleared memory.
  545. *
  546. * - In the future we may want to introduce a flight recorder
  547. * mode where the driver will automatically maintain a safe
  548. * guard band between head/tail, avoiding this overflow
  549. * condition, but we avoid the added driver complexity for
  550. * now.
  551. */
  552. if (unlikely(oastatus1 & GEN7_OASTATUS1_OABUFFER_OVERFLOW)) {
  553. ret = append_oa_status(stream, buf, count, offset,
  554. DRM_I915_PERF_RECORD_OA_BUFFER_LOST);
  555. if (ret)
  556. return ret;
  557. DRM_DEBUG("OA buffer overflow: force restart\n");
  558. dev_priv->perf.oa.ops.oa_disable(dev_priv);
  559. dev_priv->perf.oa.ops.oa_enable(dev_priv);
  560. oastatus2 = I915_READ(GEN7_OASTATUS2);
  561. oastatus1 = I915_READ(GEN7_OASTATUS1);
  562. head = oastatus2 & GEN7_OASTATUS2_HEAD_MASK;
  563. tail = oastatus1 & GEN7_OASTATUS1_TAIL_MASK;
  564. }
  565. if (unlikely(oastatus1 & GEN7_OASTATUS1_REPORT_LOST)) {
  566. ret = append_oa_status(stream, buf, count, offset,
  567. DRM_I915_PERF_RECORD_OA_REPORT_LOST);
  568. if (ret)
  569. return ret;
  570. dev_priv->perf.oa.gen7_latched_oastatus1 |=
  571. GEN7_OASTATUS1_REPORT_LOST;
  572. }
  573. ret = gen7_append_oa_reports(stream, buf, count, offset,
  574. &head, tail);
  575. /* All the report sizes are a power of two and the
  576. * head should always be incremented by some multiple
  577. * of the report size.
  578. *
  579. * A warning here, but notably if we later read back a
  580. * misaligned pointer we will treat that as a bug since
  581. * it could lead to a buffer overrun.
  582. */
  583. WARN_ONCE(head & (report_size - 1),
  584. "i915: Writing misaligned OA head pointer");
  585. /* Note: we update the head pointer here even if an error
  586. * was returned since the error may represent a short read
  587. * where some some reports were successfully copied.
  588. */
  589. I915_WRITE(GEN7_OASTATUS2,
  590. ((head & GEN7_OASTATUS2_HEAD_MASK) |
  591. OA_MEM_SELECT_GGTT));
  592. return ret;
  593. }
  594. /**
  595. * i915_oa_wait_unlocked - handles blocking IO until OA data available
  596. * @stream: An i915-perf stream opened for OA metrics
  597. *
  598. * Called when userspace tries to read() from a blocking stream FD opened
  599. * for OA metrics. It waits until the hrtimer callback finds a non-empty
  600. * OA buffer and wakes us.
  601. *
  602. * Note: it's acceptable to have this return with some false positives
  603. * since any subsequent read handling will return -EAGAIN if there isn't
  604. * really data ready for userspace yet.
  605. *
  606. * Returns: zero on success or a negative error code
  607. */
  608. static int i915_oa_wait_unlocked(struct i915_perf_stream *stream)
  609. {
  610. struct drm_i915_private *dev_priv = stream->dev_priv;
  611. /* We would wait indefinitely if periodic sampling is not enabled */
  612. if (!dev_priv->perf.oa.periodic)
  613. return -EIO;
  614. /* Note: the oa_buffer_is_empty() condition is ok to run unlocked as it
  615. * just performs mmio reads of the OA buffer head + tail pointers and
  616. * it's assumed we're handling some operation that implies the stream
  617. * can't be destroyed until completion (such as a read()) that ensures
  618. * the device + OA buffer can't disappear
  619. */
  620. return wait_event_interruptible(dev_priv->perf.oa.poll_wq,
  621. !dev_priv->perf.oa.ops.oa_buffer_is_empty(dev_priv));
  622. }
  623. /**
  624. * i915_oa_poll_wait - call poll_wait() for an OA stream poll()
  625. * @stream: An i915-perf stream opened for OA metrics
  626. * @file: An i915 perf stream file
  627. * @wait: poll() state table
  628. *
  629. * For handling userspace polling on an i915 perf stream opened for OA metrics,
  630. * this starts a poll_wait with the wait queue that our hrtimer callback wakes
  631. * when it sees data ready to read in the circular OA buffer.
  632. */
  633. static void i915_oa_poll_wait(struct i915_perf_stream *stream,
  634. struct file *file,
  635. poll_table *wait)
  636. {
  637. struct drm_i915_private *dev_priv = stream->dev_priv;
  638. poll_wait(file, &dev_priv->perf.oa.poll_wq, wait);
  639. }
  640. /**
  641. * i915_oa_read - just calls through to &i915_oa_ops->read
  642. * @stream: An i915-perf stream opened for OA metrics
  643. * @buf: destination buffer given by userspace
  644. * @count: the number of bytes userspace wants to read
  645. * @offset: (inout): the current position for writing into @buf
  646. *
  647. * Updates @offset according to the number of bytes successfully copied into
  648. * the userspace buffer.
  649. *
  650. * Returns: zero on success or a negative error code
  651. */
  652. static int i915_oa_read(struct i915_perf_stream *stream,
  653. char __user *buf,
  654. size_t count,
  655. size_t *offset)
  656. {
  657. struct drm_i915_private *dev_priv = stream->dev_priv;
  658. return dev_priv->perf.oa.ops.read(stream, buf, count, offset);
  659. }
  660. /**
  661. * oa_get_render_ctx_id - determine and hold ctx hw id
  662. * @stream: An i915-perf stream opened for OA metrics
  663. *
  664. * Determine the render context hw id, and ensure it remains fixed for the
  665. * lifetime of the stream. This ensures that we don't have to worry about
  666. * updating the context ID in OACONTROL on the fly.
  667. *
  668. * Returns: zero on success or a negative error code
  669. */
  670. static int oa_get_render_ctx_id(struct i915_perf_stream *stream)
  671. {
  672. struct drm_i915_private *dev_priv = stream->dev_priv;
  673. struct intel_engine_cs *engine = dev_priv->engine[RCS];
  674. int ret;
  675. ret = i915_mutex_lock_interruptible(&dev_priv->drm);
  676. if (ret)
  677. return ret;
  678. /* As the ID is the gtt offset of the context's vma we pin
  679. * the vma to ensure the ID remains fixed.
  680. *
  681. * NB: implied RCS engine...
  682. */
  683. ret = engine->context_pin(engine, stream->ctx);
  684. if (ret)
  685. goto unlock;
  686. /* Explicitly track the ID (instead of calling i915_ggtt_offset()
  687. * on the fly) considering the difference with gen8+ and
  688. * execlists
  689. */
  690. dev_priv->perf.oa.specific_ctx_id =
  691. i915_ggtt_offset(stream->ctx->engine[engine->id].state);
  692. unlock:
  693. mutex_unlock(&dev_priv->drm.struct_mutex);
  694. return ret;
  695. }
  696. /**
  697. * oa_put_render_ctx_id - counterpart to oa_get_render_ctx_id releases hold
  698. * @stream: An i915-perf stream opened for OA metrics
  699. *
  700. * In case anything needed doing to ensure the context HW ID would remain valid
  701. * for the lifetime of the stream, then that can be undone here.
  702. */
  703. static void oa_put_render_ctx_id(struct i915_perf_stream *stream)
  704. {
  705. struct drm_i915_private *dev_priv = stream->dev_priv;
  706. struct intel_engine_cs *engine = dev_priv->engine[RCS];
  707. mutex_lock(&dev_priv->drm.struct_mutex);
  708. dev_priv->perf.oa.specific_ctx_id = INVALID_CTX_ID;
  709. engine->context_unpin(engine, stream->ctx);
  710. mutex_unlock(&dev_priv->drm.struct_mutex);
  711. }
  712. static void
  713. free_oa_buffer(struct drm_i915_private *i915)
  714. {
  715. mutex_lock(&i915->drm.struct_mutex);
  716. i915_gem_object_unpin_map(i915->perf.oa.oa_buffer.vma->obj);
  717. i915_vma_unpin(i915->perf.oa.oa_buffer.vma);
  718. i915_gem_object_put(i915->perf.oa.oa_buffer.vma->obj);
  719. i915->perf.oa.oa_buffer.vma = NULL;
  720. i915->perf.oa.oa_buffer.vaddr = NULL;
  721. mutex_unlock(&i915->drm.struct_mutex);
  722. }
  723. static void i915_oa_stream_destroy(struct i915_perf_stream *stream)
  724. {
  725. struct drm_i915_private *dev_priv = stream->dev_priv;
  726. BUG_ON(stream != dev_priv->perf.oa.exclusive_stream);
  727. dev_priv->perf.oa.ops.disable_metric_set(dev_priv);
  728. free_oa_buffer(dev_priv);
  729. intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
  730. intel_runtime_pm_put(dev_priv);
  731. if (stream->ctx)
  732. oa_put_render_ctx_id(stream);
  733. dev_priv->perf.oa.exclusive_stream = NULL;
  734. }
  735. static void gen7_init_oa_buffer(struct drm_i915_private *dev_priv)
  736. {
  737. u32 gtt_offset = i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma);
  738. /* Pre-DevBDW: OABUFFER must be set with counters off,
  739. * before OASTATUS1, but after OASTATUS2
  740. */
  741. I915_WRITE(GEN7_OASTATUS2, gtt_offset | OA_MEM_SELECT_GGTT); /* head */
  742. I915_WRITE(GEN7_OABUFFER, gtt_offset);
  743. I915_WRITE(GEN7_OASTATUS1, gtt_offset | OABUFFER_SIZE_16M); /* tail */
  744. /* On Haswell we have to track which OASTATUS1 flags we've
  745. * already seen since they can't be cleared while periodic
  746. * sampling is enabled.
  747. */
  748. dev_priv->perf.oa.gen7_latched_oastatus1 = 0;
  749. /* NB: although the OA buffer will initially be allocated
  750. * zeroed via shmfs (and so this memset is redundant when
  751. * first allocating), we may re-init the OA buffer, either
  752. * when re-enabling a stream or in error/reset paths.
  753. *
  754. * The reason we clear the buffer for each re-init is for the
  755. * sanity check in gen7_append_oa_reports() that looks at the
  756. * report-id field to make sure it's non-zero which relies on
  757. * the assumption that new reports are being written to zeroed
  758. * memory...
  759. */
  760. memset(dev_priv->perf.oa.oa_buffer.vaddr, 0, OA_BUFFER_SIZE);
  761. /* Maybe make ->pollin per-stream state if we support multiple
  762. * concurrent streams in the future.
  763. */
  764. dev_priv->perf.oa.pollin = false;
  765. }
  766. static int alloc_oa_buffer(struct drm_i915_private *dev_priv)
  767. {
  768. struct drm_i915_gem_object *bo;
  769. struct i915_vma *vma;
  770. int ret;
  771. if (WARN_ON(dev_priv->perf.oa.oa_buffer.vma))
  772. return -ENODEV;
  773. ret = i915_mutex_lock_interruptible(&dev_priv->drm);
  774. if (ret)
  775. return ret;
  776. BUILD_BUG_ON_NOT_POWER_OF_2(OA_BUFFER_SIZE);
  777. BUILD_BUG_ON(OA_BUFFER_SIZE < SZ_128K || OA_BUFFER_SIZE > SZ_16M);
  778. bo = i915_gem_object_create(dev_priv, OA_BUFFER_SIZE);
  779. if (IS_ERR(bo)) {
  780. DRM_ERROR("Failed to allocate OA buffer\n");
  781. ret = PTR_ERR(bo);
  782. goto unlock;
  783. }
  784. ret = i915_gem_object_set_cache_level(bo, I915_CACHE_LLC);
  785. if (ret)
  786. goto err_unref;
  787. /* PreHSW required 512K alignment, HSW requires 16M */
  788. vma = i915_gem_object_ggtt_pin(bo, NULL, 0, SZ_16M, 0);
  789. if (IS_ERR(vma)) {
  790. ret = PTR_ERR(vma);
  791. goto err_unref;
  792. }
  793. dev_priv->perf.oa.oa_buffer.vma = vma;
  794. dev_priv->perf.oa.oa_buffer.vaddr =
  795. i915_gem_object_pin_map(bo, I915_MAP_WB);
  796. if (IS_ERR(dev_priv->perf.oa.oa_buffer.vaddr)) {
  797. ret = PTR_ERR(dev_priv->perf.oa.oa_buffer.vaddr);
  798. goto err_unpin;
  799. }
  800. dev_priv->perf.oa.ops.init_oa_buffer(dev_priv);
  801. DRM_DEBUG_DRIVER("OA Buffer initialized, gtt offset = 0x%x, vaddr = %p\n",
  802. i915_ggtt_offset(dev_priv->perf.oa.oa_buffer.vma),
  803. dev_priv->perf.oa.oa_buffer.vaddr);
  804. goto unlock;
  805. err_unpin:
  806. __i915_vma_unpin(vma);
  807. err_unref:
  808. i915_gem_object_put(bo);
  809. dev_priv->perf.oa.oa_buffer.vaddr = NULL;
  810. dev_priv->perf.oa.oa_buffer.vma = NULL;
  811. unlock:
  812. mutex_unlock(&dev_priv->drm.struct_mutex);
  813. return ret;
  814. }
  815. static void config_oa_regs(struct drm_i915_private *dev_priv,
  816. const struct i915_oa_reg *regs,
  817. int n_regs)
  818. {
  819. int i;
  820. for (i = 0; i < n_regs; i++) {
  821. const struct i915_oa_reg *reg = regs + i;
  822. I915_WRITE(reg->addr, reg->value);
  823. }
  824. }
  825. static int hsw_enable_metric_set(struct drm_i915_private *dev_priv)
  826. {
  827. int ret = i915_oa_select_metric_set_hsw(dev_priv);
  828. if (ret)
  829. return ret;
  830. I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) |
  831. GT_NOA_ENABLE));
  832. /* PRM:
  833. *
  834. * OA unit is using “crclk” for its functionality. When trunk
  835. * level clock gating takes place, OA clock would be gated,
  836. * unable to count the events from non-render clock domain.
  837. * Render clock gating must be disabled when OA is enabled to
  838. * count the events from non-render domain. Unit level clock
  839. * gating for RCS should also be disabled.
  840. */
  841. I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) &
  842. ~GEN7_DOP_CLOCK_GATE_ENABLE));
  843. I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) |
  844. GEN6_CSUNIT_CLOCK_GATE_DISABLE));
  845. config_oa_regs(dev_priv, dev_priv->perf.oa.mux_regs,
  846. dev_priv->perf.oa.mux_regs_len);
  847. /* It apparently takes a fairly long time for a new MUX
  848. * configuration to be be applied after these register writes.
  849. * This delay duration was derived empirically based on the
  850. * render_basic config but hopefully it covers the maximum
  851. * configuration latency.
  852. *
  853. * As a fallback, the checks in _append_oa_reports() to skip
  854. * invalid OA reports do also seem to work to discard reports
  855. * generated before this config has completed - albeit not
  856. * silently.
  857. *
  858. * Unfortunately this is essentially a magic number, since we
  859. * don't currently know of a reliable mechanism for predicting
  860. * how long the MUX config will take to apply and besides
  861. * seeing invalid reports we don't know of a reliable way to
  862. * explicitly check that the MUX config has landed.
  863. *
  864. * It's even possible we've miss characterized the underlying
  865. * problem - it just seems like the simplest explanation why
  866. * a delay at this location would mitigate any invalid reports.
  867. */
  868. usleep_range(15000, 20000);
  869. config_oa_regs(dev_priv, dev_priv->perf.oa.b_counter_regs,
  870. dev_priv->perf.oa.b_counter_regs_len);
  871. return 0;
  872. }
  873. static void hsw_disable_metric_set(struct drm_i915_private *dev_priv)
  874. {
  875. I915_WRITE(GEN6_UCGCTL1, (I915_READ(GEN6_UCGCTL1) &
  876. ~GEN6_CSUNIT_CLOCK_GATE_DISABLE));
  877. I915_WRITE(GEN7_MISCCPCTL, (I915_READ(GEN7_MISCCPCTL) |
  878. GEN7_DOP_CLOCK_GATE_ENABLE));
  879. I915_WRITE(GDT_CHICKEN_BITS, (I915_READ(GDT_CHICKEN_BITS) &
  880. ~GT_NOA_ENABLE));
  881. }
  882. static void gen7_update_oacontrol_locked(struct drm_i915_private *dev_priv)
  883. {
  884. lockdep_assert_held(&dev_priv->perf.hook_lock);
  885. if (dev_priv->perf.oa.exclusive_stream->enabled) {
  886. struct i915_gem_context *ctx =
  887. dev_priv->perf.oa.exclusive_stream->ctx;
  888. u32 ctx_id = dev_priv->perf.oa.specific_ctx_id;
  889. bool periodic = dev_priv->perf.oa.periodic;
  890. u32 period_exponent = dev_priv->perf.oa.period_exponent;
  891. u32 report_format = dev_priv->perf.oa.oa_buffer.format;
  892. I915_WRITE(GEN7_OACONTROL,
  893. (ctx_id & GEN7_OACONTROL_CTX_MASK) |
  894. (period_exponent <<
  895. GEN7_OACONTROL_TIMER_PERIOD_SHIFT) |
  896. (periodic ? GEN7_OACONTROL_TIMER_ENABLE : 0) |
  897. (report_format << GEN7_OACONTROL_FORMAT_SHIFT) |
  898. (ctx ? GEN7_OACONTROL_PER_CTX_ENABLE : 0) |
  899. GEN7_OACONTROL_ENABLE);
  900. } else
  901. I915_WRITE(GEN7_OACONTROL, 0);
  902. }
  903. static void gen7_oa_enable(struct drm_i915_private *dev_priv)
  904. {
  905. unsigned long flags;
  906. /* Reset buf pointers so we don't forward reports from before now.
  907. *
  908. * Think carefully if considering trying to avoid this, since it
  909. * also ensures status flags and the buffer itself are cleared
  910. * in error paths, and we have checks for invalid reports based
  911. * on the assumption that certain fields are written to zeroed
  912. * memory which this helps maintains.
  913. */
  914. gen7_init_oa_buffer(dev_priv);
  915. spin_lock_irqsave(&dev_priv->perf.hook_lock, flags);
  916. gen7_update_oacontrol_locked(dev_priv);
  917. spin_unlock_irqrestore(&dev_priv->perf.hook_lock, flags);
  918. }
  919. /**
  920. * i915_oa_stream_enable - handle `I915_PERF_IOCTL_ENABLE` for OA stream
  921. * @stream: An i915 perf stream opened for OA metrics
  922. *
  923. * [Re]enables hardware periodic sampling according to the period configured
  924. * when opening the stream. This also starts a hrtimer that will periodically
  925. * check for data in the circular OA buffer for notifying userspace (e.g.
  926. * during a read() or poll()).
  927. */
  928. static void i915_oa_stream_enable(struct i915_perf_stream *stream)
  929. {
  930. struct drm_i915_private *dev_priv = stream->dev_priv;
  931. dev_priv->perf.oa.ops.oa_enable(dev_priv);
  932. if (dev_priv->perf.oa.periodic)
  933. hrtimer_start(&dev_priv->perf.oa.poll_check_timer,
  934. ns_to_ktime(POLL_PERIOD),
  935. HRTIMER_MODE_REL_PINNED);
  936. }
  937. static void gen7_oa_disable(struct drm_i915_private *dev_priv)
  938. {
  939. I915_WRITE(GEN7_OACONTROL, 0);
  940. }
  941. /**
  942. * i915_oa_stream_disable - handle `I915_PERF_IOCTL_DISABLE` for OA stream
  943. * @stream: An i915 perf stream opened for OA metrics
  944. *
  945. * Stops the OA unit from periodically writing counter reports into the
  946. * circular OA buffer. This also stops the hrtimer that periodically checks for
  947. * data in the circular OA buffer, for notifying userspace.
  948. */
  949. static void i915_oa_stream_disable(struct i915_perf_stream *stream)
  950. {
  951. struct drm_i915_private *dev_priv = stream->dev_priv;
  952. dev_priv->perf.oa.ops.oa_disable(dev_priv);
  953. if (dev_priv->perf.oa.periodic)
  954. hrtimer_cancel(&dev_priv->perf.oa.poll_check_timer);
  955. }
  956. static u64 oa_exponent_to_ns(struct drm_i915_private *dev_priv, int exponent)
  957. {
  958. return div_u64(1000000000ULL * (2ULL << exponent),
  959. dev_priv->perf.oa.timestamp_frequency);
  960. }
  961. static const struct i915_perf_stream_ops i915_oa_stream_ops = {
  962. .destroy = i915_oa_stream_destroy,
  963. .enable = i915_oa_stream_enable,
  964. .disable = i915_oa_stream_disable,
  965. .wait_unlocked = i915_oa_wait_unlocked,
  966. .poll_wait = i915_oa_poll_wait,
  967. .read = i915_oa_read,
  968. };
  969. /**
  970. * i915_oa_stream_init - validate combined props for OA stream and init
  971. * @stream: An i915 perf stream
  972. * @param: The open parameters passed to `DRM_I915_PERF_OPEN`
  973. * @props: The property state that configures stream (individually validated)
  974. *
  975. * While read_properties_unlocked() validates properties in isolation it
  976. * doesn't ensure that the combination necessarily makes sense.
  977. *
  978. * At this point it has been determined that userspace wants a stream of
  979. * OA metrics, but still we need to further validate the combined
  980. * properties are OK.
  981. *
  982. * If the configuration makes sense then we can allocate memory for
  983. * a circular OA buffer and apply the requested metric set configuration.
  984. *
  985. * Returns: zero on success or a negative error code.
  986. */
  987. static int i915_oa_stream_init(struct i915_perf_stream *stream,
  988. struct drm_i915_perf_open_param *param,
  989. struct perf_open_properties *props)
  990. {
  991. struct drm_i915_private *dev_priv = stream->dev_priv;
  992. int format_size;
  993. int ret;
  994. /* If the sysfs metrics/ directory wasn't registered for some
  995. * reason then don't let userspace try their luck with config
  996. * IDs
  997. */
  998. if (!dev_priv->perf.metrics_kobj) {
  999. DRM_DEBUG("OA metrics weren't advertised via sysfs\n");
  1000. return -EINVAL;
  1001. }
  1002. if (!(props->sample_flags & SAMPLE_OA_REPORT)) {
  1003. DRM_DEBUG("Only OA report sampling supported\n");
  1004. return -EINVAL;
  1005. }
  1006. if (!dev_priv->perf.oa.ops.init_oa_buffer) {
  1007. DRM_DEBUG("OA unit not supported\n");
  1008. return -ENODEV;
  1009. }
  1010. /* To avoid the complexity of having to accurately filter
  1011. * counter reports and marshal to the appropriate client
  1012. * we currently only allow exclusive access
  1013. */
  1014. if (dev_priv->perf.oa.exclusive_stream) {
  1015. DRM_DEBUG("OA unit already in use\n");
  1016. return -EBUSY;
  1017. }
  1018. if (!props->metrics_set) {
  1019. DRM_DEBUG("OA metric set not specified\n");
  1020. return -EINVAL;
  1021. }
  1022. if (!props->oa_format) {
  1023. DRM_DEBUG("OA report format not specified\n");
  1024. return -EINVAL;
  1025. }
  1026. stream->sample_size = sizeof(struct drm_i915_perf_record_header);
  1027. format_size = dev_priv->perf.oa.oa_formats[props->oa_format].size;
  1028. stream->sample_flags |= SAMPLE_OA_REPORT;
  1029. stream->sample_size += format_size;
  1030. dev_priv->perf.oa.oa_buffer.format_size = format_size;
  1031. if (WARN_ON(dev_priv->perf.oa.oa_buffer.format_size == 0))
  1032. return -EINVAL;
  1033. dev_priv->perf.oa.oa_buffer.format =
  1034. dev_priv->perf.oa.oa_formats[props->oa_format].format;
  1035. dev_priv->perf.oa.metrics_set = props->metrics_set;
  1036. dev_priv->perf.oa.periodic = props->oa_periodic;
  1037. if (dev_priv->perf.oa.periodic) {
  1038. u32 tail;
  1039. dev_priv->perf.oa.period_exponent = props->oa_period_exponent;
  1040. /* See comment for OA_TAIL_MARGIN_NSEC for details
  1041. * about this tail_margin...
  1042. */
  1043. tail = div64_u64(OA_TAIL_MARGIN_NSEC,
  1044. oa_exponent_to_ns(dev_priv,
  1045. props->oa_period_exponent));
  1046. dev_priv->perf.oa.tail_margin = (tail + 1) * format_size;
  1047. }
  1048. if (stream->ctx) {
  1049. ret = oa_get_render_ctx_id(stream);
  1050. if (ret)
  1051. return ret;
  1052. }
  1053. ret = alloc_oa_buffer(dev_priv);
  1054. if (ret)
  1055. goto err_oa_buf_alloc;
  1056. /* PRM - observability performance counters:
  1057. *
  1058. * OACONTROL, performance counter enable, note:
  1059. *
  1060. * "When this bit is set, in order to have coherent counts,
  1061. * RC6 power state and trunk clock gating must be disabled.
  1062. * This can be achieved by programming MMIO registers as
  1063. * 0xA094=0 and 0xA090[31]=1"
  1064. *
  1065. * In our case we are expecting that taking pm + FORCEWAKE
  1066. * references will effectively disable RC6.
  1067. */
  1068. intel_runtime_pm_get(dev_priv);
  1069. intel_uncore_forcewake_get(dev_priv, FORCEWAKE_ALL);
  1070. ret = dev_priv->perf.oa.ops.enable_metric_set(dev_priv);
  1071. if (ret)
  1072. goto err_enable;
  1073. stream->ops = &i915_oa_stream_ops;
  1074. dev_priv->perf.oa.exclusive_stream = stream;
  1075. return 0;
  1076. err_enable:
  1077. intel_uncore_forcewake_put(dev_priv, FORCEWAKE_ALL);
  1078. intel_runtime_pm_put(dev_priv);
  1079. free_oa_buffer(dev_priv);
  1080. err_oa_buf_alloc:
  1081. if (stream->ctx)
  1082. oa_put_render_ctx_id(stream);
  1083. return ret;
  1084. }
  1085. /**
  1086. * i915_perf_read_locked - &i915_perf_stream_ops->read with error normalisation
  1087. * @stream: An i915 perf stream
  1088. * @file: An i915 perf stream file
  1089. * @buf: destination buffer given by userspace
  1090. * @count: the number of bytes userspace wants to read
  1091. * @ppos: (inout) file seek position (unused)
  1092. *
  1093. * Besides wrapping &i915_perf_stream_ops->read this provides a common place to
  1094. * ensure that if we've successfully copied any data then reporting that takes
  1095. * precedence over any internal error status, so the data isn't lost.
  1096. *
  1097. * For example ret will be -ENOSPC whenever there is more buffered data than
  1098. * can be copied to userspace, but that's only interesting if we weren't able
  1099. * to copy some data because it implies the userspace buffer is too small to
  1100. * receive a single record (and we never split records).
  1101. *
  1102. * Another case with ret == -EFAULT is more of a grey area since it would seem
  1103. * like bad form for userspace to ask us to overrun its buffer, but the user
  1104. * knows best:
  1105. *
  1106. * http://yarchive.net/comp/linux/partial_reads_writes.html
  1107. *
  1108. * Returns: The number of bytes copied or a negative error code on failure.
  1109. */
  1110. static ssize_t i915_perf_read_locked(struct i915_perf_stream *stream,
  1111. struct file *file,
  1112. char __user *buf,
  1113. size_t count,
  1114. loff_t *ppos)
  1115. {
  1116. /* Note we keep the offset (aka bytes read) separate from any
  1117. * error status so that the final check for whether we return
  1118. * the bytes read with a higher precedence than any error (see
  1119. * comment below) doesn't need to be handled/duplicated in
  1120. * stream->ops->read() implementations.
  1121. */
  1122. size_t offset = 0;
  1123. int ret = stream->ops->read(stream, buf, count, &offset);
  1124. return offset ?: (ret ?: -EAGAIN);
  1125. }
  1126. /**
  1127. * i915_perf_read - handles read() FOP for i915 perf stream FDs
  1128. * @file: An i915 perf stream file
  1129. * @buf: destination buffer given by userspace
  1130. * @count: the number of bytes userspace wants to read
  1131. * @ppos: (inout) file seek position (unused)
  1132. *
  1133. * The entry point for handling a read() on a stream file descriptor from
  1134. * userspace. Most of the work is left to the i915_perf_read_locked() and
  1135. * &i915_perf_stream_ops->read but to save having stream implementations (of
  1136. * which we might have multiple later) we handle blocking read here.
  1137. *
  1138. * We can also consistently treat trying to read from a disabled stream
  1139. * as an IO error so implementations can assume the stream is enabled
  1140. * while reading.
  1141. *
  1142. * Returns: The number of bytes copied or a negative error code on failure.
  1143. */
  1144. static ssize_t i915_perf_read(struct file *file,
  1145. char __user *buf,
  1146. size_t count,
  1147. loff_t *ppos)
  1148. {
  1149. struct i915_perf_stream *stream = file->private_data;
  1150. struct drm_i915_private *dev_priv = stream->dev_priv;
  1151. ssize_t ret;
  1152. /* To ensure it's handled consistently we simply treat all reads of a
  1153. * disabled stream as an error. In particular it might otherwise lead
  1154. * to a deadlock for blocking file descriptors...
  1155. */
  1156. if (!stream->enabled)
  1157. return -EIO;
  1158. if (!(file->f_flags & O_NONBLOCK)) {
  1159. /* There's the small chance of false positives from
  1160. * stream->ops->wait_unlocked.
  1161. *
  1162. * E.g. with single context filtering since we only wait until
  1163. * oabuffer has >= 1 report we don't immediately know whether
  1164. * any reports really belong to the current context
  1165. */
  1166. do {
  1167. ret = stream->ops->wait_unlocked(stream);
  1168. if (ret)
  1169. return ret;
  1170. mutex_lock(&dev_priv->perf.lock);
  1171. ret = i915_perf_read_locked(stream, file,
  1172. buf, count, ppos);
  1173. mutex_unlock(&dev_priv->perf.lock);
  1174. } while (ret == -EAGAIN);
  1175. } else {
  1176. mutex_lock(&dev_priv->perf.lock);
  1177. ret = i915_perf_read_locked(stream, file, buf, count, ppos);
  1178. mutex_unlock(&dev_priv->perf.lock);
  1179. }
  1180. if (ret >= 0) {
  1181. /* Maybe make ->pollin per-stream state if we support multiple
  1182. * concurrent streams in the future.
  1183. */
  1184. dev_priv->perf.oa.pollin = false;
  1185. }
  1186. return ret;
  1187. }
  1188. static enum hrtimer_restart oa_poll_check_timer_cb(struct hrtimer *hrtimer)
  1189. {
  1190. struct drm_i915_private *dev_priv =
  1191. container_of(hrtimer, typeof(*dev_priv),
  1192. perf.oa.poll_check_timer);
  1193. if (!dev_priv->perf.oa.ops.oa_buffer_is_empty(dev_priv)) {
  1194. dev_priv->perf.oa.pollin = true;
  1195. wake_up(&dev_priv->perf.oa.poll_wq);
  1196. }
  1197. hrtimer_forward_now(hrtimer, ns_to_ktime(POLL_PERIOD));
  1198. return HRTIMER_RESTART;
  1199. }
  1200. /**
  1201. * i915_perf_poll_locked - poll_wait() with a suitable wait queue for stream
  1202. * @dev_priv: i915 device instance
  1203. * @stream: An i915 perf stream
  1204. * @file: An i915 perf stream file
  1205. * @wait: poll() state table
  1206. *
  1207. * For handling userspace polling on an i915 perf stream, this calls through to
  1208. * &i915_perf_stream_ops->poll_wait to call poll_wait() with a wait queue that
  1209. * will be woken for new stream data.
  1210. *
  1211. * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
  1212. * with any non-file-operation driver hooks.
  1213. *
  1214. * Returns: any poll events that are ready without sleeping
  1215. */
  1216. static unsigned int i915_perf_poll_locked(struct drm_i915_private *dev_priv,
  1217. struct i915_perf_stream *stream,
  1218. struct file *file,
  1219. poll_table *wait)
  1220. {
  1221. unsigned int events = 0;
  1222. stream->ops->poll_wait(stream, file, wait);
  1223. /* Note: we don't explicitly check whether there's something to read
  1224. * here since this path may be very hot depending on what else
  1225. * userspace is polling, or on the timeout in use. We rely solely on
  1226. * the hrtimer/oa_poll_check_timer_cb to notify us when there are
  1227. * samples to read.
  1228. */
  1229. if (dev_priv->perf.oa.pollin)
  1230. events |= POLLIN;
  1231. return events;
  1232. }
  1233. /**
  1234. * i915_perf_poll - call poll_wait() with a suitable wait queue for stream
  1235. * @file: An i915 perf stream file
  1236. * @wait: poll() state table
  1237. *
  1238. * For handling userspace polling on an i915 perf stream, this ensures
  1239. * poll_wait() gets called with a wait queue that will be woken for new stream
  1240. * data.
  1241. *
  1242. * Note: Implementation deferred to i915_perf_poll_locked()
  1243. *
  1244. * Returns: any poll events that are ready without sleeping
  1245. */
  1246. static unsigned int i915_perf_poll(struct file *file, poll_table *wait)
  1247. {
  1248. struct i915_perf_stream *stream = file->private_data;
  1249. struct drm_i915_private *dev_priv = stream->dev_priv;
  1250. int ret;
  1251. mutex_lock(&dev_priv->perf.lock);
  1252. ret = i915_perf_poll_locked(dev_priv, stream, file, wait);
  1253. mutex_unlock(&dev_priv->perf.lock);
  1254. return ret;
  1255. }
  1256. /**
  1257. * i915_perf_enable_locked - handle `I915_PERF_IOCTL_ENABLE` ioctl
  1258. * @stream: A disabled i915 perf stream
  1259. *
  1260. * [Re]enables the associated capture of data for this stream.
  1261. *
  1262. * If a stream was previously enabled then there's currently no intention
  1263. * to provide userspace any guarantee about the preservation of previously
  1264. * buffered data.
  1265. */
  1266. static void i915_perf_enable_locked(struct i915_perf_stream *stream)
  1267. {
  1268. if (stream->enabled)
  1269. return;
  1270. /* Allow stream->ops->enable() to refer to this */
  1271. stream->enabled = true;
  1272. if (stream->ops->enable)
  1273. stream->ops->enable(stream);
  1274. }
  1275. /**
  1276. * i915_perf_disable_locked - handle `I915_PERF_IOCTL_DISABLE` ioctl
  1277. * @stream: An enabled i915 perf stream
  1278. *
  1279. * Disables the associated capture of data for this stream.
  1280. *
  1281. * The intention is that disabling an re-enabling a stream will ideally be
  1282. * cheaper than destroying and re-opening a stream with the same configuration,
  1283. * though there are no formal guarantees about what state or buffered data
  1284. * must be retained between disabling and re-enabling a stream.
  1285. *
  1286. * Note: while a stream is disabled it's considered an error for userspace
  1287. * to attempt to read from the stream (-EIO).
  1288. */
  1289. static void i915_perf_disable_locked(struct i915_perf_stream *stream)
  1290. {
  1291. if (!stream->enabled)
  1292. return;
  1293. /* Allow stream->ops->disable() to refer to this */
  1294. stream->enabled = false;
  1295. if (stream->ops->disable)
  1296. stream->ops->disable(stream);
  1297. }
  1298. /**
  1299. * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
  1300. * @stream: An i915 perf stream
  1301. * @cmd: the ioctl request
  1302. * @arg: the ioctl data
  1303. *
  1304. * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
  1305. * with any non-file-operation driver hooks.
  1306. *
  1307. * Returns: zero on success or a negative error code. Returns -EINVAL for
  1308. * an unknown ioctl request.
  1309. */
  1310. static long i915_perf_ioctl_locked(struct i915_perf_stream *stream,
  1311. unsigned int cmd,
  1312. unsigned long arg)
  1313. {
  1314. switch (cmd) {
  1315. case I915_PERF_IOCTL_ENABLE:
  1316. i915_perf_enable_locked(stream);
  1317. return 0;
  1318. case I915_PERF_IOCTL_DISABLE:
  1319. i915_perf_disable_locked(stream);
  1320. return 0;
  1321. }
  1322. return -EINVAL;
  1323. }
  1324. /**
  1325. * i915_perf_ioctl - support ioctl() usage with i915 perf stream FDs
  1326. * @file: An i915 perf stream file
  1327. * @cmd: the ioctl request
  1328. * @arg: the ioctl data
  1329. *
  1330. * Implementation deferred to i915_perf_ioctl_locked().
  1331. *
  1332. * Returns: zero on success or a negative error code. Returns -EINVAL for
  1333. * an unknown ioctl request.
  1334. */
  1335. static long i915_perf_ioctl(struct file *file,
  1336. unsigned int cmd,
  1337. unsigned long arg)
  1338. {
  1339. struct i915_perf_stream *stream = file->private_data;
  1340. struct drm_i915_private *dev_priv = stream->dev_priv;
  1341. long ret;
  1342. mutex_lock(&dev_priv->perf.lock);
  1343. ret = i915_perf_ioctl_locked(stream, cmd, arg);
  1344. mutex_unlock(&dev_priv->perf.lock);
  1345. return ret;
  1346. }
  1347. /**
  1348. * i915_perf_destroy_locked - destroy an i915 perf stream
  1349. * @stream: An i915 perf stream
  1350. *
  1351. * Frees all resources associated with the given i915 perf @stream, disabling
  1352. * any associated data capture in the process.
  1353. *
  1354. * Note: The &drm_i915_private->perf.lock mutex has been taken to serialize
  1355. * with any non-file-operation driver hooks.
  1356. */
  1357. static void i915_perf_destroy_locked(struct i915_perf_stream *stream)
  1358. {
  1359. if (stream->enabled)
  1360. i915_perf_disable_locked(stream);
  1361. if (stream->ops->destroy)
  1362. stream->ops->destroy(stream);
  1363. list_del(&stream->link);
  1364. if (stream->ctx)
  1365. i915_gem_context_put_unlocked(stream->ctx);
  1366. kfree(stream);
  1367. }
  1368. /**
  1369. * i915_perf_release - handles userspace close() of a stream file
  1370. * @inode: anonymous inode associated with file
  1371. * @file: An i915 perf stream file
  1372. *
  1373. * Cleans up any resources associated with an open i915 perf stream file.
  1374. *
  1375. * NB: close() can't really fail from the userspace point of view.
  1376. *
  1377. * Returns: zero on success or a negative error code.
  1378. */
  1379. static int i915_perf_release(struct inode *inode, struct file *file)
  1380. {
  1381. struct i915_perf_stream *stream = file->private_data;
  1382. struct drm_i915_private *dev_priv = stream->dev_priv;
  1383. mutex_lock(&dev_priv->perf.lock);
  1384. i915_perf_destroy_locked(stream);
  1385. mutex_unlock(&dev_priv->perf.lock);
  1386. return 0;
  1387. }
  1388. static const struct file_operations fops = {
  1389. .owner = THIS_MODULE,
  1390. .llseek = no_llseek,
  1391. .release = i915_perf_release,
  1392. .poll = i915_perf_poll,
  1393. .read = i915_perf_read,
  1394. .unlocked_ioctl = i915_perf_ioctl,
  1395. };
  1396. static struct i915_gem_context *
  1397. lookup_context(struct drm_i915_private *dev_priv,
  1398. struct drm_i915_file_private *file_priv,
  1399. u32 ctx_user_handle)
  1400. {
  1401. struct i915_gem_context *ctx;
  1402. int ret;
  1403. ret = i915_mutex_lock_interruptible(&dev_priv->drm);
  1404. if (ret)
  1405. return ERR_PTR(ret);
  1406. ctx = i915_gem_context_lookup(file_priv, ctx_user_handle);
  1407. if (!IS_ERR(ctx))
  1408. i915_gem_context_get(ctx);
  1409. mutex_unlock(&dev_priv->drm.struct_mutex);
  1410. return ctx;
  1411. }
  1412. /**
  1413. * i915_perf_open_ioctl_locked - DRM ioctl() for userspace to open a stream FD
  1414. * @dev_priv: i915 device instance
  1415. * @param: The open parameters passed to 'DRM_I915_PERF_OPEN`
  1416. * @props: individually validated u64 property value pairs
  1417. * @file: drm file
  1418. *
  1419. * See i915_perf_ioctl_open() for interface details.
  1420. *
  1421. * Implements further stream config validation and stream initialization on
  1422. * behalf of i915_perf_open_ioctl() with the &drm_i915_private->perf.lock mutex
  1423. * taken to serialize with any non-file-operation driver hooks.
  1424. *
  1425. * Note: at this point the @props have only been validated in isolation and
  1426. * it's still necessary to validate that the combination of properties makes
  1427. * sense.
  1428. *
  1429. * In the case where userspace is interested in OA unit metrics then further
  1430. * config validation and stream initialization details will be handled by
  1431. * i915_oa_stream_init(). The code here should only validate config state that
  1432. * will be relevant to all stream types / backends.
  1433. *
  1434. * Returns: zero on success or a negative error code.
  1435. */
  1436. static int
  1437. i915_perf_open_ioctl_locked(struct drm_i915_private *dev_priv,
  1438. struct drm_i915_perf_open_param *param,
  1439. struct perf_open_properties *props,
  1440. struct drm_file *file)
  1441. {
  1442. struct i915_gem_context *specific_ctx = NULL;
  1443. struct i915_perf_stream *stream = NULL;
  1444. unsigned long f_flags = 0;
  1445. int stream_fd;
  1446. int ret;
  1447. if (props->single_context) {
  1448. u32 ctx_handle = props->ctx_handle;
  1449. struct drm_i915_file_private *file_priv = file->driver_priv;
  1450. specific_ctx = lookup_context(dev_priv, file_priv, ctx_handle);
  1451. if (IS_ERR(specific_ctx)) {
  1452. ret = PTR_ERR(specific_ctx);
  1453. if (ret != -EINTR)
  1454. DRM_DEBUG("Failed to look up context with ID %u for opening perf stream\n",
  1455. ctx_handle);
  1456. goto err;
  1457. }
  1458. }
  1459. /* Similar to perf's kernel.perf_paranoid_cpu sysctl option
  1460. * we check a dev.i915.perf_stream_paranoid sysctl option
  1461. * to determine if it's ok to access system wide OA counters
  1462. * without CAP_SYS_ADMIN privileges.
  1463. */
  1464. if (!specific_ctx &&
  1465. i915_perf_stream_paranoid && !capable(CAP_SYS_ADMIN)) {
  1466. DRM_DEBUG("Insufficient privileges to open system-wide i915 perf stream\n");
  1467. ret = -EACCES;
  1468. goto err_ctx;
  1469. }
  1470. stream = kzalloc(sizeof(*stream), GFP_KERNEL);
  1471. if (!stream) {
  1472. ret = -ENOMEM;
  1473. goto err_ctx;
  1474. }
  1475. stream->dev_priv = dev_priv;
  1476. stream->ctx = specific_ctx;
  1477. ret = i915_oa_stream_init(stream, param, props);
  1478. if (ret)
  1479. goto err_alloc;
  1480. /* we avoid simply assigning stream->sample_flags = props->sample_flags
  1481. * to have _stream_init check the combination of sample flags more
  1482. * thoroughly, but still this is the expected result at this point.
  1483. */
  1484. if (WARN_ON(stream->sample_flags != props->sample_flags)) {
  1485. ret = -ENODEV;
  1486. goto err_flags;
  1487. }
  1488. list_add(&stream->link, &dev_priv->perf.streams);
  1489. if (param->flags & I915_PERF_FLAG_FD_CLOEXEC)
  1490. f_flags |= O_CLOEXEC;
  1491. if (param->flags & I915_PERF_FLAG_FD_NONBLOCK)
  1492. f_flags |= O_NONBLOCK;
  1493. stream_fd = anon_inode_getfd("[i915_perf]", &fops, stream, f_flags);
  1494. if (stream_fd < 0) {
  1495. ret = stream_fd;
  1496. goto err_open;
  1497. }
  1498. if (!(param->flags & I915_PERF_FLAG_DISABLED))
  1499. i915_perf_enable_locked(stream);
  1500. return stream_fd;
  1501. err_open:
  1502. list_del(&stream->link);
  1503. err_flags:
  1504. if (stream->ops->destroy)
  1505. stream->ops->destroy(stream);
  1506. err_alloc:
  1507. kfree(stream);
  1508. err_ctx:
  1509. if (specific_ctx)
  1510. i915_gem_context_put_unlocked(specific_ctx);
  1511. err:
  1512. return ret;
  1513. }
  1514. /**
  1515. * read_properties_unlocked - validate + copy userspace stream open properties
  1516. * @dev_priv: i915 device instance
  1517. * @uprops: The array of u64 key value pairs given by userspace
  1518. * @n_props: The number of key value pairs expected in @uprops
  1519. * @props: The stream configuration built up while validating properties
  1520. *
  1521. * Note this function only validates properties in isolation it doesn't
  1522. * validate that the combination of properties makes sense or that all
  1523. * properties necessary for a particular kind of stream have been set.
  1524. *
  1525. * Note that there currently aren't any ordering requirements for properties so
  1526. * we shouldn't validate or assume anything about ordering here. This doesn't
  1527. * rule out defining new properties with ordering requirements in the future.
  1528. */
  1529. static int read_properties_unlocked(struct drm_i915_private *dev_priv,
  1530. u64 __user *uprops,
  1531. u32 n_props,
  1532. struct perf_open_properties *props)
  1533. {
  1534. u64 __user *uprop = uprops;
  1535. int i;
  1536. memset(props, 0, sizeof(struct perf_open_properties));
  1537. if (!n_props) {
  1538. DRM_DEBUG("No i915 perf properties given\n");
  1539. return -EINVAL;
  1540. }
  1541. /* Considering that ID = 0 is reserved and assuming that we don't
  1542. * (currently) expect any configurations to ever specify duplicate
  1543. * values for a particular property ID then the last _PROP_MAX value is
  1544. * one greater than the maximum number of properties we expect to get
  1545. * from userspace.
  1546. */
  1547. if (n_props >= DRM_I915_PERF_PROP_MAX) {
  1548. DRM_DEBUG("More i915 perf properties specified than exist\n");
  1549. return -EINVAL;
  1550. }
  1551. for (i = 0; i < n_props; i++) {
  1552. u64 oa_period, oa_freq_hz;
  1553. u64 id, value;
  1554. int ret;
  1555. ret = get_user(id, uprop);
  1556. if (ret)
  1557. return ret;
  1558. ret = get_user(value, uprop + 1);
  1559. if (ret)
  1560. return ret;
  1561. if (id == 0 || id >= DRM_I915_PERF_PROP_MAX) {
  1562. DRM_DEBUG("Unknown i915 perf property ID\n");
  1563. return -EINVAL;
  1564. }
  1565. switch ((enum drm_i915_perf_property_id)id) {
  1566. case DRM_I915_PERF_PROP_CTX_HANDLE:
  1567. props->single_context = 1;
  1568. props->ctx_handle = value;
  1569. break;
  1570. case DRM_I915_PERF_PROP_SAMPLE_OA:
  1571. props->sample_flags |= SAMPLE_OA_REPORT;
  1572. break;
  1573. case DRM_I915_PERF_PROP_OA_METRICS_SET:
  1574. if (value == 0 ||
  1575. value > dev_priv->perf.oa.n_builtin_sets) {
  1576. DRM_DEBUG("Unknown OA metric set ID\n");
  1577. return -EINVAL;
  1578. }
  1579. props->metrics_set = value;
  1580. break;
  1581. case DRM_I915_PERF_PROP_OA_FORMAT:
  1582. if (value == 0 || value >= I915_OA_FORMAT_MAX) {
  1583. DRM_DEBUG("Invalid OA report format\n");
  1584. return -EINVAL;
  1585. }
  1586. if (!dev_priv->perf.oa.oa_formats[value].size) {
  1587. DRM_DEBUG("Invalid OA report format\n");
  1588. return -EINVAL;
  1589. }
  1590. props->oa_format = value;
  1591. break;
  1592. case DRM_I915_PERF_PROP_OA_EXPONENT:
  1593. if (value > OA_EXPONENT_MAX) {
  1594. DRM_DEBUG("OA timer exponent too high (> %u)\n",
  1595. OA_EXPONENT_MAX);
  1596. return -EINVAL;
  1597. }
  1598. /* Theoretically we can program the OA unit to sample
  1599. * every 160ns but don't allow that by default unless
  1600. * root.
  1601. *
  1602. * On Haswell the period is derived from the exponent
  1603. * as:
  1604. *
  1605. * period = 80ns * 2^(exponent + 1)
  1606. */
  1607. BUILD_BUG_ON(sizeof(oa_period) != 8);
  1608. oa_period = 80ull * (2ull << value);
  1609. /* This check is primarily to ensure that oa_period <=
  1610. * UINT32_MAX (before passing to do_div which only
  1611. * accepts a u32 denominator), but we can also skip
  1612. * checking anything < 1Hz which implicitly can't be
  1613. * limited via an integer oa_max_sample_rate.
  1614. */
  1615. if (oa_period <= NSEC_PER_SEC) {
  1616. u64 tmp = NSEC_PER_SEC;
  1617. do_div(tmp, oa_period);
  1618. oa_freq_hz = tmp;
  1619. } else
  1620. oa_freq_hz = 0;
  1621. if (oa_freq_hz > i915_oa_max_sample_rate &&
  1622. !capable(CAP_SYS_ADMIN)) {
  1623. DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n",
  1624. i915_oa_max_sample_rate);
  1625. return -EACCES;
  1626. }
  1627. props->oa_periodic = true;
  1628. props->oa_period_exponent = value;
  1629. break;
  1630. case DRM_I915_PERF_PROP_MAX:
  1631. MISSING_CASE(id);
  1632. return -EINVAL;
  1633. }
  1634. uprop += 2;
  1635. }
  1636. return 0;
  1637. }
  1638. /**
  1639. * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
  1640. * @dev: drm device
  1641. * @data: ioctl data copied from userspace (unvalidated)
  1642. * @file: drm file
  1643. *
  1644. * Validates the stream open parameters given by userspace including flags
  1645. * and an array of u64 key, value pair properties.
  1646. *
  1647. * Very little is assumed up front about the nature of the stream being
  1648. * opened (for instance we don't assume it's for periodic OA unit metrics). An
  1649. * i915-perf stream is expected to be a suitable interface for other forms of
  1650. * buffered data written by the GPU besides periodic OA metrics.
  1651. *
  1652. * Note we copy the properties from userspace outside of the i915 perf
  1653. * mutex to avoid an awkward lockdep with mmap_sem.
  1654. *
  1655. * Most of the implementation details are handled by
  1656. * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
  1657. * mutex for serializing with any non-file-operation driver hooks.
  1658. *
  1659. * Return: A newly opened i915 Perf stream file descriptor or negative
  1660. * error code on failure.
  1661. */
  1662. int i915_perf_open_ioctl(struct drm_device *dev, void *data,
  1663. struct drm_file *file)
  1664. {
  1665. struct drm_i915_private *dev_priv = dev->dev_private;
  1666. struct drm_i915_perf_open_param *param = data;
  1667. struct perf_open_properties props;
  1668. u32 known_open_flags;
  1669. int ret;
  1670. if (!dev_priv->perf.initialized) {
  1671. DRM_DEBUG("i915 perf interface not available for this system\n");
  1672. return -ENOTSUPP;
  1673. }
  1674. known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
  1675. I915_PERF_FLAG_FD_NONBLOCK |
  1676. I915_PERF_FLAG_DISABLED;
  1677. if (param->flags & ~known_open_flags) {
  1678. DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
  1679. return -EINVAL;
  1680. }
  1681. ret = read_properties_unlocked(dev_priv,
  1682. u64_to_user_ptr(param->properties_ptr),
  1683. param->num_properties,
  1684. &props);
  1685. if (ret)
  1686. return ret;
  1687. mutex_lock(&dev_priv->perf.lock);
  1688. ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
  1689. mutex_unlock(&dev_priv->perf.lock);
  1690. return ret;
  1691. }
  1692. /**
  1693. * i915_perf_register - exposes i915-perf to userspace
  1694. * @dev_priv: i915 device instance
  1695. *
  1696. * In particular OA metric sets are advertised under a sysfs metrics/
  1697. * directory allowing userspace to enumerate valid IDs that can be
  1698. * used to open an i915-perf stream.
  1699. */
  1700. void i915_perf_register(struct drm_i915_private *dev_priv)
  1701. {
  1702. if (!IS_HASWELL(dev_priv))
  1703. return;
  1704. if (!dev_priv->perf.initialized)
  1705. return;
  1706. /* To be sure we're synchronized with an attempted
  1707. * i915_perf_open_ioctl(); considering that we register after
  1708. * being exposed to userspace.
  1709. */
  1710. mutex_lock(&dev_priv->perf.lock);
  1711. dev_priv->perf.metrics_kobj =
  1712. kobject_create_and_add("metrics",
  1713. &dev_priv->drm.primary->kdev->kobj);
  1714. if (!dev_priv->perf.metrics_kobj)
  1715. goto exit;
  1716. if (i915_perf_register_sysfs_hsw(dev_priv)) {
  1717. kobject_put(dev_priv->perf.metrics_kobj);
  1718. dev_priv->perf.metrics_kobj = NULL;
  1719. }
  1720. exit:
  1721. mutex_unlock(&dev_priv->perf.lock);
  1722. }
  1723. /**
  1724. * i915_perf_unregister - hide i915-perf from userspace
  1725. * @dev_priv: i915 device instance
  1726. *
  1727. * i915-perf state cleanup is split up into an 'unregister' and
  1728. * 'deinit' phase where the interface is first hidden from
  1729. * userspace by i915_perf_unregister() before cleaning up
  1730. * remaining state in i915_perf_fini().
  1731. */
  1732. void i915_perf_unregister(struct drm_i915_private *dev_priv)
  1733. {
  1734. if (!IS_HASWELL(dev_priv))
  1735. return;
  1736. if (!dev_priv->perf.metrics_kobj)
  1737. return;
  1738. i915_perf_unregister_sysfs_hsw(dev_priv);
  1739. kobject_put(dev_priv->perf.metrics_kobj);
  1740. dev_priv->perf.metrics_kobj = NULL;
  1741. }
  1742. static struct ctl_table oa_table[] = {
  1743. {
  1744. .procname = "perf_stream_paranoid",
  1745. .data = &i915_perf_stream_paranoid,
  1746. .maxlen = sizeof(i915_perf_stream_paranoid),
  1747. .mode = 0644,
  1748. .proc_handler = proc_dointvec_minmax,
  1749. .extra1 = &zero,
  1750. .extra2 = &one,
  1751. },
  1752. {
  1753. .procname = "oa_max_sample_rate",
  1754. .data = &i915_oa_max_sample_rate,
  1755. .maxlen = sizeof(i915_oa_max_sample_rate),
  1756. .mode = 0644,
  1757. .proc_handler = proc_dointvec_minmax,
  1758. .extra1 = &zero,
  1759. .extra2 = &oa_sample_rate_hard_limit,
  1760. },
  1761. {}
  1762. };
  1763. static struct ctl_table i915_root[] = {
  1764. {
  1765. .procname = "i915",
  1766. .maxlen = 0,
  1767. .mode = 0555,
  1768. .child = oa_table,
  1769. },
  1770. {}
  1771. };
  1772. static struct ctl_table dev_root[] = {
  1773. {
  1774. .procname = "dev",
  1775. .maxlen = 0,
  1776. .mode = 0555,
  1777. .child = i915_root,
  1778. },
  1779. {}
  1780. };
  1781. /**
  1782. * i915_perf_init - initialize i915-perf state on module load
  1783. * @dev_priv: i915 device instance
  1784. *
  1785. * Initializes i915-perf state without exposing anything to userspace.
  1786. *
  1787. * Note: i915-perf initialization is split into an 'init' and 'register'
  1788. * phase with the i915_perf_register() exposing state to userspace.
  1789. */
  1790. void i915_perf_init(struct drm_i915_private *dev_priv)
  1791. {
  1792. if (!IS_HASWELL(dev_priv))
  1793. return;
  1794. hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
  1795. CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  1796. dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
  1797. init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
  1798. INIT_LIST_HEAD(&dev_priv->perf.streams);
  1799. mutex_init(&dev_priv->perf.lock);
  1800. spin_lock_init(&dev_priv->perf.hook_lock);
  1801. dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
  1802. dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
  1803. dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
  1804. dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
  1805. dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
  1806. dev_priv->perf.oa.ops.read = gen7_oa_read;
  1807. dev_priv->perf.oa.ops.oa_buffer_is_empty =
  1808. gen7_oa_buffer_is_empty_fop_unlocked;
  1809. dev_priv->perf.oa.timestamp_frequency = 12500000;
  1810. dev_priv->perf.oa.oa_formats = hsw_oa_formats;
  1811. dev_priv->perf.oa.n_builtin_sets =
  1812. i915_oa_n_builtin_metric_sets_hsw;
  1813. dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
  1814. dev_priv->perf.initialized = true;
  1815. }
  1816. /**
  1817. * i915_perf_fini - Counter part to i915_perf_init()
  1818. * @dev_priv: i915 device instance
  1819. */
  1820. void i915_perf_fini(struct drm_i915_private *dev_priv)
  1821. {
  1822. if (!dev_priv->perf.initialized)
  1823. return;
  1824. unregister_sysctl_table(dev_priv->perf.sysctl_header);
  1825. memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
  1826. dev_priv->perf.initialized = false;
  1827. }