i915_perf.c 68 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096
  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. assert_spin_locked(&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_alloc;
  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. if (stream->ops->destroy)
  1504. stream->ops->destroy(stream);
  1505. err_alloc:
  1506. kfree(stream);
  1507. err_ctx:
  1508. if (specific_ctx)
  1509. i915_gem_context_put_unlocked(specific_ctx);
  1510. err:
  1511. return ret;
  1512. }
  1513. /**
  1514. * read_properties_unlocked - validate + copy userspace stream open properties
  1515. * @dev_priv: i915 device instance
  1516. * @uprops: The array of u64 key value pairs given by userspace
  1517. * @n_props: The number of key value pairs expected in @uprops
  1518. * @props: The stream configuration built up while validating properties
  1519. *
  1520. * Note this function only validates properties in isolation it doesn't
  1521. * validate that the combination of properties makes sense or that all
  1522. * properties necessary for a particular kind of stream have been set.
  1523. *
  1524. * Note that there currently aren't any ordering requirements for properties so
  1525. * we shouldn't validate or assume anything about ordering here. This doesn't
  1526. * rule out defining new properties with ordering requirements in the future.
  1527. */
  1528. static int read_properties_unlocked(struct drm_i915_private *dev_priv,
  1529. u64 __user *uprops,
  1530. u32 n_props,
  1531. struct perf_open_properties *props)
  1532. {
  1533. u64 __user *uprop = uprops;
  1534. int i;
  1535. memset(props, 0, sizeof(struct perf_open_properties));
  1536. if (!n_props) {
  1537. DRM_DEBUG("No i915 perf properties given\n");
  1538. return -EINVAL;
  1539. }
  1540. /* Considering that ID = 0 is reserved and assuming that we don't
  1541. * (currently) expect any configurations to ever specify duplicate
  1542. * values for a particular property ID then the last _PROP_MAX value is
  1543. * one greater than the maximum number of properties we expect to get
  1544. * from userspace.
  1545. */
  1546. if (n_props >= DRM_I915_PERF_PROP_MAX) {
  1547. DRM_DEBUG("More i915 perf properties specified than exist\n");
  1548. return -EINVAL;
  1549. }
  1550. for (i = 0; i < n_props; i++) {
  1551. u64 oa_period, oa_freq_hz;
  1552. u64 id, value;
  1553. int ret;
  1554. ret = get_user(id, uprop);
  1555. if (ret)
  1556. return ret;
  1557. ret = get_user(value, uprop + 1);
  1558. if (ret)
  1559. return ret;
  1560. switch ((enum drm_i915_perf_property_id)id) {
  1561. case DRM_I915_PERF_PROP_CTX_HANDLE:
  1562. props->single_context = 1;
  1563. props->ctx_handle = value;
  1564. break;
  1565. case DRM_I915_PERF_PROP_SAMPLE_OA:
  1566. props->sample_flags |= SAMPLE_OA_REPORT;
  1567. break;
  1568. case DRM_I915_PERF_PROP_OA_METRICS_SET:
  1569. if (value == 0 ||
  1570. value > dev_priv->perf.oa.n_builtin_sets) {
  1571. DRM_DEBUG("Unknown OA metric set ID\n");
  1572. return -EINVAL;
  1573. }
  1574. props->metrics_set = value;
  1575. break;
  1576. case DRM_I915_PERF_PROP_OA_FORMAT:
  1577. if (value == 0 || value >= I915_OA_FORMAT_MAX) {
  1578. DRM_DEBUG("Invalid OA report format\n");
  1579. return -EINVAL;
  1580. }
  1581. if (!dev_priv->perf.oa.oa_formats[value].size) {
  1582. DRM_DEBUG("Invalid OA report format\n");
  1583. return -EINVAL;
  1584. }
  1585. props->oa_format = value;
  1586. break;
  1587. case DRM_I915_PERF_PROP_OA_EXPONENT:
  1588. if (value > OA_EXPONENT_MAX) {
  1589. DRM_DEBUG("OA timer exponent too high (> %u)\n",
  1590. OA_EXPONENT_MAX);
  1591. return -EINVAL;
  1592. }
  1593. /* Theoretically we can program the OA unit to sample
  1594. * every 160ns but don't allow that by default unless
  1595. * root.
  1596. *
  1597. * On Haswell the period is derived from the exponent
  1598. * as:
  1599. *
  1600. * period = 80ns * 2^(exponent + 1)
  1601. */
  1602. BUILD_BUG_ON(sizeof(oa_period) != 8);
  1603. oa_period = 80ull * (2ull << value);
  1604. /* This check is primarily to ensure that oa_period <=
  1605. * UINT32_MAX (before passing to do_div which only
  1606. * accepts a u32 denominator), but we can also skip
  1607. * checking anything < 1Hz which implicitly can't be
  1608. * limited via an integer oa_max_sample_rate.
  1609. */
  1610. if (oa_period <= NSEC_PER_SEC) {
  1611. u64 tmp = NSEC_PER_SEC;
  1612. do_div(tmp, oa_period);
  1613. oa_freq_hz = tmp;
  1614. } else
  1615. oa_freq_hz = 0;
  1616. if (oa_freq_hz > i915_oa_max_sample_rate &&
  1617. !capable(CAP_SYS_ADMIN)) {
  1618. DRM_DEBUG("OA exponent would exceed the max sampling frequency (sysctl dev.i915.oa_max_sample_rate) %uHz without root privileges\n",
  1619. i915_oa_max_sample_rate);
  1620. return -EACCES;
  1621. }
  1622. props->oa_periodic = true;
  1623. props->oa_period_exponent = value;
  1624. break;
  1625. default:
  1626. MISSING_CASE(id);
  1627. DRM_DEBUG("Unknown i915 perf property ID\n");
  1628. return -EINVAL;
  1629. }
  1630. uprop += 2;
  1631. }
  1632. return 0;
  1633. }
  1634. /**
  1635. * i915_perf_open_ioctl - DRM ioctl() for userspace to open a stream FD
  1636. * @dev: drm device
  1637. * @data: ioctl data copied from userspace (unvalidated)
  1638. * @file: drm file
  1639. *
  1640. * Validates the stream open parameters given by userspace including flags
  1641. * and an array of u64 key, value pair properties.
  1642. *
  1643. * Very little is assumed up front about the nature of the stream being
  1644. * opened (for instance we don't assume it's for periodic OA unit metrics). An
  1645. * i915-perf stream is expected to be a suitable interface for other forms of
  1646. * buffered data written by the GPU besides periodic OA metrics.
  1647. *
  1648. * Note we copy the properties from userspace outside of the i915 perf
  1649. * mutex to avoid an awkward lockdep with mmap_sem.
  1650. *
  1651. * Most of the implementation details are handled by
  1652. * i915_perf_open_ioctl_locked() after taking the &drm_i915_private->perf.lock
  1653. * mutex for serializing with any non-file-operation driver hooks.
  1654. *
  1655. * Return: A newly opened i915 Perf stream file descriptor or negative
  1656. * error code on failure.
  1657. */
  1658. int i915_perf_open_ioctl(struct drm_device *dev, void *data,
  1659. struct drm_file *file)
  1660. {
  1661. struct drm_i915_private *dev_priv = dev->dev_private;
  1662. struct drm_i915_perf_open_param *param = data;
  1663. struct perf_open_properties props;
  1664. u32 known_open_flags;
  1665. int ret;
  1666. if (!dev_priv->perf.initialized) {
  1667. DRM_DEBUG("i915 perf interface not available for this system\n");
  1668. return -ENOTSUPP;
  1669. }
  1670. known_open_flags = I915_PERF_FLAG_FD_CLOEXEC |
  1671. I915_PERF_FLAG_FD_NONBLOCK |
  1672. I915_PERF_FLAG_DISABLED;
  1673. if (param->flags & ~known_open_flags) {
  1674. DRM_DEBUG("Unknown drm_i915_perf_open_param flag\n");
  1675. return -EINVAL;
  1676. }
  1677. ret = read_properties_unlocked(dev_priv,
  1678. u64_to_user_ptr(param->properties_ptr),
  1679. param->num_properties,
  1680. &props);
  1681. if (ret)
  1682. return ret;
  1683. mutex_lock(&dev_priv->perf.lock);
  1684. ret = i915_perf_open_ioctl_locked(dev_priv, param, &props, file);
  1685. mutex_unlock(&dev_priv->perf.lock);
  1686. return ret;
  1687. }
  1688. /**
  1689. * i915_perf_register - exposes i915-perf to userspace
  1690. * @dev_priv: i915 device instance
  1691. *
  1692. * In particular OA metric sets are advertised under a sysfs metrics/
  1693. * directory allowing userspace to enumerate valid IDs that can be
  1694. * used to open an i915-perf stream.
  1695. */
  1696. void i915_perf_register(struct drm_i915_private *dev_priv)
  1697. {
  1698. if (!IS_HASWELL(dev_priv))
  1699. return;
  1700. if (!dev_priv->perf.initialized)
  1701. return;
  1702. /* To be sure we're synchronized with an attempted
  1703. * i915_perf_open_ioctl(); considering that we register after
  1704. * being exposed to userspace.
  1705. */
  1706. mutex_lock(&dev_priv->perf.lock);
  1707. dev_priv->perf.metrics_kobj =
  1708. kobject_create_and_add("metrics",
  1709. &dev_priv->drm.primary->kdev->kobj);
  1710. if (!dev_priv->perf.metrics_kobj)
  1711. goto exit;
  1712. if (i915_perf_register_sysfs_hsw(dev_priv)) {
  1713. kobject_put(dev_priv->perf.metrics_kobj);
  1714. dev_priv->perf.metrics_kobj = NULL;
  1715. }
  1716. exit:
  1717. mutex_unlock(&dev_priv->perf.lock);
  1718. }
  1719. /**
  1720. * i915_perf_unregister - hide i915-perf from userspace
  1721. * @dev_priv: i915 device instance
  1722. *
  1723. * i915-perf state cleanup is split up into an 'unregister' and
  1724. * 'deinit' phase where the interface is first hidden from
  1725. * userspace by i915_perf_unregister() before cleaning up
  1726. * remaining state in i915_perf_fini().
  1727. */
  1728. void i915_perf_unregister(struct drm_i915_private *dev_priv)
  1729. {
  1730. if (!IS_HASWELL(dev_priv))
  1731. return;
  1732. if (!dev_priv->perf.metrics_kobj)
  1733. return;
  1734. i915_perf_unregister_sysfs_hsw(dev_priv);
  1735. kobject_put(dev_priv->perf.metrics_kobj);
  1736. dev_priv->perf.metrics_kobj = NULL;
  1737. }
  1738. static struct ctl_table oa_table[] = {
  1739. {
  1740. .procname = "perf_stream_paranoid",
  1741. .data = &i915_perf_stream_paranoid,
  1742. .maxlen = sizeof(i915_perf_stream_paranoid),
  1743. .mode = 0644,
  1744. .proc_handler = proc_dointvec_minmax,
  1745. .extra1 = &zero,
  1746. .extra2 = &one,
  1747. },
  1748. {
  1749. .procname = "oa_max_sample_rate",
  1750. .data = &i915_oa_max_sample_rate,
  1751. .maxlen = sizeof(i915_oa_max_sample_rate),
  1752. .mode = 0644,
  1753. .proc_handler = proc_dointvec_minmax,
  1754. .extra1 = &zero,
  1755. .extra2 = &oa_sample_rate_hard_limit,
  1756. },
  1757. {}
  1758. };
  1759. static struct ctl_table i915_root[] = {
  1760. {
  1761. .procname = "i915",
  1762. .maxlen = 0,
  1763. .mode = 0555,
  1764. .child = oa_table,
  1765. },
  1766. {}
  1767. };
  1768. static struct ctl_table dev_root[] = {
  1769. {
  1770. .procname = "dev",
  1771. .maxlen = 0,
  1772. .mode = 0555,
  1773. .child = i915_root,
  1774. },
  1775. {}
  1776. };
  1777. /**
  1778. * i915_perf_init - initialize i915-perf state on module load
  1779. * @dev_priv: i915 device instance
  1780. *
  1781. * Initializes i915-perf state without exposing anything to userspace.
  1782. *
  1783. * Note: i915-perf initialization is split into an 'init' and 'register'
  1784. * phase with the i915_perf_register() exposing state to userspace.
  1785. */
  1786. void i915_perf_init(struct drm_i915_private *dev_priv)
  1787. {
  1788. if (!IS_HASWELL(dev_priv))
  1789. return;
  1790. hrtimer_init(&dev_priv->perf.oa.poll_check_timer,
  1791. CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  1792. dev_priv->perf.oa.poll_check_timer.function = oa_poll_check_timer_cb;
  1793. init_waitqueue_head(&dev_priv->perf.oa.poll_wq);
  1794. INIT_LIST_HEAD(&dev_priv->perf.streams);
  1795. mutex_init(&dev_priv->perf.lock);
  1796. spin_lock_init(&dev_priv->perf.hook_lock);
  1797. dev_priv->perf.oa.ops.init_oa_buffer = gen7_init_oa_buffer;
  1798. dev_priv->perf.oa.ops.enable_metric_set = hsw_enable_metric_set;
  1799. dev_priv->perf.oa.ops.disable_metric_set = hsw_disable_metric_set;
  1800. dev_priv->perf.oa.ops.oa_enable = gen7_oa_enable;
  1801. dev_priv->perf.oa.ops.oa_disable = gen7_oa_disable;
  1802. dev_priv->perf.oa.ops.read = gen7_oa_read;
  1803. dev_priv->perf.oa.ops.oa_buffer_is_empty =
  1804. gen7_oa_buffer_is_empty_fop_unlocked;
  1805. dev_priv->perf.oa.timestamp_frequency = 12500000;
  1806. dev_priv->perf.oa.oa_formats = hsw_oa_formats;
  1807. dev_priv->perf.oa.n_builtin_sets =
  1808. i915_oa_n_builtin_metric_sets_hsw;
  1809. dev_priv->perf.sysctl_header = register_sysctl_table(dev_root);
  1810. dev_priv->perf.initialized = true;
  1811. }
  1812. /**
  1813. * i915_perf_fini - Counter part to i915_perf_init()
  1814. * @dev_priv: i915 device instance
  1815. */
  1816. void i915_perf_fini(struct drm_i915_private *dev_priv)
  1817. {
  1818. if (!dev_priv->perf.initialized)
  1819. return;
  1820. unregister_sysctl_table(dev_priv->perf.sysctl_header);
  1821. memset(&dev_priv->perf.oa.ops, 0, sizeof(dev_priv->perf.oa.ops));
  1822. dev_priv->perf.initialized = false;
  1823. }