]> git.ipfire.org Git - thirdparty/linux.git/blame - kernel/events/core.c
Merge tag 'io_uring-6.16-20250630' of git://git.kernel.dk/linux
[thirdparty/linux.git] / kernel / events / core.c
CommitLineData
8e86e015 1// SPDX-License-Identifier: GPL-2.0
0793a61d 2/*
57c0c15b 3 * Performance events core code:
0793a61d 4 *
98144511 5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
e7e7ee2e 6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
90eec103 7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
d36b6910 8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
0793a61d
TG
9 */
10
11#include <linux/fs.h>
b9cacc7b 12#include <linux/mm.h>
0793a61d
TG
13#include <linux/cpu.h>
14#include <linux/smp.h>
2e80a82a 15#include <linux/idr.h>
04289bb9 16#include <linux/file.h>
0793a61d 17#include <linux/poll.h>
5a0e3ad6 18#include <linux/slab.h>
76e1d904 19#include <linux/hash.h>
12351ef8 20#include <linux/tick.h>
0793a61d 21#include <linux/sysfs.h>
22a4f650 22#include <linux/dcache.h>
0793a61d 23#include <linux/percpu.h>
22a4f650 24#include <linux/ptrace.h>
c277443c 25#include <linux/reboot.h>
b9cacc7b 26#include <linux/vmstat.h>
abe43400 27#include <linux/device.h>
6e5fdeed 28#include <linux/export.h>
906010b2 29#include <linux/vmalloc.h>
b9cacc7b 30#include <linux/hardirq.h>
03911132 31#include <linux/hugetlb.h>
b9cacc7b 32#include <linux/rculist.h>
0793a61d
TG
33#include <linux/uaccess.h>
34#include <linux/syscalls.h>
35#include <linux/anon_inodes.h>
aa9c4c0f 36#include <linux/kernel_stat.h>
39bed6cb 37#include <linux/cgroup.h>
cdd6c482 38#include <linux/perf_event.h>
af658dca 39#include <linux/trace_events.h>
3c502e7a 40#include <linux/hw_breakpoint.h>
c5ebcedb 41#include <linux/mm_types.h>
c464c76e 42#include <linux/module.h>
f972eb63 43#include <linux/mman.h>
b3f20785 44#include <linux/compat.h>
2541517c
AS
45#include <linux/bpf.h>
46#include <linux/filter.h>
375637bc
AS
47#include <linux/namei.h>
48#include <linux/parser.h>
e6017571 49#include <linux/sched/clock.h>
6e84f315 50#include <linux/sched/mm.h>
e4222673
HB
51#include <linux/proc_ns.h>
52#include <linux/mount.h>
6eef8a71 53#include <linux/min_heap.h>
8d97e718 54#include <linux/highmem.h>
8af26be0 55#include <linux/pgtable.h>
88a16a13 56#include <linux/buildid.h>
ca6c2132 57#include <linux/task_work.h>
506e64e7 58#include <linux/percpu-rwsem.h>
0793a61d 59
76369139
FW
60#include "internal.h"
61
4e193bd4
TB
62#include <asm/irq_regs.h>
63
272325c4
PZ
64typedef int (*remote_function_f)(void *);
65
fe4b04fa 66struct remote_function_call {
e7e7ee2e 67 struct task_struct *p;
272325c4 68 remote_function_f func;
e7e7ee2e
IM
69 void *info;
70 int ret;
fe4b04fa
PZ
71};
72
73static void remote_function(void *data)
74{
75 struct remote_function_call *tfc = data;
76 struct task_struct *p = tfc->p;
77
78 if (p) {
0da4cf3e
PZ
79 /* -EAGAIN */
80 if (task_cpu(p) != smp_processor_id())
81 return;
82
83 /*
84 * Now that we're on right CPU with IRQs disabled, we can test
85 * if we hit the right task without races.
86 */
87
88 tfc->ret = -ESRCH; /* No such (running) process */
89 if (p != current)
fe4b04fa
PZ
90 return;
91 }
92
93 tfc->ret = tfc->func(tfc->info);
94}
95
96/**
97 * task_function_call - call a function on the cpu on which a task runs
98 * @p: the task to evaluate
99 * @func: the function to be called
100 * @info: the function call argument
101 *
102 * Calls the function @func when the task is currently running. This might
2ed6edd3
BR
103 * be on the current CPU, which just calls the function directly. This will
104 * retry due to any failures in smp_call_function_single(), such as if the
105 * task_cpu() goes offline concurrently.
fe4b04fa 106 *
6d6b8b9f 107 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
fe4b04fa
PZ
108 */
109static int
272325c4 110task_function_call(struct task_struct *p, remote_function_f func, void *info)
fe4b04fa
PZ
111{
112 struct remote_function_call data = {
e7e7ee2e
IM
113 .p = p,
114 .func = func,
115 .info = info,
0da4cf3e 116 .ret = -EAGAIN,
fe4b04fa 117 };
0da4cf3e 118 int ret;
fe4b04fa 119
2ed6edd3
BR
120 for (;;) {
121 ret = smp_call_function_single(task_cpu(p), remote_function,
122 &data, 1);
6d6b8b9f
KJ
123 if (!ret)
124 ret = data.ret;
2ed6edd3
BR
125
126 if (ret != -EAGAIN)
127 break;
128
129 cond_resched();
130 }
fe4b04fa 131
0da4cf3e 132 return ret;
fe4b04fa
PZ
133}
134
135/**
136 * cpu_function_call - call a function on the cpu
a1ddf524 137 * @cpu: target cpu to queue this function
fe4b04fa
PZ
138 * @func: the function to be called
139 * @info: the function call argument
140 *
141 * Calls the function @func on the remote cpu.
142 *
143 * returns: @func return value or -ENXIO when the cpu is offline
144 */
272325c4 145static int cpu_function_call(int cpu, remote_function_f func, void *info)
fe4b04fa
PZ
146{
147 struct remote_function_call data = {
e7e7ee2e
IM
148 .p = NULL,
149 .func = func,
150 .info = info,
151 .ret = -ENXIO, /* No such CPU */
fe4b04fa
PZ
152 };
153
154 smp_call_function_single(cpu, remote_function, &data, 1);
155
156 return data.ret;
157}
158
5d95a2af
PZ
159enum event_type_t {
160 EVENT_FLEXIBLE = 0x01,
161 EVENT_PINNED = 0x02,
162 EVENT_TIME = 0x04,
163 EVENT_FROZEN = 0x08,
164 /* see ctx_resched() for details */
165 EVENT_CPU = 0x10,
166 EVENT_CGROUP = 0x20,
167
168 /* compound helpers */
169 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
170 EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN,
171};
172
173static inline void __perf_ctx_lock(struct perf_event_context *ctx)
174{
175 raw_spin_lock(&ctx->lock);
176 WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN);
177}
178
fae3fde6
PZ
179static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
180 struct perf_event_context *ctx)
0017960f 181{
5d95a2af 182 __perf_ctx_lock(&cpuctx->ctx);
fae3fde6 183 if (ctx)
5d95a2af
PZ
184 __perf_ctx_lock(ctx);
185}
186
187static inline void __perf_ctx_unlock(struct perf_event_context *ctx)
188{
189 /*
190 * If ctx_sched_in() didn't again set any ALL flags, clean up
191 * after ctx_sched_out() by clearing is_active.
192 */
193 if (ctx->is_active & EVENT_FROZEN) {
194 if (!(ctx->is_active & EVENT_ALL))
195 ctx->is_active = 0;
196 else
197 ctx->is_active &= ~EVENT_FROZEN;
198 }
199 raw_spin_unlock(&ctx->lock);
fae3fde6
PZ
200}
201
202static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
203 struct perf_event_context *ctx)
204{
205 if (ctx)
5d95a2af
PZ
206 __perf_ctx_unlock(ctx);
207 __perf_ctx_unlock(&cpuctx->ctx);
fae3fde6
PZ
208}
209
3172fb98
LG
210typedef struct {
211 struct perf_cpu_context *cpuctx;
212 struct perf_event_context *ctx;
213} class_perf_ctx_lock_t;
214
215static inline void class_perf_ctx_lock_destructor(class_perf_ctx_lock_t *_T)
216{ perf_ctx_unlock(_T->cpuctx, _T->ctx); }
217
218static inline class_perf_ctx_lock_t
219class_perf_ctx_lock_constructor(struct perf_cpu_context *cpuctx,
220 struct perf_event_context *ctx)
221{ perf_ctx_lock(cpuctx, ctx); return (class_perf_ctx_lock_t){ cpuctx, ctx }; }
222
63b6da39
PZ
223#define TASK_TOMBSTONE ((void *)-1L)
224
225static bool is_kernel_event(struct perf_event *event)
226{
f47c02c0 227 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
63b6da39
PZ
228}
229
bd275681
PZ
230static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
231
232struct perf_event_context *perf_cpu_task_ctx(void)
233{
234 lockdep_assert_irqs_disabled();
235 return this_cpu_ptr(&perf_cpu_context)->task_ctx;
236}
237
39a43640
PZ
238/*
239 * On task ctx scheduling...
240 *
241 * When !ctx->nr_events a task context will not be scheduled. This means
242 * we can disable the scheduler hooks (for performance) without leaving
243 * pending task ctx state.
244 *
245 * This however results in two special cases:
246 *
247 * - removing the last event from a task ctx; this is relatively straight
248 * forward and is done in __perf_remove_from_context.
249 *
250 * - adding the first event to a task ctx; this is tricky because we cannot
251 * rely on ctx->is_active and therefore cannot use event_function_call().
252 * See perf_install_in_context().
253 *
39a43640
PZ
254 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
255 */
256
fae3fde6
PZ
257typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
258 struct perf_event_context *, void *);
259
260struct event_function_struct {
261 struct perf_event *event;
262 event_f func;
263 void *data;
264};
265
266static int event_function(void *info)
267{
268 struct event_function_struct *efs = info;
269 struct perf_event *event = efs->event;
0017960f 270 struct perf_event_context *ctx = event->ctx;
bd275681 271 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
fae3fde6 272 struct perf_event_context *task_ctx = cpuctx->task_ctx;
63b6da39 273 int ret = 0;
fae3fde6 274
16444645 275 lockdep_assert_irqs_disabled();
fae3fde6 276
63b6da39 277 perf_ctx_lock(cpuctx, task_ctx);
fae3fde6
PZ
278 /*
279 * Since we do the IPI call without holding ctx->lock things can have
280 * changed, double check we hit the task we set out to hit.
fae3fde6
PZ
281 */
282 if (ctx->task) {
63b6da39 283 if (ctx->task != current) {
0da4cf3e 284 ret = -ESRCH;
63b6da39
PZ
285 goto unlock;
286 }
fae3fde6 287
fae3fde6
PZ
288 /*
289 * We only use event_function_call() on established contexts,
290 * and event_function() is only ever called when active (or
291 * rather, we'll have bailed in task_function_call() or the
292 * above ctx->task != current test), therefore we must have
293 * ctx->is_active here.
294 */
295 WARN_ON_ONCE(!ctx->is_active);
296 /*
297 * And since we have ctx->is_active, cpuctx->task_ctx must
298 * match.
299 */
63b6da39
PZ
300 WARN_ON_ONCE(task_ctx != ctx);
301 } else {
302 WARN_ON_ONCE(&cpuctx->ctx != ctx);
fae3fde6 303 }
63b6da39 304
fae3fde6 305 efs->func(event, cpuctx, ctx, efs->data);
63b6da39 306unlock:
fae3fde6
PZ
307 perf_ctx_unlock(cpuctx, task_ctx);
308
63b6da39 309 return ret;
fae3fde6
PZ
310}
311
fae3fde6 312static void event_function_call(struct perf_event *event, event_f func, void *data)
0017960f
PZ
313{
314 struct perf_event_context *ctx = event->ctx;
63b6da39 315 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
fe826cc2 316 struct perf_cpu_context *cpuctx;
fae3fde6
PZ
317 struct event_function_struct efs = {
318 .event = event,
319 .func = func,
320 .data = data,
321 };
0017960f 322
c97f4736
PZ
323 if (!event->parent) {
324 /*
325 * If this is a !child event, we must hold ctx::mutex to
c034f48e 326 * stabilize the event->ctx relation. See
c97f4736
PZ
327 * perf_event_ctx_lock().
328 */
329 lockdep_assert_held(&ctx->mutex);
330 }
0017960f
PZ
331
332 if (!task) {
fae3fde6 333 cpu_function_call(event->cpu, event_function, &efs);
0017960f
PZ
334 return;
335 }
336
63b6da39
PZ
337 if (task == TASK_TOMBSTONE)
338 return;
339
a096309b 340again:
fae3fde6 341 if (!task_function_call(task, event_function, &efs))
0017960f
PZ
342 return;
343
fe826cc2
NK
344 local_irq_disable();
345 cpuctx = this_cpu_ptr(&perf_cpu_context);
558abc7e 346 perf_ctx_lock(cpuctx, ctx);
63b6da39
PZ
347 /*
348 * Reload the task pointer, it might have been changed by
349 * a concurrent perf_event_context_sched_out().
350 */
351 task = ctx->task;
fe826cc2
NK
352 if (task == TASK_TOMBSTONE)
353 goto unlock;
a096309b 354 if (ctx->is_active) {
558abc7e 355 perf_ctx_unlock(cpuctx, ctx);
fe826cc2 356 local_irq_enable();
a096309b
PZ
357 goto again;
358 }
359 func(event, NULL, ctx, data);
fe826cc2 360unlock:
558abc7e 361 perf_ctx_unlock(cpuctx, ctx);
fe826cc2 362 local_irq_enable();
0017960f
PZ
363}
364
cca20946
PZ
365/*
366 * Similar to event_function_call() + event_function(), but hard assumes IRQs
367 * are already disabled and we're on the right CPU.
368 */
369static void event_function_local(struct perf_event *event, event_f func, void *data)
370{
371 struct perf_event_context *ctx = event->ctx;
bd275681 372 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
cca20946
PZ
373 struct task_struct *task = READ_ONCE(ctx->task);
374 struct perf_event_context *task_ctx = NULL;
375
16444645 376 lockdep_assert_irqs_disabled();
cca20946
PZ
377
378 if (task) {
379 if (task == TASK_TOMBSTONE)
380 return;
381
382 task_ctx = ctx;
383 }
384
385 perf_ctx_lock(cpuctx, task_ctx);
386
387 task = ctx->task;
388 if (task == TASK_TOMBSTONE)
389 goto unlock;
390
391 if (task) {
392 /*
393 * We must be either inactive or active and the right task,
394 * otherwise we're screwed, since we cannot IPI to somewhere
395 * else.
396 */
397 if (ctx->is_active) {
398 if (WARN_ON_ONCE(task != current))
399 goto unlock;
400
401 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
402 goto unlock;
403 }
404 } else {
405 WARN_ON_ONCE(&cpuctx->ctx != ctx);
406 }
407
408 func(event, cpuctx, ctx, data);
409unlock:
410 perf_ctx_unlock(cpuctx, task_ctx);
411}
412
e5d1367f
SE
413#define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
414 PERF_FLAG_FD_OUTPUT |\
a21b0b35
YD
415 PERF_FLAG_PID_CGROUP |\
416 PERF_FLAG_FD_CLOEXEC)
e5d1367f 417
bce38cd5
SE
418/*
419 * branch priv levels that need permission checks
420 */
421#define PERF_SAMPLE_BRANCH_PERM_PLM \
422 (PERF_SAMPLE_BRANCH_KERNEL |\
423 PERF_SAMPLE_BRANCH_HV)
424
e5d1367f
SE
425/*
426 * perf_sched_events : >0 events exist
e5d1367f 427 */
9107c89e
PZ
428
429static void perf_sched_delayed(struct work_struct *work);
430DEFINE_STATIC_KEY_FALSE(perf_sched_events);
431static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
432static DEFINE_MUTEX(perf_sched_mutex);
433static atomic_t perf_sched_count;
434
f2fb6bef 435static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
e5d1367f 436
cdd6c482
IM
437static atomic_t nr_mmap_events __read_mostly;
438static atomic_t nr_comm_events __read_mostly;
e4222673 439static atomic_t nr_namespaces_events __read_mostly;
cdd6c482 440static atomic_t nr_task_events __read_mostly;
948b26b6 441static atomic_t nr_freq_events __read_mostly;
45ac1403 442static atomic_t nr_switch_events __read_mostly;
76193a94 443static atomic_t nr_ksymbol_events __read_mostly;
6ee52e2a 444static atomic_t nr_bpf_events __read_mostly;
96aaab68 445static atomic_t nr_cgroup_events __read_mostly;
e17d43b9 446static atomic_t nr_text_poke_events __read_mostly;
88a16a13 447static atomic_t nr_build_id_events __read_mostly;
9ee318a7 448
108b02cf
PZ
449static LIST_HEAD(pmus);
450static DEFINE_MUTEX(pmus_lock);
451static struct srcu_struct pmus_srcu;
a63fbed7 452static cpumask_var_t perf_online_mask;
4ba4f1af
KL
453static cpumask_var_t perf_online_core_mask;
454static cpumask_var_t perf_online_die_mask;
455static cpumask_var_t perf_online_cluster_mask;
456static cpumask_var_t perf_online_pkg_mask;
457static cpumask_var_t perf_online_sys_mask;
bdacfaf2 458static struct kmem_cache *perf_event_cache;
108b02cf 459
0764771d 460/*
cdd6c482 461 * perf event paranoia level:
0fbdea19
IM
462 * -1 - not paranoid at all
463 * 0 - disallow raw tracepoint access for unpriv
cdd6c482 464 * 1 - disallow cpu events for unpriv
0fbdea19 465 * 2 - disallow kernel profiling for unpriv
0764771d 466 */
0161028b 467int sysctl_perf_event_paranoid __read_mostly = 2;
0764771d 468
8aeacf25
JG
469/* Minimum for 512 kiB + 1 user control page. 'free' kiB per user. */
470static int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024);
df58ab24
PZ
471
472/*
cdd6c482 473 * max perf event sample rate
df58ab24 474 */
14c63f17
DH
475#define DEFAULT_MAX_SAMPLE_RATE 100000
476#define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
477#define DEFAULT_CPU_TIME_MAX_PERCENT 25
478
479int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
8aeacf25 480static int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
14c63f17
DH
481
482static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
483static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
484
d9494cb4
PZ
485static int perf_sample_allowed_ns __read_mostly =
486 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
14c63f17 487
18ab2cd3 488static void update_perf_cpu_limits(void)
14c63f17
DH
489{
490 u64 tmp = perf_sample_period_ns;
491
492 tmp *= sysctl_perf_cpu_time_max_percent;
91a612ee
PZ
493 tmp = div_u64(tmp, 100);
494 if (!tmp)
495 tmp = 1;
496
497 WRITE_ONCE(perf_sample_allowed_ns, tmp);
14c63f17 498}
163ec435 499
bd275681 500static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc);
9e630205 501
8aeacf25 502static int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write,
e6814ec3 503 void *buffer, size_t *lenp, loff_t *ppos)
163ec435 504{
1a51c5da
SE
505 int ret;
506 int perf_cpu = sysctl_perf_cpu_time_max_percent;
ab7fdefb
KL
507 /*
508 * If throttling is disabled don't allow the write:
509 */
1a51c5da 510 if (write && (perf_cpu == 100 || perf_cpu == 0))
ab7fdefb
KL
511 return -EINVAL;
512
1a51c5da
SE
513 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
514 if (ret || !write)
515 return ret;
516
163ec435 517 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
14c63f17
DH
518 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
519 update_perf_cpu_limits();
520
521 return 0;
522}
523
8aeacf25 524static int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write,
32927393 525 void *buffer, size_t *lenp, loff_t *ppos)
14c63f17 526{
1572e45a 527 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
14c63f17
DH
528
529 if (ret || !write)
530 return ret;
531
b303e7c1
PZ
532 if (sysctl_perf_cpu_time_max_percent == 100 ||
533 sysctl_perf_cpu_time_max_percent == 0) {
91a612ee
PZ
534 printk(KERN_WARNING
535 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
536 WRITE_ONCE(perf_sample_allowed_ns, 0);
537 } else {
538 update_perf_cpu_limits();
539 }
163ec435
PZ
540
541 return 0;
542}
1ccd1549 543
8aeacf25
JG
544static const struct ctl_table events_core_sysctl_table[] = {
545 /*
546 * User-space relies on this file as a feature check for
547 * perf_events being enabled. It's an ABI, do not remove!
548 */
549 {
550 .procname = "perf_event_paranoid",
551 .data = &sysctl_perf_event_paranoid,
552 .maxlen = sizeof(sysctl_perf_event_paranoid),
553 .mode = 0644,
554 .proc_handler = proc_dointvec,
555 },
556 {
557 .procname = "perf_event_mlock_kb",
558 .data = &sysctl_perf_event_mlock,
559 .maxlen = sizeof(sysctl_perf_event_mlock),
560 .mode = 0644,
561 .proc_handler = proc_dointvec,
562 },
563 {
564 .procname = "perf_event_max_sample_rate",
565 .data = &sysctl_perf_event_sample_rate,
566 .maxlen = sizeof(sysctl_perf_event_sample_rate),
567 .mode = 0644,
568 .proc_handler = perf_event_max_sample_rate_handler,
569 .extra1 = SYSCTL_ONE,
570 },
571 {
572 .procname = "perf_cpu_time_max_percent",
573 .data = &sysctl_perf_cpu_time_max_percent,
574 .maxlen = sizeof(sysctl_perf_cpu_time_max_percent),
575 .mode = 0644,
576 .proc_handler = perf_cpu_time_max_percent_handler,
577 .extra1 = SYSCTL_ZERO,
578 .extra2 = SYSCTL_ONE_HUNDRED,
579 },
580};
581
582static int __init init_events_core_sysctls(void)
583{
584 register_sysctl_init("kernel", events_core_sysctl_table);
585 return 0;
586}
587core_initcall(init_events_core_sysctls);
588
589
14c63f17
DH
590/*
591 * perf samples are done in some very critical code paths (NMIs).
592 * If they take too much CPU time, the system can lock up and not
593 * get any real work done. This will drop the sample rate when
594 * we detect that events are taking too long.
595 */
596#define NR_ACCUMULATED_SAMPLES 128
d9494cb4 597static DEFINE_PER_CPU(u64, running_sample_length);
14c63f17 598
91a612ee
PZ
599static u64 __report_avg;
600static u64 __report_allowed;
601
6a02ad66 602static void perf_duration_warn(struct irq_work *w)
14c63f17 603{
0d87d7ec 604 printk_ratelimited(KERN_INFO
91a612ee
PZ
605 "perf: interrupt took too long (%lld > %lld), lowering "
606 "kernel.perf_event_max_sample_rate to %d\n",
607 __report_avg, __report_allowed,
608 sysctl_perf_event_sample_rate);
6a02ad66
PZ
609}
610
611static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
612
613void perf_sample_event_took(u64 sample_len_ns)
614{
91a612ee
PZ
615 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
616 u64 running_len;
617 u64 avg_len;
618 u32 max;
14c63f17 619
91a612ee 620 if (max_len == 0)
14c63f17
DH
621 return;
622
91a612ee
PZ
623 /* Decay the counter by 1 average sample. */
624 running_len = __this_cpu_read(running_sample_length);
625 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
626 running_len += sample_len_ns;
627 __this_cpu_write(running_sample_length, running_len);
14c63f17
DH
628
629 /*
ddd36b7e 630 * Note: this will be biased artificially low until we have
91a612ee 631 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
14c63f17
DH
632 * from having to maintain a count.
633 */
91a612ee
PZ
634 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
635 if (avg_len <= max_len)
14c63f17
DH
636 return;
637
91a612ee
PZ
638 __report_avg = avg_len;
639 __report_allowed = max_len;
14c63f17 640
91a612ee
PZ
641 /*
642 * Compute a throttle threshold 25% below the current duration.
643 */
644 avg_len += avg_len / 4;
645 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
646 if (avg_len < max)
647 max /= (u32)avg_len;
648 else
649 max = 1;
14c63f17 650
91a612ee
PZ
651 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
652 WRITE_ONCE(max_samples_per_tick, max);
653
654 sysctl_perf_event_sample_rate = max * HZ;
655 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
6a02ad66 656
cd578abb 657 if (!irq_work_queue(&perf_duration_work)) {
91a612ee 658 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
cd578abb 659 "kernel.perf_event_max_sample_rate to %d\n",
91a612ee 660 __report_avg, __report_allowed,
cd578abb
PZ
661 sysctl_perf_event_sample_rate);
662 }
14c63f17
DH
663}
664
cdd6c482 665static atomic64_t perf_event_id;
a96bbc16 666
e5d1367f
SE
667static void update_context_time(struct perf_event_context *ctx);
668static u64 perf_event_time(struct perf_event *event);
0b3fcf17 669
cdd6c482 670void __weak perf_event_print_debug(void) { }
0793a61d 671
0b3fcf17
SE
672static inline u64 perf_clock(void)
673{
674 return local_clock();
675}
676
34f43927
PZ
677static inline u64 perf_event_clock(struct perf_event *event)
678{
679 return event->clock();
680}
681
0d3d73aa
PZ
682/*
683 * State based event timekeeping...
684 *
685 * The basic idea is to use event->state to determine which (if any) time
686 * fields to increment with the current delta. This means we only need to
687 * update timestamps when we change state or when they are explicitly requested
688 * (read).
689 *
690 * Event groups make things a little more complicated, but not terribly so. The
691 * rules for a group are that if the group leader is OFF the entire group is
ddd36b7e 692 * OFF, irrespective of what the group member states are. This results in
0d3d73aa
PZ
693 * __perf_effective_state().
694 *
ddd36b7e 695 * A further ramification is that when a group leader flips between OFF and
0d3d73aa
PZ
696 * !OFF, we need to update all group member times.
697 *
698 *
699 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
700 * need to make sure the relevant context time is updated before we try and
701 * update our timestamps.
702 */
703
704static __always_inline enum perf_event_state
705__perf_effective_state(struct perf_event *event)
706{
707 struct perf_event *leader = event->group_leader;
708
709 if (leader->state <= PERF_EVENT_STATE_OFF)
710 return leader->state;
711
712 return event->state;
713}
714
715static __always_inline void
716__perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
717{
718 enum perf_event_state state = __perf_effective_state(event);
719 u64 delta = now - event->tstamp;
720
721 *enabled = event->total_time_enabled;
722 if (state >= PERF_EVENT_STATE_INACTIVE)
723 *enabled += delta;
724
725 *running = event->total_time_running;
726 if (state >= PERF_EVENT_STATE_ACTIVE)
727 *running += delta;
728}
729
730static void perf_event_update_time(struct perf_event *event)
731{
732 u64 now = perf_event_time(event);
733
734 __perf_update_times(event, now, &event->total_time_enabled,
735 &event->total_time_running);
736 event->tstamp = now;
737}
738
739static void perf_event_update_sibling_time(struct perf_event *leader)
740{
741 struct perf_event *sibling;
742
edb39592 743 for_each_sibling_event(sibling, leader)
0d3d73aa
PZ
744 perf_event_update_time(sibling);
745}
746
747static void
748perf_event_set_state(struct perf_event *event, enum perf_event_state state)
749{
750 if (event->state == state)
751 return;
752
753 perf_event_update_time(event);
754 /*
755 * If a group leader gets enabled/disabled all its siblings
756 * are affected too.
757 */
758 if ((event->state < 0) ^ (state < 0))
759 perf_event_update_sibling_time(event);
760
761 WRITE_ONCE(event->state, state);
762}
763
09f5e7dc
PZ
764/*
765 * UP store-release, load-acquire
766 */
767
768#define __store_release(ptr, val) \
769do { \
770 barrier(); \
771 WRITE_ONCE(*(ptr), (val)); \
772} while (0)
773
774#define __load_acquire(ptr) \
775({ \
776 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \
777 barrier(); \
778 ___p; \
779})
780
2d17cf1a
PZ
781#define for_each_epc(_epc, _ctx, _pmu, _cgroup) \
782 list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \
783 if (_cgroup && !_epc->nr_cgroups) \
784 continue; \
785 else if (_pmu && _epc->pmu != _pmu) \
786 continue; \
787 else
788
f06cc667 789static void perf_ctx_disable(struct perf_event_context *ctx, bool cgroup)
bd275681
PZ
790{
791 struct perf_event_pmu_context *pmu_ctx;
792
2d17cf1a 793 for_each_epc(pmu_ctx, ctx, NULL, cgroup)
bd275681
PZ
794 perf_pmu_disable(pmu_ctx->pmu);
795}
796
f06cc667 797static void perf_ctx_enable(struct perf_event_context *ctx, bool cgroup)
bd275681
PZ
798{
799 struct perf_event_pmu_context *pmu_ctx;
800
2d17cf1a 801 for_each_epc(pmu_ctx, ctx, NULL, cgroup)
bd275681
PZ
802 perf_pmu_enable(pmu_ctx->pmu);
803}
804
2d17cf1a
PZ
805static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
806static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type);
bd275681 807
e5d1367f
SE
808#ifdef CONFIG_CGROUP_PERF
809
e5d1367f
SE
810static inline bool
811perf_cgroup_match(struct perf_event *event)
812{
bd275681 813 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
e5d1367f 814
ef824fa1
TH
815 /* @event doesn't care about cgroup */
816 if (!event->cgrp)
817 return true;
818
819 /* wants specific cgroup scope but @cpuctx isn't associated with any */
820 if (!cpuctx->cgrp)
821 return false;
822
823 /*
824 * Cgroup scoping is recursive. An event enabled for a cgroup is
825 * also enabled for all its descendant cgroups. If @cpuctx's
826 * cgroup is a descendant of @event's (the test covers identity
827 * case), it's a match.
828 */
829 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
830 event->cgrp->css.cgroup);
e5d1367f
SE
831}
832
e5d1367f
SE
833static inline void perf_detach_cgroup(struct perf_event *event)
834{
4e2ba650 835 css_put(&event->cgrp->css);
e5d1367f
SE
836 event->cgrp = NULL;
837}
838
839static inline int is_cgroup_event(struct perf_event *event)
840{
841 return event->cgrp != NULL;
842}
843
844static inline u64 perf_cgroup_event_time(struct perf_event *event)
845{
846 struct perf_cgroup_info *t;
847
848 t = per_cpu_ptr(event->cgrp->info, event->cpu);
849 return t->time;
850}
851
09f5e7dc 852static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
e5d1367f 853{
09f5e7dc 854 struct perf_cgroup_info *t;
e5d1367f 855
09f5e7dc
PZ
856 t = per_cpu_ptr(event->cgrp->info, event->cpu);
857 if (!__load_acquire(&t->active))
858 return t->time;
859 now += READ_ONCE(t->timeoffset);
860 return now;
861}
e5d1367f 862
09f5e7dc
PZ
863static inline void __update_cgrp_time(struct perf_cgroup_info *info, u64 now, bool adv)
864{
865 if (adv)
866 info->time += now - info->timestamp;
e5d1367f 867 info->timestamp = now;
09f5e7dc
PZ
868 /*
869 * see update_context_time()
870 */
871 WRITE_ONCE(info->timeoffset, info->time - info->timestamp);
e5d1367f
SE
872}
873
09f5e7dc 874static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final)
e5d1367f 875{
c917e0f2
SL
876 struct perf_cgroup *cgrp = cpuctx->cgrp;
877 struct cgroup_subsys_state *css;
09f5e7dc 878 struct perf_cgroup_info *info;
c917e0f2
SL
879
880 if (cgrp) {
09f5e7dc
PZ
881 u64 now = perf_clock();
882
c917e0f2
SL
883 for (css = &cgrp->css; css; css = css->parent) {
884 cgrp = container_of(css, struct perf_cgroup, css);
09f5e7dc
PZ
885 info = this_cpu_ptr(cgrp->info);
886
887 __update_cgrp_time(info, now, true);
888 if (final)
889 __store_release(&info->active, 0);
c917e0f2
SL
890 }
891 }
e5d1367f
SE
892}
893
894static inline void update_cgrp_time_from_event(struct perf_event *event)
895{
09f5e7dc 896 struct perf_cgroup_info *info;
3f7cce3c 897
e5d1367f 898 /*
3f7cce3c
SE
899 * ensure we access cgroup data only when needed and
900 * when we know the cgroup is pinned (css_get)
e5d1367f 901 */
3f7cce3c 902 if (!is_cgroup_event(event))
e5d1367f
SE
903 return;
904
6875186a 905 info = this_cpu_ptr(event->cgrp->info);
3f7cce3c
SE
906 /*
907 * Do not update time when cgroup is not active
908 */
6875186a 909 if (info->active)
09f5e7dc 910 __update_cgrp_time(info, perf_clock(), true);
e5d1367f
SE
911}
912
913static inline void
a0827713 914perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
e5d1367f 915{
a0827713
CZ
916 struct perf_event_context *ctx = &cpuctx->ctx;
917 struct perf_cgroup *cgrp = cpuctx->cgrp;
e5d1367f 918 struct perf_cgroup_info *info;
c917e0f2 919 struct cgroup_subsys_state *css;
e5d1367f 920
3f7cce3c
SE
921 /*
922 * ctx->lock held by caller
923 * ensure we do not access cgroup data
924 * unless we have the cgroup pinned (css_get)
925 */
a0827713 926 if (!cgrp)
e5d1367f
SE
927 return;
928
a0827713 929 WARN_ON_ONCE(!ctx->nr_cgroups);
c917e0f2
SL
930
931 for (css = &cgrp->css; css; css = css->parent) {
932 cgrp = container_of(css, struct perf_cgroup, css);
933 info = this_cpu_ptr(cgrp->info);
09f5e7dc
PZ
934 __update_cgrp_time(info, ctx->timestamp, false);
935 __store_release(&info->active, 1);
c917e0f2 936 }
e5d1367f
SE
937}
938
e5d1367f
SE
939/*
940 * reschedule events based on the cgroup constraint of task.
e5d1367f 941 */
96492a6c 942static void perf_cgroup_switch(struct task_struct *task)
e5d1367f 943{
bd275681 944 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
96492a6c 945 struct perf_cgroup *cgrp;
e5d1367f 946
f841b682
CZ
947 /*
948 * cpuctx->cgrp is set when the first cgroup event enabled,
949 * and is cleared when the last cgroup event disabled.
950 */
951 if (READ_ONCE(cpuctx->cgrp) == NULL)
952 return;
96492a6c 953
bd275681 954 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
f841b682
CZ
955
956 cgrp = perf_cgroup_from_task(task, NULL);
bd275681
PZ
957 if (READ_ONCE(cpuctx->cgrp) == cgrp)
958 return;
e5d1367f 959
3172fb98
LG
960 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx);
961 /*
962 * Re-check, could've raced vs perf_remove_from_context().
963 */
964 if (READ_ONCE(cpuctx->cgrp) == NULL)
965 return;
966
f06cc667 967 perf_ctx_disable(&cpuctx->ctx, true);
e5d1367f 968
2d17cf1a 969 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
bd275681
PZ
970 /*
971 * must not be done before ctxswout due
972 * to update_cgrp_time_from_cpuctx() in
973 * ctx_sched_out()
974 */
975 cpuctx->cgrp = cgrp;
976 /*
977 * set cgrp before ctxsw in to allow
978 * perf_cgroup_set_timestamp() in ctx_sched_in()
979 * to not have to pass task around
980 */
2d17cf1a 981 ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP);
e5d1367f 982
f06cc667 983 perf_ctx_enable(&cpuctx->ctx, true);
e5d1367f
SE
984}
985
c2283c93
IR
986static int perf_cgroup_ensure_storage(struct perf_event *event,
987 struct cgroup_subsys_state *css)
988{
989 struct perf_cpu_context *cpuctx;
990 struct perf_event **storage;
991 int cpu, heap_size, ret = 0;
992
993 /*
ddd36b7e 994 * Allow storage to have sufficient space for an iterator for each
c2283c93
IR
995 * possibly nested cgroup plus an iterator for events with no cgroup.
996 */
997 for (heap_size = 1; css; css = css->parent)
998 heap_size++;
999
1000 for_each_possible_cpu(cpu) {
bd275681 1001 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
c2283c93
IR
1002 if (heap_size <= cpuctx->heap_size)
1003 continue;
1004
1005 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
1006 GFP_KERNEL, cpu_to_node(cpu));
1007 if (!storage) {
1008 ret = -ENOMEM;
1009 break;
1010 }
1011
1012 raw_spin_lock_irq(&cpuctx->ctx.lock);
1013 if (cpuctx->heap_size < heap_size) {
1014 swap(cpuctx->heap, storage);
1015 if (storage == cpuctx->heap_default)
1016 storage = NULL;
1017 cpuctx->heap_size = heap_size;
1018 }
1019 raw_spin_unlock_irq(&cpuctx->ctx.lock);
1020
1021 kfree(storage);
1022 }
1023
1024 return ret;
1025}
1026
e5d1367f
SE
1027static inline int perf_cgroup_connect(int fd, struct perf_event *event,
1028 struct perf_event_attr *attr,
1029 struct perf_event *group_leader)
1030{
1031 struct perf_cgroup *cgrp;
1032 struct cgroup_subsys_state *css;
6348be02 1033 CLASS(fd, f)(fd);
2903ff01 1034 int ret = 0;
e5d1367f 1035
6348be02 1036 if (fd_empty(f))
e5d1367f
SE
1037 return -EBADF;
1038
1da91ea8 1039 css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry,
ec903c0c 1040 &perf_event_cgrp_subsys);
6348be02
AV
1041 if (IS_ERR(css))
1042 return PTR_ERR(css);
e5d1367f 1043
c2283c93
IR
1044 ret = perf_cgroup_ensure_storage(event, css);
1045 if (ret)
6348be02 1046 return ret;
c2283c93 1047
e5d1367f
SE
1048 cgrp = container_of(css, struct perf_cgroup, css);
1049 event->cgrp = cgrp;
1050
1051 /*
1052 * all events in a group must monitor
1053 * the same cgroup because a task belongs
1054 * to only one perf cgroup at a time
1055 */
1056 if (group_leader && group_leader->cgrp != cgrp) {
1057 perf_detach_cgroup(event);
1058 ret = -EINVAL;
e5d1367f 1059 }
e5d1367f
SE
1060 return ret;
1061}
1062
db4a8356 1063static inline void
33238c50 1064perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
db4a8356
DCC
1065{
1066 struct perf_cpu_context *cpuctx;
1067
1068 if (!is_cgroup_event(event))
1069 return;
1070
f06cc667
PZ
1071 event->pmu_ctx->nr_cgroups++;
1072
db4a8356
DCC
1073 /*
1074 * Because cgroup events are always per-cpu events,
07c59729 1075 * @ctx == &cpuctx->ctx.
db4a8356 1076 */
07c59729 1077 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
33801b94 1078
33238c50 1079 if (ctx->nr_cgroups++)
33801b94 1080 return;
33238c50 1081
e19cd0b6 1082 cpuctx->cgrp = perf_cgroup_from_task(current, ctx);
33238c50
PZ
1083}
1084
1085static inline void
1086perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1087{
1088 struct perf_cpu_context *cpuctx;
1089
1090 if (!is_cgroup_event(event))
33801b94 1091 return;
1092
f06cc667
PZ
1093 event->pmu_ctx->nr_cgroups--;
1094
33238c50
PZ
1095 /*
1096 * Because cgroup events are always per-cpu events,
1097 * @ctx == &cpuctx->ctx.
1098 */
1099 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
1100
1101 if (--ctx->nr_cgroups)
1102 return;
1103
e19cd0b6 1104 cpuctx->cgrp = NULL;
db4a8356
DCC
1105}
1106
e5d1367f
SE
1107#else /* !CONFIG_CGROUP_PERF */
1108
1109static inline bool
1110perf_cgroup_match(struct perf_event *event)
1111{
1112 return true;
1113}
1114
1115static inline void perf_detach_cgroup(struct perf_event *event)
1116{}
1117
1118static inline int is_cgroup_event(struct perf_event *event)
1119{
1120 return 0;
1121}
1122
e5d1367f
SE
1123static inline void update_cgrp_time_from_event(struct perf_event *event)
1124{
1125}
1126
09f5e7dc
PZ
1127static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx,
1128 bool final)
e5d1367f
SE
1129{
1130}
1131
e5d1367f
SE
1132static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1133 struct perf_event_attr *attr,
1134 struct perf_event *group_leader)
1135{
1136 return -EINVAL;
1137}
1138
1139static inline void
a0827713 1140perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx)
e5d1367f
SE
1141{
1142}
1143
09f5e7dc 1144static inline u64 perf_cgroup_event_time(struct perf_event *event)
e5d1367f 1145{
09f5e7dc 1146 return 0;
e5d1367f
SE
1147}
1148
09f5e7dc 1149static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now)
e5d1367f
SE
1150{
1151 return 0;
1152}
1153
db4a8356 1154static inline void
33238c50 1155perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx)
db4a8356
DCC
1156{
1157}
1158
33238c50
PZ
1159static inline void
1160perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx)
1161{
1162}
96492a6c
CZ
1163
1164static void perf_cgroup_switch(struct task_struct *task)
1165{
1166}
e5d1367f
SE
1167#endif
1168
9e630205
SE
1169/*
1170 * set default to be dependent on timer tick just
1171 * like original code
1172 */
1173#define PERF_CPU_HRTIMER (1000 / HZ)
1174/*
8a1115ff 1175 * function must be called with interrupts disabled
9e630205 1176 */
272325c4 1177static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
9e630205 1178{
bd275681 1179 struct perf_cpu_pmu_context *cpc;
8d5bce0c 1180 bool rotations;
9e630205 1181
16444645 1182 lockdep_assert_irqs_disabled();
9e630205 1183
bd275681
PZ
1184 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer);
1185 rotations = perf_rotate_context(cpc);
9e630205 1186
bd275681 1187 raw_spin_lock(&cpc->hrtimer_lock);
4cfafd30 1188 if (rotations)
bd275681 1189 hrtimer_forward_now(hr, cpc->hrtimer_interval);
4cfafd30 1190 else
bd275681
PZ
1191 cpc->hrtimer_active = 0;
1192 raw_spin_unlock(&cpc->hrtimer_lock);
9e630205 1193
4cfafd30 1194 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
9e630205
SE
1195}
1196
bd275681 1197static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu)
9e630205 1198{
bd275681
PZ
1199 struct hrtimer *timer = &cpc->hrtimer;
1200 struct pmu *pmu = cpc->epc.pmu;
272325c4 1201 u64 interval;
9e630205 1202
62b85639
SE
1203 /*
1204 * check default is sane, if not set then force to
1205 * default interval (1/tick)
1206 */
272325c4
PZ
1207 interval = pmu->hrtimer_interval_ms;
1208 if (interval < 1)
1209 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
62b85639 1210
bd275681 1211 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
9e630205 1212
bd275681 1213 raw_spin_lock_init(&cpc->hrtimer_lock);
022a2235
NC
1214 hrtimer_setup(timer, perf_mux_hrtimer_handler, CLOCK_MONOTONIC,
1215 HRTIMER_MODE_ABS_PINNED_HARD);
9e630205
SE
1216}
1217
bd275681 1218static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc)
9e630205 1219{
bd275681 1220 struct hrtimer *timer = &cpc->hrtimer;
4cfafd30 1221 unsigned long flags;
9e630205 1222
bd275681
PZ
1223 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags);
1224 if (!cpc->hrtimer_active) {
1225 cpc->hrtimer_active = 1;
1226 hrtimer_forward_now(timer, cpc->hrtimer_interval);
30f9028b 1227 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
4cfafd30 1228 }
bd275681 1229 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags);
9e630205 1230
272325c4 1231 return 0;
9e630205
SE
1232}
1233
1af6239d
PZ
1234static int perf_mux_hrtimer_restart_ipi(void *arg)
1235{
1236 return perf_mux_hrtimer_restart(arg);
1237}
1238
b2996f56
PZ
1239static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu)
1240{
4eabf533 1241 return *this_cpu_ptr(pmu->cpu_pmu_context);
b2996f56
PZ
1242}
1243
33696fc0 1244void perf_pmu_disable(struct pmu *pmu)
9e35ad38 1245{
b2996f56 1246 int *count = &this_cpc(pmu)->pmu_disable_count;
33696fc0
PZ
1247 if (!(*count)++)
1248 pmu->pmu_disable(pmu);
9e35ad38 1249}
9e35ad38 1250
33696fc0 1251void perf_pmu_enable(struct pmu *pmu)
9e35ad38 1252{
b2996f56 1253 int *count = &this_cpc(pmu)->pmu_disable_count;
33696fc0
PZ
1254 if (!--(*count))
1255 pmu->pmu_enable(pmu);
9e35ad38 1256}
9e35ad38 1257
bd275681 1258static void perf_assert_pmu_disabled(struct pmu *pmu)
2fde4f94 1259{
b2996f56 1260 int *count = &this_cpc(pmu)->pmu_disable_count;
4baeb068 1261 WARN_ON_ONCE(*count == 0);
9e35ad38 1262}
9e35ad38 1263
8ce939a0
PZI
1264static inline void perf_pmu_read(struct perf_event *event)
1265{
1266 if (event->state == PERF_EVENT_STATE_ACTIVE)
1267 event->pmu->read(event);
1268}
1269
cdd6c482 1270static void get_ctx(struct perf_event_context *ctx)
a63eaf34 1271{
8c94abbb 1272 refcount_inc(&ctx->refcount);
a63eaf34
PM
1273}
1274
4af57ef2
YZ
1275static void free_ctx(struct rcu_head *head)
1276{
1277 struct perf_event_context *ctx;
1278
1279 ctx = container_of(head, struct perf_event_context, rcu_head);
4af57ef2
YZ
1280 kfree(ctx);
1281}
1282
cdd6c482 1283static void put_ctx(struct perf_event_context *ctx)
a63eaf34 1284{
8c94abbb 1285 if (refcount_dec_and_test(&ctx->refcount)) {
564c2b21
PM
1286 if (ctx->parent_ctx)
1287 put_ctx(ctx->parent_ctx);
63b6da39 1288 if (ctx->task && ctx->task != TASK_TOMBSTONE)
c93f7669 1289 put_task_struct(ctx->task);
4af57ef2 1290 call_rcu(&ctx->rcu_head, free_ctx);
2839f393
FW
1291 } else {
1292 smp_mb__after_atomic(); /* pairs with wait_var_event() */
1293 if (ctx->task == TASK_TOMBSTONE)
1294 wake_up_var(&ctx->refcount);
564c2b21 1295 }
a63eaf34
PM
1296}
1297
f63a8daa
PZ
1298/*
1299 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1300 * perf_pmu_migrate_context() we need some magic.
1301 *
1302 * Those places that change perf_event::ctx will hold both
1303 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1304 *
8b10c5e2
PZ
1305 * Lock ordering is by mutex address. There are two other sites where
1306 * perf_event_context::mutex nests and those are:
1307 *
1308 * - perf_event_exit_task_context() [ child , 0 ]
8ba289b8
PZ
1309 * perf_event_exit_event()
1310 * put_event() [ parent, 1 ]
8b10c5e2
PZ
1311 *
1312 * - perf_event_init_context() [ parent, 0 ]
1313 * inherit_task_group()
1314 * inherit_group()
1315 * inherit_event()
1316 * perf_event_alloc()
1317 * perf_init_event()
1318 * perf_try_init_event() [ child , 1 ]
1319 *
1320 * While it appears there is an obvious deadlock here -- the parent and child
1321 * nesting levels are inverted between the two. This is in fact safe because
1322 * life-time rules separate them. That is an exiting task cannot fork, and a
1323 * spawning task cannot (yet) exit.
1324 *
c034f48e 1325 * But remember that these are parent<->child context relations, and
8b10c5e2
PZ
1326 * migration does not affect children, therefore these two orderings should not
1327 * interact.
f63a8daa
PZ
1328 *
1329 * The change in perf_event::ctx does not affect children (as claimed above)
1330 * because the sys_perf_event_open() case will install a new event and break
1331 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1332 * concerned with cpuctx and that doesn't have children.
1333 *
1334 * The places that change perf_event::ctx will issue:
1335 *
1336 * perf_remove_from_context();
1337 * synchronize_rcu();
1338 * perf_install_in_context();
1339 *
1340 * to affect the change. The remove_from_context() + synchronize_rcu() should
1341 * quiesce the event, after which we can install it in the new location. This
1342 * means that only external vectors (perf_fops, prctl) can perturb the event
1343 * while in transit. Therefore all such accessors should also acquire
1344 * perf_event_context::mutex to serialize against this.
1345 *
1346 * However; because event->ctx can change while we're waiting to acquire
1347 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1348 * function.
1349 *
1350 * Lock order:
f7cfd871 1351 * exec_update_lock
f63a8daa
PZ
1352 * task_struct::perf_event_mutex
1353 * perf_event_context::mutex
f63a8daa 1354 * perf_event::child_mutex;
07c4a776 1355 * perf_event_context::lock
c1e8d7c6 1356 * mmap_lock
2ab9d830
PZ
1357 * perf_event::mmap_mutex
1358 * perf_buffer::aux_mutex
18736eef 1359 * perf_addr_filters_head::lock
82d94856
PZ
1360 *
1361 * cpu_hotplug_lock
1362 * pmus_lock
1363 * cpuctx->mutex / perf_event_context::mutex
f63a8daa 1364 */
a83fe28e
PZ
1365static struct perf_event_context *
1366perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
f63a8daa
PZ
1367{
1368 struct perf_event_context *ctx;
1369
1370again:
1371 rcu_read_lock();
6aa7de05 1372 ctx = READ_ONCE(event->ctx);
8c94abbb 1373 if (!refcount_inc_not_zero(&ctx->refcount)) {
f63a8daa
PZ
1374 rcu_read_unlock();
1375 goto again;
1376 }
1377 rcu_read_unlock();
1378
a83fe28e 1379 mutex_lock_nested(&ctx->mutex, nesting);
f63a8daa
PZ
1380 if (event->ctx != ctx) {
1381 mutex_unlock(&ctx->mutex);
1382 put_ctx(ctx);
1383 goto again;
1384 }
1385
1386 return ctx;
1387}
1388
a83fe28e
PZ
1389static inline struct perf_event_context *
1390perf_event_ctx_lock(struct perf_event *event)
1391{
1392 return perf_event_ctx_lock_nested(event, 0);
1393}
1394
f63a8daa
PZ
1395static void perf_event_ctx_unlock(struct perf_event *event,
1396 struct perf_event_context *ctx)
1397{
1398 mutex_unlock(&ctx->mutex);
1399 put_ctx(ctx);
1400}
1401
211de6eb
PZ
1402/*
1403 * This must be done under the ctx->lock, such as to serialize against
1404 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1405 * calling scheduler related locks and ctx->lock nests inside those.
1406 */
1407static __must_check struct perf_event_context *
1408unclone_ctx(struct perf_event_context *ctx)
71a851b4 1409{
211de6eb
PZ
1410 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1411
1412 lockdep_assert_held(&ctx->lock);
1413
1414 if (parent_ctx)
71a851b4 1415 ctx->parent_ctx = NULL;
5a3126d4 1416 ctx->generation++;
211de6eb
PZ
1417
1418 return parent_ctx;
71a851b4
PZ
1419}
1420
1d953111
ON
1421static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1422 enum pid_type type)
6844c09d 1423{
1d953111 1424 u32 nr;
6844c09d
ACM
1425 /*
1426 * only top level events have the pid namespace they were created in
1427 */
1428 if (event->parent)
1429 event = event->parent;
1430
1d953111
ON
1431 nr = __task_pid_nr_ns(p, type, event->ns);
1432 /* avoid -1 if it is idle thread or runs in another ns */
1433 if (!nr && !pid_alive(p))
1434 nr = -1;
1435 return nr;
6844c09d
ACM
1436}
1437
1d953111 1438static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
6844c09d 1439{
6883f81a 1440 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1d953111 1441}
6844c09d 1442
1d953111
ON
1443static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1444{
1445 return perf_event_pid_type(event, p, PIDTYPE_PID);
6844c09d
ACM
1446}
1447
7f453c24 1448/*
cdd6c482 1449 * If we inherit events we want to return the parent event id
7f453c24
PZ
1450 * to userspace.
1451 */
cdd6c482 1452static u64 primary_event_id(struct perf_event *event)
7f453c24 1453{
cdd6c482 1454 u64 id = event->id;
7f453c24 1455
cdd6c482
IM
1456 if (event->parent)
1457 id = event->parent->id;
7f453c24
PZ
1458
1459 return id;
1460}
1461
25346b93 1462/*
cdd6c482 1463 * Get the perf_event_context for a task and lock it.
63b6da39 1464 *
c034f48e 1465 * This has to cope with the fact that until it is locked,
25346b93
PM
1466 * the context could get moved to another task.
1467 */
cdd6c482 1468static struct perf_event_context *
bd275681 1469perf_lock_task_context(struct task_struct *task, unsigned long *flags)
25346b93 1470{
cdd6c482 1471 struct perf_event_context *ctx;
25346b93 1472
9ed6060d 1473retry:
058ebd0e
PZ
1474 /*
1475 * One of the few rules of preemptible RCU is that one cannot do
1476 * rcu_read_unlock() while holding a scheduler (or nested) lock when
2fd59077 1477 * part of the read side critical section was irqs-enabled -- see
058ebd0e
PZ
1478 * rcu_read_unlock_special().
1479 *
1480 * Since ctx->lock nests under rq->lock we must ensure the entire read
2fd59077 1481 * side critical section has interrupts disabled.
058ebd0e 1482 */
2fd59077 1483 local_irq_save(*flags);
058ebd0e 1484 rcu_read_lock();
bd275681 1485 ctx = rcu_dereference(task->perf_event_ctxp);
25346b93
PM
1486 if (ctx) {
1487 /*
1488 * If this context is a clone of another, it might
1489 * get swapped for another underneath us by
cdd6c482 1490 * perf_event_task_sched_out, though the
25346b93
PM
1491 * rcu_read_lock() protects us from any context
1492 * getting freed. Lock the context and check if it
1493 * got swapped before we could get the lock, and retry
1494 * if so. If we locked the right context, then it
1495 * can't get swapped on us any more.
1496 */
2fd59077 1497 raw_spin_lock(&ctx->lock);
bd275681 1498 if (ctx != rcu_dereference(task->perf_event_ctxp)) {
2fd59077 1499 raw_spin_unlock(&ctx->lock);
058ebd0e 1500 rcu_read_unlock();
2fd59077 1501 local_irq_restore(*flags);
25346b93
PM
1502 goto retry;
1503 }
b49a9e7e 1504
63b6da39 1505 if (ctx->task == TASK_TOMBSTONE ||
8c94abbb 1506 !refcount_inc_not_zero(&ctx->refcount)) {
2fd59077 1507 raw_spin_unlock(&ctx->lock);
b49a9e7e 1508 ctx = NULL;
828b6f0e
PZ
1509 } else {
1510 WARN_ON_ONCE(ctx->task != task);
b49a9e7e 1511 }
25346b93
PM
1512 }
1513 rcu_read_unlock();
2fd59077
PM
1514 if (!ctx)
1515 local_irq_restore(*flags);
25346b93
PM
1516 return ctx;
1517}
1518
1519/*
1520 * Get the context for a task and increment its pin_count so it
1521 * can't get swapped to another task. This also increments its
1522 * reference count so that the context can't get freed.
1523 */
8dc85d54 1524static struct perf_event_context *
bd275681 1525perf_pin_task_context(struct task_struct *task)
25346b93 1526{
cdd6c482 1527 struct perf_event_context *ctx;
25346b93
PM
1528 unsigned long flags;
1529
bd275681 1530 ctx = perf_lock_task_context(task, &flags);
25346b93
PM
1531 if (ctx) {
1532 ++ctx->pin_count;
e625cce1 1533 raw_spin_unlock_irqrestore(&ctx->lock, flags);
25346b93
PM
1534 }
1535 return ctx;
1536}
1537
cdd6c482 1538static void perf_unpin_context(struct perf_event_context *ctx)
25346b93
PM
1539{
1540 unsigned long flags;
1541
e625cce1 1542 raw_spin_lock_irqsave(&ctx->lock, flags);
25346b93 1543 --ctx->pin_count;
e625cce1 1544 raw_spin_unlock_irqrestore(&ctx->lock, flags);
25346b93
PM
1545}
1546
f67218c3
PZ
1547/*
1548 * Update the record of the current time in a context.
1549 */
09f5e7dc 1550static void __update_context_time(struct perf_event_context *ctx, bool adv)
f67218c3
PZ
1551{
1552 u64 now = perf_clock();
1553
f3c0eba2
PZ
1554 lockdep_assert_held(&ctx->lock);
1555
09f5e7dc
PZ
1556 if (adv)
1557 ctx->time += now - ctx->timestamp;
f67218c3 1558 ctx->timestamp = now;
09f5e7dc
PZ
1559
1560 /*
1561 * The above: time' = time + (now - timestamp), can be re-arranged
1562 * into: time` = now + (time - timestamp), which gives a single value
1563 * offset to compute future time without locks on.
1564 *
1565 * See perf_event_time_now(), which can be used from NMI context where
1566 * it's (obviously) not possible to acquire ctx->lock in order to read
1567 * both the above values in a consistent manner.
1568 */
1569 WRITE_ONCE(ctx->timeoffset, ctx->time - ctx->timestamp);
1570}
1571
1572static void update_context_time(struct perf_event_context *ctx)
1573{
1574 __update_context_time(ctx, true);
f67218c3
PZ
1575}
1576
4158755d
SE
1577static u64 perf_event_time(struct perf_event *event)
1578{
1579 struct perf_event_context *ctx = event->ctx;
e5d1367f 1580
09f5e7dc
PZ
1581 if (unlikely(!ctx))
1582 return 0;
1583
e5d1367f
SE
1584 if (is_cgroup_event(event))
1585 return perf_cgroup_event_time(event);
1586
09f5e7dc
PZ
1587 return ctx->time;
1588}
1589
1590static u64 perf_event_time_now(struct perf_event *event, u64 now)
1591{
1592 struct perf_event_context *ctx = event->ctx;
1593
1594 if (unlikely(!ctx))
1595 return 0;
1596
1597 if (is_cgroup_event(event))
1598 return perf_cgroup_event_time_now(event, now);
1599
1600 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME))
1601 return ctx->time;
1602
1603 now += READ_ONCE(ctx->timeoffset);
1604 return now;
4158755d
SE
1605}
1606
487f05e1
AS
1607static enum event_type_t get_event_type(struct perf_event *event)
1608{
1609 struct perf_event_context *ctx = event->ctx;
1610 enum event_type_t event_type;
1611
1612 lockdep_assert_held(&ctx->lock);
1613
3bda69c1
AS
1614 /*
1615 * It's 'group type', really, because if our group leader is
1616 * pinned, so are we.
1617 */
1618 if (event->group_leader != event)
1619 event = event->group_leader;
1620
487f05e1
AS
1621 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1622 if (!ctx->task)
1623 event_type |= EVENT_CPU;
1624
1625 return event_type;
1626}
1627
8e1a2031 1628/*
161c85fa 1629 * Helper function to initialize event group nodes.
8e1a2031 1630 */
161c85fa 1631static void init_event_group(struct perf_event *event)
8e1a2031
AB
1632{
1633 RB_CLEAR_NODE(&event->group_node);
1634 event->group_index = 0;
1635}
1636
1637/*
1638 * Extract pinned or flexible groups from the context
161c85fa 1639 * based on event attrs bits.
8e1a2031
AB
1640 */
1641static struct perf_event_groups *
1642get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
889ff015
FW
1643{
1644 if (event->attr.pinned)
1645 return &ctx->pinned_groups;
1646 else
1647 return &ctx->flexible_groups;
1648}
1649
8e1a2031 1650/*
161c85fa 1651 * Helper function to initializes perf_event_group trees.
8e1a2031 1652 */
161c85fa 1653static void perf_event_groups_init(struct perf_event_groups *groups)
8e1a2031
AB
1654{
1655 groups->tree = RB_ROOT;
1656 groups->index = 0;
1657}
1658
a3b89864
PZ
1659static inline struct cgroup *event_cgroup(const struct perf_event *event)
1660{
1661 struct cgroup *cgroup = NULL;
1662
1663#ifdef CONFIG_CGROUP_PERF
1664 if (event->cgrp)
1665 cgroup = event->cgrp->css.cgroup;
1666#endif
1667
1668 return cgroup;
1669}
1670
8e1a2031
AB
1671/*
1672 * Compare function for event groups;
161c85fa
PZ
1673 *
1674 * Implements complex key that first sorts by CPU and then by virtual index
1675 * which provides ordering when rotating groups for the same CPU.
8e1a2031 1676 */
a3b89864 1677static __always_inline int
bd275681
PZ
1678perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu,
1679 const struct cgroup *left_cgroup, const u64 left_group_index,
1680 const struct perf_event *right)
8e1a2031 1681{
a3b89864
PZ
1682 if (left_cpu < right->cpu)
1683 return -1;
1684 if (left_cpu > right->cpu)
1685 return 1;
161c85fa 1686
bd275681
PZ
1687 if (left_pmu) {
1688 if (left_pmu < right->pmu_ctx->pmu)
1689 return -1;
1690 if (left_pmu > right->pmu_ctx->pmu)
1691 return 1;
1692 }
1693
95ed6c70 1694#ifdef CONFIG_CGROUP_PERF
a3b89864
PZ
1695 {
1696 const struct cgroup *right_cgroup = event_cgroup(right);
1697
1698 if (left_cgroup != right_cgroup) {
1699 if (!left_cgroup) {
1700 /*
1701 * Left has no cgroup but right does, no
1702 * cgroups come first.
1703 */
1704 return -1;
1705 }
1706 if (!right_cgroup) {
1707 /*
1708 * Right has no cgroup but left does, no
1709 * cgroups come first.
1710 */
1711 return 1;
1712 }
1713 /* Two dissimilar cgroups, order by id. */
1714 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup))
1715 return -1;
1716
1717 return 1;
95ed6c70 1718 }
95ed6c70
IR
1719 }
1720#endif
1721
a3b89864
PZ
1722 if (left_group_index < right->group_index)
1723 return -1;
1724 if (left_group_index > right->group_index)
1725 return 1;
1726
1727 return 0;
1728}
161c85fa 1729
a3b89864
PZ
1730#define __node_2_pe(node) \
1731 rb_entry((node), struct perf_event, group_node)
1732
1733static inline bool __group_less(struct rb_node *a, const struct rb_node *b)
1734{
1735 struct perf_event *e = __node_2_pe(a);
bd275681
PZ
1736 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e),
1737 e->group_index, __node_2_pe(b)) < 0;
a3b89864
PZ
1738}
1739
1740struct __group_key {
1741 int cpu;
bd275681 1742 struct pmu *pmu;
a3b89864
PZ
1743 struct cgroup *cgroup;
1744};
1745
1746static inline int __group_cmp(const void *key, const struct rb_node *node)
1747{
1748 const struct __group_key *a = key;
1749 const struct perf_event *b = __node_2_pe(node);
1750
bd275681
PZ
1751 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */
1752 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b);
1753}
1754
1755static inline int
1756__group_cmp_ignore_cgroup(const void *key, const struct rb_node *node)
1757{
1758 const struct __group_key *a = key;
1759 const struct perf_event *b = __node_2_pe(node);
1760
1761 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */
1762 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b),
1763 b->group_index, b);
8e1a2031
AB
1764}
1765
1766/*
bd275681
PZ
1767 * Insert @event into @groups' tree; using
1768 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index}
1769 * as key. This places it last inside the {cpu,pmu,cgroup} subtree.
8e1a2031
AB
1770 */
1771static void
1772perf_event_groups_insert(struct perf_event_groups *groups,
161c85fa 1773 struct perf_event *event)
8e1a2031 1774{
8e1a2031
AB
1775 event->group_index = ++groups->index;
1776
a3b89864 1777 rb_add(&event->group_node, &groups->tree, __group_less);
8e1a2031
AB
1778}
1779
1780/*
161c85fa 1781 * Helper function to insert event into the pinned or flexible groups.
8e1a2031
AB
1782 */
1783static void
1784add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1785{
1786 struct perf_event_groups *groups;
1787
1788 groups = get_event_groups(event, ctx);
1789 perf_event_groups_insert(groups, event);
1790}
1791
1792/*
161c85fa 1793 * Delete a group from a tree.
8e1a2031
AB
1794 */
1795static void
1796perf_event_groups_delete(struct perf_event_groups *groups,
161c85fa 1797 struct perf_event *event)
8e1a2031 1798{
161c85fa
PZ
1799 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1800 RB_EMPTY_ROOT(&groups->tree));
8e1a2031 1801
161c85fa 1802 rb_erase(&event->group_node, &groups->tree);
8e1a2031
AB
1803 init_event_group(event);
1804}
1805
1806/*
161c85fa 1807 * Helper function to delete event from its groups.
8e1a2031
AB
1808 */
1809static void
1810del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1811{
1812 struct perf_event_groups *groups;
1813
1814 groups = get_event_groups(event, ctx);
1815 perf_event_groups_delete(groups, event);
1816}
1817
1818/*
bd275681 1819 * Get the leftmost event in the {cpu,pmu,cgroup} subtree.
8e1a2031
AB
1820 */
1821static struct perf_event *
95ed6c70 1822perf_event_groups_first(struct perf_event_groups *groups, int cpu,
bd275681 1823 struct pmu *pmu, struct cgroup *cgrp)
8e1a2031 1824{
a3b89864
PZ
1825 struct __group_key key = {
1826 .cpu = cpu,
bd275681 1827 .pmu = pmu,
a3b89864
PZ
1828 .cgroup = cgrp,
1829 };
1830 struct rb_node *node;
95ed6c70 1831
a3b89864
PZ
1832 node = rb_find_first(&key, &groups->tree, __group_cmp);
1833 if (node)
1834 return __node_2_pe(node);
8e1a2031 1835
a3b89864 1836 return NULL;
8e1a2031
AB
1837}
1838
1cac7b1a 1839static struct perf_event *
bd275681 1840perf_event_groups_next(struct perf_event *event, struct pmu *pmu)
1cac7b1a 1841{
a3b89864
PZ
1842 struct __group_key key = {
1843 .cpu = event->cpu,
bd275681 1844 .pmu = pmu,
a3b89864
PZ
1845 .cgroup = event_cgroup(event),
1846 };
1847 struct rb_node *next;
1cac7b1a 1848
a3b89864
PZ
1849 next = rb_next_match(&key, &event->group_node, __group_cmp);
1850 if (next)
1851 return __node_2_pe(next);
95ed6c70 1852
a3b89864 1853 return NULL;
1cac7b1a
PZ
1854}
1855
bd275681
PZ
1856#define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \
1857 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \
1858 event; event = perf_event_groups_next(event, pmu))
1859
8e1a2031 1860/*
161c85fa 1861 * Iterate through the whole groups tree.
8e1a2031 1862 */
6e6804d2
PZ
1863#define perf_event_groups_for_each(event, groups) \
1864 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1865 typeof(*event), group_node); event; \
1866 event = rb_entry_safe(rb_next(&event->group_node), \
1867 typeof(*event), group_node))
8e1a2031 1868
7e8b2556
BG
1869/*
1870 * Does the event attribute request inherit with PERF_SAMPLE_READ
1871 */
1872static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr)
1873{
1874 return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ);
1875}
1876
fccc714b 1877/*
788faab7 1878 * Add an event from the lists for its context.
fccc714b
PZ
1879 * Must be called with ctx->mutex and ctx->lock held.
1880 */
04289bb9 1881static void
cdd6c482 1882list_add_event(struct perf_event *event, struct perf_event_context *ctx)
04289bb9 1883{
c994d613
PZ
1884 lockdep_assert_held(&ctx->lock);
1885
8a49542c
PZ
1886 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1887 event->attach_state |= PERF_ATTACH_CONTEXT;
04289bb9 1888
0d3d73aa
PZ
1889 event->tstamp = perf_event_time(event);
1890
04289bb9 1891 /*
8a49542c
PZ
1892 * If we're a stand alone event or group leader, we go to the context
1893 * list, group events are kept attached to the group so that
1894 * perf_group_detach can, at all times, locate all siblings.
04289bb9 1895 */
8a49542c 1896 if (event->group_leader == event) {
4ff6a8de 1897 event->group_caps = event->event_caps;
8e1a2031 1898 add_event_to_groups(event, ctx);
5c148194 1899 }
592903cd 1900
cdd6c482
IM
1901 list_add_rcu(&event->event_entry, &ctx->event_list);
1902 ctx->nr_events++;
82ff0c02
RH
1903 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
1904 ctx->nr_user++;
cdd6c482 1905 if (event->attr.inherit_stat)
bfbd3381 1906 ctx->nr_stat++;
7e8b2556
BG
1907 if (has_inherit_and_sample_read(&event->attr))
1908 local_inc(&ctx->nr_no_switch_fast);
5a3126d4 1909
33238c50
PZ
1910 if (event->state > PERF_EVENT_STATE_OFF)
1911 perf_cgroup_event_enable(event, ctx);
1912
5a3126d4 1913 ctx->generation++;
bd275681 1914 event->pmu_ctx->nr_events++;
04289bb9
IM
1915}
1916
0231bb53
JO
1917/*
1918 * Initialize event state based on the perf_event_attr::disabled.
1919 */
1920static inline void perf_event__state_init(struct perf_event *event)
1921{
1922 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1923 PERF_EVENT_STATE_INACTIVE;
1924}
1925
382c27f4 1926static int __perf_event_read_size(u64 read_format, int nr_siblings)
c320c7b7
ACM
1927{
1928 int entry = sizeof(u64); /* value */
1929 int size = 0;
1930 int nr = 1;
1931
382c27f4 1932 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
c320c7b7
ACM
1933 size += sizeof(u64);
1934
382c27f4 1935 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
c320c7b7
ACM
1936 size += sizeof(u64);
1937
382c27f4 1938 if (read_format & PERF_FORMAT_ID)
c320c7b7
ACM
1939 entry += sizeof(u64);
1940
382c27f4 1941 if (read_format & PERF_FORMAT_LOST)
119a784c
NK
1942 entry += sizeof(u64);
1943
382c27f4 1944 if (read_format & PERF_FORMAT_GROUP) {
a723968c 1945 nr += nr_siblings;
c320c7b7
ACM
1946 size += sizeof(u64);
1947 }
1948
382c27f4
PZ
1949 /*
1950 * Since perf_event_validate_size() limits this to 16k and inhibits
1951 * adding more siblings, this will never overflow.
1952 */
1953 return size + nr * entry;
c320c7b7
ACM
1954}
1955
a723968c 1956static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
c320c7b7
ACM
1957{
1958 struct perf_sample_data *data;
c320c7b7
ACM
1959 u16 size = 0;
1960
c320c7b7
ACM
1961 if (sample_type & PERF_SAMPLE_IP)
1962 size += sizeof(data->ip);
1963
6844c09d
ACM
1964 if (sample_type & PERF_SAMPLE_ADDR)
1965 size += sizeof(data->addr);
1966
1967 if (sample_type & PERF_SAMPLE_PERIOD)
1968 size += sizeof(data->period);
1969
2a6c6b7d
KL
1970 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
1971 size += sizeof(data->weight.full);
c3feedf2 1972
6844c09d
ACM
1973 if (sample_type & PERF_SAMPLE_READ)
1974 size += event->read_size;
1975
d6be9ad6
SE
1976 if (sample_type & PERF_SAMPLE_DATA_SRC)
1977 size += sizeof(data->data_src.val);
1978
fdfbbd07
AK
1979 if (sample_type & PERF_SAMPLE_TRANSACTION)
1980 size += sizeof(data->txn);
1981
fc7ce9c7
KL
1982 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1983 size += sizeof(data->phys_addr);
1984
6546b19f
NK
1985 if (sample_type & PERF_SAMPLE_CGROUP)
1986 size += sizeof(data->cgroup);
1987
8d97e718
KL
1988 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
1989 size += sizeof(data->data_page_size);
1990
995f088e
SE
1991 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
1992 size += sizeof(data->code_page_size);
1993
6844c09d
ACM
1994 event->header_size = size;
1995}
1996
a723968c
PZ
1997/*
1998 * Called at perf_event creation and when events are attached/detached from a
1999 * group.
2000 */
2001static void perf_event__header_size(struct perf_event *event)
2002{
382c27f4
PZ
2003 event->read_size =
2004 __perf_event_read_size(event->attr.read_format,
2005 event->group_leader->nr_siblings);
a723968c
PZ
2006 __perf_event_header_size(event, event->attr.sample_type);
2007}
2008
6844c09d
ACM
2009static void perf_event__id_header_size(struct perf_event *event)
2010{
2011 struct perf_sample_data *data;
2012 u64 sample_type = event->attr.sample_type;
2013 u16 size = 0;
2014
c320c7b7
ACM
2015 if (sample_type & PERF_SAMPLE_TID)
2016 size += sizeof(data->tid_entry);
2017
2018 if (sample_type & PERF_SAMPLE_TIME)
2019 size += sizeof(data->time);
2020
ff3d527c
AH
2021 if (sample_type & PERF_SAMPLE_IDENTIFIER)
2022 size += sizeof(data->id);
2023
c320c7b7
ACM
2024 if (sample_type & PERF_SAMPLE_ID)
2025 size += sizeof(data->id);
2026
2027 if (sample_type & PERF_SAMPLE_STREAM_ID)
2028 size += sizeof(data->stream_id);
2029
2030 if (sample_type & PERF_SAMPLE_CPU)
2031 size += sizeof(data->cpu_entry);
2032
6844c09d 2033 event->id_header_size = size;
c320c7b7
ACM
2034}
2035
382c27f4
PZ
2036/*
2037 * Check that adding an event to the group does not result in anybody
2038 * overflowing the 64k event limit imposed by the output buffer.
2039 *
2040 * Specifically, check that the read_size for the event does not exceed 16k,
2041 * read_size being the one term that grows with groups size. Since read_size
2042 * depends on per-event read_format, also (re)check the existing events.
2043 *
2044 * This leaves 48k for the constant size fields and things like callchains,
2045 * branch stacks and register sets.
2046 */
a723968c
PZ
2047static bool perf_event_validate_size(struct perf_event *event)
2048{
382c27f4 2049 struct perf_event *sibling, *group_leader = event->group_leader;
a723968c 2050
382c27f4
PZ
2051 if (__perf_event_read_size(event->attr.read_format,
2052 group_leader->nr_siblings + 1) > 16*1024)
a723968c
PZ
2053 return false;
2054
382c27f4
PZ
2055 if (__perf_event_read_size(group_leader->attr.read_format,
2056 group_leader->nr_siblings + 1) > 16*1024)
2057 return false;
2058
7e2c1e4b
MR
2059 /*
2060 * When creating a new group leader, group_leader->ctx is initialized
2061 * after the size has been validated, but we cannot safely use
2062 * for_each_sibling_event() until group_leader->ctx is set. A new group
2063 * leader cannot have any siblings yet, so we can safely skip checking
2064 * the non-existent siblings.
2065 */
2066 if (event == group_leader)
2067 return true;
2068
382c27f4
PZ
2069 for_each_sibling_event(sibling, group_leader) {
2070 if (__perf_event_read_size(sibling->attr.read_format,
2071 group_leader->nr_siblings + 1) > 16*1024)
2072 return false;
2073 }
2074
a723968c
PZ
2075 return true;
2076}
2077
8a49542c
PZ
2078static void perf_group_attach(struct perf_event *event)
2079{
c320c7b7 2080 struct perf_event *group_leader = event->group_leader, *pos;
8a49542c 2081
a76a82a3
PZ
2082 lockdep_assert_held(&event->ctx->lock);
2083
74c3337c 2084 /*
bd275681
PZ
2085 * We can have double attach due to group movement (move_group) in
2086 * perf_event_open().
74c3337c
PZ
2087 */
2088 if (event->attach_state & PERF_ATTACH_GROUP)
2089 return;
2090
8a49542c
PZ
2091 event->attach_state |= PERF_ATTACH_GROUP;
2092
2093 if (group_leader == event)
2094 return;
2095
652884fe
PZ
2096 WARN_ON_ONCE(group_leader->ctx != event->ctx);
2097
4ff6a8de 2098 group_leader->group_caps &= event->event_caps;
8a49542c 2099
8343aae6 2100 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
8a49542c 2101 group_leader->nr_siblings++;
32671e37 2102 group_leader->group_generation++;
c320c7b7
ACM
2103
2104 perf_event__header_size(group_leader);
2105
edb39592 2106 for_each_sibling_event(pos, group_leader)
c320c7b7 2107 perf_event__header_size(pos);
8a49542c
PZ
2108}
2109
a63eaf34 2110/*
788faab7 2111 * Remove an event from the lists for its context.
fccc714b 2112 * Must be called with ctx->mutex and ctx->lock held.
a63eaf34 2113 */
04289bb9 2114static void
cdd6c482 2115list_del_event(struct perf_event *event, struct perf_event_context *ctx)
04289bb9 2116{
652884fe
PZ
2117 WARN_ON_ONCE(event->ctx != ctx);
2118 lockdep_assert_held(&ctx->lock);
2119
8a49542c
PZ
2120 /*
2121 * We can have double detach due to exit/hot-unplug + close.
2122 */
2123 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
a63eaf34 2124 return;
8a49542c
PZ
2125
2126 event->attach_state &= ~PERF_ATTACH_CONTEXT;
2127
cdd6c482 2128 ctx->nr_events--;
82ff0c02
RH
2129 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT)
2130 ctx->nr_user--;
cdd6c482 2131 if (event->attr.inherit_stat)
bfbd3381 2132 ctx->nr_stat--;
7e8b2556
BG
2133 if (has_inherit_and_sample_read(&event->attr))
2134 local_dec(&ctx->nr_no_switch_fast);
8bc20959 2135
cdd6c482 2136 list_del_rcu(&event->event_entry);
04289bb9 2137
8a49542c 2138 if (event->group_leader == event)
8e1a2031 2139 del_event_from_groups(event, ctx);
5c148194 2140
5a3126d4 2141 ctx->generation++;
bd275681 2142 event->pmu_ctx->nr_events--;
050735b0
PZ
2143}
2144
ab43762e
AS
2145static int
2146perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2147{
2148 if (!has_aux(aux_event))
2149 return 0;
2150
2151 if (!event->pmu->aux_output_match)
2152 return 0;
2153
2154 return event->pmu->aux_output_match(aux_event);
2155}
2156
2157static void put_event(struct perf_event *event);
61988e36
PZ
2158static void __event_disable(struct perf_event *event,
2159 struct perf_event_context *ctx,
2160 enum perf_event_state state);
ab43762e
AS
2161
2162static void perf_put_aux_event(struct perf_event *event)
2163{
2164 struct perf_event_context *ctx = event->ctx;
ab43762e
AS
2165 struct perf_event *iter;
2166
2167 /*
2168 * If event uses aux_event tear down the link
2169 */
2170 if (event->aux_event) {
2171 iter = event->aux_event;
2172 event->aux_event = NULL;
2173 put_event(iter);
2174 return;
2175 }
2176
2177 /*
2178 * If the event is an aux_event, tear down all links to
2179 * it from other events.
2180 */
881097c0 2181 for_each_sibling_event(iter, event) {
ab43762e
AS
2182 if (iter->aux_event != event)
2183 continue;
2184
2185 iter->aux_event = NULL;
2186 put_event(event);
2187
2188 /*
2189 * If it's ACTIVE, schedule it out and put it into ERROR
2190 * state so that we don't try to schedule it again. Note
2191 * that perf_event_enable() will clear the ERROR status.
2192 */
61988e36 2193 __event_disable(iter, ctx, PERF_EVENT_STATE_ERROR);
ab43762e
AS
2194 }
2195}
2196
a4faf00d
AS
2197static bool perf_need_aux_event(struct perf_event *event)
2198{
18d92bb5 2199 return event->attr.aux_output || has_aux_action(event);
a4faf00d
AS
2200}
2201
ab43762e
AS
2202static int perf_get_aux_event(struct perf_event *event,
2203 struct perf_event *group_leader)
2204{
2205 /*
2206 * Our group leader must be an aux event if we want to be
2207 * an aux_output. This way, the aux event will precede its
2208 * aux_output events in the group, and therefore will always
2209 * schedule first.
2210 */
2211 if (!group_leader)
2212 return 0;
2213
a4faf00d
AS
2214 /*
2215 * aux_output and aux_sample_size are mutually exclusive.
2216 */
2217 if (event->attr.aux_output && event->attr.aux_sample_size)
2218 return 0;
2219
2220 if (event->attr.aux_output &&
2221 !perf_aux_output_match(event, group_leader))
2222 return 0;
2223
18d92bb5
AH
2224 if ((event->attr.aux_pause || event->attr.aux_resume) &&
2225 !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
2226 return 0;
2227
a4faf00d 2228 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
ab43762e
AS
2229 return 0;
2230
2231 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2232 return 0;
2233
2234 /*
2235 * Link aux_outputs to their aux event; this is undone in
2236 * perf_group_detach() by perf_put_aux_event(). When the
2237 * group in torn down, the aux_output events loose their
2238 * link to the aux_event and can't schedule any more.
2239 */
2240 event->aux_event = group_leader;
2241
2242 return 1;
2243}
2244
ab6f824c
PZ
2245static inline struct list_head *get_event_list(struct perf_event *event)
2246{
bd275681
PZ
2247 return event->attr.pinned ? &event->pmu_ctx->pinned_active :
2248 &event->pmu_ctx->flexible_active;
ab6f824c
PZ
2249}
2250
8a49542c 2251static void perf_group_detach(struct perf_event *event)
050735b0 2252{
9f0c4fa1 2253 struct perf_event *leader = event->group_leader;
050735b0 2254 struct perf_event *sibling, *tmp;
6668128a 2255 struct perf_event_context *ctx = event->ctx;
8a49542c 2256
6668128a 2257 lockdep_assert_held(&ctx->lock);
a76a82a3 2258
8a49542c
PZ
2259 /*
2260 * We can have double detach due to exit/hot-unplug + close.
2261 */
2262 if (!(event->attach_state & PERF_ATTACH_GROUP))
2263 return;
2264
2265 event->attach_state &= ~PERF_ATTACH_GROUP;
2266
ab43762e
AS
2267 perf_put_aux_event(event);
2268
8a49542c
PZ
2269 /*
2270 * If this is a sibling, remove it from its group.
2271 */
9f0c4fa1 2272 if (leader != event) {
8343aae6 2273 list_del_init(&event->sibling_list);
8a49542c 2274 event->group_leader->nr_siblings--;
32671e37 2275 event->group_leader->group_generation++;
c320c7b7 2276 goto out;
8a49542c
PZ
2277 }
2278
04289bb9 2279 /*
cdd6c482
IM
2280 * If this was a group event with sibling events then
2281 * upgrade the siblings to singleton events by adding them
8a49542c 2282 * to whatever list we are on.
04289bb9 2283 */
8343aae6 2284 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
8e1a2031 2285
61988e36
PZ
2286 /*
2287 * Events that have PERF_EV_CAP_SIBLING require being part of
2288 * a group and cannot exist on their own, schedule them out
2289 * and move them into the ERROR state. Also see
2290 * _perf_event_enable(), it will not be able to recover this
2291 * ERROR state.
2292 */
9f0c4fa1 2293 if (sibling->event_caps & PERF_EV_CAP_SIBLING)
61988e36 2294 __event_disable(sibling, ctx, PERF_EVENT_STATE_ERROR);
9f0c4fa1 2295
04289bb9 2296 sibling->group_leader = sibling;
24868367 2297 list_del_init(&sibling->sibling_list);
d6f962b5
FW
2298
2299 /* Inherit group flags from the previous leader */
4ff6a8de 2300 sibling->group_caps = event->group_caps;
652884fe 2301
fd0815f6 2302 if (sibling->attach_state & PERF_ATTACH_CONTEXT) {
8e1a2031 2303 add_event_to_groups(sibling, event->ctx);
6668128a 2304
ab6f824c
PZ
2305 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2306 list_add_tail(&sibling->active_list, get_event_list(sibling));
8e1a2031
AB
2307 }
2308
652884fe 2309 WARN_ON_ONCE(sibling->ctx != event->ctx);
04289bb9 2310 }
c320c7b7
ACM
2311
2312out:
9f0c4fa1 2313 for_each_sibling_event(tmp, leader)
c320c7b7 2314 perf_event__header_size(tmp);
9f0c4fa1
KL
2315
2316 perf_event__header_size(leader);
04289bb9
IM
2317}
2318
ef54c1a4
PZ
2319static void sync_child_event(struct perf_event *child_event);
2320
2321static void perf_child_detach(struct perf_event *event)
2322{
2323 struct perf_event *parent_event = event->parent;
2324
2325 if (!(event->attach_state & PERF_ATTACH_CHILD))
2326 return;
2327
2328 event->attach_state &= ~PERF_ATTACH_CHILD;
2329
2330 if (WARN_ON_ONCE(!parent_event))
2331 return;
2332
0a00a43b
PZ
2333 /*
2334 * Can't check this from an IPI, the holder is likey another CPU.
2335 *
ef54c1a4 2336 lockdep_assert_held(&parent_event->child_mutex);
0a00a43b 2337 */
ef54c1a4
PZ
2338
2339 sync_child_event(event);
2340 list_del_init(&event->child_list);
2341}
2342
fadfe7be
JO
2343static bool is_orphaned_event(struct perf_event *event)
2344{
a69b0ca4 2345 return event->state == PERF_EVENT_STATE_DEAD;
fadfe7be
JO
2346}
2347
fa66f07a
SE
2348static inline int
2349event_filter_match(struct perf_event *event)
2350{
0b8f1e2e 2351 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
bd275681 2352 perf_cgroup_match(event);
fa66f07a
SE
2353}
2354
ca559503
KL
2355static inline bool is_event_in_freq_mode(struct perf_event *event)
2356{
2357 return event->attr.freq && event->attr.sample_freq;
2358}
2359
9ffcfa6f 2360static void
bd275681 2361event_sched_out(struct perf_event *event, struct perf_event_context *ctx)
3b6f9e5c 2362{
bd275681 2363 struct perf_event_pmu_context *epc = event->pmu_ctx;
b2996f56 2364 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
0d3d73aa 2365 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
652884fe 2366
bd275681
PZ
2367 // XXX cpc serialization, probably per-cpu IRQ disabled
2368
652884fe
PZ
2369 WARN_ON_ONCE(event->ctx != ctx);
2370 lockdep_assert_held(&ctx->lock);
2371
cdd6c482 2372 if (event->state != PERF_EVENT_STATE_ACTIVE)
9ffcfa6f 2373 return;
3b6f9e5c 2374
6668128a
PZ
2375 /*
2376 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2377 * we can schedule events _OUT_ individually through things like
2378 * __perf_remove_from_context().
2379 */
2380 list_del_init(&event->active_list);
2381
44377277
AS
2382 perf_pmu_disable(event->pmu);
2383
28a967c3
PZ
2384 event->pmu->del(event, 0);
2385 event->oncpu = -1;
0d3d73aa 2386
ca6c2132
PZ
2387 if (event->pending_disable) {
2388 event->pending_disable = 0;
33238c50 2389 perf_cgroup_event_disable(event, ctx);
0d3d73aa 2390 state = PERF_EVENT_STATE_OFF;
970892a9 2391 }
ca6c2132 2392
0d3d73aa 2393 perf_event_set_state(event, state);
3b6f9e5c 2394
cdd6c482 2395 if (!is_software_event(event))
bd275681 2396 cpc->active_oncpu--;
ca559503 2397 if (is_event_in_freq_mode(event)) {
0f5a2601 2398 ctx->nr_freq--;
0259bf63
NK
2399 epc->nr_freq--;
2400 }
bd275681
PZ
2401 if (event->attr.exclusive || !cpc->active_oncpu)
2402 cpc->exclusive = 0;
44377277
AS
2403
2404 perf_pmu_enable(event->pmu);
3b6f9e5c
PM
2405}
2406
d859e29f 2407static void
bd275681 2408group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx)
d859e29f 2409{
cdd6c482 2410 struct perf_event *event;
0d3d73aa
PZ
2411
2412 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2413 return;
d859e29f 2414
bd275681 2415 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu);
3f005e7d 2416
bd275681 2417 event_sched_out(group_event, ctx);
d859e29f
PM
2418
2419 /*
2420 * Schedule out siblings (if any):
2421 */
edb39592 2422 for_each_sibling_event(event, group_event)
bd275681 2423 event_sched_out(event, ctx);
d859e29f
PM
2424}
2425
9a32bd99 2426static inline void
5d95a2af 2427__ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, bool final)
9a32bd99
PZ
2428{
2429 if (ctx->is_active & EVENT_TIME) {
5d95a2af
PZ
2430 if (ctx->is_active & EVENT_FROZEN)
2431 return;
9a32bd99 2432 update_context_time(ctx);
5d95a2af 2433 update_cgrp_time_from_cpuctx(cpuctx, final);
9a32bd99
PZ
2434 }
2435}
2436
5d95a2af
PZ
2437static inline void
2438ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2439{
2440 __ctx_time_update(cpuctx, ctx, false);
2441}
2442
2443/*
2444 * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock().
2445 */
2446static inline void
2447ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx)
2448{
2449 ctx_time_update(cpuctx, ctx);
2450 if (ctx->is_active & EVENT_TIME)
2451 ctx->is_active |= EVENT_FROZEN;
2452}
2453
9a32bd99
PZ
2454static inline void
2455ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event)
2456{
2457 if (ctx->is_active & EVENT_TIME) {
5d95a2af
PZ
2458 if (ctx->is_active & EVENT_FROZEN)
2459 return;
9a32bd99
PZ
2460 update_context_time(ctx);
2461 update_cgrp_time_from_event(event);
2462 }
2463}
2464
45a0e07a 2465#define DETACH_GROUP 0x01UL
ef54c1a4 2466#define DETACH_CHILD 0x02UL
da916e96
PZ
2467#define DETACH_EXIT 0x04UL
2468#define DETACH_REVOKE 0x08UL
2469#define DETACH_DEAD 0x10UL
0017960f 2470
0793a61d 2471/*
cdd6c482 2472 * Cross CPU call to remove a performance event
0793a61d 2473 *
cdd6c482 2474 * We disable the event on the hardware level first. After that we
0793a61d
TG
2475 * remove it from the context list.
2476 */
fae3fde6
PZ
2477static void
2478__perf_remove_from_context(struct perf_event *event,
2479 struct perf_cpu_context *cpuctx,
2480 struct perf_event_context *ctx,
2481 void *info)
0793a61d 2482{
bd275681 2483 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx;
a3c3c666 2484 enum perf_event_state state = PERF_EVENT_STATE_OFF;
45a0e07a 2485 unsigned long flags = (unsigned long)info;
0793a61d 2486
9a32bd99 2487 ctx_time_update(cpuctx, ctx);
3c5c8711 2488
517e6a30
PZ
2489 /*
2490 * Ensure event_sched_out() switches to OFF, at the very least
2491 * this avoids raising perf_pending_task() at this time.
2492 */
a3c3c666
YY
2493 if (flags & DETACH_EXIT)
2494 state = PERF_EVENT_STATE_EXIT;
da916e96
PZ
2495 if (flags & DETACH_REVOKE)
2496 state = PERF_EVENT_STATE_REVOKED;
3b7a34ae 2497 if (flags & DETACH_DEAD)
a3c3c666 2498 state = PERF_EVENT_STATE_DEAD;
3b7a34ae 2499
bd275681 2500 event_sched_out(event, ctx);
3b7a34ae
YY
2501
2502 if (event->state > PERF_EVENT_STATE_OFF)
2503 perf_cgroup_event_disable(event, ctx);
2504
b02b41c8
PZ
2505 perf_event_set_state(event, min(event->state, state));
2506
45a0e07a 2507 if (flags & DETACH_GROUP)
46ce0fe9 2508 perf_group_detach(event);
ef54c1a4
PZ
2509 if (flags & DETACH_CHILD)
2510 perf_child_detach(event);
cdd6c482 2511 list_del_event(event, ctx);
39a43640 2512
bd275681
PZ
2513 if (!pmu_ctx->nr_events) {
2514 pmu_ctx->rotate_necessary = 0;
2515
2516 if (ctx->task && ctx->is_active) {
b2996f56 2517 struct perf_cpu_pmu_context *cpc = this_cpc(pmu_ctx->pmu);
bd275681 2518
bd275681
PZ
2519 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
2520 cpc->task_epc = NULL;
2521 }
2522 }
2523
39a43640 2524 if (!ctx->nr_events && ctx->is_active) {
09f5e7dc
PZ
2525 if (ctx == &cpuctx->ctx)
2526 update_cgrp_time_from_cpuctx(cpuctx, true);
2527
64ce3126 2528 ctx->is_active = 0;
39a43640
PZ
2529 if (ctx->task) {
2530 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2531 cpuctx->task_ctx = NULL;
2532 }
64ce3126 2533 }
0793a61d
TG
2534}
2535
0793a61d 2536/*
cdd6c482 2537 * Remove the event from a task's (or a CPU's) list of events.
0793a61d 2538 *
cdd6c482
IM
2539 * If event->ctx is a cloned context, callers must make sure that
2540 * every task struct that event->ctx->task could possibly point to
c93f7669
PM
2541 * remains valid. This is OK when called from perf_release since
2542 * that only calls us on the top-level context, which can't be a clone.
cdd6c482 2543 * When called from perf_event_exit_task, it's OK because the
c93f7669 2544 * context has been detached from its task.
0793a61d 2545 */
45a0e07a 2546static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
0793a61d 2547{
a76a82a3
PZ
2548 struct perf_event_context *ctx = event->ctx;
2549
2550 lockdep_assert_held(&ctx->mutex);
0793a61d 2551
a76a82a3 2552 /*
ef54c1a4
PZ
2553 * Because of perf_event_exit_task(), perf_remove_from_context() ought
2554 * to work in the face of TASK_TOMBSTONE, unlike every other
2555 * event_function_call() user.
a76a82a3 2556 */
ef54c1a4 2557 raw_spin_lock_irq(&ctx->lock);
bd275681
PZ
2558 if (!ctx->is_active) {
2559 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context),
ef54c1a4 2560 ctx, (void *)flags);
a76a82a3 2561 raw_spin_unlock_irq(&ctx->lock);
ef54c1a4 2562 return;
a76a82a3 2563 }
ef54c1a4
PZ
2564 raw_spin_unlock_irq(&ctx->lock);
2565
2566 event_function_call(event, __perf_remove_from_context, (void *)flags);
0793a61d
TG
2567}
2568
61988e36
PZ
2569static void __event_disable(struct perf_event *event,
2570 struct perf_event_context *ctx,
2571 enum perf_event_state state)
2572{
2573 event_sched_out(event, ctx);
2574 perf_cgroup_event_disable(event, ctx);
2575 perf_event_set_state(event, state);
2576}
2577
d859e29f 2578/*
cdd6c482 2579 * Cross CPU call to disable a performance event
d859e29f 2580 */
fae3fde6
PZ
2581static void __perf_event_disable(struct perf_event *event,
2582 struct perf_cpu_context *cpuctx,
2583 struct perf_event_context *ctx,
2584 void *info)
7b648018 2585{
fae3fde6
PZ
2586 if (event->state < PERF_EVENT_STATE_INACTIVE)
2587 return;
7b648018 2588
bd275681 2589 perf_pmu_disable(event->pmu_ctx->pmu);
9a32bd99 2590 ctx_time_update_event(ctx, event);
bd275681 2591
61988e36
PZ
2592 /*
2593 * When disabling a group leader, the whole group becomes ineligible
2594 * to run, so schedule out the full group.
2595 */
fae3fde6 2596 if (event == event->group_leader)
bd275681 2597 group_sched_out(event, ctx);
0d3d73aa 2598
61988e36
PZ
2599 /*
2600 * But only mark the leader OFF; the siblings will remain
2601 * INACTIVE.
2602 */
2603 __event_disable(event, ctx, PERF_EVENT_STATE_OFF);
bd275681
PZ
2604
2605 perf_pmu_enable(event->pmu_ctx->pmu);
7b648018
PZ
2606}
2607
d859e29f 2608/*
788faab7 2609 * Disable an event.
c93f7669 2610 *
cdd6c482
IM
2611 * If event->ctx is a cloned context, callers must make sure that
2612 * every task struct that event->ctx->task could possibly point to
9f014e3a 2613 * remains valid. This condition is satisfied when called through
cdd6c482
IM
2614 * perf_event_for_each_child or perf_event_for_each because they
2615 * hold the top-level event's child_mutex, so any descendant that
8ba289b8
PZ
2616 * goes to exit will block in perf_event_exit_event().
2617 *
2b84def9 2618 * When called from perf_pending_disable it's OK because event->ctx
c93f7669 2619 * is the current context on this CPU and preemption is disabled,
cdd6c482 2620 * hence we can't get into perf_event_task_sched_out for this context.
d859e29f 2621 */
f63a8daa 2622static void _perf_event_disable(struct perf_event *event)
d859e29f 2623{
cdd6c482 2624 struct perf_event_context *ctx = event->ctx;
d859e29f 2625
e625cce1 2626 raw_spin_lock_irq(&ctx->lock);
7b648018 2627 if (event->state <= PERF_EVENT_STATE_OFF) {
e625cce1 2628 raw_spin_unlock_irq(&ctx->lock);
7b648018 2629 return;
53cfbf59 2630 }
e625cce1 2631 raw_spin_unlock_irq(&ctx->lock);
7b648018 2632
fae3fde6
PZ
2633 event_function_call(event, __perf_event_disable, NULL);
2634}
2635
2636void perf_event_disable_local(struct perf_event *event)
2637{
2638 event_function_local(event, __perf_event_disable, NULL);
d859e29f 2639}
f63a8daa
PZ
2640
2641/*
2642 * Strictly speaking kernel users cannot create groups and therefore this
2643 * interface does not need the perf_event_ctx_lock() magic.
2644 */
2645void perf_event_disable(struct perf_event *event)
2646{
2647 struct perf_event_context *ctx;
2648
2649 ctx = perf_event_ctx_lock(event);
2650 _perf_event_disable(event);
2651 perf_event_ctx_unlock(event, ctx);
2652}
dcfce4a0 2653EXPORT_SYMBOL_GPL(perf_event_disable);
d859e29f 2654
5aab90ce
JO
2655void perf_event_disable_inatomic(struct perf_event *event)
2656{
ca6c2132 2657 event->pending_disable = 1;
2b84def9 2658 irq_work_queue(&event->pending_disable_irq);
5aab90ce
JO
2659}
2660
4fe757dd
PZ
2661#define MAX_INTERRUPTS (~0ULL)
2662
2663static void perf_log_throttle(struct perf_event *event, int enable);
ec0d7729 2664static void perf_log_itrace_start(struct perf_event *event);
4fe757dd 2665
9734e25f
KL
2666static void perf_event_unthrottle(struct perf_event *event, bool start)
2667{
2668 event->hw.interrupts = 0;
2669 if (start)
2670 event->pmu->start(event, 0);
e800ac51
KL
2671 if (event == event->group_leader)
2672 perf_log_throttle(event, 1);
9734e25f
KL
2673}
2674
2675static void perf_event_throttle(struct perf_event *event)
2676{
9734e25f 2677 event->hw.interrupts = MAX_INTERRUPTS;
bc4394e5 2678 event->pmu->stop(event, 0);
e800ac51
KL
2679 if (event == event->group_leader)
2680 perf_log_throttle(event, 0);
9734e25f
KL
2681}
2682
2683static void perf_event_unthrottle_group(struct perf_event *event, bool skip_start_event)
2684{
2685 struct perf_event *sibling, *leader = event->group_leader;
2686
2687 perf_event_unthrottle(leader, skip_start_event ? leader != event : true);
2688 for_each_sibling_event(sibling, leader)
2689 perf_event_unthrottle(sibling, skip_start_event ? sibling != event : true);
2690}
2691
2692static void perf_event_throttle_group(struct perf_event *event)
2693{
2694 struct perf_event *sibling, *leader = event->group_leader;
2695
2696 perf_event_throttle(leader);
2697 for_each_sibling_event(sibling, leader)
2698 perf_event_throttle(sibling);
2699}
2700
235c7fc7 2701static int
bd275681 2702event_sched_in(struct perf_event *event, struct perf_event_context *ctx)
235c7fc7 2703{
bd275681 2704 struct perf_event_pmu_context *epc = event->pmu_ctx;
b2996f56 2705 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
44377277 2706 int ret = 0;
4158755d 2707
ab6f824c
PZ
2708 WARN_ON_ONCE(event->ctx != ctx);
2709
63342411
PZ
2710 lockdep_assert_held(&ctx->lock);
2711
cdd6c482 2712 if (event->state <= PERF_EVENT_STATE_OFF)
235c7fc7
IM
2713 return 0;
2714
95ff4ca2
AS
2715 WRITE_ONCE(event->oncpu, smp_processor_id());
2716 /*
0c1cbc18
PZ
2717 * Order event::oncpu write to happen before the ACTIVE state is
2718 * visible. This allows perf_event_{stop,read}() to observe the correct
2719 * ->oncpu if it sees ACTIVE.
95ff4ca2
AS
2720 */
2721 smp_wmb();
0d3d73aa 2722 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
4fe757dd
PZ
2723
2724 /*
2725 * Unthrottle events, since we scheduled we might have missed several
2726 * ticks already, also for a heavily scheduling task there is little
2727 * guarantee it'll get a tick in a timely manner.
2728 */
9734e25f
KL
2729 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS))
2730 perf_event_unthrottle(event, false);
4fe757dd 2731
44377277
AS
2732 perf_pmu_disable(event->pmu);
2733
ec0d7729
AS
2734 perf_log_itrace_start(event);
2735
a4eaf7f1 2736 if (event->pmu->add(event, PERF_EF_START)) {
0d3d73aa 2737 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
cdd6c482 2738 event->oncpu = -1;
44377277
AS
2739 ret = -EAGAIN;
2740 goto out;
235c7fc7
IM
2741 }
2742
cdd6c482 2743 if (!is_software_event(event))
bd275681 2744 cpc->active_oncpu++;
ca559503 2745 if (is_event_in_freq_mode(event)) {
0f5a2601 2746 ctx->nr_freq++;
0259bf63
NK
2747 epc->nr_freq++;
2748 }
cdd6c482 2749 if (event->attr.exclusive)
bd275681 2750 cpc->exclusive = 1;
3b6f9e5c 2751
44377277
AS
2752out:
2753 perf_pmu_enable(event->pmu);
2754
2755 return ret;
235c7fc7
IM
2756}
2757
6751b71e 2758static int
bd275681 2759group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx)
6751b71e 2760{
6bde9b6c 2761 struct perf_event *event, *partial_group = NULL;
bd275681 2762 struct pmu *pmu = group_event->pmu_ctx->pmu;
6751b71e 2763
cdd6c482 2764 if (group_event->state == PERF_EVENT_STATE_OFF)
6751b71e
PM
2765 return 0;
2766
fbbe0701 2767 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
6bde9b6c 2768
bd275681 2769 if (event_sched_in(group_event, ctx))
251ff2d4 2770 goto error;
6751b71e
PM
2771
2772 /*
2773 * Schedule in siblings as one group (if any):
2774 */
edb39592 2775 for_each_sibling_event(event, group_event) {
bd275681 2776 if (event_sched_in(event, ctx)) {
cdd6c482 2777 partial_group = event;
6751b71e
PM
2778 goto group_error;
2779 }
2780 }
2781
9ffcfa6f 2782 if (!pmu->commit_txn(pmu))
6e85158c 2783 return 0;
9ffcfa6f 2784
6751b71e
PM
2785group_error:
2786 /*
2787 * Groups can be scheduled in as one unit only, so undo any
2788 * partial group before returning:
0d3d73aa 2789 * The events up to the failed event are scheduled out normally.
6751b71e 2790 */
edb39592 2791 for_each_sibling_event(event, group_event) {
cdd6c482 2792 if (event == partial_group)
0d3d73aa 2793 break;
d7842da4 2794
bd275681 2795 event_sched_out(event, ctx);
6751b71e 2796 }
bd275681 2797 event_sched_out(group_event, ctx);
6751b71e 2798
251ff2d4 2799error:
ad5133b7 2800 pmu->cancel_txn(pmu);
6751b71e
PM
2801 return -EAGAIN;
2802}
2803
3b6f9e5c 2804/*
cdd6c482 2805 * Work out whether we can put this event group on the CPU now.
3b6f9e5c 2806 */
bd275681 2807static int group_can_go_on(struct perf_event *event, int can_add_hw)
3b6f9e5c 2808{
bd275681 2809 struct perf_event_pmu_context *epc = event->pmu_ctx;
b2996f56 2810 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu);
bd275681 2811
3b6f9e5c 2812 /*
cdd6c482 2813 * Groups consisting entirely of software events can always go on.
3b6f9e5c 2814 */
4ff6a8de 2815 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
3b6f9e5c
PM
2816 return 1;
2817 /*
2818 * If an exclusive group is already on, no other hardware
cdd6c482 2819 * events can go on.
3b6f9e5c 2820 */
bd275681 2821 if (cpc->exclusive)
3b6f9e5c
PM
2822 return 0;
2823 /*
2824 * If this group is exclusive and there are already
cdd6c482 2825 * events on the CPU, it can't go on.
3b6f9e5c 2826 */
1908dc91 2827 if (event->attr.exclusive && !list_empty(get_event_list(event)))
3b6f9e5c
PM
2828 return 0;
2829 /*
2830 * Otherwise, try to add it if all previous groups were able
2831 * to go on.
2832 */
2833 return can_add_hw;
2834}
2835
cdd6c482
IM
2836static void add_event_to_ctx(struct perf_event *event,
2837 struct perf_event_context *ctx)
53cfbf59 2838{
cdd6c482 2839 list_add_event(event, ctx);
8a49542c 2840 perf_group_attach(event);
53cfbf59
PM
2841}
2842
bd275681 2843static void task_ctx_sched_out(struct perf_event_context *ctx,
2d17cf1a
PZ
2844 struct pmu *pmu,
2845 enum event_type_t event_type)
bd2afa49 2846{
bd275681
PZ
2847 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2848
bd2afa49
PZ
2849 if (!cpuctx->task_ctx)
2850 return;
2851
2852 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2853 return;
2854
2d17cf1a 2855 ctx_sched_out(ctx, pmu, event_type);
bd2afa49
PZ
2856}
2857
dce5855b 2858static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2d17cf1a
PZ
2859 struct perf_event_context *ctx,
2860 struct pmu *pmu)
dce5855b 2861{
2d17cf1a 2862 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED);
dce5855b 2863 if (ctx)
2d17cf1a
PZ
2864 ctx_sched_in(ctx, pmu, EVENT_PINNED);
2865 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
dce5855b 2866 if (ctx)
2d17cf1a 2867 ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE);
dce5855b
PZ
2868}
2869
487f05e1
AS
2870/*
2871 * We want to maintain the following priority of scheduling:
2872 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2873 * - task pinned (EVENT_PINNED)
2874 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2875 * - task flexible (EVENT_FLEXIBLE).
2876 *
2877 * In order to avoid unscheduling and scheduling back in everything every
2878 * time an event is added, only do it for the groups of equal priority and
2879 * below.
2880 *
2881 * This can be called after a batch operation on task events, in which case
2882 * event_type is a bit mask of the types of events involved. For CPU events,
2883 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2884 */
3e349507 2885static void ctx_resched(struct perf_cpu_context *cpuctx,
487f05e1 2886 struct perf_event_context *task_ctx,
2d17cf1a 2887 struct pmu *pmu, enum event_type_t event_type)
0017960f 2888{
487f05e1 2889 bool cpu_event = !!(event_type & EVENT_CPU);
2d17cf1a 2890 struct perf_event_pmu_context *epc;
487f05e1
AS
2891
2892 /*
2893 * If pinned groups are involved, flexible groups also need to be
2894 * scheduled out.
2895 */
2896 if (event_type & EVENT_PINNED)
2897 event_type |= EVENT_FLEXIBLE;
2898
bd275681 2899 event_type &= EVENT_ALL;
bd903afe 2900
2d17cf1a
PZ
2901 for_each_epc(epc, &cpuctx->ctx, pmu, false)
2902 perf_pmu_disable(epc->pmu);
2903
bd275681 2904 if (task_ctx) {
2d17cf1a
PZ
2905 for_each_epc(epc, task_ctx, pmu, false)
2906 perf_pmu_disable(epc->pmu);
2907
2908 task_ctx_sched_out(task_ctx, pmu, event_type);
bd275681 2909 }
487f05e1
AS
2910
2911 /*
2912 * Decide which cpu ctx groups to schedule out based on the types
2913 * of events that caused rescheduling:
2914 * - EVENT_CPU: schedule out corresponding groups;
2915 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2916 * - otherwise, do nothing more.
2917 */
2918 if (cpu_event)
2d17cf1a 2919 ctx_sched_out(&cpuctx->ctx, pmu, event_type);
bd275681 2920 else if (event_type & EVENT_PINNED)
2d17cf1a
PZ
2921 ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE);
2922
2923 perf_event_sched_in(cpuctx, task_ctx, pmu);
487f05e1 2924
2d17cf1a
PZ
2925 for_each_epc(epc, &cpuctx->ctx, pmu, false)
2926 perf_pmu_enable(epc->pmu);
bd275681 2927
2d17cf1a
PZ
2928 if (task_ctx) {
2929 for_each_epc(epc, task_ctx, pmu, false)
2930 perf_pmu_enable(epc->pmu);
2931 }
0017960f
PZ
2932}
2933
c68d224e
SE
2934void perf_pmu_resched(struct pmu *pmu)
2935{
bd275681 2936 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
c68d224e
SE
2937 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2938
2939 perf_ctx_lock(cpuctx, task_ctx);
2d17cf1a 2940 ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU);
c68d224e
SE
2941 perf_ctx_unlock(cpuctx, task_ctx);
2942}
2943
0793a61d 2944/*
cdd6c482 2945 * Cross CPU call to install and enable a performance event
682076ae 2946 *
a096309b
PZ
2947 * Very similar to remote_function() + event_function() but cannot assume that
2948 * things like ctx->is_active and cpuctx->task_ctx are set.
0793a61d 2949 */
fe4b04fa 2950static int __perf_install_in_context(void *info)
0793a61d 2951{
a096309b
PZ
2952 struct perf_event *event = info;
2953 struct perf_event_context *ctx = event->ctx;
bd275681 2954 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2c29ef0f 2955 struct perf_event_context *task_ctx = cpuctx->task_ctx;
63cae12b 2956 bool reprogram = true;
a096309b 2957 int ret = 0;
0793a61d 2958
63b6da39 2959 raw_spin_lock(&cpuctx->ctx.lock);
39a43640 2960 if (ctx->task) {
b58f6b0d
PZ
2961 raw_spin_lock(&ctx->lock);
2962 task_ctx = ctx;
a096309b 2963
63cae12b 2964 reprogram = (ctx->task == current);
b58f6b0d 2965
39a43640 2966 /*
63cae12b
PZ
2967 * If the task is running, it must be running on this CPU,
2968 * otherwise we cannot reprogram things.
2969 *
2970 * If its not running, we don't care, ctx->lock will
2971 * serialize against it becoming runnable.
39a43640 2972 */
63cae12b
PZ
2973 if (task_curr(ctx->task) && !reprogram) {
2974 ret = -ESRCH;
2975 goto unlock;
2976 }
a096309b 2977
63cae12b 2978 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
63b6da39
PZ
2979 } else if (task_ctx) {
2980 raw_spin_lock(&task_ctx->lock);
2c29ef0f 2981 }
b58f6b0d 2982
33801b94 2983#ifdef CONFIG_CGROUP_PERF
33238c50 2984 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) {
33801b94 2985 /*
2986 * If the current cgroup doesn't match the event's
2987 * cgroup, we should not try to schedule it.
2988 */
2989 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2990 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2991 event->cgrp->css.cgroup);
2992 }
2993#endif
2994
63cae12b 2995 if (reprogram) {
5d95a2af 2996 ctx_time_freeze(cpuctx, ctx);
a096309b 2997 add_event_to_ctx(event, ctx);
2d17cf1a
PZ
2998 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu,
2999 get_event_type(event));
a096309b
PZ
3000 } else {
3001 add_event_to_ctx(event, ctx);
3002 }
3003
63b6da39 3004unlock:
2c29ef0f 3005 perf_ctx_unlock(cpuctx, task_ctx);
fe4b04fa 3006
a096309b 3007 return ret;
0793a61d
TG
3008}
3009
8a58ddae
AS
3010static bool exclusive_event_installable(struct perf_event *event,
3011 struct perf_event_context *ctx);
3012
0793a61d 3013/*
a096309b
PZ
3014 * Attach a performance event to a context.
3015 *
3016 * Very similar to event_function_call, see comment there.
0793a61d
TG
3017 */
3018static void
cdd6c482
IM
3019perf_install_in_context(struct perf_event_context *ctx,
3020 struct perf_event *event,
0793a61d
TG
3021 int cpu)
3022{
a096309b 3023 struct task_struct *task = READ_ONCE(ctx->task);
39a43640 3024
fe4b04fa
PZ
3025 lockdep_assert_held(&ctx->mutex);
3026
8a58ddae
AS
3027 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
3028
0cda4c02 3029 if (event->cpu != -1)
bd275681 3030 WARN_ON_ONCE(event->cpu != cpu);
c3f00c70 3031
0b8f1e2e
PZ
3032 /*
3033 * Ensures that if we can observe event->ctx, both the event and ctx
3034 * will be 'complete'. See perf_iterate_sb_cpu().
3035 */
3036 smp_store_release(&event->ctx, ctx);
3037
db0503e4
PZ
3038 /*
3039 * perf_event_attr::disabled events will not run and can be initialized
3040 * without IPI. Except when this is the first event for the context, in
3041 * that case we need the magic of the IPI to set ctx->is_active.
3042 *
3043 * The IOC_ENABLE that is sure to follow the creation of a disabled
3044 * event will issue the IPI and reprogram the hardware.
3045 */
c5de60cd
NK
3046 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF &&
3047 ctx->nr_events && !is_cgroup_event(event)) {
db0503e4
PZ
3048 raw_spin_lock_irq(&ctx->lock);
3049 if (ctx->task == TASK_TOMBSTONE) {
3050 raw_spin_unlock_irq(&ctx->lock);
3051 return;
3052 }
3053 add_event_to_ctx(event, ctx);
3054 raw_spin_unlock_irq(&ctx->lock);
3055 return;
3056 }
3057
a096309b
PZ
3058 if (!task) {
3059 cpu_function_call(cpu, __perf_install_in_context, event);
3060 return;
3061 }
3062
3063 /*
3064 * Should not happen, we validate the ctx is still alive before calling.
3065 */
3066 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
3067 return;
3068
39a43640
PZ
3069 /*
3070 * Installing events is tricky because we cannot rely on ctx->is_active
3071 * to be set in case this is the nr_events 0 -> 1 transition.
63cae12b
PZ
3072 *
3073 * Instead we use task_curr(), which tells us if the task is running.
3074 * However, since we use task_curr() outside of rq::lock, we can race
3075 * against the actual state. This means the result can be wrong.
3076 *
3077 * If we get a false positive, we retry, this is harmless.
3078 *
3079 * If we get a false negative, things are complicated. If we are after
3080 * perf_event_context_sched_in() ctx::lock will serialize us, and the
3081 * value must be correct. If we're before, it doesn't matter since
3082 * perf_event_context_sched_in() will program the counter.
3083 *
3084 * However, this hinges on the remote context switch having observed
3085 * our task->perf_event_ctxp[] store, such that it will in fact take
3086 * ctx::lock in perf_event_context_sched_in().
3087 *
3088 * We do this by task_function_call(), if the IPI fails to hit the task
3089 * we know any future context switch of task must see the
3090 * perf_event_ctpx[] store.
39a43640 3091 */
63cae12b 3092
63b6da39 3093 /*
63cae12b
PZ
3094 * This smp_mb() orders the task->perf_event_ctxp[] store with the
3095 * task_cpu() load, such that if the IPI then does not find the task
3096 * running, a future context switch of that task must observe the
3097 * store.
63b6da39 3098 */
63cae12b
PZ
3099 smp_mb();
3100again:
3101 if (!task_function_call(task, __perf_install_in_context, event))
a096309b
PZ
3102 return;
3103
3104 raw_spin_lock_irq(&ctx->lock);
3105 task = ctx->task;
84c4e620 3106 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
a096309b
PZ
3107 /*
3108 * Cannot happen because we already checked above (which also
3109 * cannot happen), and we hold ctx->mutex, which serializes us
3110 * against perf_event_exit_task_context().
3111 */
63b6da39
PZ
3112 raw_spin_unlock_irq(&ctx->lock);
3113 return;
3114 }
39a43640 3115 /*
63cae12b
PZ
3116 * If the task is not running, ctx->lock will avoid it becoming so,
3117 * thus we can safely install the event.
39a43640 3118 */
63cae12b
PZ
3119 if (task_curr(task)) {
3120 raw_spin_unlock_irq(&ctx->lock);
3121 goto again;
3122 }
3123 add_event_to_ctx(event, ctx);
3124 raw_spin_unlock_irq(&ctx->lock);
0793a61d
TG
3125}
3126
d859e29f 3127/*
cdd6c482 3128 * Cross CPU call to enable a performance event
d859e29f 3129 */
fae3fde6
PZ
3130static void __perf_event_enable(struct perf_event *event,
3131 struct perf_cpu_context *cpuctx,
3132 struct perf_event_context *ctx,
3133 void *info)
04289bb9 3134{
cdd6c482 3135 struct perf_event *leader = event->group_leader;
fae3fde6 3136 struct perf_event_context *task_ctx;
04289bb9 3137
6e801e01
PZ
3138 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3139 event->state <= PERF_EVENT_STATE_ERROR)
fae3fde6 3140 return;
3cbed429 3141
5d95a2af 3142 ctx_time_freeze(cpuctx, ctx);
bd2afa49 3143
0d3d73aa 3144 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
33238c50 3145 perf_cgroup_event_enable(event, ctx);
04289bb9 3146
fae3fde6
PZ
3147 if (!ctx->is_active)
3148 return;
3149
5d95a2af 3150 if (!event_filter_match(event))
fae3fde6 3151 return;
f4c4176f 3152
04289bb9 3153 /*
cdd6c482 3154 * If the event is in a group and isn't the group leader,
d859e29f 3155 * then don't put it on unless the group is on.
04289bb9 3156 */
5d95a2af 3157 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
fae3fde6 3158 return;
fe4b04fa 3159
fae3fde6
PZ
3160 task_ctx = cpuctx->task_ctx;
3161 if (ctx->task)
3162 WARN_ON_ONCE(task_ctx != ctx);
d859e29f 3163
2d17cf1a 3164 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event));
7b648018
PZ
3165}
3166
d859e29f 3167/*
788faab7 3168 * Enable an event.
c93f7669 3169 *
cdd6c482
IM
3170 * If event->ctx is a cloned context, callers must make sure that
3171 * every task struct that event->ctx->task could possibly point to
c93f7669 3172 * remains valid. This condition is satisfied when called through
cdd6c482
IM
3173 * perf_event_for_each_child or perf_event_for_each as described
3174 * for perf_event_disable.
d859e29f 3175 */
f63a8daa 3176static void _perf_event_enable(struct perf_event *event)
d859e29f 3177{
cdd6c482 3178 struct perf_event_context *ctx = event->ctx;
d859e29f 3179
7b648018 3180 raw_spin_lock_irq(&ctx->lock);
6e801e01
PZ
3181 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
3182 event->state < PERF_EVENT_STATE_ERROR) {
9f0c4fa1 3183out:
7b648018 3184 raw_spin_unlock_irq(&ctx->lock);
d859e29f
PM
3185 return;
3186 }
3187
d859e29f 3188 /*
cdd6c482 3189 * If the event is in error state, clear that first.
7b648018
PZ
3190 *
3191 * That way, if we see the event in error state below, we know that it
3192 * has gone back into error state, as distinct from the task having
3193 * been scheduled away before the cross-call arrived.
d859e29f 3194 */
9f0c4fa1
KL
3195 if (event->state == PERF_EVENT_STATE_ERROR) {
3196 /*
3197 * Detached SIBLING events cannot leave ERROR state.
3198 */
3199 if (event->event_caps & PERF_EV_CAP_SIBLING &&
3200 event->group_leader == event)
3201 goto out;
3202
cdd6c482 3203 event->state = PERF_EVENT_STATE_OFF;
9f0c4fa1 3204 }
e625cce1 3205 raw_spin_unlock_irq(&ctx->lock);
fe4b04fa 3206
fae3fde6 3207 event_function_call(event, __perf_event_enable, NULL);
d859e29f 3208}
f63a8daa
PZ
3209
3210/*
3211 * See perf_event_disable();
3212 */
3213void perf_event_enable(struct perf_event *event)
3214{
3215 struct perf_event_context *ctx;
3216
3217 ctx = perf_event_ctx_lock(event);
3218 _perf_event_enable(event);
3219 perf_event_ctx_unlock(event, ctx);
3220}
dcfce4a0 3221EXPORT_SYMBOL_GPL(perf_event_enable);
d859e29f 3222
375637bc
AS
3223struct stop_event_data {
3224 struct perf_event *event;
3225 unsigned int restart;
3226};
3227
95ff4ca2
AS
3228static int __perf_event_stop(void *info)
3229{
375637bc
AS
3230 struct stop_event_data *sd = info;
3231 struct perf_event *event = sd->event;
95ff4ca2 3232
375637bc 3233 /* if it's already INACTIVE, do nothing */
95ff4ca2
AS
3234 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3235 return 0;
3236
3237 /* matches smp_wmb() in event_sched_in() */
3238 smp_rmb();
3239
3240 /*
3241 * There is a window with interrupts enabled before we get here,
3242 * so we need to check again lest we try to stop another CPU's event.
3243 */
3244 if (READ_ONCE(event->oncpu) != smp_processor_id())
3245 return -EAGAIN;
3246
3247 event->pmu->stop(event, PERF_EF_UPDATE);
3248
375637bc
AS
3249 /*
3250 * May race with the actual stop (through perf_pmu_output_stop()),
3251 * but it is only used for events with AUX ring buffer, and such
3252 * events will refuse to restart because of rb::aux_mmap_count==0,
3253 * see comments in perf_aux_output_begin().
3254 *
788faab7 3255 * Since this is happening on an event-local CPU, no trace is lost
375637bc
AS
3256 * while restarting.
3257 */
3258 if (sd->restart)
c9bbdd48 3259 event->pmu->start(event, 0);
375637bc 3260
95ff4ca2
AS
3261 return 0;
3262}
3263
767ae086 3264static int perf_event_stop(struct perf_event *event, int restart)
375637bc
AS
3265{
3266 struct stop_event_data sd = {
3267 .event = event,
767ae086 3268 .restart = restart,
375637bc
AS
3269 };
3270 int ret = 0;
3271
3272 do {
3273 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3274 return 0;
3275
3276 /* matches smp_wmb() in event_sched_in() */
3277 smp_rmb();
3278
3279 /*
3280 * We only want to restart ACTIVE events, so if the event goes
3281 * inactive here (event->oncpu==-1), there's nothing more to do;
3282 * fall through with ret==-ENXIO.
3283 */
3284 ret = cpu_function_call(READ_ONCE(event->oncpu),
3285 __perf_event_stop, &sd);
3286 } while (ret == -EAGAIN);
3287
3288 return ret;
3289}
3290
3291/*
3292 * In order to contain the amount of racy and tricky in the address filter
3293 * configuration management, it is a two part process:
3294 *
3295 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3296 * we update the addresses of corresponding vmas in
c60f83b8 3297 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
375637bc
AS
3298 * (p2) when an event is scheduled in (pmu::add), it calls
3299 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3300 * if the generation has changed since the previous call.
3301 *
3302 * If (p1) happens while the event is active, we restart it to force (p2).
3303 *
3304 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3305 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3306 * ioctl;
3307 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
c1e8d7c6 3308 * registered mapping, called for every new mmap(), with mm::mmap_lock down
375637bc
AS
3309 * for reading;
3310 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3311 * of exec.
3312 */
3313void perf_event_addr_filters_sync(struct perf_event *event)
3314{
3315 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3316
3317 if (!has_addr_filter(event))
3318 return;
3319
3320 raw_spin_lock(&ifh->lock);
3321 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3322 event->pmu->addr_filters_sync(event);
3323 event->hw.addr_filters_gen = event->addr_filters_gen;
3324 }
3325 raw_spin_unlock(&ifh->lock);
3326}
3327EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3328
f63a8daa 3329static int _perf_event_refresh(struct perf_event *event, int refresh)
79f14641 3330{
2023b359 3331 /*
cdd6c482 3332 * not supported on inherited events
2023b359 3333 */
2e939d1d 3334 if (event->attr.inherit || !is_sampling_event(event))
2023b359
PZ
3335 return -EINVAL;
3336
cdd6c482 3337 atomic_add(refresh, &event->event_limit);
f63a8daa 3338 _perf_event_enable(event);
2023b359
PZ
3339
3340 return 0;
79f14641 3341}
f63a8daa
PZ
3342
3343/*
3344 * See perf_event_disable()
3345 */
3346int perf_event_refresh(struct perf_event *event, int refresh)
3347{
3348 struct perf_event_context *ctx;
3349 int ret;
3350
3351 ctx = perf_event_ctx_lock(event);
3352 ret = _perf_event_refresh(event, refresh);
3353 perf_event_ctx_unlock(event, ctx);
3354
3355 return ret;
3356}
26ca5c11 3357EXPORT_SYMBOL_GPL(perf_event_refresh);
79f14641 3358
32ff77e8
MC
3359static int perf_event_modify_breakpoint(struct perf_event *bp,
3360 struct perf_event_attr *attr)
3361{
3362 int err;
3363
3364 _perf_event_disable(bp);
3365
3366 err = modify_user_hw_breakpoint_check(bp, attr, true);
32ff77e8 3367
bf06278c 3368 if (!bp->attr.disabled)
32ff77e8 3369 _perf_event_enable(bp);
bf06278c
JO
3370
3371 return err;
32ff77e8
MC
3372}
3373
3c25fc97
ME
3374/*
3375 * Copy event-type-independent attributes that may be modified.
3376 */
3377static void perf_event_modify_copy_attr(struct perf_event_attr *to,
3378 const struct perf_event_attr *from)
3379{
3380 to->sig_data = from->sig_data;
3381}
3382
32ff77e8
MC
3383static int perf_event_modify_attr(struct perf_event *event,
3384 struct perf_event_attr *attr)
3385{
47f661ec
ME
3386 int (*func)(struct perf_event *, struct perf_event_attr *);
3387 struct perf_event *child;
3388 int err;
3389
32ff77e8
MC
3390 if (event->attr.type != attr->type)
3391 return -EINVAL;
3392
3393 switch (event->attr.type) {
3394 case PERF_TYPE_BREAKPOINT:
47f661ec
ME
3395 func = perf_event_modify_breakpoint;
3396 break;
32ff77e8
MC
3397 default:
3398 /* Place holder for future additions. */
3399 return -EOPNOTSUPP;
3400 }
47f661ec
ME
3401
3402 WARN_ON_ONCE(event->ctx->parent_ctx);
3403
3404 mutex_lock(&event->child_mutex);
3c25fc97
ME
3405 /*
3406 * Event-type-independent attributes must be copied before event-type
3407 * modification, which will validate that final attributes match the
3408 * source attributes after all relevant attributes have been copied.
3409 */
3410 perf_event_modify_copy_attr(&event->attr, attr);
47f661ec
ME
3411 err = func(event, attr);
3412 if (err)
3413 goto out;
3414 list_for_each_entry(child, &event->child_list, child_list) {
3c25fc97 3415 perf_event_modify_copy_attr(&child->attr, attr);
47f661ec
ME
3416 err = func(child, attr);
3417 if (err)
3418 goto out;
3419 }
3420out:
3421 mutex_unlock(&event->child_mutex);
3422 return err;
32ff77e8
MC
3423}
3424
bd275681
PZ
3425static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx,
3426 enum event_type_t event_type)
235c7fc7 3427{
bd275681 3428 struct perf_event_context *ctx = pmu_ctx->ctx;
6668128a 3429 struct perf_event *event, *tmp;
bd275681
PZ
3430 struct pmu *pmu = pmu_ctx->pmu;
3431
5d95a2af 3432 if (ctx->task && !(ctx->is_active & EVENT_ALL)) {
b2996f56 3433 struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
bd275681 3434
bd275681
PZ
3435 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3436 cpc->task_epc = NULL;
3437 }
3438
3e15a3fe 3439 if (!(event_type & EVENT_ALL))
bd275681
PZ
3440 return;
3441
3442 perf_pmu_disable(pmu);
3443 if (event_type & EVENT_PINNED) {
3444 list_for_each_entry_safe(event, tmp,
3445 &pmu_ctx->pinned_active,
3446 active_list)
3447 group_sched_out(event, ctx);
3448 }
3449
3450 if (event_type & EVENT_FLEXIBLE) {
3451 list_for_each_entry_safe(event, tmp,
3452 &pmu_ctx->flexible_active,
3453 active_list)
3454 group_sched_out(event, ctx);
3455 /*
3456 * Since we cleared EVENT_FLEXIBLE, also clear
3457 * rotate_necessary, is will be reset by
3458 * ctx_flexible_sched_in() when needed.
3459 */
3460 pmu_ctx->rotate_necessary = 0;
3461 }
3462 perf_pmu_enable(pmu);
3463}
3464
2d17cf1a
PZ
3465/*
3466 * Be very careful with the @pmu argument since this will change ctx state.
3467 * The @pmu argument works for ctx_resched(), because that is symmetric in
3468 * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant.
3469 *
3470 * However, if you were to be asymmetrical, you could end up with messed up
3471 * state, eg. ctx->is_active cleared even though most EPCs would still actually
3472 * be active.
3473 */
bd275681 3474static void
2d17cf1a 3475ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
bd275681
PZ
3476{
3477 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3478 struct perf_event_pmu_context *pmu_ctx;
db24d33e 3479 int is_active = ctx->is_active;
f06cc667
PZ
3480 bool cgroup = event_type & EVENT_CGROUP;
3481
3482 event_type &= ~EVENT_CGROUP;
235c7fc7 3483
c994d613 3484 lockdep_assert_held(&ctx->lock);
235c7fc7 3485
39a43640
PZ
3486 if (likely(!ctx->nr_events)) {
3487 /*
3488 * See __perf_remove_from_context().
3489 */
3490 WARN_ON_ONCE(ctx->is_active);
3491 if (ctx->task)
3492 WARN_ON_ONCE(cpuctx->task_ctx);
facc4307 3493 return;
39a43640
PZ
3494 }
3495
8fdc6539
PZ
3496 /*
3497 * Always update time if it was set; not only when it changes.
3498 * Otherwise we can 'forget' to update time for any but the last
3499 * context we sched out. For example:
3500 *
3501 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3502 * ctx_sched_out(.event_type = EVENT_PINNED)
3503 *
3504 * would only update time for the pinned events.
3505 */
5d95a2af
PZ
3506 __ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx);
3507
3508 /*
3509 * CPU-release for the below ->is_active store,
3510 * see __load_acquire() in perf_event_time_now()
3511 */
3512 barrier();
3513 ctx->is_active &= ~event_type;
3514
3515 if (!(ctx->is_active & EVENT_ALL)) {
09f5e7dc 3516 /*
5d95a2af
PZ
3517 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now()
3518 * does not observe a hole. perf_ctx_unlock() will clean up.
09f5e7dc 3519 */
5d95a2af
PZ
3520 if (ctx->is_active & EVENT_FROZEN)
3521 ctx->is_active &= EVENT_TIME_FROZEN;
3522 else
3523 ctx->is_active = 0;
09f5e7dc
PZ
3524 }
3525
09f5e7dc
PZ
3526 if (ctx->task) {
3527 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
5d95a2af 3528 if (!(ctx->is_active & EVENT_ALL))
09f5e7dc 3529 cpuctx->task_ctx = NULL;
3cbaa590
PZ
3530 }
3531
8fdc6539
PZ
3532 is_active ^= ctx->is_active; /* changed bits */
3533
2d17cf1a 3534 for_each_epc(pmu_ctx, ctx, pmu, cgroup)
bd275681 3535 __pmu_ctx_sched_out(pmu_ctx, is_active);
235c7fc7
IM
3536}
3537
564c2b21 3538/*
5a3126d4
PZ
3539 * Test whether two contexts are equivalent, i.e. whether they have both been
3540 * cloned from the same version of the same context.
3541 *
3542 * Equivalence is measured using a generation number in the context that is
3543 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3544 * and list_del_event().
564c2b21 3545 */
cdd6c482
IM
3546static int context_equiv(struct perf_event_context *ctx1,
3547 struct perf_event_context *ctx2)
564c2b21 3548{
211de6eb
PZ
3549 lockdep_assert_held(&ctx1->lock);
3550 lockdep_assert_held(&ctx2->lock);
3551
5a3126d4
PZ
3552 /* Pinning disables the swap optimization */
3553 if (ctx1->pin_count || ctx2->pin_count)
3554 return 0;
3555
3556 /* If ctx1 is the parent of ctx2 */
3557 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3558 return 1;
3559
3560 /* If ctx2 is the parent of ctx1 */
3561 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3562 return 1;
3563
3564 /*
3565 * If ctx1 and ctx2 have the same parent; we flatten the parent
3566 * hierarchy, see perf_event_init_context().
3567 */
3568 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3569 ctx1->parent_gen == ctx2->parent_gen)
3570 return 1;
3571
3572 /* Unmatched */
3573 return 0;
564c2b21
PM
3574}
3575
cdd6c482
IM
3576static void __perf_event_sync_stat(struct perf_event *event,
3577 struct perf_event *next_event)
bfbd3381
PZ
3578{
3579 u64 value;
3580
cdd6c482 3581 if (!event->attr.inherit_stat)
bfbd3381
PZ
3582 return;
3583
3584 /*
cdd6c482 3585 * Update the event value, we cannot use perf_event_read()
bfbd3381
PZ
3586 * because we're in the middle of a context switch and have IRQs
3587 * disabled, which upsets smp_call_function_single(), however
cdd6c482 3588 * we know the event must be on the current CPU, therefore we
bfbd3381
PZ
3589 * don't need to use it.
3590 */
8ce939a0 3591 perf_pmu_read(event);
bfbd3381 3592
0d3d73aa 3593 perf_event_update_time(event);
bfbd3381
PZ
3594
3595 /*
cdd6c482 3596 * In order to keep per-task stats reliable we need to flip the event
bfbd3381
PZ
3597 * values when we flip the contexts.
3598 */
e7850595
PZ
3599 value = local64_read(&next_event->count);
3600 value = local64_xchg(&event->count, value);
3601 local64_set(&next_event->count, value);
bfbd3381 3602
cdd6c482
IM
3603 swap(event->total_time_enabled, next_event->total_time_enabled);
3604 swap(event->total_time_running, next_event->total_time_running);
19d2e755 3605
bfbd3381 3606 /*
19d2e755 3607 * Since we swizzled the values, update the user visible data too.
bfbd3381 3608 */
cdd6c482
IM
3609 perf_event_update_userpage(event);
3610 perf_event_update_userpage(next_event);
bfbd3381
PZ
3611}
3612
cdd6c482
IM
3613static void perf_event_sync_stat(struct perf_event_context *ctx,
3614 struct perf_event_context *next_ctx)
bfbd3381 3615{
cdd6c482 3616 struct perf_event *event, *next_event;
bfbd3381
PZ
3617
3618 if (!ctx->nr_stat)
3619 return;
3620
02ffdbc8
PZ
3621 update_context_time(ctx);
3622
cdd6c482
IM
3623 event = list_first_entry(&ctx->event_list,
3624 struct perf_event, event_entry);
bfbd3381 3625
cdd6c482
IM
3626 next_event = list_first_entry(&next_ctx->event_list,
3627 struct perf_event, event_entry);
bfbd3381 3628
cdd6c482
IM
3629 while (&event->event_entry != &ctx->event_list &&
3630 &next_event->event_entry != &next_ctx->event_list) {
bfbd3381 3631
cdd6c482 3632 __perf_event_sync_stat(event, next_event);
bfbd3381 3633
cdd6c482
IM
3634 event = list_next_entry(event, event_entry);
3635 next_event = list_next_entry(next_event, event_entry);
bfbd3381
PZ
3636 }
3637}
3638
d57e94f5
KL
3639static void perf_ctx_sched_task_cb(struct perf_event_context *ctx,
3640 struct task_struct *task, bool sched_in)
bd275681
PZ
3641{
3642 struct perf_event_pmu_context *pmu_ctx;
3643 struct perf_cpu_pmu_context *cpc;
3644
3645 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
b2996f56 3646 cpc = this_cpc(pmu_ctx->pmu);
bd275681
PZ
3647
3648 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task)
d57e94f5 3649 pmu_ctx->pmu->sched_task(pmu_ctx, task, sched_in);
bd275681
PZ
3650 }
3651}
3652
3653static void
3654perf_event_context_sched_out(struct task_struct *task, struct task_struct *next)
0793a61d 3655{
bd275681 3656 struct perf_event_context *ctx = task->perf_event_ctxp;
cdd6c482 3657 struct perf_event_context *next_ctx;
5a3126d4 3658 struct perf_event_context *parent, *next_parent;
c93f7669 3659 int do_switch = 1;
0793a61d 3660
108b02cf
PZ
3661 if (likely(!ctx))
3662 return;
10989fb2 3663
c93f7669 3664 rcu_read_lock();
bd275681 3665 next_ctx = rcu_dereference(next->perf_event_ctxp);
5a3126d4
PZ
3666 if (!next_ctx)
3667 goto unlock;
3668
3669 parent = rcu_dereference(ctx->parent_ctx);
3670 next_parent = rcu_dereference(next_ctx->parent_ctx);
3671
3672 /* If neither context have a parent context; they cannot be clones. */
802c8a61 3673 if (!parent && !next_parent)
5a3126d4
PZ
3674 goto unlock;
3675
3676 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
c93f7669
PM
3677 /*
3678 * Looks like the two contexts are clones, so we might be
3679 * able to optimize the context switch. We lock both
3680 * contexts and check that they are clones under the
3681 * lock (including re-checking that neither has been
3682 * uncloned in the meantime). It doesn't matter which
3683 * order we take the locks because no other cpu could
3684 * be trying to lock both of these tasks.
3685 */
e625cce1
TG
3686 raw_spin_lock(&ctx->lock);
3687 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
c93f7669 3688 if (context_equiv(ctx, next_ctx)) {
c2b98a86 3689
f06cc667 3690 perf_ctx_disable(ctx, false);
ca6c2132 3691
79bd2330
BG
3692 /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */
3693 if (local_read(&ctx->nr_no_switch_fast) ||
3694 local_read(&next_ctx->nr_no_switch_fast)) {
ca6c2132
PZ
3695 /*
3696 * Must not swap out ctx when there's pending
3697 * events that rely on the ctx->task relation.
7e8b2556
BG
3698 *
3699 * Likewise, when a context contains inherit +
3700 * SAMPLE_READ events they should be switched
3701 * out using the slow path so that they are
3702 * treated as if they were distinct contexts.
ca6c2132
PZ
3703 */
3704 raw_spin_unlock(&next_ctx->lock);
3705 rcu_read_unlock();
3706 goto inside_switch;
3707 }
3708
63b6da39
PZ
3709 WRITE_ONCE(ctx->task, next);
3710 WRITE_ONCE(next_ctx->task, task);
5a158c3c 3711
d57e94f5 3712 perf_ctx_sched_task_cb(ctx, task, false);
5a158c3c 3713
f06cc667 3714 perf_ctx_enable(ctx, false);
44fae179 3715
63b6da39
PZ
3716 /*
3717 * RCU_INIT_POINTER here is safe because we've not
3718 * modified the ctx and the above modification of
bd2da08d
KL
3719 * ctx->task is immaterial since this value is
3720 * always verified under ctx->lock which we're now
3721 * holding.
63b6da39 3722 */
bd275681
PZ
3723 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx);
3724 RCU_INIT_POINTER(next->perf_event_ctxp, ctx);
63b6da39 3725
c93f7669 3726 do_switch = 0;
bfbd3381 3727
cdd6c482 3728 perf_event_sync_stat(ctx, next_ctx);
c93f7669 3729 }
e625cce1
TG
3730 raw_spin_unlock(&next_ctx->lock);
3731 raw_spin_unlock(&ctx->lock);
564c2b21 3732 }
5a3126d4 3733unlock:
c93f7669 3734 rcu_read_unlock();
564c2b21 3735
c93f7669 3736 if (do_switch) {
facc4307 3737 raw_spin_lock(&ctx->lock);
f06cc667 3738 perf_ctx_disable(ctx, false);
44fae179 3739
ca6c2132 3740inside_switch:
d57e94f5 3741 perf_ctx_sched_task_cb(ctx, task, false);
2d17cf1a 3742 task_ctx_sched_out(ctx, NULL, EVENT_ALL);
44fae179 3743
f06cc667 3744 perf_ctx_enable(ctx, false);
facc4307 3745 raw_spin_unlock(&ctx->lock);
c93f7669 3746 }
0793a61d
TG
3747}
3748
a5398bff 3749static DEFINE_PER_CPU(struct list_head, sched_cb_list);
bd275681 3750static DEFINE_PER_CPU(int, perf_sched_cb_usages);
a5398bff 3751
ba532500
YZ
3752void perf_sched_cb_dec(struct pmu *pmu)
3753{
b2996f56 3754 struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
e48c1788 3755
a5398bff 3756 this_cpu_dec(perf_sched_cb_usages);
bd275681 3757 barrier();
a5398bff 3758
bd275681
PZ
3759 if (!--cpc->sched_cb_usage)
3760 list_del(&cpc->sched_cb_entry);
ba532500
YZ
3761}
3762
e48c1788 3763
ba532500
YZ
3764void perf_sched_cb_inc(struct pmu *pmu)
3765{
b2996f56 3766 struct perf_cpu_pmu_context *cpc = this_cpc(pmu);
e48c1788 3767
bd275681
PZ
3768 if (!cpc->sched_cb_usage++)
3769 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
a5398bff 3770
bd275681 3771 barrier();
a5398bff 3772 this_cpu_inc(perf_sched_cb_usages);
ba532500
YZ
3773}
3774
3775/*
3776 * This function provides the context switch callback to the lower code
3777 * layer. It is invoked ONLY when the context switch callback is enabled.
09e61b4f
PZ
3778 *
3779 * This callback is relevant even to per-cpu events; for example multi event
3780 * PEBS requires this to provide PID/TID information. This requires we flush
3781 * all queued PEBS records before we context switch to a new task.
ba532500 3782 */
d57e94f5
KL
3783static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc,
3784 struct task_struct *task, bool sched_in)
556cccad 3785{
bd275681 3786 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
556cccad
KL
3787 struct pmu *pmu;
3788
bd275681 3789 pmu = cpc->epc.pmu;
556cccad 3790
bd275681 3791 /* software PMUs will not have sched_task */
556cccad
KL
3792 if (WARN_ON_ONCE(!pmu->sched_task))
3793 return;
3794
3795 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3796 perf_pmu_disable(pmu);
3797
d57e94f5 3798 pmu->sched_task(cpc->task_epc, task, sched_in);
556cccad
KL
3799
3800 perf_pmu_enable(pmu);
3801 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3802}
3803
a5398bff
KL
3804static void perf_pmu_sched_task(struct task_struct *prev,
3805 struct task_struct *next,
3806 bool sched_in)
3807{
bd275681
PZ
3808 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
3809 struct perf_cpu_pmu_context *cpc;
a5398bff 3810
bd275681
PZ
3811 /* cpuctx->task_ctx will be handled in perf_event_context_sched_in/out */
3812 if (prev == next || cpuctx->task_ctx)
a5398bff
KL
3813 return;
3814
bd275681 3815 list_for_each_entry(cpc, this_cpu_ptr(&sched_cb_list), sched_cb_entry)
d57e94f5 3816 __perf_pmu_sched_task(cpc, sched_in ? next : prev, sched_in);
a5398bff
KL
3817}
3818
45ac1403
AH
3819static void perf_event_switch(struct task_struct *task,
3820 struct task_struct *next_prev, bool sched_in);
3821
8dc85d54
PZ
3822/*
3823 * Called from scheduler to remove the events of the current task,
3824 * with interrupts disabled.
3825 *
3826 * We stop each event and update the event value in event->count.
3827 *
3828 * This does not protect us against NMI, but disable()
3829 * sets the disabled bit in the control field of event _before_
3830 * accessing the event control register. If a NMI hits, then it will
3831 * not restart the event.
3832 */
ab0cce56
JO
3833void __perf_event_task_sched_out(struct task_struct *task,
3834 struct task_struct *next)
8dc85d54 3835{
a5398bff
KL
3836 if (__this_cpu_read(perf_sched_cb_usages))
3837 perf_pmu_sched_task(task, next, false);
3838
45ac1403
AH
3839 if (atomic_read(&nr_switch_events))
3840 perf_event_switch(task, next, false);
3841
bd275681 3842 perf_event_context_sched_out(task, next);
e5d1367f
SE
3843
3844 /*
3845 * if cgroup events exist on this CPU, then we need
3846 * to check if we have to switch out PMU state.
3847 * cgroup event are system-wide mode only
3848 */
f841b682 3849 perf_cgroup_switch(next);
8dc85d54
PZ
3850}
3851
267607e8 3852static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args)
0793a61d 3853{
24fb6b8e
IR
3854 const struct perf_event *le = *(const struct perf_event **)l;
3855 const struct perf_event *re = *(const struct perf_event **)r;
6eef8a71
IR
3856
3857 return le->group_index < re->group_index;
3858}
3859
873ce257
KWC
3860DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap);
3861
6eef8a71 3862static const struct min_heap_callbacks perf_min_heap = {
6eef8a71 3863 .less = perf_less_group_idx,
083ad287 3864 .swp = NULL,
6eef8a71
IR
3865};
3866
873ce257 3867static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event)
6eef8a71
IR
3868{
3869 struct perf_event **itrs = heap->data;
3870
3871 if (event) {
3872 itrs[heap->nr] = event;
3873 heap->nr++;
3874 }
3875}
3876
bd275681
PZ
3877static void __link_epc(struct perf_event_pmu_context *pmu_ctx)
3878{
3879 struct perf_cpu_pmu_context *cpc;
3880
3881 if (!pmu_ctx->ctx->task)
3882 return;
3883
b2996f56 3884 cpc = this_cpc(pmu_ctx->pmu);
bd275681
PZ
3885 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx);
3886 cpc->task_epc = pmu_ctx;
3887}
3888
3889static noinline int visit_groups_merge(struct perf_event_context *ctx,
836196be 3890 struct perf_event_groups *groups, int cpu,
bd275681 3891 struct pmu *pmu,
6eef8a71
IR
3892 int (*func)(struct perf_event *, void *),
3893 void *data)
3894{
95ed6c70
IR
3895#ifdef CONFIG_CGROUP_PERF
3896 struct cgroup_subsys_state *css = NULL;
3897#endif
bd275681 3898 struct perf_cpu_context *cpuctx = NULL;
6eef8a71
IR
3899 /* Space for per CPU and/or any CPU event iterators. */
3900 struct perf_event *itrs[2];
873ce257 3901 struct perf_event_min_heap event_heap;
836196be 3902 struct perf_event **evt;
1cac7b1a 3903 int ret;
8e1a2031 3904
bd275681
PZ
3905 if (pmu->filter && pmu->filter(pmu, cpu))
3906 return 0;
3907
3908 if (!ctx->task) {
3909 cpuctx = this_cpu_ptr(&perf_cpu_context);
873ce257 3910 event_heap = (struct perf_event_min_heap){
836196be
IR
3911 .data = cpuctx->heap,
3912 .nr = 0,
3913 .size = cpuctx->heap_size,
3914 };
c2283c93
IR
3915
3916 lockdep_assert_held(&cpuctx->ctx.lock);
95ed6c70
IR
3917
3918#ifdef CONFIG_CGROUP_PERF
3919 if (cpuctx->cgrp)
3920 css = &cpuctx->cgrp->css;
3921#endif
836196be 3922 } else {
873ce257 3923 event_heap = (struct perf_event_min_heap){
836196be
IR
3924 .data = itrs,
3925 .nr = 0,
3926 .size = ARRAY_SIZE(itrs),
3927 };
3928 /* Events not within a CPU context may be on any CPU. */
bd275681 3929 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL));
836196be
IR
3930 }
3931 evt = event_heap.data;
3932
bd275681 3933 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL));
95ed6c70
IR
3934
3935#ifdef CONFIG_CGROUP_PERF
3936 for (; css; css = css->parent)
bd275681 3937 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup));
95ed6c70 3938#endif
1cac7b1a 3939
bd275681
PZ
3940 if (event_heap.nr) {
3941 __link_epc((*evt)->pmu_ctx);
3942 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu);
3943 }
3944
92a8b224 3945 min_heapify_all_inline(&event_heap, &perf_min_heap, NULL);
1cac7b1a 3946
6eef8a71 3947 while (event_heap.nr) {
1cac7b1a
PZ
3948 ret = func(*evt, data);
3949 if (ret)
3950 return ret;
3951
bd275681 3952 *evt = perf_event_groups_next(*evt, pmu);
6eef8a71 3953 if (*evt)
92a8b224 3954 min_heap_sift_down_inline(&event_heap, 0, &perf_min_heap, NULL);
6eef8a71 3955 else
92a8b224 3956 min_heap_pop_inline(&event_heap, &perf_min_heap, NULL);
8e1a2031 3957 }
0793a61d 3958
1cac7b1a
PZ
3959 return 0;
3960}
3961
09f5e7dc
PZ
3962/*
3963 * Because the userpage is strictly per-event (there is no concept of context,
3964 * so there cannot be a context indirection), every userpage must be updated
3965 * when context time starts :-(
3966 *
3967 * IOW, we must not miss EVENT_TIME edges.
3968 */
f7925653
SL
3969static inline bool event_update_userpage(struct perf_event *event)
3970{
3971 if (likely(!atomic_read(&event->mmap_count)))
3972 return false;
3973
3974 perf_event_update_time(event);
f7925653
SL
3975 perf_event_update_userpage(event);
3976
3977 return true;
3978}
3979
3980static inline void group_update_userpage(struct perf_event *group_event)
3981{
3982 struct perf_event *event;
3983
3984 if (!event_update_userpage(group_event))
3985 return;
3986
3987 for_each_sibling_event(event, group_event)
3988 event_update_userpage(event);
3989}
3990
ab6f824c 3991static int merge_sched_in(struct perf_event *event, void *data)
1cac7b1a 3992{
2c2366c7 3993 struct perf_event_context *ctx = event->ctx;
2c2366c7 3994 int *can_add_hw = data;
ab6f824c 3995
1cac7b1a
PZ
3996 if (event->state <= PERF_EVENT_STATE_OFF)
3997 return 0;
3998
3999 if (!event_filter_match(event))
4000 return 0;
4001
bd275681
PZ
4002 if (group_can_go_on(event, *can_add_hw)) {
4003 if (!group_sched_in(event, ctx))
ab6f824c 4004 list_add_tail(&event->active_list, get_event_list(event));
6668128a 4005 }
1cac7b1a 4006
ab6f824c 4007 if (event->state == PERF_EVENT_STATE_INACTIVE) {
f7925653 4008 *can_add_hw = 0;
33238c50
PZ
4009 if (event->attr.pinned) {
4010 perf_cgroup_event_disable(event, ctx);
ab6f824c 4011 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
f4b07fd6
NK
4012
4013 if (*perf_event_fasync(event))
0db61388 4014 event->pending_kill = POLL_ERR;
f4b07fd6
NK
4015
4016 perf_event_wakeup(event);
f7925653 4017 } else {
b2996f56 4018 struct perf_cpu_pmu_context *cpc = this_cpc(event->pmu_ctx->pmu);
bd275681
PZ
4019
4020 event->pmu_ctx->rotate_necessary = 1;
bd275681 4021 perf_mux_hrtimer_restart(cpc);
f7925653 4022 group_update_userpage(event);
33238c50 4023 }
3b6f9e5c 4024 }
1cac7b1a
PZ
4025
4026 return 0;
5b0311e1
FW
4027}
4028
f06cc667
PZ
4029static void pmu_groups_sched_in(struct perf_event_context *ctx,
4030 struct perf_event_groups *groups,
4031 struct pmu *pmu)
5b0311e1 4032{
2c2366c7 4033 int can_add_hw = 1;
f06cc667
PZ
4034 visit_groups_merge(ctx, groups, smp_processor_id(), pmu,
4035 merge_sched_in, &can_add_hw);
1cac7b1a 4036}
8e1a2031 4037
2d17cf1a
PZ
4038static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx,
4039 enum event_type_t event_type)
1cac7b1a 4040{
2d17cf1a 4041 struct perf_event_context *ctx = pmu_ctx->ctx;
836196be 4042
2d17cf1a
PZ
4043 if (event_type & EVENT_PINNED)
4044 pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu);
4045 if (event_type & EVENT_FLEXIBLE)
4046 pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu);
5b0311e1
FW
4047}
4048
4049static void
2d17cf1a 4050ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type)
5b0311e1 4051{
bd275681 4052 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
2d17cf1a 4053 struct perf_event_pmu_context *pmu_ctx;
db24d33e 4054 int is_active = ctx->is_active;
f06cc667
PZ
4055 bool cgroup = event_type & EVENT_CGROUP;
4056
4057 event_type &= ~EVENT_CGROUP;
c994d613
PZ
4058
4059 lockdep_assert_held(&ctx->lock);
e5d1367f 4060
5b0311e1 4061 if (likely(!ctx->nr_events))
facc4307 4062 return;
5b0311e1 4063
baf1b12a 4064 if (!(is_active & EVENT_TIME)) {
09f5e7dc
PZ
4065 /* start ctx time */
4066 __update_context_time(ctx, false);
a0827713 4067 perf_cgroup_set_timestamp(cpuctx);
09f5e7dc
PZ
4068 /*
4069 * CPU-release for the below ->is_active store,
4070 * see __load_acquire() in perf_event_time_now()
4071 */
4072 barrier();
4073 }
4074
3cbaa590 4075 ctx->is_active |= (event_type | EVENT_TIME);
63e30d3e 4076 if (ctx->task) {
5d95a2af 4077 if (!(is_active & EVENT_ALL))
63e30d3e
PZ
4078 cpuctx->task_ctx = ctx;
4079 else
4080 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
4081 }
4082
3cbaa590
PZ
4083 is_active ^= ctx->is_active; /* changed bits */
4084
5b0311e1
FW
4085 /*
4086 * First go through the list and put on any pinned groups
4087 * in order to give them the best chance of going on.
4088 */
2d17cf1a
PZ
4089 if (is_active & EVENT_PINNED) {
4090 for_each_epc(pmu_ctx, ctx, pmu, cgroup)
4091 __pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED);
4092 }
5b0311e1
FW
4093
4094 /* Then walk through the lower prio flexible groups */
2d17cf1a
PZ
4095 if (is_active & EVENT_FLEXIBLE) {
4096 for_each_epc(pmu_ctx, ctx, pmu, cgroup)
4097 __pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE);
4098 }
235c7fc7
IM
4099}
4100
bd275681 4101static void perf_event_context_sched_in(struct task_struct *task)
329c0e01 4102{
bd275681
PZ
4103 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4104 struct perf_event_context *ctx;
329c0e01 4105
bd275681
PZ
4106 rcu_read_lock();
4107 ctx = rcu_dereference(task->perf_event_ctxp);
4108 if (!ctx)
4109 goto rcu_unlock;
235c7fc7 4110
bd275681
PZ
4111 if (cpuctx->task_ctx == ctx) {
4112 perf_ctx_lock(cpuctx, ctx);
f06cc667 4113 perf_ctx_disable(ctx, false);
012669c7 4114
d57e94f5 4115 perf_ctx_sched_task_cb(ctx, task, true);
012669c7 4116
f06cc667 4117 perf_ctx_enable(ctx, false);
bd275681
PZ
4118 perf_ctx_unlock(cpuctx, ctx);
4119 goto rcu_unlock;
556cccad 4120 }
329c0e01 4121
facc4307 4122 perf_ctx_lock(cpuctx, ctx);
fdccc3fb 4123 /*
4124 * We must check ctx->nr_events while holding ctx->lock, such
4125 * that we serialize against perf_install_in_context().
4126 */
4127 if (!ctx->nr_events)
4128 goto unlock;
4129
f06cc667 4130 perf_ctx_disable(ctx, false);
329c0e01
FW
4131 /*
4132 * We want to keep the following priority order:
4133 * cpu pinned (that don't need to move), task pinned,
4134 * cpu flexible, task flexible.
fe45bafb
AS
4135 *
4136 * However, if task's ctx is not carrying any pinned
4137 * events, no need to flip the cpuctx's events around.
329c0e01 4138 */
bd275681 4139 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) {
f06cc667 4140 perf_ctx_disable(&cpuctx->ctx, false);
2d17cf1a 4141 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE);
bd275681
PZ
4142 }
4143
2d17cf1a 4144 perf_event_sched_in(cpuctx, ctx, NULL);
556cccad 4145
d57e94f5 4146 perf_ctx_sched_task_cb(cpuctx->task_ctx, task, true);
556cccad 4147
bd275681 4148 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
f06cc667 4149 perf_ctx_enable(&cpuctx->ctx, false);
bd275681 4150
f06cc667 4151 perf_ctx_enable(ctx, false);
fdccc3fb 4152
4153unlock:
facc4307 4154 perf_ctx_unlock(cpuctx, ctx);
bd275681
PZ
4155rcu_unlock:
4156 rcu_read_unlock();
235c7fc7
IM
4157}
4158
8dc85d54
PZ
4159/*
4160 * Called from scheduler to add the events of the current task
4161 * with interrupts disabled.
4162 *
4163 * We restore the event value and then enable it.
4164 *
4165 * This does not protect us against NMI, but enable()
4166 * sets the enabled bit in the control field of event _before_
4167 * accessing the event control register. If a NMI hits, then it will
4168 * keep the event running.
4169 */
ab0cce56
JO
4170void __perf_event_task_sched_in(struct task_struct *prev,
4171 struct task_struct *task)
8dc85d54 4172{
bd275681 4173 perf_event_context_sched_in(task);
d010b332 4174
45ac1403
AH
4175 if (atomic_read(&nr_switch_events))
4176 perf_event_switch(task, prev, true);
a5398bff
KL
4177
4178 if (__this_cpu_read(perf_sched_cb_usages))
4179 perf_pmu_sched_task(prev, task, true);
235c7fc7
IM
4180}
4181
abd50713
PZ
4182static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
4183{
4184 u64 frequency = event->attr.sample_freq;
4185 u64 sec = NSEC_PER_SEC;
4186 u64 divisor, dividend;
4187
4188 int count_fls, nsec_fls, frequency_fls, sec_fls;
4189
4190 count_fls = fls64(count);
4191 nsec_fls = fls64(nsec);
4192 frequency_fls = fls64(frequency);
4193 sec_fls = 30;
4194
4195 /*
4196 * We got @count in @nsec, with a target of sample_freq HZ
4197 * the target period becomes:
4198 *
4199 * @count * 10^9
4200 * period = -------------------
4201 * @nsec * sample_freq
4202 *
4203 */
4204
4205 /*
4206 * Reduce accuracy by one bit such that @a and @b converge
4207 * to a similar magnitude.
4208 */
fe4b04fa 4209#define REDUCE_FLS(a, b) \
abd50713
PZ
4210do { \
4211 if (a##_fls > b##_fls) { \
4212 a >>= 1; \
4213 a##_fls--; \
4214 } else { \
4215 b >>= 1; \
4216 b##_fls--; \
4217 } \
4218} while (0)
4219
4220 /*
4221 * Reduce accuracy until either term fits in a u64, then proceed with
4222 * the other, so that finally we can do a u64/u64 division.
4223 */
4224 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
4225 REDUCE_FLS(nsec, frequency);
4226 REDUCE_FLS(sec, count);
4227 }
4228
4229 if (count_fls + sec_fls > 64) {
4230 divisor = nsec * frequency;
4231
4232 while (count_fls + sec_fls > 64) {
4233 REDUCE_FLS(count, sec);
4234 divisor >>= 1;
4235 }
4236
4237 dividend = count * sec;
4238 } else {
4239 dividend = count * sec;
4240
4241 while (nsec_fls + frequency_fls > 64) {
4242 REDUCE_FLS(nsec, frequency);
4243 dividend >>= 1;
4244 }
4245
4246 divisor = nsec * frequency;
4247 }
4248
f6ab91ad
PZ
4249 if (!divisor)
4250 return dividend;
4251
abd50713
PZ
4252 return div64_u64(dividend, divisor);
4253}
4254
e050e3f0
SE
4255static DEFINE_PER_CPU(int, perf_throttled_count);
4256static DEFINE_PER_CPU(u64, perf_throttled_seq);
4257
f39d47ff 4258static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
bd2b5b12 4259{
cdd6c482 4260 struct hw_perf_event *hwc = &event->hw;
f6ab91ad 4261 s64 period, sample_period;
bd2b5b12
PZ
4262 s64 delta;
4263
abd50713 4264 period = perf_calculate_period(event, nsec, count);
bd2b5b12
PZ
4265
4266 delta = (s64)(period - hwc->sample_period);
62c0b106
LG
4267 if (delta >= 0)
4268 delta += 7;
4269 else
4270 delta -= 7;
4271 delta /= 8; /* low pass filter */
bd2b5b12
PZ
4272
4273 sample_period = hwc->sample_period + delta;
4274
4275 if (!sample_period)
4276 sample_period = 1;
4277
bd2b5b12 4278 hwc->sample_period = sample_period;
abd50713 4279
e7850595 4280 if (local64_read(&hwc->period_left) > 8*sample_period) {
f39d47ff
SE
4281 if (disable)
4282 event->pmu->stop(event, PERF_EF_UPDATE);
4283
e7850595 4284 local64_set(&hwc->period_left, 0);
f39d47ff
SE
4285
4286 if (disable)
4287 event->pmu->start(event, PERF_EF_RELOAD);
abd50713 4288 }
bd2b5b12
PZ
4289}
4290
0259bf63 4291static void perf_adjust_freq_unthr_events(struct list_head *event_list)
60db5e09 4292{
cdd6c482
IM
4293 struct perf_event *event;
4294 struct hw_perf_event *hwc;
e050e3f0 4295 u64 now, period = TICK_NSEC;
abd50713 4296 s64 delta;
60db5e09 4297
0259bf63 4298 list_for_each_entry(event, event_list, active_list) {
cdd6c482 4299 if (event->state != PERF_EVENT_STATE_ACTIVE)
60db5e09
PZ
4300 continue;
4301
bd275681 4302 // XXX use visit thingy to avoid the -1,cpu match
5632ab12 4303 if (!event_filter_match(event))
5d27c23d
PZ
4304 continue;
4305
cdd6c482 4306 hwc = &event->hw;
6a24ed6c 4307
9734e25f
KL
4308 if (hwc->interrupts == MAX_INTERRUPTS)
4309 perf_event_unthrottle_group(event, is_event_in_freq_mode(event));
a78ac325 4310
ca559503 4311 if (!is_event_in_freq_mode(event))
0259bf63 4312 continue;
60db5e09 4313
e050e3f0
SE
4314 /*
4315 * stop the event and update event->count
4316 */
4317 event->pmu->stop(event, PERF_EF_UPDATE);
4318
e7850595 4319 now = local64_read(&event->count);
abd50713
PZ
4320 delta = now - hwc->freq_count_stamp;
4321 hwc->freq_count_stamp = now;
60db5e09 4322
e050e3f0
SE
4323 /*
4324 * restart the event
4325 * reload only if value has changed
f39d47ff
SE
4326 * we have stopped the event so tell that
4327 * to perf_adjust_period() to avoid stopping it
4328 * twice.
e050e3f0 4329 */
abd50713 4330 if (delta > 0)
f39d47ff 4331 perf_adjust_period(event, period, delta, false);
e050e3f0
SE
4332
4333 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
0259bf63
NK
4334 }
4335}
4336
4337/*
4338 * combine freq adjustment with unthrottling to avoid two passes over the
4339 * events. At the same time, make sure, having freq events does not change
4340 * the rate of unthrottling as that would introduce bias.
4341 */
4342static void
4343perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle)
4344{
4345 struct perf_event_pmu_context *pmu_ctx;
4346
4347 /*
4348 * only need to iterate over all events iff:
4349 * - context have events in frequency mode (needs freq adjust)
4350 * - there are events to unthrottle on this cpu
4351 */
4352 if (!(ctx->nr_freq || unthrottle))
4353 return;
4354
4355 raw_spin_lock(&ctx->lock);
4356
4357 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) {
4358 if (!(pmu_ctx->nr_freq || unthrottle))
4359 continue;
4360 if (!perf_pmu_ctx_is_active(pmu_ctx))
4361 continue;
4362 if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT)
4363 continue;
4364
4365 perf_pmu_disable(pmu_ctx->pmu);
4366 perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active);
4367 perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active);
4368 perf_pmu_enable(pmu_ctx->pmu);
60db5e09 4369 }
e050e3f0
SE
4370
4371 raw_spin_unlock(&ctx->lock);
60db5e09
PZ
4372}
4373
235c7fc7 4374/*
8703a7cf 4375 * Move @event to the tail of the @ctx's elegible events.
235c7fc7 4376 */
8703a7cf 4377static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
0793a61d 4378{
dddd3379
TG
4379 /*
4380 * Rotate the first entry last of non-pinned groups. Rotation might be
4381 * disabled by the inheritance code.
4382 */
8703a7cf
PZ
4383 if (ctx->rotate_disable)
4384 return;
8e1a2031 4385
8703a7cf
PZ
4386 perf_event_groups_delete(&ctx->flexible_groups, event);
4387 perf_event_groups_insert(&ctx->flexible_groups, event);
235c7fc7
IM
4388}
4389
7fa343b7 4390/* pick an event from the flexible_groups to rotate */
8d5bce0c 4391static inline struct perf_event *
bd275681 4392ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx)
235c7fc7 4393{
7fa343b7 4394 struct perf_event *event;
bd275681
PZ
4395 struct rb_node *node;
4396 struct rb_root *tree;
4397 struct __group_key key = {
4398 .pmu = pmu_ctx->pmu,
4399 };
7fa343b7
SL
4400
4401 /* pick the first active flexible event */
bd275681 4402 event = list_first_entry_or_null(&pmu_ctx->flexible_active,
7fa343b7 4403 struct perf_event, active_list);
bd275681
PZ
4404 if (event)
4405 goto out;
7fa343b7
SL
4406
4407 /* if no active flexible event, pick the first event */
bd275681 4408 tree = &pmu_ctx->ctx->flexible_groups.tree;
7fa343b7 4409
bd275681
PZ
4410 if (!pmu_ctx->ctx->task) {
4411 key.cpu = smp_processor_id();
4412
4413 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4414 if (node)
4415 event = __node_2_pe(node);
4416 goto out;
7fa343b7
SL
4417 }
4418
bd275681
PZ
4419 key.cpu = -1;
4420 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4421 if (node) {
4422 event = __node_2_pe(node);
4423 goto out;
4424 }
4425
4426 key.cpu = smp_processor_id();
4427 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup);
4428 if (node)
4429 event = __node_2_pe(node);
4430
4431out:
90c91dfb
PZ
4432 /*
4433 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
4434 * finds there are unschedulable events, it will set it again.
4435 */
bd275681 4436 pmu_ctx->rotate_necessary = 0;
90c91dfb 4437
7fa343b7 4438 return event;
8d5bce0c
PZ
4439}
4440
bd275681 4441static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc)
8d5bce0c 4442{
bd275681
PZ
4443 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4444 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL;
8d5bce0c 4445 struct perf_event *cpu_event = NULL, *task_event = NULL;
fd7d5517 4446 int cpu_rotate, task_rotate;
bd275681 4447 struct pmu *pmu;
8d5bce0c
PZ
4448
4449 /*
4450 * Since we run this from IRQ context, nobody can install new
4451 * events, thus the event count values are stable.
4452 */
7fc23a53 4453
bd275681
PZ
4454 cpu_epc = &cpc->epc;
4455 pmu = cpu_epc->pmu;
4456 task_epc = cpc->task_epc;
4457
4458 cpu_rotate = cpu_epc->rotate_necessary;
bd275681 4459 task_rotate = task_epc ? task_epc->rotate_necessary : 0;
9717e6cd 4460
8d5bce0c
PZ
4461 if (!(cpu_rotate || task_rotate))
4462 return false;
0f5a2601 4463
facc4307 4464 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
bd275681 4465 perf_pmu_disable(pmu);
60db5e09 4466
8d5bce0c 4467 if (task_rotate)
bd275681 4468 task_event = ctx_event_to_rotate(task_epc);
8d5bce0c 4469 if (cpu_rotate)
bd275681 4470 cpu_event = ctx_event_to_rotate(cpu_epc);
8703a7cf 4471
8d5bce0c
PZ
4472 /*
4473 * As per the order given at ctx_resched() first 'pop' task flexible
4474 * and then, if needed CPU flexible.
4475 */
bd275681
PZ
4476 if (task_event || (task_epc && cpu_event)) {
4477 update_context_time(task_epc->ctx);
4478 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE);
4479 }
0793a61d 4480
bd275681
PZ
4481 if (cpu_event) {
4482 update_context_time(&cpuctx->ctx);
4483 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE);
8d5bce0c 4484 rotate_ctx(&cpuctx->ctx, cpu_event);
2d17cf1a 4485 __pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE);
bd275681 4486 }
235c7fc7 4487
bd275681
PZ
4488 if (task_event)
4489 rotate_ctx(task_epc->ctx, task_event);
235c7fc7 4490
bd275681 4491 if (task_event || (task_epc && cpu_event))
2d17cf1a 4492 __pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE);
235c7fc7 4493
bd275681 4494 perf_pmu_enable(pmu);
0f5a2601 4495 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
9e630205 4496
8d5bce0c 4497 return true;
e9d2b064
PZ
4498}
4499
4500void perf_event_task_tick(void)
4501{
bd275681
PZ
4502 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4503 struct perf_event_context *ctx;
e050e3f0 4504 int throttled;
b5ab4cd5 4505
16444645 4506 lockdep_assert_irqs_disabled();
e9d2b064 4507
e050e3f0
SE
4508 __this_cpu_inc(perf_throttled_seq);
4509 throttled = __this_cpu_xchg(perf_throttled_count, 0);
555e0c1e 4510 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
e050e3f0 4511
bd275681
PZ
4512 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled);
4513
4514 rcu_read_lock();
4515 ctx = rcu_dereference(current->perf_event_ctxp);
4516 if (ctx)
4517 perf_adjust_freq_unthr_context(ctx, !!throttled);
4518 rcu_read_unlock();
0793a61d
TG
4519}
4520
889ff015
FW
4521static int event_enable_on_exec(struct perf_event *event,
4522 struct perf_event_context *ctx)
4523{
4524 if (!event->attr.enable_on_exec)
4525 return 0;
4526
4527 event->attr.enable_on_exec = 0;
4528 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4529 return 0;
4530
0d3d73aa 4531 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
889ff015
FW
4532
4533 return 1;
4534}
4535
57e7986e 4536/*
cdd6c482 4537 * Enable all of a task's events that have been marked enable-on-exec.
57e7986e
PM
4538 * This expects task == current.
4539 */
bd275681 4540static void perf_event_enable_on_exec(struct perf_event_context *ctx)
57e7986e 4541{
bd275681 4542 struct perf_event_context *clone_ctx = NULL;
487f05e1 4543 enum event_type_t event_type = 0;
3e349507 4544 struct perf_cpu_context *cpuctx;
cdd6c482 4545 struct perf_event *event;
57e7986e
PM
4546 unsigned long flags;
4547 int enabled = 0;
4548
4549 local_irq_save(flags);
bd275681
PZ
4550 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx))
4551 goto out;
4552
4553 if (!ctx->nr_events)
57e7986e
PM
4554 goto out;
4555
bd275681 4556 cpuctx = this_cpu_ptr(&perf_cpu_context);
3e349507 4557 perf_ctx_lock(cpuctx, ctx);
5d95a2af 4558 ctx_time_freeze(cpuctx, ctx);
bd275681 4559
487f05e1 4560 list_for_each_entry(event, &ctx->event_list, event_entry) {
3e349507 4561 enabled |= event_enable_on_exec(event, ctx);
487f05e1
AS
4562 event_type |= get_event_type(event);
4563 }
57e7986e
PM
4564
4565 /*
3e349507 4566 * Unclone and reschedule this context if we enabled any event.
57e7986e 4567 */
3e349507 4568 if (enabled) {
211de6eb 4569 clone_ctx = unclone_ctx(ctx);
2d17cf1a 4570 ctx_resched(cpuctx, ctx, NULL, event_type);
3e349507
PZ
4571 }
4572 perf_ctx_unlock(cpuctx, ctx);
57e7986e 4573
9ed6060d 4574out:
57e7986e 4575 local_irq_restore(flags);
211de6eb
PZ
4576
4577 if (clone_ctx)
4578 put_ctx(clone_ctx);
57e7986e
PM
4579}
4580
2e498d0a
ME
4581static void perf_remove_from_owner(struct perf_event *event);
4582static void perf_event_exit_event(struct perf_event *event,
da916e96
PZ
4583 struct perf_event_context *ctx,
4584 bool revoke);
2e498d0a
ME
4585
4586/*
4587 * Removes all events from the current task that have been marked
4588 * remove-on-exec, and feeds their values back to parent events.
4589 */
bd275681 4590static void perf_event_remove_on_exec(struct perf_event_context *ctx)
2e498d0a 4591{
bd275681 4592 struct perf_event_context *clone_ctx = NULL;
2e498d0a 4593 struct perf_event *event, *next;
2e498d0a
ME
4594 unsigned long flags;
4595 bool modified = false;
4596
2e498d0a
ME
4597 mutex_lock(&ctx->mutex);
4598
4599 if (WARN_ON_ONCE(ctx->task != current))
4600 goto unlock;
4601
4602 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) {
4603 if (!event->attr.remove_on_exec)
4604 continue;
4605
4606 if (!is_kernel_event(event))
4607 perf_remove_from_owner(event);
4608
4609 modified = true;
4610
da916e96 4611 perf_event_exit_event(event, ctx, false);
2e498d0a
ME
4612 }
4613
4614 raw_spin_lock_irqsave(&ctx->lock, flags);
4615 if (modified)
4616 clone_ctx = unclone_ctx(ctx);
2e498d0a
ME
4617 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4618
4619unlock:
4620 mutex_unlock(&ctx->mutex);
4621
2e498d0a
ME
4622 if (clone_ctx)
4623 put_ctx(clone_ctx);
4624}
4625
0492d4c5
PZ
4626struct perf_read_data {
4627 struct perf_event *event;
4628 bool group;
7d88962e 4629 int ret;
0492d4c5
PZ
4630};
4631
a48a36b3
KL
4632static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu);
4633
451d24d1 4634static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
d6a2f903 4635{
a48a36b3 4636 int local_cpu = smp_processor_id();
d6a2f903
DCC
4637 u16 local_pkg, event_pkg;
4638
1765bb61
TK
4639 if ((unsigned)event_cpu >= nr_cpu_ids)
4640 return event_cpu;
4641
a48a36b3
KL
4642 if (event->group_caps & PERF_EV_CAP_READ_SCOPE) {
4643 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu);
451d24d1 4644
a48a36b3
KL
4645 if (cpumask && cpumask_test_cpu(local_cpu, cpumask))
4646 return local_cpu;
4647 }
451d24d1 4648
a48a36b3 4649 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
451d24d1
PZ
4650 event_pkg = topology_physical_package_id(event_cpu);
4651 local_pkg = topology_physical_package_id(local_cpu);
d6a2f903
DCC
4652
4653 if (event_pkg == local_pkg)
4654 return local_cpu;
4655 }
4656
4657 return event_cpu;
4658}
4659
0793a61d 4660/*
cdd6c482 4661 * Cross CPU call to read the hardware event
0793a61d 4662 */
cdd6c482 4663static void __perf_event_read(void *info)
0793a61d 4664{
0492d4c5
PZ
4665 struct perf_read_data *data = info;
4666 struct perf_event *sub, *event = data->event;
cdd6c482 4667 struct perf_event_context *ctx = event->ctx;
bd275681 4668 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
4a00c16e 4669 struct pmu *pmu = event->pmu;
621a01ea 4670
e1ac3614
PM
4671 /*
4672 * If this is a task context, we need to check whether it is
4673 * the current task context of this cpu. If not it has been
4674 * scheduled out before the smp call arrived. In that case
cdd6c482
IM
4675 * event->count would have been updated to a recent sample
4676 * when the event was scheduled out.
e1ac3614
PM
4677 */
4678 if (ctx->task && cpuctx->task_ctx != ctx)
4679 return;
4680
e625cce1 4681 raw_spin_lock(&ctx->lock);
9a32bd99 4682 ctx_time_update_event(ctx, event);
0492d4c5 4683
0d3d73aa
PZ
4684 perf_event_update_time(event);
4685 if (data->group)
4686 perf_event_update_sibling_time(event);
0c1cbc18 4687
4a00c16e
SB
4688 if (event->state != PERF_EVENT_STATE_ACTIVE)
4689 goto unlock;
0492d4c5 4690
4a00c16e
SB
4691 if (!data->group) {
4692 pmu->read(event);
4693 data->ret = 0;
0492d4c5 4694 goto unlock;
4a00c16e
SB
4695 }
4696
4697 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4698
4699 pmu->read(event);
0492d4c5 4700
8ce939a0
PZI
4701 for_each_sibling_event(sub, event)
4702 perf_pmu_read(sub);
4a00c16e
SB
4703
4704 data->ret = pmu->commit_txn(pmu);
0492d4c5
PZ
4705
4706unlock:
e625cce1 4707 raw_spin_unlock(&ctx->lock);
0793a61d
TG
4708}
4709
7e8b2556 4710static inline u64 perf_event_count(struct perf_event *event, bool self)
b5e58793 4711{
7e8b2556
BG
4712 if (self)
4713 return local64_read(&event->count);
4714
c39a0e2c 4715 return local64_read(&event->count) + atomic64_read(&event->child_count);
b5e58793
PZ
4716}
4717
09f5e7dc
PZ
4718static void calc_timer_values(struct perf_event *event,
4719 u64 *now,
4720 u64 *enabled,
4721 u64 *running)
4722{
4723 u64 ctx_time;
4724
4725 *now = perf_clock();
4726 ctx_time = perf_event_time_now(event, *now);
4727 __perf_update_times(event, ctx_time, enabled, running);
4728}
4729
ffe8690c
KX
4730/*
4731 * NMI-safe method to read a local event, that is an event that
4732 * is:
4733 * - either for the current task, or for this CPU
4734 * - does not have inherit set, for inherited task events
4735 * will not be local and we cannot read them atomically
4736 * - must not have a pmu::count method
4737 */
7d9285e8
YS
4738int perf_event_read_local(struct perf_event *event, u64 *value,
4739 u64 *enabled, u64 *running)
ffe8690c
KX
4740{
4741 unsigned long flags;
1765bb61
TK
4742 int event_oncpu;
4743 int event_cpu;
f91840a3 4744 int ret = 0;
ffe8690c
KX
4745
4746 /*
4747 * Disabling interrupts avoids all counter scheduling (context
4748 * switches, timer based rotation and IPIs).
4749 */
4750 local_irq_save(flags);
4751
ffe8690c
KX
4752 /*
4753 * It must not be an event with inherit set, we cannot read
4754 * all child counters from atomic context.
4755 */
f91840a3
AS
4756 if (event->attr.inherit) {
4757 ret = -EOPNOTSUPP;
4758 goto out;
4759 }
ffe8690c 4760
f91840a3
AS
4761 /* If this is a per-task event, it must be for current */
4762 if ((event->attach_state & PERF_ATTACH_TASK) &&
4763 event->hw.target != current) {
4764 ret = -EINVAL;
4765 goto out;
4766 }
4767
1765bb61
TK
4768 /*
4769 * Get the event CPU numbers, and adjust them to local if the event is
4770 * a per-package event that can be read locally
4771 */
4772 event_oncpu = __perf_event_read_cpu(event, event->oncpu);
4773 event_cpu = __perf_event_read_cpu(event, event->cpu);
4774
f91840a3
AS
4775 /* If this is a per-CPU event, it must be for this CPU */
4776 if (!(event->attach_state & PERF_ATTACH_TASK) &&
1765bb61 4777 event_cpu != smp_processor_id()) {
f91840a3
AS
4778 ret = -EINVAL;
4779 goto out;
4780 }
ffe8690c 4781
befb1b3c 4782 /* If this is a pinned event it must be running on this CPU */
1765bb61 4783 if (event->attr.pinned && event_oncpu != smp_processor_id()) {
befb1b3c
RC
4784 ret = -EBUSY;
4785 goto out;
4786 }
4787
ffe8690c
KX
4788 /*
4789 * If the event is currently on this CPU, its either a per-task event,
4790 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4791 * oncpu == -1).
4792 */
1765bb61 4793 if (event_oncpu == smp_processor_id())
ffe8690c
KX
4794 event->pmu->read(event);
4795
f91840a3 4796 *value = local64_read(&event->count);
0d3d73aa 4797 if (enabled || running) {
99643bab 4798 u64 __enabled, __running, __now;
0d3d73aa 4799
09f5e7dc 4800 calc_timer_values(event, &__now, &__enabled, &__running);
0d3d73aa
PZ
4801 if (enabled)
4802 *enabled = __enabled;
4803 if (running)
4804 *running = __running;
4805 }
f91840a3 4806out:
ffe8690c
KX
4807 local_irq_restore(flags);
4808
f91840a3 4809 return ret;
ffe8690c
KX
4810}
4811
7d88962e 4812static int perf_event_read(struct perf_event *event, bool group)
0793a61d 4813{
0c1cbc18 4814 enum perf_event_state state = READ_ONCE(event->state);
451d24d1 4815 int event_cpu, ret = 0;
7d88962e 4816
0793a61d 4817 /*
cdd6c482
IM
4818 * If event is enabled and currently active on a CPU, update the
4819 * value in the event structure:
0793a61d 4820 */
0c1cbc18
PZ
4821again:
4822 if (state == PERF_EVENT_STATE_ACTIVE) {
4823 struct perf_read_data data;
4824
4825 /*
4826 * Orders the ->state and ->oncpu loads such that if we see
4827 * ACTIVE we must also see the right ->oncpu.
4828 *
4829 * Matches the smp_wmb() from event_sched_in().
4830 */
4831 smp_rmb();
d6a2f903 4832
451d24d1
PZ
4833 event_cpu = READ_ONCE(event->oncpu);
4834 if ((unsigned)event_cpu >= nr_cpu_ids)
4835 return 0;
4836
0c1cbc18
PZ
4837 data = (struct perf_read_data){
4838 .event = event,
4839 .group = group,
4840 .ret = 0,
4841 };
4842
451d24d1
PZ
4843 preempt_disable();
4844 event_cpu = __perf_event_read_cpu(event, event_cpu);
d6a2f903 4845
58763148
PZ
4846 /*
4847 * Purposely ignore the smp_call_function_single() return
4848 * value.
4849 *
451d24d1 4850 * If event_cpu isn't a valid CPU it means the event got
58763148
PZ
4851 * scheduled out and that will have updated the event count.
4852 *
4853 * Therefore, either way, we'll have an up-to-date event count
4854 * after this.
4855 */
451d24d1
PZ
4856 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4857 preempt_enable();
58763148 4858 ret = data.ret;
0c1cbc18
PZ
4859
4860 } else if (state == PERF_EVENT_STATE_INACTIVE) {
2b8988c9
PZ
4861 struct perf_event_context *ctx = event->ctx;
4862 unsigned long flags;
4863
e625cce1 4864 raw_spin_lock_irqsave(&ctx->lock, flags);
0c1cbc18
PZ
4865 state = event->state;
4866 if (state != PERF_EVENT_STATE_INACTIVE) {
4867 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4868 goto again;
4869 }
4870
c530ccd9 4871 /*
0c1cbc18
PZ
4872 * May read while context is not active (e.g., thread is
4873 * blocked), in that case we cannot update context time
c530ccd9 4874 */
9a32bd99 4875 ctx_time_update_event(ctx, event);
0c1cbc18 4876
0d3d73aa 4877 perf_event_update_time(event);
0492d4c5 4878 if (group)
0d3d73aa 4879 perf_event_update_sibling_time(event);
e625cce1 4880 raw_spin_unlock_irqrestore(&ctx->lock, flags);
0793a61d 4881 }
7d88962e
SB
4882
4883 return ret;
0793a61d
TG
4884}
4885
a63eaf34 4886/*
cdd6c482 4887 * Initialize the perf_event context in a task_struct:
a63eaf34 4888 */
eb184479 4889static void __perf_event_init_context(struct perf_event_context *ctx)
a63eaf34 4890{
e625cce1 4891 raw_spin_lock_init(&ctx->lock);
a63eaf34 4892 mutex_init(&ctx->mutex);
bd275681 4893 INIT_LIST_HEAD(&ctx->pmu_ctx_list);
8e1a2031
AB
4894 perf_event_groups_init(&ctx->pinned_groups);
4895 perf_event_groups_init(&ctx->flexible_groups);
a63eaf34 4896 INIT_LIST_HEAD(&ctx->event_list);
8c94abbb 4897 refcount_set(&ctx->refcount, 1);
eb184479
PZ
4898}
4899
bd275681
PZ
4900static void
4901__perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu)
4902{
4903 epc->pmu = pmu;
4904 INIT_LIST_HEAD(&epc->pmu_ctx_entry);
4905 INIT_LIST_HEAD(&epc->pinned_active);
4906 INIT_LIST_HEAD(&epc->flexible_active);
4907 atomic_set(&epc->refcount, 1);
4908}
4909
eb184479 4910static struct perf_event_context *
bd275681 4911alloc_perf_context(struct task_struct *task)
eb184479
PZ
4912{
4913 struct perf_event_context *ctx;
4914
4915 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4916 if (!ctx)
4917 return NULL;
4918
4919 __perf_event_init_context(ctx);
7b3c92b8
MWO
4920 if (task)
4921 ctx->task = get_task_struct(task);
eb184479
PZ
4922
4923 return ctx;
a63eaf34
PM
4924}
4925
2ebd4ffb
MH
4926static struct task_struct *
4927find_lively_task_by_vpid(pid_t vpid)
4928{
4929 struct task_struct *task;
0793a61d
TG
4930
4931 rcu_read_lock();
2ebd4ffb 4932 if (!vpid)
0793a61d
TG
4933 task = current;
4934 else
2ebd4ffb 4935 task = find_task_by_vpid(vpid);
0793a61d
TG
4936 if (task)
4937 get_task_struct(task);
4938 rcu_read_unlock();
4939
4940 if (!task)
4941 return ERR_PTR(-ESRCH);
4942
2ebd4ffb 4943 return task;
2ebd4ffb
MH
4944}
4945
fe4b04fa
PZ
4946/*
4947 * Returns a matching context with refcount and pincount.
4948 */
108b02cf 4949static struct perf_event_context *
bd275681 4950find_get_context(struct task_struct *task, struct perf_event *event)
0793a61d 4951{
211de6eb 4952 struct perf_event_context *ctx, *clone_ctx = NULL;
22a4f650 4953 struct perf_cpu_context *cpuctx;
25346b93 4954 unsigned long flags;
bd275681 4955 int err;
0793a61d 4956
22a4ec72 4957 if (!task) {
cdd6c482 4958 /* Must be root to operate on a CPU event: */
9ec84f79 4959 err = perf_allow_cpu();
da97e184
JFG
4960 if (err)
4961 return ERR_PTR(err);
0793a61d 4962
bd275681 4963 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
0793a61d 4964 ctx = &cpuctx->ctx;
c93f7669 4965 get_ctx(ctx);
6c605f83 4966 raw_spin_lock_irqsave(&ctx->lock, flags);
fe4b04fa 4967 ++ctx->pin_count;
6c605f83 4968 raw_spin_unlock_irqrestore(&ctx->lock, flags);
0793a61d 4969
0793a61d
TG
4970 return ctx;
4971 }
4972
8dc85d54 4973 err = -EINVAL;
9ed6060d 4974retry:
bd275681 4975 ctx = perf_lock_task_context(task, &flags);
c93f7669 4976 if (ctx) {
211de6eb 4977 clone_ctx = unclone_ctx(ctx);
fe4b04fa 4978 ++ctx->pin_count;
4af57ef2 4979
e625cce1 4980 raw_spin_unlock_irqrestore(&ctx->lock, flags);
211de6eb
PZ
4981
4982 if (clone_ctx)
4983 put_ctx(clone_ctx);
9137fb28 4984 } else {
bd275681 4985 ctx = alloc_perf_context(task);
c93f7669
PM
4986 err = -ENOMEM;
4987 if (!ctx)
4988 goto errout;
eb184479 4989
dbe08d82
ON
4990 err = 0;
4991 mutex_lock(&task->perf_event_mutex);
4992 /*
4993 * If it has already passed perf_event_exit_task().
4994 * we must see PF_EXITING, it takes this mutex too.
4995 */
4996 if (task->flags & PF_EXITING)
4997 err = -ESRCH;
bd275681 4998 else if (task->perf_event_ctxp)
dbe08d82 4999 err = -EAGAIN;
fe4b04fa 5000 else {
9137fb28 5001 get_ctx(ctx);
fe4b04fa 5002 ++ctx->pin_count;
bd275681 5003 rcu_assign_pointer(task->perf_event_ctxp, ctx);
fe4b04fa 5004 }
dbe08d82
ON
5005 mutex_unlock(&task->perf_event_mutex);
5006
5007 if (unlikely(err)) {
9137fb28 5008 put_ctx(ctx);
dbe08d82
ON
5009
5010 if (err == -EAGAIN)
5011 goto retry;
5012 goto errout;
a63eaf34
PM
5013 }
5014 }
5015
0793a61d 5016 return ctx;
c93f7669 5017
9ed6060d 5018errout:
c93f7669 5019 return ERR_PTR(err);
0793a61d
TG
5020}
5021
bd275681
PZ
5022static struct perf_event_pmu_context *
5023find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx,
5024 struct perf_event *event)
5025{
2016066c 5026 struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc;
bd275681
PZ
5027
5028 if (!ctx->task) {
889c58b3
PZ
5029 /*
5030 * perf_pmu_migrate_context() / __perf_pmu_install_event()
5031 * relies on the fact that find_get_pmu_context() cannot fail
5032 * for CPU contexts.
5033 */
bd275681
PZ
5034 struct perf_cpu_pmu_context *cpc;
5035
4eabf533 5036 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, event->cpu);
bd275681 5037 epc = &cpc->epc;
4f64a6c9 5038 raw_spin_lock_irq(&ctx->lock);
bd275681 5039 if (!epc->ctx) {
4eabf533
PZ
5040 /*
5041 * One extra reference for the pmu; see perf_pmu_free().
5042 */
5043 atomic_set(&epc->refcount, 2);
bd275681 5044 epc->embedded = 1;
bd275681
PZ
5045 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5046 epc->ctx = ctx;
bd275681
PZ
5047 } else {
5048 WARN_ON_ONCE(epc->ctx != ctx);
5049 atomic_inc(&epc->refcount);
5050 }
4f64a6c9 5051 raw_spin_unlock_irq(&ctx->lock);
bd275681
PZ
5052 return epc;
5053 }
5054
5055 new = kzalloc(sizeof(*epc), GFP_KERNEL);
5056 if (!new)
5057 return ERR_PTR(-ENOMEM);
5058
bd275681
PZ
5059 __perf_init_event_pmu_context(new, pmu);
5060
5061 /*
5062 * XXX
5063 *
5064 * lockdep_assert_held(&ctx->mutex);
5065 *
5066 * can't because perf_event_init_task() doesn't actually hold the
5067 * child_ctx->mutex.
5068 */
5069
5070 raw_spin_lock_irq(&ctx->lock);
5071 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) {
5072 if (epc->pmu == pmu) {
5073 WARN_ON_ONCE(epc->ctx != ctx);
5074 atomic_inc(&epc->refcount);
5075 goto found_epc;
5076 }
2016066c
LG
5077 /* Make sure the pmu_ctx_list is sorted by PMU type: */
5078 if (!pos && epc->pmu->type > pmu->type)
5079 pos = epc;
bd275681
PZ
5080 }
5081
5082 epc = new;
5083 new = NULL;
5084
2016066c
LG
5085 if (!pos)
5086 list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list);
5087 else
5088 list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev);
5089
bd275681
PZ
5090 epc->ctx = ctx;
5091
5092found_epc:
bd275681 5093 raw_spin_unlock_irq(&ctx->lock);
bd275681
PZ
5094 kfree(new);
5095
5096 return epc;
5097}
5098
5099static void get_pmu_ctx(struct perf_event_pmu_context *epc)
5100{
5101 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount));
5102}
5103
4eabf533
PZ
5104static void free_cpc_rcu(struct rcu_head *head)
5105{
5106 struct perf_cpu_pmu_context *cpc =
5107 container_of(head, typeof(*cpc), epc.rcu_head);
5108
4eabf533
PZ
5109 kfree(cpc);
5110}
5111
bd275681
PZ
5112static void free_epc_rcu(struct rcu_head *head)
5113{
5114 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head);
5115
bd275681
PZ
5116 kfree(epc);
5117}
5118
5119static void put_pmu_ctx(struct perf_event_pmu_context *epc)
5120{
4f64a6c9 5121 struct perf_event_context *ctx = epc->ctx;
bd275681
PZ
5122 unsigned long flags;
5123
4f64a6c9
JC
5124 /*
5125 * XXX
5126 *
5127 * lockdep_assert_held(&ctx->mutex);
5128 *
5129 * can't because of the call-site in _free_event()/put_event()
5130 * which isn't always called under ctx->mutex.
5131 */
5132 if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags))
bd275681
PZ
5133 return;
5134
4f64a6c9 5135 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry));
bd275681 5136
4f64a6c9
JC
5137 list_del_init(&epc->pmu_ctx_entry);
5138 epc->ctx = NULL;
bd275681
PZ
5139
5140 WARN_ON_ONCE(!list_empty(&epc->pinned_active));
5141 WARN_ON_ONCE(!list_empty(&epc->flexible_active));
5142
4f64a6c9
JC
5143 raw_spin_unlock_irqrestore(&ctx->lock, flags);
5144
4eabf533
PZ
5145 if (epc->embedded) {
5146 call_rcu(&epc->rcu_head, free_cpc_rcu);
bd275681 5147 return;
4eabf533 5148 }
bd275681
PZ
5149
5150 call_rcu(&epc->rcu_head, free_epc_rcu);
5151}
5152
6fb2915d
LZ
5153static void perf_event_free_filter(struct perf_event *event);
5154
cdd6c482 5155static void free_event_rcu(struct rcu_head *head)
592903cd 5156{
bd275681 5157 struct perf_event *event = container_of(head, typeof(*event), rcu_head);
592903cd 5158
cdd6c482
IM
5159 if (event->ns)
5160 put_pid_ns(event->ns);
6fb2915d 5161 perf_event_free_filter(event);
bdacfaf2 5162 kmem_cache_free(perf_event_cache, event);
592903cd
PZ
5163}
5164
b69cf536 5165static void ring_buffer_attach(struct perf_event *event,
56de4e8f 5166 struct perf_buffer *rb);
925d519a 5167
f2fb6bef
KL
5168static void detach_sb_event(struct perf_event *event)
5169{
5170 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
5171
5172 raw_spin_lock(&pel->lock);
5173 list_del_rcu(&event->sb_list);
5174 raw_spin_unlock(&pel->lock);
5175}
5176
a4f144eb 5177static bool is_sb_event(struct perf_event *event)
f2fb6bef 5178{
a4f144eb
DCC
5179 struct perf_event_attr *attr = &event->attr;
5180
f2fb6bef 5181 if (event->parent)
a4f144eb 5182 return false;
f2fb6bef
KL
5183
5184 if (event->attach_state & PERF_ATTACH_TASK)
a4f144eb 5185 return false;
f2fb6bef 5186
a4f144eb
DCC
5187 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
5188 attr->comm || attr->comm_exec ||
76193a94 5189 attr->task || attr->ksymbol ||
e17d43b9 5190 attr->context_switch || attr->text_poke ||
21038f2b 5191 attr->bpf_event)
a4f144eb 5192 return true;
da916e96 5193
a4f144eb
DCC
5194 return false;
5195}
5196
5197static void unaccount_pmu_sb_event(struct perf_event *event)
5198{
5199 if (is_sb_event(event))
5200 detach_sb_event(event);
f2fb6bef
KL
5201}
5202
555e0c1e
FW
5203#ifdef CONFIG_NO_HZ_FULL
5204static DEFINE_SPINLOCK(nr_freq_lock);
5205#endif
5206
5207static void unaccount_freq_event_nohz(void)
5208{
5209#ifdef CONFIG_NO_HZ_FULL
5210 spin_lock(&nr_freq_lock);
5211 if (atomic_dec_and_test(&nr_freq_events))
5212 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
5213 spin_unlock(&nr_freq_lock);
5214#endif
5215}
5216
5217static void unaccount_freq_event(void)
5218{
5219 if (tick_nohz_full_enabled())
5220 unaccount_freq_event_nohz();
5221 else
5222 atomic_dec(&nr_freq_events);
5223}
5224
506e64e7
KL
5225
5226static struct perf_ctx_data *
5227alloc_perf_ctx_data(struct kmem_cache *ctx_cache, bool global)
5228{
5229 struct perf_ctx_data *cd;
5230
5231 cd = kzalloc(sizeof(*cd), GFP_KERNEL);
5232 if (!cd)
5233 return NULL;
5234
5235 cd->data = kmem_cache_zalloc(ctx_cache, GFP_KERNEL);
5236 if (!cd->data) {
5237 kfree(cd);
5238 return NULL;
5239 }
5240
5241 cd->global = global;
5242 cd->ctx_cache = ctx_cache;
5243 refcount_set(&cd->refcount, 1);
5244
5245 return cd;
5246}
5247
5248static void free_perf_ctx_data(struct perf_ctx_data *cd)
5249{
5250 kmem_cache_free(cd->ctx_cache, cd->data);
5251 kfree(cd);
5252}
5253
5254static void __free_perf_ctx_data_rcu(struct rcu_head *rcu_head)
5255{
5256 struct perf_ctx_data *cd;
5257
5258 cd = container_of(rcu_head, struct perf_ctx_data, rcu_head);
5259 free_perf_ctx_data(cd);
5260}
5261
5262static inline void perf_free_ctx_data_rcu(struct perf_ctx_data *cd)
5263{
5264 call_rcu(&cd->rcu_head, __free_perf_ctx_data_rcu);
5265}
5266
5267static int
5268attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache,
5269 bool global)
5270{
5271 struct perf_ctx_data *cd, *old = NULL;
5272
5273 cd = alloc_perf_ctx_data(ctx_cache, global);
5274 if (!cd)
5275 return -ENOMEM;
5276
5277 for (;;) {
5278 if (try_cmpxchg((struct perf_ctx_data **)&task->perf_ctx_data, &old, cd)) {
5279 if (old)
5280 perf_free_ctx_data_rcu(old);
5281 return 0;
5282 }
5283
5284 if (!old) {
5285 /*
5286 * After seeing a dead @old, we raced with
5287 * removal and lost, try again to install @cd.
5288 */
5289 continue;
5290 }
5291
5292 if (refcount_inc_not_zero(&old->refcount)) {
5293 free_perf_ctx_data(cd); /* unused */
5294 return 0;
5295 }
5296
5297 /*
5298 * @old is a dead object, refcount==0 is stable, try and
5299 * replace it with @cd.
5300 */
5301 }
5302 return 0;
5303}
5304
5305static void __detach_global_ctx_data(void);
5306DEFINE_STATIC_PERCPU_RWSEM(global_ctx_data_rwsem);
5307static refcount_t global_ctx_data_ref;
5308
5309static int
5310attach_global_ctx_data(struct kmem_cache *ctx_cache)
5311{
5312 struct task_struct *g, *p;
5313 struct perf_ctx_data *cd;
5314 int ret;
5315
5316 if (refcount_inc_not_zero(&global_ctx_data_ref))
5317 return 0;
5318
5319 guard(percpu_write)(&global_ctx_data_rwsem);
5320 if (refcount_inc_not_zero(&global_ctx_data_ref))
5321 return 0;
5322again:
5323 /* Allocate everything */
5324 scoped_guard (rcu) {
5325 for_each_process_thread(g, p) {
5326 cd = rcu_dereference(p->perf_ctx_data);
5327 if (cd && !cd->global) {
5328 cd->global = 1;
5329 if (!refcount_inc_not_zero(&cd->refcount))
5330 cd = NULL;
5331 }
5332 if (!cd) {
5333 get_task_struct(p);
5334 goto alloc;
5335 }
5336 }
5337 }
5338
5339 refcount_set(&global_ctx_data_ref, 1);
5340
5341 return 0;
5342alloc:
5343 ret = attach_task_ctx_data(p, ctx_cache, true);
5344 put_task_struct(p);
5345 if (ret) {
5346 __detach_global_ctx_data();
5347 return ret;
5348 }
5349 goto again;
5350}
5351
5352static int
5353attach_perf_ctx_data(struct perf_event *event)
5354{
5355 struct task_struct *task = event->hw.target;
5356 struct kmem_cache *ctx_cache = event->pmu->task_ctx_cache;
5357 int ret;
5358
5359 if (!ctx_cache)
5360 return -ENOMEM;
5361
5362 if (task)
5363 return attach_task_ctx_data(task, ctx_cache, false);
5364
5365 ret = attach_global_ctx_data(ctx_cache);
5366 if (ret)
5367 return ret;
5368
5369 event->attach_state |= PERF_ATTACH_GLOBAL_DATA;
5370 return 0;
5371}
5372
5373static void
5374detach_task_ctx_data(struct task_struct *p)
5375{
5376 struct perf_ctx_data *cd;
5377
5378 scoped_guard (rcu) {
5379 cd = rcu_dereference(p->perf_ctx_data);
5380 if (!cd || !refcount_dec_and_test(&cd->refcount))
5381 return;
5382 }
5383
5384 /*
5385 * The old ctx_data may be lost because of the race.
5386 * Nothing is required to do for the case.
5387 * See attach_task_ctx_data().
5388 */
5389 if (try_cmpxchg((struct perf_ctx_data **)&p->perf_ctx_data, &cd, NULL))
5390 perf_free_ctx_data_rcu(cd);
5391}
5392
5393static void __detach_global_ctx_data(void)
5394{
5395 struct task_struct *g, *p;
5396 struct perf_ctx_data *cd;
5397
5398again:
5399 scoped_guard (rcu) {
5400 for_each_process_thread(g, p) {
5401 cd = rcu_dereference(p->perf_ctx_data);
5402 if (!cd || !cd->global)
5403 continue;
5404 cd->global = 0;
5405 get_task_struct(p);
5406 goto detach;
5407 }
5408 }
5409 return;
5410detach:
5411 detach_task_ctx_data(p);
5412 put_task_struct(p);
5413 goto again;
5414}
5415
5416static void detach_global_ctx_data(void)
5417{
5418 if (refcount_dec_not_one(&global_ctx_data_ref))
5419 return;
5420
5421 guard(percpu_write)(&global_ctx_data_rwsem);
5422 if (!refcount_dec_and_test(&global_ctx_data_ref))
5423 return;
5424
5425 /* remove everything */
5426 __detach_global_ctx_data();
5427}
5428
5429static void detach_perf_ctx_data(struct perf_event *event)
5430{
5431 struct task_struct *task = event->hw.target;
5432
5433 event->attach_state &= ~PERF_ATTACH_TASK_DATA;
5434
5435 if (task)
5436 return detach_task_ctx_data(task);
5437
5438 if (event->attach_state & PERF_ATTACH_GLOBAL_DATA) {
5439 detach_global_ctx_data();
5440 event->attach_state &= ~PERF_ATTACH_GLOBAL_DATA;
5441 }
5442}
5443
4beb31f3
FW
5444static void unaccount_event(struct perf_event *event)
5445{
25432ae9
PZ
5446 bool dec = false;
5447
4beb31f3
FW
5448 if (event->parent)
5449 return;
5450
a5398bff 5451 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
25432ae9 5452 dec = true;
4beb31f3
FW
5453 if (event->attr.mmap || event->attr.mmap_data)
5454 atomic_dec(&nr_mmap_events);
88a16a13
JO
5455 if (event->attr.build_id)
5456 atomic_dec(&nr_build_id_events);
4beb31f3
FW
5457 if (event->attr.comm)
5458 atomic_dec(&nr_comm_events);
e4222673
HB
5459 if (event->attr.namespaces)
5460 atomic_dec(&nr_namespaces_events);
96aaab68
NK
5461 if (event->attr.cgroup)
5462 atomic_dec(&nr_cgroup_events);
4beb31f3
FW
5463 if (event->attr.task)
5464 atomic_dec(&nr_task_events);
948b26b6 5465 if (event->attr.freq)
555e0c1e 5466 unaccount_freq_event();
45ac1403 5467 if (event->attr.context_switch) {
25432ae9 5468 dec = true;
45ac1403
AH
5469 atomic_dec(&nr_switch_events);
5470 }
4beb31f3 5471 if (is_cgroup_event(event))
25432ae9 5472 dec = true;
4beb31f3 5473 if (has_branch_stack(event))
25432ae9 5474 dec = true;
76193a94
SL
5475 if (event->attr.ksymbol)
5476 atomic_dec(&nr_ksymbol_events);
6ee52e2a
SL
5477 if (event->attr.bpf_event)
5478 atomic_dec(&nr_bpf_events);
e17d43b9
AH
5479 if (event->attr.text_poke)
5480 atomic_dec(&nr_text_poke_events);
25432ae9 5481
9107c89e
PZ
5482 if (dec) {
5483 if (!atomic_add_unless(&perf_sched_count, -1, 1))
5484 schedule_delayed_work(&perf_sched_work, HZ);
5485 }
4beb31f3 5486
f2fb6bef 5487 unaccount_pmu_sb_event(event);
4beb31f3 5488}
925d519a 5489
9107c89e
PZ
5490static void perf_sched_delayed(struct work_struct *work)
5491{
5492 mutex_lock(&perf_sched_mutex);
5493 if (atomic_dec_and_test(&perf_sched_count))
5494 static_branch_disable(&perf_sched_events);
5495 mutex_unlock(&perf_sched_mutex);
5496}
5497
bed5b25a
AS
5498/*
5499 * The following implement mutual exclusion of events on "exclusive" pmus
5500 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
5501 * at a time, so we disallow creating events that might conflict, namely:
5502 *
5503 * 1) cpu-wide events in the presence of per-task events,
5504 * 2) per-task events in the presence of cpu-wide events,
bd275681 5505 * 3) two matching events on the same perf_event_context.
bed5b25a
AS
5506 *
5507 * The former two cases are handled in the allocation path (perf_event_alloc(),
a0733e69 5508 * _free_event()), the latter -- before the first perf_install_in_context().
bed5b25a
AS
5509 */
5510static int exclusive_event_init(struct perf_event *event)
5511{
5512 struct pmu *pmu = event->pmu;
5513
8a58ddae 5514 if (!is_exclusive_pmu(pmu))
bed5b25a
AS
5515 return 0;
5516
5517 /*
5518 * Prevent co-existence of per-task and cpu-wide events on the
5519 * same exclusive pmu.
5520 *
5521 * Negative pmu::exclusive_cnt means there are cpu-wide
5522 * events on this "exclusive" pmu, positive means there are
5523 * per-task events.
5524 *
5525 * Since this is called in perf_event_alloc() path, event::ctx
5526 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
5527 * to mean "per-task event", because unlike other attach states it
5528 * never gets cleared.
5529 */
5530 if (event->attach_state & PERF_ATTACH_TASK) {
5531 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
5532 return -EBUSY;
5533 } else {
5534 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
5535 return -EBUSY;
5536 }
5537
c70ca298
PZ
5538 event->attach_state |= PERF_ATTACH_EXCLUSIVE;
5539
bed5b25a
AS
5540 return 0;
5541}
5542
5543static void exclusive_event_destroy(struct perf_event *event)
5544{
5545 struct pmu *pmu = event->pmu;
5546
bed5b25a
AS
5547 /* see comment in exclusive_event_init() */
5548 if (event->attach_state & PERF_ATTACH_TASK)
5549 atomic_dec(&pmu->exclusive_cnt);
5550 else
5551 atomic_inc(&pmu->exclusive_cnt);
c70ca298
PZ
5552
5553 event->attach_state &= ~PERF_ATTACH_EXCLUSIVE;
bed5b25a
AS
5554}
5555
5556static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
5557{
3bf6215a 5558 if ((e1->pmu == e2->pmu) &&
bed5b25a
AS
5559 (e1->cpu == e2->cpu ||
5560 e1->cpu == -1 ||
5561 e2->cpu == -1))
5562 return true;
5563 return false;
5564}
5565
bed5b25a
AS
5566static bool exclusive_event_installable(struct perf_event *event,
5567 struct perf_event_context *ctx)
5568{
5569 struct perf_event *iter_event;
5570 struct pmu *pmu = event->pmu;
5571
8a58ddae
AS
5572 lockdep_assert_held(&ctx->mutex);
5573
5574 if (!is_exclusive_pmu(pmu))
bed5b25a
AS
5575 return true;
5576
5577 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
5578 if (exclusive_event_match(iter_event, event))
5579 return false;
5580 }
5581
5582 return true;
5583}
5584
adc38b4c 5585static void perf_free_addr_filters(struct perf_event *event);
375637bc 5586
c70ca298
PZ
5587/* vs perf_event_alloc() error */
5588static void __free_event(struct perf_event *event)
f1600952 5589{
da916e96
PZ
5590 struct pmu *pmu = event->pmu;
5591
c70ca298
PZ
5592 if (event->attach_state & PERF_ATTACH_CALLCHAIN)
5593 put_callchain_buffers();
9ee318a7 5594
c70ca298 5595 kfree(event->addr_filter_ranges);
da97e184 5596
c70ca298
PZ
5597 if (event->attach_state & PERF_ATTACH_EXCLUSIVE)
5598 exclusive_event_destroy(event);
a4be7c27 5599
e5d1367f
SE
5600 if (is_cgroup_event(event))
5601 perf_detach_cgroup(event);
5602
506e64e7
KL
5603 if (event->attach_state & PERF_ATTACH_TASK_DATA)
5604 detach_perf_ctx_data(event);
5605
a0733e69
PZ
5606 if (event->destroy)
5607 event->destroy(event);
5608
1cf8dfe8
PZ
5609 /*
5610 * Must be after ->destroy(), due to uprobe_perf_close() using
5611 * hw.target.
5612 */
621b6d2e
PB
5613 if (event->hw.target)
5614 put_task_struct(event->hw.target);
5615
c70ca298
PZ
5616 if (event->pmu_ctx) {
5617 /*
5618 * put_pmu_ctx() needs an event->ctx reference, because of
5619 * epc->ctx.
5620 */
da916e96 5621 WARN_ON_ONCE(!pmu);
c70ca298
PZ
5622 WARN_ON_ONCE(!event->ctx);
5623 WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx);
bd275681 5624 put_pmu_ctx(event->pmu_ctx);
c70ca298 5625 }
bd275681 5626
1cf8dfe8 5627 /*
c70ca298
PZ
5628 * perf_event_free_task() relies on put_ctx() being 'last', in
5629 * particular all task references must be cleaned up.
1cf8dfe8
PZ
5630 */
5631 if (event->ctx)
5632 put_ctx(event->ctx);
5633
da916e96
PZ
5634 if (pmu) {
5635 module_put(pmu->module);
5636 scoped_guard (spinlock, &pmu->events_lock) {
5637 list_del(&event->pmu_list);
5638 wake_up_var(pmu);
5639 }
5640 }
a0733e69
PZ
5641
5642 call_rcu(&event->rcu_head, free_event_rcu);
f1600952
PZ
5643}
5644
8f2221f5
PZ
5645DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T))
5646
c70ca298
PZ
5647/* vs perf_event_alloc() success */
5648static void _free_event(struct perf_event *event)
5649{
5650 irq_work_sync(&event->pending_irq);
5651 irq_work_sync(&event->pending_disable_irq);
c70ca298
PZ
5652
5653 unaccount_event(event);
5654
5655 security_perf_event_free(event);
5656
5657 if (event->rb) {
5658 /*
5659 * Can happen when we close an event with re-directed output.
5660 *
5661 * Since we have a 0 refcount, perf_mmap_close() will skip
5662 * over us; possibly making our ring_buffer_put() the last.
5663 */
5664 mutex_lock(&event->mmap_mutex);
5665 ring_buffer_attach(event, NULL);
5666 mutex_unlock(&event->mmap_mutex);
5667 }
5668
5669 perf_event_free_bpf_prog(event);
adc38b4c 5670 perf_free_addr_filters(event);
c70ca298
PZ
5671
5672 __free_event(event);
5673}
5674
22d38bab
FW
5675/*
5676 * Used to free events which have a known refcount of 1, such as in error paths
5677 * of inherited events.
5678 */
5679static void free_event(struct perf_event *event)
5680{
5681 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
5682 "unexpected event refcount: %ld; ptr=%p\n",
5683 atomic_long_read(&event->refcount), event)) {
5684 /* leak to avoid use-after-free */
5685 return;
5686 }
5687
5688 _free_event(event);
5689}
5690
a66a3052 5691/*
f8697762 5692 * Remove user event from the owner task.
a66a3052 5693 */
f8697762 5694static void perf_remove_from_owner(struct perf_event *event)
fb0459d7 5695{
8882135b 5696 struct task_struct *owner;
fb0459d7 5697
8882135b 5698 rcu_read_lock();
8882135b 5699 /*
f47c02c0
PZ
5700 * Matches the smp_store_release() in perf_event_exit_task(). If we
5701 * observe !owner it means the list deletion is complete and we can
5702 * indeed free this event, otherwise we need to serialize on
8882135b
PZ
5703 * owner->perf_event_mutex.
5704 */
506458ef 5705 owner = READ_ONCE(event->owner);
8882135b
PZ
5706 if (owner) {
5707 /*
5708 * Since delayed_put_task_struct() also drops the last
5709 * task reference we can safely take a new reference
5710 * while holding the rcu_read_lock().
5711 */
5712 get_task_struct(owner);
5713 }
5714 rcu_read_unlock();
5715
5716 if (owner) {
f63a8daa
PZ
5717 /*
5718 * If we're here through perf_event_exit_task() we're already
5719 * holding ctx->mutex which would be an inversion wrt. the
5720 * normal lock order.
5721 *
5722 * However we can safely take this lock because its the child
5723 * ctx->mutex.
5724 */
5725 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
5726
8882135b
PZ
5727 /*
5728 * We have to re-check the event->owner field, if it is cleared
5729 * we raced with perf_event_exit_task(), acquiring the mutex
5730 * ensured they're done, and we can proceed with freeing the
5731 * event.
5732 */
f47c02c0 5733 if (event->owner) {
8882135b 5734 list_del_init(&event->owner_entry);
f47c02c0
PZ
5735 smp_store_release(&event->owner, NULL);
5736 }
8882135b
PZ
5737 mutex_unlock(&owner->perf_event_mutex);
5738 put_task_struct(owner);
5739 }
f8697762
JO
5740}
5741
f8697762
JO
5742static void put_event(struct perf_event *event)
5743{
56799bc0
FW
5744 struct perf_event *parent;
5745
f8697762
JO
5746 if (!atomic_long_dec_and_test(&event->refcount))
5747 return;
5748
56799bc0 5749 parent = event->parent;
c6e5b732 5750 _free_event(event);
56799bc0
FW
5751
5752 /* Matches the refcount bump in inherit_event() */
d20eb2d5 5753 if (parent)
56799bc0 5754 put_event(parent);
c6e5b732
PZ
5755}
5756
5757/*
5758 * Kill an event dead; while event:refcount will preserve the event
5759 * object, it will not preserve its functionality. Once the last 'user'
5760 * gives up the object, we'll destroy the thing.
5761 */
5762int perf_event_release_kernel(struct perf_event *event)
5763{
a4f4bb6d 5764 struct perf_event_context *ctx = event->ctx;
c6e5b732
PZ
5765 struct perf_event *child, *tmp;
5766
a4f4bb6d 5767 /*
bd275681
PZ
5768 * If we got here through err_alloc: free_event(event); we will not
5769 * have attached to a context yet.
a4f4bb6d
PZ
5770 */
5771 if (!ctx) {
5772 WARN_ON_ONCE(event->attach_state &
5773 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
5774 goto no_ctx;
5775 }
5776
f8697762
JO
5777 if (!is_kernel_event(event))
5778 perf_remove_from_owner(event);
8882135b 5779
5fa7c8ec 5780 ctx = perf_event_ctx_lock(event);
a83fe28e 5781 WARN_ON_ONCE(ctx->parent_ctx);
683ede43 5782
683ede43 5783 /*
d8a8cfc7 5784 * Mark this event as STATE_DEAD, there is no external reference to it
a69b0ca4 5785 * anymore.
683ede43 5786 *
a69b0ca4
PZ
5787 * Anybody acquiring event->child_mutex after the below loop _must_
5788 * also see this, most importantly inherit_event() which will avoid
5789 * placing more children on the list.
683ede43 5790 *
c6e5b732
PZ
5791 * Thus this guarantees that we will in fact observe and kill _ALL_
5792 * child events.
683ede43 5793 */
da916e96
PZ
5794 if (event->state > PERF_EVENT_STATE_REVOKED) {
5795 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD);
5796 } else {
5797 event->state = PERF_EVENT_STATE_DEAD;
5798 }
a69b0ca4
PZ
5799
5800 perf_event_ctx_unlock(event, ctx);
683ede43 5801
c6e5b732
PZ
5802again:
5803 mutex_lock(&event->child_mutex);
5804 list_for_each_entry(child, &event->child_list, child_list) {
c6e5b732
PZ
5805 /*
5806 * Cannot change, child events are not migrated, see the
5807 * comment with perf_event_ctx_lock_nested().
5808 */
506458ef 5809 ctx = READ_ONCE(child->ctx);
c6e5b732
PZ
5810 /*
5811 * Since child_mutex nests inside ctx::mutex, we must jump
5812 * through hoops. We start by grabbing a reference on the ctx.
5813 *
5814 * Since the event cannot get freed while we hold the
5815 * child_mutex, the context must also exist and have a !0
5816 * reference count.
5817 */
5818 get_ctx(ctx);
5819
5820 /*
5821 * Now that we have a ctx ref, we can drop child_mutex, and
5822 * acquire ctx::mutex without fear of it going away. Then we
5823 * can re-acquire child_mutex.
5824 */
5825 mutex_unlock(&event->child_mutex);
5826 mutex_lock(&ctx->mutex);
5827 mutex_lock(&event->child_mutex);
5828
5829 /*
5830 * Now that we hold ctx::mutex and child_mutex, revalidate our
5831 * state, if child is still the first entry, it didn't get freed
5832 * and we can continue doing so.
5833 */
5834 tmp = list_first_entry_or_null(&event->child_list,
5835 struct perf_event, child_list);
5836 if (tmp == child) {
0a00a43b 5837 perf_remove_from_context(child, DETACH_GROUP | DETACH_CHILD);
3e8671e0
PZ
5838 } else {
5839 child = NULL;
c6e5b732
PZ
5840 }
5841
5842 mutex_unlock(&event->child_mutex);
5843 mutex_unlock(&ctx->mutex);
3e8671e0
PZ
5844
5845 if (child) {
5846 /* Last reference unless ->pending_task work is pending */
5847 put_event(child);
5848 }
c6e5b732 5849 put_ctx(ctx);
74751ef5 5850
c6e5b732
PZ
5851 goto again;
5852 }
5853 mutex_unlock(&event->child_mutex);
5854
a4f4bb6d 5855no_ctx:
56799bc0
FW
5856 /*
5857 * Last reference unless ->pending_task work is pending on this event
5858 * or any of its children.
5859 */
5860 put_event(event);
683ede43
PZ
5861 return 0;
5862}
5863EXPORT_SYMBOL_GPL(perf_event_release_kernel);
5864
8b10c5e2
PZ
5865/*
5866 * Called when the last reference to the file is gone.
5867 */
a6fa941d
AV
5868static int perf_release(struct inode *inode, struct file *file)
5869{
c6e5b732 5870 perf_event_release_kernel(file->private_data);
a6fa941d 5871 return 0;
fb0459d7 5872}
fb0459d7 5873
ca0dd44c 5874static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
e53c0994 5875{
cdd6c482 5876 struct perf_event *child;
e53c0994
PZ
5877 u64 total = 0;
5878
59ed446f
PZ
5879 *enabled = 0;
5880 *running = 0;
5881
6f10581a 5882 mutex_lock(&event->child_mutex);
01add3ea 5883
7d88962e 5884 (void)perf_event_read(event, false);
7e8b2556 5885 total += perf_event_count(event, false);
01add3ea 5886
59ed446f
PZ
5887 *enabled += event->total_time_enabled +
5888 atomic64_read(&event->child_total_time_enabled);
5889 *running += event->total_time_running +
5890 atomic64_read(&event->child_total_time_running);
5891
5892 list_for_each_entry(child, &event->child_list, child_list) {
7d88962e 5893 (void)perf_event_read(child, false);
7e8b2556 5894 total += perf_event_count(child, false);
59ed446f
PZ
5895 *enabled += child->total_time_enabled;
5896 *running += child->total_time_running;
5897 }
6f10581a 5898 mutex_unlock(&event->child_mutex);
e53c0994
PZ
5899
5900 return total;
5901}
ca0dd44c
PZ
5902
5903u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5904{
5905 struct perf_event_context *ctx;
5906 u64 count;
5907
5908 ctx = perf_event_ctx_lock(event);
5909 count = __perf_event_read_value(event, enabled, running);
5910 perf_event_ctx_unlock(event, ctx);
5911
5912 return count;
5913}
fb0459d7 5914EXPORT_SYMBOL_GPL(perf_event_read_value);
e53c0994 5915
7d88962e 5916static int __perf_read_group_add(struct perf_event *leader,
fa8c2693 5917 u64 read_format, u64 *values)
3dab77fb 5918{
2aeb1883 5919 struct perf_event_context *ctx = leader->ctx;
32671e37 5920 struct perf_event *sub, *parent;
2aeb1883 5921 unsigned long flags;
fa8c2693 5922 int n = 1; /* skip @nr */
7d88962e 5923 int ret;
f63a8daa 5924
7d88962e
SB
5925 ret = perf_event_read(leader, true);
5926 if (ret)
5927 return ret;
abf4868b 5928
a9cd8194 5929 raw_spin_lock_irqsave(&ctx->lock, flags);
32671e37
PZ
5930 /*
5931 * Verify the grouping between the parent and child (inherited)
5932 * events is still in tact.
5933 *
5934 * Specifically:
5935 * - leader->ctx->lock pins leader->sibling_list
5936 * - parent->child_mutex pins parent->child_list
5937 * - parent->ctx->mutex pins parent->sibling_list
5938 *
5939 * Because parent->ctx != leader->ctx (and child_list nests inside
5940 * ctx->mutex), group destruction is not atomic between children, also
5941 * see perf_event_release_kernel(). Additionally, parent can grow the
5942 * group.
5943 *
5944 * Therefore it is possible to have parent and child groups in a
5945 * different configuration and summing over such a beast makes no sense
5946 * what so ever.
5947 *
5948 * Reject this.
5949 */
5950 parent = leader->parent;
5951 if (parent &&
5952 (parent->group_generation != leader->group_generation ||
5953 parent->nr_siblings != leader->nr_siblings)) {
5954 ret = -ECHILD;
5955 goto unlock;
5956 }
a9cd8194 5957
fa8c2693
PZ
5958 /*
5959 * Since we co-schedule groups, {enabled,running} times of siblings
5960 * will be identical to those of the leader, so we only publish one
5961 * set.
5962 */
5963 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5964 values[n++] += leader->total_time_enabled +
5965 atomic64_read(&leader->child_total_time_enabled);
5966 }
3dab77fb 5967
fa8c2693
PZ
5968 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5969 values[n++] += leader->total_time_running +
5970 atomic64_read(&leader->child_total_time_running);
5971 }
5972
5973 /*
5974 * Write {count,id} tuples for every sibling.
5975 */
7e8b2556 5976 values[n++] += perf_event_count(leader, false);
abf4868b
PZ
5977 if (read_format & PERF_FORMAT_ID)
5978 values[n++] = primary_event_id(leader);
119a784c
NK
5979 if (read_format & PERF_FORMAT_LOST)
5980 values[n++] = atomic64_read(&leader->lost_samples);
3dab77fb 5981
edb39592 5982 for_each_sibling_event(sub, leader) {
7e8b2556 5983 values[n++] += perf_event_count(sub, false);
fa8c2693
PZ
5984 if (read_format & PERF_FORMAT_ID)
5985 values[n++] = primary_event_id(sub);
119a784c
NK
5986 if (read_format & PERF_FORMAT_LOST)
5987 values[n++] = atomic64_read(&sub->lost_samples);
fa8c2693 5988 }
7d88962e 5989
32671e37 5990unlock:
2aeb1883 5991 raw_spin_unlock_irqrestore(&ctx->lock, flags);
32671e37 5992 return ret;
fa8c2693 5993}
3dab77fb 5994
fa8c2693
PZ
5995static int perf_read_group(struct perf_event *event,
5996 u64 read_format, char __user *buf)
5997{
5998 struct perf_event *leader = event->group_leader, *child;
5999 struct perf_event_context *ctx = leader->ctx;
7d88962e 6000 int ret;
fa8c2693 6001 u64 *values;
3dab77fb 6002
fa8c2693 6003 lockdep_assert_held(&ctx->mutex);
3dab77fb 6004
fa8c2693
PZ
6005 values = kzalloc(event->read_size, GFP_KERNEL);
6006 if (!values)
6007 return -ENOMEM;
3dab77fb 6008
fa8c2693
PZ
6009 values[0] = 1 + leader->nr_siblings;
6010
fa8c2693 6011 mutex_lock(&leader->child_mutex);
abf4868b 6012
7d88962e
SB
6013 ret = __perf_read_group_add(leader, read_format, values);
6014 if (ret)
6015 goto unlock;
6016
6017 list_for_each_entry(child, &leader->child_list, child_list) {
6018 ret = __perf_read_group_add(child, read_format, values);
6019 if (ret)
6020 goto unlock;
6021 }
abf4868b 6022
fa8c2693 6023 mutex_unlock(&leader->child_mutex);
abf4868b 6024
7d88962e 6025 ret = event->read_size;
fa8c2693
PZ
6026 if (copy_to_user(buf, values, event->read_size))
6027 ret = -EFAULT;
7d88962e 6028 goto out;
fa8c2693 6029
7d88962e
SB
6030unlock:
6031 mutex_unlock(&leader->child_mutex);
6032out:
fa8c2693 6033 kfree(values);
abf4868b 6034 return ret;
3dab77fb
PZ
6035}
6036
b15f495b 6037static int perf_read_one(struct perf_event *event,
3dab77fb
PZ
6038 u64 read_format, char __user *buf)
6039{
59ed446f 6040 u64 enabled, running;
119a784c 6041 u64 values[5];
3dab77fb
PZ
6042 int n = 0;
6043
ca0dd44c 6044 values[n++] = __perf_event_read_value(event, &enabled, &running);
59ed446f
PZ
6045 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6046 values[n++] = enabled;
6047 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6048 values[n++] = running;
3dab77fb 6049 if (read_format & PERF_FORMAT_ID)
cdd6c482 6050 values[n++] = primary_event_id(event);
119a784c
NK
6051 if (read_format & PERF_FORMAT_LOST)
6052 values[n++] = atomic64_read(&event->lost_samples);
3dab77fb
PZ
6053
6054 if (copy_to_user(buf, values, n * sizeof(u64)))
6055 return -EFAULT;
6056
6057 return n * sizeof(u64);
6058}
6059
dc633982
JO
6060static bool is_event_hup(struct perf_event *event)
6061{
6062 bool no_children;
6063
a69b0ca4 6064 if (event->state > PERF_EVENT_STATE_EXIT)
dc633982
JO
6065 return false;
6066
6067 mutex_lock(&event->child_mutex);
6068 no_children = list_empty(&event->child_list);
6069 mutex_unlock(&event->child_mutex);
6070 return no_children;
6071}
6072
0793a61d 6073/*
cdd6c482 6074 * Read the performance event - simple non blocking version for now
0793a61d
TG
6075 */
6076static ssize_t
b15f495b 6077__perf_read(struct perf_event *event, char __user *buf, size_t count)
0793a61d 6078{
cdd6c482 6079 u64 read_format = event->attr.read_format;
3dab77fb 6080 int ret;
0793a61d 6081
3b6f9e5c 6082 /*
788faab7 6083 * Return end-of-file for a read on an event that is in
3b6f9e5c
PM
6084 * error state (i.e. because it was pinned but it couldn't be
6085 * scheduled on to the CPU at some point).
6086 */
f6938a56 6087 if (event->state == PERF_EVENT_STATE_ERROR)
3b6f9e5c
PM
6088 return 0;
6089
c320c7b7 6090 if (count < event->read_size)
3dab77fb
PZ
6091 return -ENOSPC;
6092
cdd6c482 6093 WARN_ON_ONCE(event->ctx->parent_ctx);
3dab77fb 6094 if (read_format & PERF_FORMAT_GROUP)
b15f495b 6095 ret = perf_read_group(event, read_format, buf);
3dab77fb 6096 else
b15f495b 6097 ret = perf_read_one(event, read_format, buf);
0793a61d 6098
3dab77fb 6099 return ret;
0793a61d
TG
6100}
6101
0793a61d
TG
6102static ssize_t
6103perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
6104{
cdd6c482 6105 struct perf_event *event = file->private_data;
f63a8daa
PZ
6106 struct perf_event_context *ctx;
6107 int ret;
0793a61d 6108
da97e184
JFG
6109 ret = security_perf_event_read(event);
6110 if (ret)
6111 return ret;
6112
f63a8daa 6113 ctx = perf_event_ctx_lock(event);
b15f495b 6114 ret = __perf_read(event, buf, count);
f63a8daa
PZ
6115 perf_event_ctx_unlock(event, ctx);
6116
6117 return ret;
0793a61d
TG
6118}
6119
9dd95748 6120static __poll_t perf_poll(struct file *file, poll_table *wait)
0793a61d 6121{
cdd6c482 6122 struct perf_event *event = file->private_data;
56de4e8f 6123 struct perf_buffer *rb;
a9a08845 6124 __poll_t events = EPOLLHUP;
c7138f37 6125
da916e96
PZ
6126 if (event->state <= PERF_EVENT_STATE_REVOKED)
6127 return EPOLLERR;
6128
e708d7ad 6129 poll_wait(file, &event->waitq, wait);
179033b3 6130
da916e96
PZ
6131 if (event->state <= PERF_EVENT_STATE_REVOKED)
6132 return EPOLLERR;
6133
dc633982 6134 if (is_event_hup(event))
179033b3 6135 return events;
c7138f37 6136
f4b07fd6
NK
6137 if (unlikely(READ_ONCE(event->state) == PERF_EVENT_STATE_ERROR &&
6138 event->attr.pinned))
0db61388 6139 return EPOLLERR;
f4b07fd6 6140
10c6db11 6141 /*
9bb5d40c
PZ
6142 * Pin the event->rb by taking event->mmap_mutex; otherwise
6143 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
10c6db11
PZ
6144 */
6145 mutex_lock(&event->mmap_mutex);
9bb5d40c
PZ
6146 rb = event->rb;
6147 if (rb)
76369139 6148 events = atomic_xchg(&rb->poll, 0);
10c6db11 6149 mutex_unlock(&event->mmap_mutex);
0793a61d
TG
6150 return events;
6151}
6152
f63a8daa 6153static void _perf_event_reset(struct perf_event *event)
6de6a7b9 6154{
7d88962e 6155 (void)perf_event_read(event, false);
e7850595 6156 local64_set(&event->count, 0);
cdd6c482 6157 perf_event_update_userpage(event);
3df5edad
PZ
6158}
6159
52ba4b0b
LX
6160/* Assume it's not an event with inherit set. */
6161u64 perf_event_pause(struct perf_event *event, bool reset)
6162{
6163 struct perf_event_context *ctx;
6164 u64 count;
6165
6166 ctx = perf_event_ctx_lock(event);
6167 WARN_ON_ONCE(event->attr.inherit);
6168 _perf_event_disable(event);
6169 count = local64_read(&event->count);
6170 if (reset)
6171 local64_set(&event->count, 0);
6172 perf_event_ctx_unlock(event, ctx);
6173
6174 return count;
6175}
6176EXPORT_SYMBOL_GPL(perf_event_pause);
6177
c93f7669 6178/*
cdd6c482
IM
6179 * Holding the top-level event's child_mutex means that any
6180 * descendant process that has inherited this event will block
8ba289b8 6181 * in perf_event_exit_event() if it goes to exit, thus satisfying the
cdd6c482 6182 * task existence requirements of perf_event_enable/disable.
c93f7669 6183 */
cdd6c482
IM
6184static void perf_event_for_each_child(struct perf_event *event,
6185 void (*func)(struct perf_event *))
3df5edad 6186{
cdd6c482 6187 struct perf_event *child;
3df5edad 6188
cdd6c482 6189 WARN_ON_ONCE(event->ctx->parent_ctx);
f63a8daa 6190
cdd6c482
IM
6191 mutex_lock(&event->child_mutex);
6192 func(event);
6193 list_for_each_entry(child, &event->child_list, child_list)
3df5edad 6194 func(child);
cdd6c482 6195 mutex_unlock(&event->child_mutex);
3df5edad
PZ
6196}
6197
cdd6c482
IM
6198static void perf_event_for_each(struct perf_event *event,
6199 void (*func)(struct perf_event *))
3df5edad 6200{
cdd6c482
IM
6201 struct perf_event_context *ctx = event->ctx;
6202 struct perf_event *sibling;
3df5edad 6203
f63a8daa
PZ
6204 lockdep_assert_held(&ctx->mutex);
6205
cdd6c482 6206 event = event->group_leader;
75f937f2 6207
cdd6c482 6208 perf_event_for_each_child(event, func);
edb39592 6209 for_each_sibling_event(sibling, event)
724b6daa 6210 perf_event_for_each_child(sibling, func);
6de6a7b9
PZ
6211}
6212
fae3fde6
PZ
6213static void __perf_event_period(struct perf_event *event,
6214 struct perf_cpu_context *cpuctx,
6215 struct perf_event_context *ctx,
6216 void *info)
c7999c6f 6217{
fae3fde6 6218 u64 value = *((u64 *)info);
c7999c6f 6219 bool active;
08247e31 6220
cdd6c482 6221 if (event->attr.freq) {
cdd6c482 6222 event->attr.sample_freq = value;
08247e31 6223 } else {
cdd6c482
IM
6224 event->attr.sample_period = value;
6225 event->hw.sample_period = value;
08247e31 6226 }
bad7192b
PZ
6227
6228 active = (event->state == PERF_EVENT_STATE_ACTIVE);
6229 if (active) {
bd275681 6230 perf_pmu_disable(event->pmu);
bad7192b
PZ
6231 event->pmu->stop(event, PERF_EF_UPDATE);
6232 }
6233
6234 local64_set(&event->hw.period_left, 0);
6235
6236 if (active) {
6237 event->pmu->start(event, PERF_EF_RELOAD);
9734e25f
KL
6238 /*
6239 * Once the period is force-reset, the event starts immediately.
6240 * But the event/group could be throttled. Unthrottle the
6241 * event/group now to avoid the next tick trying to unthrottle
6242 * while we already re-started the event/group.
6243 */
6244 if (event->hw.interrupts == MAX_INTERRUPTS)
6245 perf_event_unthrottle_group(event, true);
bd275681 6246 perf_pmu_enable(event->pmu);
bad7192b 6247 }
c7999c6f
PZ
6248}
6249
81ec3f3c
JO
6250static int perf_event_check_period(struct perf_event *event, u64 value)
6251{
6252 return event->pmu->check_period(event, value);
6253}
6254
3ca270fc 6255static int _perf_event_period(struct perf_event *event, u64 value)
c7999c6f 6256{
c7999c6f
PZ
6257 if (!is_sampling_event(event))
6258 return -EINVAL;
6259
c7999c6f
PZ
6260 if (!value)
6261 return -EINVAL;
6262
0d398441
KL
6263 if (event->attr.freq) {
6264 if (value > sysctl_perf_event_sample_rate)
6265 return -EINVAL;
6266 } else {
6267 if (perf_event_check_period(event, value))
6268 return -EINVAL;
6269 if (value & (1ULL << 63))
6270 return -EINVAL;
6271 }
913a90bc 6272
fae3fde6 6273 event_function_call(event, __perf_event_period, &value);
08247e31 6274
c7999c6f 6275 return 0;
08247e31
PZ
6276}
6277
3ca270fc
LX
6278int perf_event_period(struct perf_event *event, u64 value)
6279{
6280 struct perf_event_context *ctx;
6281 int ret;
6282
6283 ctx = perf_event_ctx_lock(event);
6284 ret = _perf_event_period(event, value);
6285 perf_event_ctx_unlock(event, ctx);
6286
6287 return ret;
6288}
6289EXPORT_SYMBOL_GPL(perf_event_period);
6290
ac9721f3
PZ
6291static const struct file_operations perf_fops;
6292
4dd53b84 6293static inline bool is_perf_file(struct fd f)
ac9721f3 6294{
4dd53b84 6295 return !fd_empty(f) && fd_file(f)->f_op == &perf_fops;
ac9721f3
PZ
6296}
6297
6298static int perf_event_set_output(struct perf_event *event,
6299 struct perf_event *output_event);
6fb2915d 6300static int perf_event_set_filter(struct perf_event *event, void __user *arg);
32ff77e8
MC
6301static int perf_copy_attr(struct perf_event_attr __user *uattr,
6302 struct perf_event_attr *attr);
7ed9138a
PZ
6303static int __perf_event_set_bpf_prog(struct perf_event *event,
6304 struct bpf_prog *prog,
6305 u64 bpf_cookie);
a4be7c27 6306
f63a8daa 6307static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
d859e29f 6308{
cdd6c482 6309 void (*func)(struct perf_event *);
3df5edad 6310 u32 flags = arg;
d859e29f 6311
da916e96
PZ
6312 if (event->state <= PERF_EVENT_STATE_REVOKED)
6313 return -ENODEV;
6314
d859e29f 6315 switch (cmd) {
cdd6c482 6316 case PERF_EVENT_IOC_ENABLE:
f63a8daa 6317 func = _perf_event_enable;
d859e29f 6318 break;
cdd6c482 6319 case PERF_EVENT_IOC_DISABLE:
f63a8daa 6320 func = _perf_event_disable;
79f14641 6321 break;
cdd6c482 6322 case PERF_EVENT_IOC_RESET:
f63a8daa 6323 func = _perf_event_reset;
6de6a7b9 6324 break;
3df5edad 6325
cdd6c482 6326 case PERF_EVENT_IOC_REFRESH:
f63a8daa 6327 return _perf_event_refresh(event, arg);
08247e31 6328
cdd6c482 6329 case PERF_EVENT_IOC_PERIOD:
3ca270fc
LX
6330 {
6331 u64 value;
08247e31 6332
3ca270fc
LX
6333 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
6334 return -EFAULT;
08247e31 6335
3ca270fc
LX
6336 return _perf_event_period(event, value);
6337 }
cf4957f1
JO
6338 case PERF_EVENT_IOC_ID:
6339 {
6340 u64 id = primary_event_id(event);
6341
6342 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
6343 return -EFAULT;
6344 return 0;
6345 }
6346
cdd6c482 6347 case PERF_EVENT_IOC_SET_OUTPUT:
ac9721f3 6348 {
4dd53b84
AV
6349 CLASS(fd, output)(arg); // arg == -1 => empty
6350 struct perf_event *output_event = NULL;
ac9721f3 6351 if (arg != -1) {
4dd53b84
AV
6352 if (!is_perf_file(output))
6353 return -EBADF;
1da91ea8 6354 output_event = fd_file(output)->private_data;
ac9721f3 6355 }
4dd53b84 6356 return perf_event_set_output(event, output_event);
ac9721f3 6357 }
a4be7c27 6358
6fb2915d
LZ
6359 case PERF_EVENT_IOC_SET_FILTER:
6360 return perf_event_set_filter(event, (void __user *)arg);
6361
2541517c 6362 case PERF_EVENT_IOC_SET_BPF:
652c1b17
AN
6363 {
6364 struct bpf_prog *prog;
6365 int err;
6366
6367 prog = bpf_prog_get(arg);
6368 if (IS_ERR(prog))
6369 return PTR_ERR(prog);
6370
7ed9138a 6371 err = __perf_event_set_bpf_prog(event, prog, 0);
652c1b17
AN
6372 if (err) {
6373 bpf_prog_put(prog);
6374 return err;
6375 }
6376
6377 return 0;
6378 }
2541517c 6379
86e7972f 6380 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
56de4e8f 6381 struct perf_buffer *rb;
86e7972f
WN
6382
6383 rcu_read_lock();
6384 rb = rcu_dereference(event->rb);
6385 if (!rb || !rb->nr_pages) {
6386 rcu_read_unlock();
6387 return -EINVAL;
6388 }
6389 rb_toggle_paused(rb, !!arg);
6390 rcu_read_unlock();
6391 return 0;
6392 }
f371b304
YS
6393
6394 case PERF_EVENT_IOC_QUERY_BPF:
f4e2298e 6395 return perf_event_query_prog_array(event, (void __user *)arg);
32ff77e8
MC
6396
6397 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
6398 struct perf_event_attr new_attr;
6399 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
6400 &new_attr);
6401
6402 if (err)
6403 return err;
6404
6405 return perf_event_modify_attr(event, &new_attr);
6406 }
d859e29f 6407 default:
3df5edad 6408 return -ENOTTY;
d859e29f 6409 }
3df5edad
PZ
6410
6411 if (flags & PERF_IOC_FLAG_GROUP)
cdd6c482 6412 perf_event_for_each(event, func);
3df5edad 6413 else
cdd6c482 6414 perf_event_for_each_child(event, func);
3df5edad
PZ
6415
6416 return 0;
d859e29f
PM
6417}
6418
f63a8daa
PZ
6419static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
6420{
6421 struct perf_event *event = file->private_data;
6422 struct perf_event_context *ctx;
6423 long ret;
6424
da97e184
JFG
6425 /* Treat ioctl like writes as it is likely a mutating operation. */
6426 ret = security_perf_event_write(event);
6427 if (ret)
6428 return ret;
6429
f63a8daa
PZ
6430 ctx = perf_event_ctx_lock(event);
6431 ret = _perf_ioctl(event, cmd, arg);
6432 perf_event_ctx_unlock(event, ctx);
6433
6434 return ret;
6435}
6436
b3f20785
PM
6437#ifdef CONFIG_COMPAT
6438static long perf_compat_ioctl(struct file *file, unsigned int cmd,
6439 unsigned long arg)
6440{
6441 switch (_IOC_NR(cmd)) {
6442 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
6443 case _IOC_NR(PERF_EVENT_IOC_ID):
82489c5f
ES
6444 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
6445 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
b3f20785
PM
6446 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
6447 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
6448 cmd &= ~IOCSIZE_MASK;
6449 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
6450 }
6451 break;
6452 }
6453 return perf_ioctl(file, cmd, arg);
6454}
6455#else
6456# define perf_compat_ioctl NULL
6457#endif
6458
cdd6c482 6459int perf_event_task_enable(void)
771d7cde 6460{
f63a8daa 6461 struct perf_event_context *ctx;
cdd6c482 6462 struct perf_event *event;
771d7cde 6463
cdd6c482 6464 mutex_lock(&current->perf_event_mutex);
f63a8daa
PZ
6465 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
6466 ctx = perf_event_ctx_lock(event);
6467 perf_event_for_each_child(event, _perf_event_enable);
6468 perf_event_ctx_unlock(event, ctx);
6469 }
cdd6c482 6470 mutex_unlock(&current->perf_event_mutex);
771d7cde
PZ
6471
6472 return 0;
6473}
6474
cdd6c482 6475int perf_event_task_disable(void)
771d7cde 6476{
f63a8daa 6477 struct perf_event_context *ctx;
cdd6c482 6478 struct perf_event *event;
771d7cde 6479
cdd6c482 6480 mutex_lock(&current->perf_event_mutex);
f63a8daa
PZ
6481 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
6482 ctx = perf_event_ctx_lock(event);
6483 perf_event_for_each_child(event, _perf_event_disable);
6484 perf_event_ctx_unlock(event, ctx);
6485 }
cdd6c482 6486 mutex_unlock(&current->perf_event_mutex);
771d7cde
PZ
6487
6488 return 0;
6489}
6490
cdd6c482 6491static int perf_event_index(struct perf_event *event)
194002b2 6492{
a4eaf7f1
PZ
6493 if (event->hw.state & PERF_HES_STOPPED)
6494 return 0;
6495
cdd6c482 6496 if (event->state != PERF_EVENT_STATE_ACTIVE)
194002b2
PZ
6497 return 0;
6498
35edc2a5 6499 return event->pmu->event_idx(event);
194002b2
PZ
6500}
6501
fa731587
PZ
6502static void perf_event_init_userpage(struct perf_event *event)
6503{
6504 struct perf_event_mmap_page *userpg;
56de4e8f 6505 struct perf_buffer *rb;
fa731587
PZ
6506
6507 rcu_read_lock();
6508 rb = rcu_dereference(event->rb);
6509 if (!rb)
6510 goto unlock;
6511
6512 userpg = rb->user_page;
6513
6514 /* Allow new userspace to detect that bit 0 is deprecated */
6515 userpg->cap_bit0_is_deprecated = 1;
6516 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
e8c6deac
AS
6517 userpg->data_offset = PAGE_SIZE;
6518 userpg->data_size = perf_data_size(rb);
fa731587
PZ
6519
6520unlock:
6521 rcu_read_unlock();
6522}
6523
c1317ec2
AL
6524void __weak arch_perf_update_userpage(
6525 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
e3f3541c
PZ
6526{
6527}
6528
38ff667b
PZ
6529/*
6530 * Callers need to ensure there can be no nesting of this function, otherwise
6531 * the seqlock logic goes bad. We can not serialize this because the arch
6532 * code calls this from NMI context.
6533 */
cdd6c482 6534void perf_event_update_userpage(struct perf_event *event)
37d81828 6535{
cdd6c482 6536 struct perf_event_mmap_page *userpg;
56de4e8f 6537 struct perf_buffer *rb;
e3f3541c 6538 u64 enabled, running, now;
38ff667b
PZ
6539
6540 rcu_read_lock();
5ec4c599
PZ
6541 rb = rcu_dereference(event->rb);
6542 if (!rb)
6543 goto unlock;
6544
0d641208
EM
6545 /*
6546 * compute total_time_enabled, total_time_running
6547 * based on snapshot values taken when the event
6548 * was last scheduled in.
6549 *
6550 * we cannot simply called update_context_time()
6551 * because of locking issue as we can be called in
6552 * NMI context
6553 */
e3f3541c 6554 calc_timer_values(event, &now, &enabled, &running);
38ff667b 6555
76369139 6556 userpg = rb->user_page;
7b732a75 6557 /*
9d2dcc8f
MF
6558 * Disable preemption to guarantee consistent time stamps are stored to
6559 * the user page.
7b732a75
PZ
6560 */
6561 preempt_disable();
37d81828 6562 ++userpg->lock;
92f22a38 6563 barrier();
cdd6c482 6564 userpg->index = perf_event_index(event);
7e8b2556 6565 userpg->offset = perf_event_count(event, false);
365a4038 6566 if (userpg->index)
e7850595 6567 userpg->offset -= local64_read(&event->hw.prev_count);
7b732a75 6568
0d641208 6569 userpg->time_enabled = enabled +
cdd6c482 6570 atomic64_read(&event->child_total_time_enabled);
7f8b4e4e 6571
0d641208 6572 userpg->time_running = running +
cdd6c482 6573 atomic64_read(&event->child_total_time_running);
7f8b4e4e 6574
c1317ec2 6575 arch_perf_update_userpage(event, userpg, now);
e3f3541c 6576
92f22a38 6577 barrier();
37d81828 6578 ++userpg->lock;
7b732a75 6579 preempt_enable();
38ff667b 6580unlock:
7b732a75 6581 rcu_read_unlock();
37d81828 6582}
82975c46 6583EXPORT_SYMBOL_GPL(perf_event_update_userpage);
37d81828 6584
10c6db11 6585static void ring_buffer_attach(struct perf_event *event,
56de4e8f 6586 struct perf_buffer *rb)
10c6db11 6587{
56de4e8f 6588 struct perf_buffer *old_rb = NULL;
10c6db11
PZ
6589 unsigned long flags;
6590
961c3912
JC
6591 WARN_ON_ONCE(event->parent);
6592
b69cf536
PZ
6593 if (event->rb) {
6594 /*
6595 * Should be impossible, we set this when removing
6596 * event->rb_entry and wait/clear when adding event->rb_entry.
6597 */
6598 WARN_ON_ONCE(event->rcu_pending);
10c6db11 6599
b69cf536 6600 old_rb = event->rb;
b69cf536
PZ
6601 spin_lock_irqsave(&old_rb->event_lock, flags);
6602 list_del_rcu(&event->rb_entry);
6603 spin_unlock_irqrestore(&old_rb->event_lock, flags);
10c6db11 6604
2f993cf0
ON
6605 event->rcu_batches = get_state_synchronize_rcu();
6606 event->rcu_pending = 1;
b69cf536 6607 }
10c6db11 6608
b69cf536 6609 if (rb) {
2f993cf0
ON
6610 if (event->rcu_pending) {
6611 cond_synchronize_rcu(event->rcu_batches);
6612 event->rcu_pending = 0;
6613 }
6614
b69cf536
PZ
6615 spin_lock_irqsave(&rb->event_lock, flags);
6616 list_add_rcu(&event->rb_entry, &rb->event_list);
6617 spin_unlock_irqrestore(&rb->event_lock, flags);
6618 }
6619
767ae086
AS
6620 /*
6621 * Avoid racing with perf_mmap_close(AUX): stop the event
6622 * before swizzling the event::rb pointer; if it's getting
6623 * unmapped, its aux_mmap_count will be 0 and it won't
6624 * restart. See the comment in __perf_pmu_output_stop().
6625 *
6626 * Data will inevitably be lost when set_output is done in
6627 * mid-air, but then again, whoever does it like this is
6628 * not in for the data anyway.
6629 */
6630 if (has_aux(event))
6631 perf_event_stop(event, 0);
6632
b69cf536
PZ
6633 rcu_assign_pointer(event->rb, rb);
6634
6635 if (old_rb) {
6636 ring_buffer_put(old_rb);
6637 /*
6638 * Since we detached before setting the new rb, so that we
6639 * could attach the new rb, we could have missed a wakeup.
6640 * Provide it now.
6641 */
6642 wake_up_all(&event->waitq);
6643 }
10c6db11
PZ
6644}
6645
6646static void ring_buffer_wakeup(struct perf_event *event)
6647{
56de4e8f 6648 struct perf_buffer *rb;
10c6db11 6649
961c3912
JC
6650 if (event->parent)
6651 event = event->parent;
6652
10c6db11
PZ
6653 rcu_read_lock();
6654 rb = rcu_dereference(event->rb);
9bb5d40c
PZ
6655 if (rb) {
6656 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
6657 wake_up_all(&event->waitq);
6658 }
10c6db11
PZ
6659 rcu_read_unlock();
6660}
6661
56de4e8f 6662struct perf_buffer *ring_buffer_get(struct perf_event *event)
7b732a75 6663{
56de4e8f 6664 struct perf_buffer *rb;
7b732a75 6665
961c3912
JC
6666 if (event->parent)
6667 event = event->parent;
6668
ac9721f3 6669 rcu_read_lock();
76369139
FW
6670 rb = rcu_dereference(event->rb);
6671 if (rb) {
fecb8ed2 6672 if (!refcount_inc_not_zero(&rb->refcount))
76369139 6673 rb = NULL;
ac9721f3
PZ
6674 }
6675 rcu_read_unlock();
6676
76369139 6677 return rb;
ac9721f3
PZ
6678}
6679
56de4e8f 6680void ring_buffer_put(struct perf_buffer *rb)
ac9721f3 6681{
fecb8ed2 6682 if (!refcount_dec_and_test(&rb->refcount))
ac9721f3 6683 return;
7b732a75 6684
9bb5d40c 6685 WARN_ON_ONCE(!list_empty(&rb->event_list));
10c6db11 6686
76369139 6687 call_rcu(&rb->rcu_head, rb_free_rcu);
7b732a75
PZ
6688}
6689
da916e96
PZ
6690typedef void (*mapped_f)(struct perf_event *event, struct mm_struct *mm);
6691
6692#define get_mapped(event, func) \
6693({ struct pmu *pmu; \
6694 mapped_f f = NULL; \
6695 guard(rcu)(); \
6696 pmu = READ_ONCE(event->pmu); \
6697 if (pmu) \
6698 f = pmu->func; \
6699 f; \
6700})
6701
7b732a75
PZ
6702static void perf_mmap_open(struct vm_area_struct *vma)
6703{
cdd6c482 6704 struct perf_event *event = vma->vm_file->private_data;
da916e96 6705 mapped_f mapped = get_mapped(event, event_mapped);
7b732a75 6706
cdd6c482 6707 atomic_inc(&event->mmap_count);
9bb5d40c 6708 atomic_inc(&event->rb->mmap_count);
1e0fb9ec 6709
45bfb2e5
PZ
6710 if (vma->vm_pgoff)
6711 atomic_inc(&event->rb->aux_mmap_count);
6712
da916e96
PZ
6713 if (mapped)
6714 mapped(event, vma->vm_mm);
7b732a75
PZ
6715}
6716
95ff4ca2
AS
6717static void perf_pmu_output_stop(struct perf_event *event);
6718
9bb5d40c
PZ
6719/*
6720 * A buffer can be mmap()ed multiple times; either directly through the same
6721 * event, or through other events by use of perf_event_set_output().
6722 *
6723 * In order to undo the VM accounting done by perf_mmap() we need to destroy
6724 * the buffer here, where we still have a VM context. This means we need
6725 * to detach all events redirecting to us.
6726 */
7b732a75
PZ
6727static void perf_mmap_close(struct vm_area_struct *vma)
6728{
cdd6c482 6729 struct perf_event *event = vma->vm_file->private_data;
da916e96 6730 mapped_f unmapped = get_mapped(event, event_unmapped);
56de4e8f 6731 struct perf_buffer *rb = ring_buffer_get(event);
9bb5d40c
PZ
6732 struct user_struct *mmap_user = rb->mmap_user;
6733 int mmap_locked = rb->mmap_locked;
6734 unsigned long size = perf_data_size(rb);
f91072ed 6735 bool detach_rest = false;
789f90fc 6736
da916e96
PZ
6737 /* FIXIES vs perf_pmu_unregister() */
6738 if (unmapped)
6739 unmapped(event, vma->vm_mm);
1e0fb9ec 6740
45bfb2e5 6741 /*
2ab9d830
PZ
6742 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex
6743 * to avoid complications.
45bfb2e5
PZ
6744 */
6745 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
2ab9d830 6746 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) {
95ff4ca2
AS
6747 /*
6748 * Stop all AUX events that are writing to this buffer,
6749 * so that we can free its AUX pages and corresponding PMU
6750 * data. Note that after rb::aux_mmap_count dropped to zero,
6751 * they won't start any more (see perf_aux_output_begin()).
6752 */
6753 perf_pmu_output_stop(event);
6754
6755 /* now it's safe to free the pages */
36b3db03
AS
6756 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
6757 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
45bfb2e5 6758
95ff4ca2 6759 /* this has to be the last one */
45bfb2e5 6760 rb_free_aux(rb);
ca3bb3d0 6761 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
95ff4ca2 6762
2ab9d830 6763 mutex_unlock(&rb->aux_mutex);
45bfb2e5
PZ
6764 }
6765
f91072ed
JO
6766 if (atomic_dec_and_test(&rb->mmap_count))
6767 detach_rest = true;
9bb5d40c
PZ
6768
6769 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
b69cf536 6770 goto out_put;
9bb5d40c 6771
b69cf536 6772 ring_buffer_attach(event, NULL);
9bb5d40c
PZ
6773 mutex_unlock(&event->mmap_mutex);
6774
6775 /* If there's still other mmap()s of this buffer, we're done. */
f91072ed 6776 if (!detach_rest)
b69cf536 6777 goto out_put;
ac9721f3 6778
9bb5d40c
PZ
6779 /*
6780 * No other mmap()s, detach from all other events that might redirect
6781 * into the now unreachable buffer. Somewhat complicated by the
6782 * fact that rb::event_lock otherwise nests inside mmap_mutex.
6783 */
6784again:
6785 rcu_read_lock();
6786 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
6787 if (!atomic_long_inc_not_zero(&event->refcount)) {
6788 /*
6789 * This event is en-route to free_event() which will
6790 * detach it and remove it from the list.
6791 */
6792 continue;
6793 }
6794 rcu_read_unlock();
789f90fc 6795
9bb5d40c
PZ
6796 mutex_lock(&event->mmap_mutex);
6797 /*
6798 * Check we didn't race with perf_event_set_output() which can
6799 * swizzle the rb from under us while we were waiting to
6800 * acquire mmap_mutex.
6801 *
6802 * If we find a different rb; ignore this event, a next
6803 * iteration will no longer find it on the list. We have to
6804 * still restart the iteration to make sure we're not now
6805 * iterating the wrong list.
6806 */
b69cf536
PZ
6807 if (event->rb == rb)
6808 ring_buffer_attach(event, NULL);
6809
cdd6c482 6810 mutex_unlock(&event->mmap_mutex);
9bb5d40c 6811 put_event(event);
ac9721f3 6812
9bb5d40c
PZ
6813 /*
6814 * Restart the iteration; either we're on the wrong list or
6815 * destroyed its integrity by doing a deletion.
6816 */
6817 goto again;
7b732a75 6818 }
9bb5d40c
PZ
6819 rcu_read_unlock();
6820
6821 /*
6822 * It could be there's still a few 0-ref events on the list; they'll
6823 * get cleaned up by free_event() -- they'll also still have their
6824 * ref on the rb and will free it whenever they are done with it.
6825 *
6826 * Aside from that, this buffer is 'fully' detached and unmapped,
6827 * undo the VM accounting.
6828 */
6829
d44248a4
SL
6830 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
6831 &mmap_user->locked_vm);
70f8a3ca 6832 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
9bb5d40c
PZ
6833 free_uid(mmap_user);
6834
b69cf536 6835out_put:
9bb5d40c 6836 ring_buffer_put(rb); /* could be last */
37d81828
PM
6837}
6838
b709eb87
LS
6839static vm_fault_t perf_mmap_pfn_mkwrite(struct vm_fault *vmf)
6840{
6841 /* The first page is the user control page, others are read-only. */
6842 return vmf->pgoff == 0 ? 0 : VM_FAULT_SIGBUS;
6843}
6844
f0f37e2f 6845static const struct vm_operations_struct perf_mmap_vmops = {
43a21ea8 6846 .open = perf_mmap_open,
fca0c116 6847 .close = perf_mmap_close, /* non mergeable */
b709eb87 6848 .pfn_mkwrite = perf_mmap_pfn_mkwrite,
37d81828
PM
6849};
6850
b709eb87
LS
6851static int map_range(struct perf_buffer *rb, struct vm_area_struct *vma)
6852{
6853 unsigned long nr_pages = vma_pages(vma);
6854 int err = 0;
6855 unsigned long pagenum;
6856
6857 /*
6858 * We map this as a VM_PFNMAP VMA.
6859 *
6860 * This is not ideal as this is designed broadly for mappings of PFNs
6861 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which
6862 * !pfn_valid(pfn).
6863 *
6864 * We are mapping kernel-allocated memory (memory we manage ourselves)
6865 * which would more ideally be mapped using vm_insert_page() or a
6866 * similar mechanism, that is as a VM_MIXEDMAP mapping.
6867 *
6868 * However this won't work here, because:
6869 *
6870 * 1. It uses vma->vm_page_prot, but this field has not been completely
6871 * setup at the point of the f_op->mmp() hook, so we are unable to
6872 * indicate that this should be mapped CoW in order that the
6873 * mkwrite() hook can be invoked to make the first page R/W and the
6874 * rest R/O as desired.
6875 *
6876 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in
6877 * vm_normal_page() returning a struct page * pointer, which means
6878 * vm_ops->page_mkwrite() will be invoked rather than
6879 * vm_ops->pfn_mkwrite(), and this means we have to set page->mapping
6880 * to work around retry logic in the fault handler, however this
6881 * field is no longer allowed to be used within struct page.
6882 *
6883 * 3. Having a struct page * made available in the fault logic also
6884 * means that the page gets put on the rmap and becomes
6885 * inappropriately accessible and subject to map and ref counting.
6886 *
6887 * Ideally we would have a mechanism that could explicitly express our
6888 * desires, but this is not currently the case, so we instead use
6889 * VM_PFNMAP.
6890 *
6891 * We manage the lifetime of these mappings with internal refcounts (see
6892 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of
6893 * this mapping is maintained correctly.
6894 */
6895 for (pagenum = 0; pagenum < nr_pages; pagenum++) {
6896 unsigned long va = vma->vm_start + PAGE_SIZE * pagenum;
6897 struct page *page = perf_mmap_to_page(rb, vma->vm_pgoff + pagenum);
6898
6899 if (page == NULL) {
6900 err = -EINVAL;
6901 break;
6902 }
6903
6904 /* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */
6905 err = remap_pfn_range(vma, va, page_to_pfn(page), PAGE_SIZE,
6906 vm_get_page_prot(vma->vm_flags & ~VM_SHARED));
6907 if (err)
6908 break;
6909 }
6910
6911#ifdef CONFIG_MMU
6912 /* Clear any partial mappings on error. */
6913 if (err)
6914 zap_page_range_single(vma, vma->vm_start, nr_pages * PAGE_SIZE, NULL);
6915#endif
6916
6917 return err;
6918}
6919
37d81828
PM
6920static int perf_mmap(struct file *file, struct vm_area_struct *vma)
6921{
cdd6c482 6922 struct perf_event *event = file->private_data;
22a4f650 6923 unsigned long user_locked, user_lock_limit;
789f90fc 6924 struct user_struct *user = current_user();
2ab9d830 6925 struct mutex *aux_mutex = NULL;
56de4e8f 6926 struct perf_buffer *rb = NULL;
22a4f650 6927 unsigned long locked, lock_limit;
7b732a75
PZ
6928 unsigned long vma_size;
6929 unsigned long nr_pages;
45bfb2e5 6930 long user_extra = 0, extra = 0;
0983593f 6931 int ret, flags = 0;
da916e96 6932 mapped_f mapped;
37d81828 6933
c7920614
PZ
6934 /*
6935 * Don't allow mmap() of inherited per-task counters. This would
6936 * create a performance issue due to all children writing to the
76369139 6937 * same rb.
c7920614
PZ
6938 */
6939 if (event->cpu == -1 && event->attr.inherit)
6940 return -EINVAL;
6941
43a21ea8 6942 if (!(vma->vm_flags & VM_SHARED))
37d81828 6943 return -EINVAL;
7b732a75 6944
da97e184
JFG
6945 ret = security_perf_event_read(event);
6946 if (ret)
6947 return ret;
6948
7b732a75 6949 vma_size = vma->vm_end - vma->vm_start;
0c8a4e41
PZ
6950 nr_pages = vma_size / PAGE_SIZE;
6951
6952 if (nr_pages > INT_MAX)
6953 return -ENOMEM;
6954
6955 if (vma_size != PAGE_SIZE * nr_pages)
6956 return -EINVAL;
6957
6958 user_extra = nr_pages;
45bfb2e5 6959
0983593f
PZ
6960 mutex_lock(&event->mmap_mutex);
6961 ret = -EINVAL;
6962
da916e96
PZ
6963 /*
6964 * This relies on __pmu_detach_event() taking mmap_mutex after marking
6965 * the event REVOKED. Either we observe the state, or __pmu_detach_event()
6966 * will detach the rb created here.
6967 */
6968 if (event->state <= PERF_EVENT_STATE_REVOKED) {
6969 ret = -ENODEV;
6970 goto unlock;
6971 }
6972
45bfb2e5 6973 if (vma->vm_pgoff == 0) {
0c8a4e41 6974 nr_pages -= 1;
95487837
PZ
6975
6976 /*
6977 * If we have rb pages ensure they're a power-of-two number, so we
6978 * can do bitmasks instead of modulo.
6979 */
6980 if (nr_pages != 0 && !is_power_of_2(nr_pages))
0983593f 6981 goto unlock;
95487837 6982
95487837 6983 WARN_ON_ONCE(event->ctx->parent_ctx);
8eaec7bb 6984
95487837 6985 if (event->rb) {
0983593f 6986 if (data_page_nr(event->rb) != nr_pages)
95487837 6987 goto unlock;
95487837 6988
8eaec7bb 6989 if (atomic_inc_not_zero(&event->rb->mmap_count)) {
95487837 6990 /*
8eaec7bb
PZ
6991 * Success -- managed to mmap() the same buffer
6992 * multiple times.
95487837 6993 */
8eaec7bb
PZ
6994 ret = 0;
6995 /* We need the rb to map pages. */
6996 rb = event->rb;
6997 goto unlock;
95487837
PZ
6998 }
6999
8eaec7bb
PZ
7000 /*
7001 * Raced against perf_mmap_close()'s
7002 * atomic_dec_and_mutex_lock() remove the
7003 * event and continue as if !event->rb
7004 */
7005 ring_buffer_attach(event, NULL);
95487837 7006 }
8eaec7bb 7007
45bfb2e5
PZ
7008 } else {
7009 /*
7010 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
7011 * mapped, all subsequent mappings should have the same size
7012 * and offset. Must be above the normal perf buffer.
7013 */
7014 u64 aux_offset, aux_size;
7015
45bfb2e5
PZ
7016 rb = event->rb;
7017 if (!rb)
7018 goto aux_unlock;
7019
2ab9d830
PZ
7020 aux_mutex = &rb->aux_mutex;
7021 mutex_lock(aux_mutex);
7022
6aa7de05
MR
7023 aux_offset = READ_ONCE(rb->user_page->aux_offset);
7024 aux_size = READ_ONCE(rb->user_page->aux_size);
45bfb2e5
PZ
7025
7026 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
7027 goto aux_unlock;
7028
7029 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
7030 goto aux_unlock;
7031
7032 /* already mapped with a different offset */
7033 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
7034 goto aux_unlock;
7035
7036 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
7037 goto aux_unlock;
7038
7039 /* already mapped with a different size */
7040 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
7041 goto aux_unlock;
7042
7043 if (!is_power_of_2(nr_pages))
7044 goto aux_unlock;
7045
7046 if (!atomic_inc_not_zero(&rb->mmap_count))
7047 goto aux_unlock;
7048
7049 if (rb_has_aux(rb)) {
7050 atomic_inc(&rb->aux_mmap_count);
7051 ret = 0;
7052 goto unlock;
7053 }
7054
7055 atomic_set(&rb->aux_mmap_count, 1);
ebb3c4c4
PZ
7056 }
7057
cdd6c482 7058 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
a3862d3f
IM
7059
7060 /*
7061 * Increase the limit linearly with more CPUs:
7062 */
7063 user_lock_limit *= num_online_cpus();
7064
00346155
SL
7065 user_locked = atomic_long_read(&user->locked_vm);
7066
7067 /*
7068 * sysctl_perf_event_mlock may have changed, so that
7069 * user->locked_vm > user_lock_limit
7070 */
7071 if (user_locked > user_lock_limit)
7072 user_locked = user_lock_limit;
7073 user_locked += user_extra;
c5078f78 7074
c4b75479 7075 if (user_locked > user_lock_limit) {
d44248a4
SL
7076 /*
7077 * charge locked_vm until it hits user_lock_limit;
7078 * charge the rest from pinned_vm
7079 */
789f90fc 7080 extra = user_locked - user_lock_limit;
d44248a4
SL
7081 user_extra -= extra;
7082 }
7b732a75 7083
78d7d407 7084 lock_limit = rlimit(RLIMIT_MEMLOCK);
7b732a75 7085 lock_limit >>= PAGE_SHIFT;
70f8a3ca 7086 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
7b732a75 7087
da97e184 7088 if ((locked > lock_limit) && perf_is_paranoid() &&
459ec28a 7089 !capable(CAP_IPC_LOCK)) {
ebb3c4c4
PZ
7090 ret = -EPERM;
7091 goto unlock;
7092 }
7b732a75 7093
45bfb2e5 7094 WARN_ON(!rb && event->rb);
906010b2 7095
d57e34fd 7096 if (vma->vm_flags & VM_WRITE)
76369139 7097 flags |= RING_BUFFER_WRITABLE;
d57e34fd 7098
76369139 7099 if (!rb) {
45bfb2e5
PZ
7100 rb = rb_alloc(nr_pages,
7101 event->attr.watermark ? event->attr.wakeup_watermark : 0,
7102 event->cpu, flags);
26cb63ad 7103
45bfb2e5
PZ
7104 if (!rb) {
7105 ret = -ENOMEM;
7106 goto unlock;
7107 }
43a21ea8 7108
45bfb2e5
PZ
7109 atomic_set(&rb->mmap_count, 1);
7110 rb->mmap_user = get_current_user();
7111 rb->mmap_locked = extra;
26cb63ad 7112
45bfb2e5 7113 ring_buffer_attach(event, rb);
ac9721f3 7114
f7925653 7115 perf_event_update_time(event);
45bfb2e5
PZ
7116 perf_event_init_userpage(event);
7117 perf_event_update_userpage(event);
7118 } else {
1a594131
AS
7119 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
7120 event->attr.aux_watermark, flags);
45bfb2e5
PZ
7121 if (!ret)
7122 rb->aux_mmap_locked = extra;
7123 }
9a0f05cb 7124
0983593f
PZ
7125 ret = 0;
7126
ebb3c4c4 7127unlock:
45bfb2e5
PZ
7128 if (!ret) {
7129 atomic_long_add(user_extra, &user->locked_vm);
70f8a3ca 7130 atomic64_add(extra, &vma->vm_mm->pinned_vm);
45bfb2e5 7131
ac9721f3 7132 atomic_inc(&event->mmap_count);
45bfb2e5
PZ
7133 } else if (rb) {
7134 atomic_dec(&rb->mmap_count);
7135 }
7136aux_unlock:
2ab9d830
PZ
7137 if (aux_mutex)
7138 mutex_unlock(aux_mutex);
cdd6c482 7139 mutex_unlock(&event->mmap_mutex);
37d81828 7140
9bb5d40c
PZ
7141 /*
7142 * Since pinned accounting is per vm we cannot allow fork() to copy our
7143 * vma.
7144 */
1c71222e 7145 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP);
37d81828 7146 vma->vm_ops = &perf_mmap_vmops;
7b732a75 7147
b709eb87
LS
7148 if (!ret)
7149 ret = map_range(rb, vma);
7150
da916e96
PZ
7151 mapped = get_mapped(event, event_mapped);
7152 if (mapped)
7153 mapped(event, vma->vm_mm);
1e0fb9ec 7154
7b732a75 7155 return ret;
37d81828
PM
7156}
7157
3c446b3d
PZ
7158static int perf_fasync(int fd, struct file *filp, int on)
7159{
496ad9aa 7160 struct inode *inode = file_inode(filp);
cdd6c482 7161 struct perf_event *event = filp->private_data;
3c446b3d
PZ
7162 int retval;
7163
da916e96
PZ
7164 if (event->state <= PERF_EVENT_STATE_REVOKED)
7165 return -ENODEV;
7166
5955102c 7167 inode_lock(inode);
cdd6c482 7168 retval = fasync_helper(fd, filp, on, &event->fasync);
5955102c 7169 inode_unlock(inode);
3c446b3d
PZ
7170
7171 if (retval < 0)
7172 return retval;
7173
7174 return 0;
7175}
7176
0793a61d
TG
7177static const struct file_operations perf_fops = {
7178 .release = perf_release,
7179 .read = perf_read,
7180 .poll = perf_poll,
d859e29f 7181 .unlocked_ioctl = perf_ioctl,
b3f20785 7182 .compat_ioctl = perf_compat_ioctl,
37d81828 7183 .mmap = perf_mmap,
3c446b3d 7184 .fasync = perf_fasync,
0793a61d
TG
7185};
7186
925d519a 7187/*
cdd6c482 7188 * Perf event wakeup
925d519a
PZ
7189 *
7190 * If there's data, ensure we set the poll() state and publish everything
7191 * to user-space before waking everybody up.
7192 */
7193
cdd6c482 7194void perf_event_wakeup(struct perf_event *event)
925d519a 7195{
10c6db11 7196 ring_buffer_wakeup(event);
4c9e2542 7197
cdd6c482 7198 if (event->pending_kill) {
fed66e2c 7199 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
cdd6c482 7200 event->pending_kill = 0;
4c9e2542 7201 }
925d519a
PZ
7202}
7203
97ba62b2
ME
7204static void perf_sigtrap(struct perf_event *event)
7205{
97ba62b2
ME
7206 /*
7207 * We'd expect this to only occur if the irq_work is delayed and either
7208 * ctx->task or current has changed in the meantime. This can be the
7209 * case on architectures that do not implement arch_irq_work_raise().
7210 */
7211 if (WARN_ON_ONCE(event->ctx->task != current))
7212 return;
7213
7214 /*
ca6c2132
PZ
7215 * Both perf_pending_task() and perf_pending_irq() can race with the
7216 * task exiting.
97ba62b2
ME
7217 */
7218 if (current->flags & PF_EXITING)
7219 return;
7220
78ed93d7 7221 send_sig_perf((void __user *)event->pending_addr,
0d6d062c 7222 event->orig_type, event->attr.sig_data);
97ba62b2
ME
7223}
7224
ca6c2132
PZ
7225/*
7226 * Deliver the pending work in-event-context or follow the context.
7227 */
2b84def9 7228static void __perf_pending_disable(struct perf_event *event)
1d54ad94 7229{
ca6c2132 7230 int cpu = READ_ONCE(event->oncpu);
1d54ad94 7231
ca6c2132
PZ
7232 /*
7233 * If the event isn't running; we done. event_sched_out() will have
7234 * taken care of things.
7235 */
1d54ad94
PZ
7236 if (cpu < 0)
7237 return;
7238
ca6c2132
PZ
7239 /*
7240 * Yay, we hit home and are in the context of the event.
7241 */
1d54ad94 7242 if (cpu == smp_processor_id()) {
ca6c2132
PZ
7243 if (event->pending_disable) {
7244 event->pending_disable = 0;
7245 perf_event_disable_local(event);
97ba62b2 7246 }
1d54ad94
PZ
7247 return;
7248 }
7249
7250 /*
7251 * CPU-A CPU-B
7252 *
7253 * perf_event_disable_inatomic()
1476b218 7254 * @pending_disable = 1;
1d54ad94
PZ
7255 * irq_work_queue();
7256 *
7257 * sched-out
1476b218 7258 * @pending_disable = 0;
1d54ad94
PZ
7259 *
7260 * sched-in
7261 * perf_event_disable_inatomic()
1476b218 7262 * @pending_disable = 1;
1d54ad94
PZ
7263 * irq_work_queue(); // FAILS
7264 *
7265 * irq_work_run()
2b84def9 7266 * perf_pending_disable()
1d54ad94
PZ
7267 *
7268 * But the event runs on CPU-B and wants disabling there.
7269 */
2b84def9
SAS
7270 irq_work_queue_on(&event->pending_disable_irq, cpu);
7271}
7272
7273static void perf_pending_disable(struct irq_work *entry)
7274{
7275 struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq);
7276 int rctx;
7277
7278 /*
7279 * If we 'fail' here, that's OK, it means recursion is already disabled
7280 * and we won't recurse 'further'.
7281 */
7282 rctx = perf_swevent_get_recursion_context();
7283 __perf_pending_disable(event);
7284 if (rctx >= 0)
7285 perf_swevent_put_recursion_context(rctx);
1d54ad94
PZ
7286}
7287
ca6c2132 7288static void perf_pending_irq(struct irq_work *entry)
79f14641 7289{
ca6c2132 7290 struct perf_event *event = container_of(entry, struct perf_event, pending_irq);
d525211f
PZ
7291 int rctx;
7292
d525211f
PZ
7293 /*
7294 * If we 'fail' here, that's OK, it means recursion is already disabled
7295 * and we won't recurse 'further'.
7296 */
ca6c2132 7297 rctx = perf_swevent_get_recursion_context();
79f14641 7298
ca6c2132
PZ
7299 /*
7300 * The wakeup isn't bound to the context of the event -- it can happen
7301 * irrespective of where the event is.
7302 */
cdd6c482
IM
7303 if (event->pending_wakeup) {
7304 event->pending_wakeup = 0;
7305 perf_event_wakeup(event);
79f14641 7306 }
d525211f
PZ
7307
7308 if (rctx >= 0)
7309 perf_swevent_put_recursion_context(rctx);
79f14641
PZ
7310}
7311
ca6c2132
PZ
7312static void perf_pending_task(struct callback_head *head)
7313{
7314 struct perf_event *event = container_of(head, struct perf_event, pending_task);
7315 int rctx;
7316
7317 /*
7318 * If we 'fail' here, that's OK, it means recursion is already disabled
7319 * and we won't recurse 'further'.
7320 */
ca6c2132
PZ
7321 rctx = perf_swevent_get_recursion_context();
7322
7323 if (event->pending_work) {
7324 event->pending_work = 0;
7325 perf_sigtrap(event);
79bd2330 7326 local_dec(&event->ctx->nr_no_switch_fast);
ca6c2132 7327 }
56799bc0 7328 put_event(event);
ca6c2132
PZ
7329
7330 if (rctx >= 0)
7331 perf_swevent_put_recursion_context(rctx);
ca6c2132
PZ
7332}
7333
2aef6f30 7334#ifdef CONFIG_GUEST_PERF_EVENTS
ff083a2d 7335struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
39447b38 7336
87b940a0
SC
7337DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state);
7338DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip);
7339DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr);
39447b38 7340
2934e3d0 7341void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
39447b38 7342{
ff083a2d 7343 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
2934e3d0 7344 return;
ff083a2d
SC
7345
7346 rcu_assign_pointer(perf_guest_cbs, cbs);
87b940a0
SC
7347 static_call_update(__perf_guest_state, cbs->state);
7348 static_call_update(__perf_guest_get_ip, cbs->get_ip);
7349
7350 /* Implementing ->handle_intel_pt_intr is optional. */
7351 if (cbs->handle_intel_pt_intr)
7352 static_call_update(__perf_guest_handle_intel_pt_intr,
7353 cbs->handle_intel_pt_intr);
39447b38
ZY
7354}
7355EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
7356
2934e3d0 7357void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
39447b38 7358{
ff083a2d 7359 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
2934e3d0 7360 return;
ff083a2d
SC
7361
7362 rcu_assign_pointer(perf_guest_cbs, NULL);
87b940a0
SC
7363 static_call_update(__perf_guest_state, (void *)&__static_call_return0);
7364 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0);
7365 static_call_update(__perf_guest_handle_intel_pt_intr,
7366 (void *)&__static_call_return0);
ff083a2d 7367 synchronize_rcu();
39447b38
ZY
7368}
7369EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
2aef6f30 7370#endif
39447b38 7371
2c47e7a7 7372static bool should_sample_guest(struct perf_event *event)
04782e63 7373{
2c47e7a7
CL
7374 return !event->attr.exclude_guest && perf_guest_state();
7375}
7376
7377unsigned long perf_misc_flags(struct perf_event *event,
7378 struct pt_regs *regs)
7379{
7380 if (should_sample_guest(event))
7381 return perf_arch_guest_misc_flags(regs);
7382
04782e63
CL
7383 return perf_arch_misc_flags(regs);
7384}
7385
2c47e7a7
CL
7386unsigned long perf_instruction_pointer(struct perf_event *event,
7387 struct pt_regs *regs)
04782e63 7388{
2c47e7a7
CL
7389 if (should_sample_guest(event))
7390 return perf_guest_get_ip();
7391
04782e63
CL
7392 return perf_arch_instruction_pointer(regs);
7393}
7394
4018994f
JO
7395static void
7396perf_output_sample_regs(struct perf_output_handle *handle,
7397 struct pt_regs *regs, u64 mask)
7398{
7399 int bit;
29dd3288 7400 DECLARE_BITMAP(_mask, 64);
4018994f 7401
29dd3288
MS
7402 bitmap_from_u64(_mask, mask);
7403 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
4018994f
JO
7404 u64 val;
7405
7406 val = perf_reg_value(regs, bit);
7407 perf_output_put(handle, val);
7408 }
7409}
7410
60e2364e 7411static void perf_sample_regs_user(struct perf_regs *regs_user,
76a4efa8 7412 struct pt_regs *regs)
4018994f 7413{
88a7c26a
AL
7414 if (user_mode(regs)) {
7415 regs_user->abi = perf_reg_abi(current);
2565711f 7416 regs_user->regs = regs;
085ebfe9 7417 } else if (!(current->flags & PF_KTHREAD)) {
76a4efa8 7418 perf_get_regs_user(regs_user, regs);
2565711f
PZ
7419 } else {
7420 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
7421 regs_user->regs = NULL;
4018994f
JO
7422 }
7423}
7424
60e2364e
SE
7425static void perf_sample_regs_intr(struct perf_regs *regs_intr,
7426 struct pt_regs *regs)
7427{
7428 regs_intr->regs = regs;
7429 regs_intr->abi = perf_reg_abi(current);
7430}
7431
7432
c5ebcedb
JO
7433/*
7434 * Get remaining task size from user stack pointer.
7435 *
7436 * It'd be better to take stack vma map and limit this more
9f014e3a 7437 * precisely, but there's no way to get it safely under interrupt,
c5ebcedb
JO
7438 * so using TASK_SIZE as limit.
7439 */
7440static u64 perf_ustack_task_size(struct pt_regs *regs)
7441{
7442 unsigned long addr = perf_user_stack_pointer(regs);
7443
7444 if (!addr || addr >= TASK_SIZE)
7445 return 0;
7446
7447 return TASK_SIZE - addr;
7448}
7449
7450static u16
7451perf_sample_ustack_size(u16 stack_size, u16 header_size,
7452 struct pt_regs *regs)
7453{
7454 u64 task_size;
7455
7456 /* No regs, no stack pointer, no dump. */
7457 if (!regs)
7458 return 0;
7459
4f6fc782
PZ
7460 /* No mm, no stack, no dump. */
7461 if (!current->mm)
7462 return 0;
7463
c5ebcedb
JO
7464 /*
7465 * Check if we fit in with the requested stack size into the:
7466 * - TASK_SIZE
7467 * If we don't, we limit the size to the TASK_SIZE.
7468 *
7469 * - remaining sample size
7470 * If we don't, we customize the stack size to
7471 * fit in to the remaining sample size.
7472 */
7473
7474 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
7475 stack_size = min(stack_size, (u16) task_size);
7476
7477 /* Current header size plus static size and dynamic size. */
7478 header_size += 2 * sizeof(u64);
7479
7480 /* Do we fit in with the current stack dump size? */
7481 if ((u16) (header_size + stack_size) < header_size) {
7482 /*
7483 * If we overflow the maximum size for the sample,
7484 * we customize the stack dump size to fit in.
7485 */
7486 stack_size = USHRT_MAX - header_size - sizeof(u64);
7487 stack_size = round_up(stack_size, sizeof(u64));
7488 }
7489
7490 return stack_size;
7491}
7492
7493static void
7494perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
7495 struct pt_regs *regs)
7496{
7497 /* Case of a kernel thread, nothing to dump */
7498 if (!regs) {
7499 u64 size = 0;
7500 perf_output_put(handle, size);
7501 } else {
7502 unsigned long sp;
7503 unsigned int rem;
7504 u64 dyn_size;
7505
7506 /*
7507 * We dump:
7508 * static size
7509 * - the size requested by user or the best one we can fit
7510 * in to the sample max size
7511 * data
7512 * - user stack dump data
7513 * dynamic size
7514 * - the actual dumped size
7515 */
7516
7517 /* Static size. */
7518 perf_output_put(handle, dump_size);
7519
7520 /* Data. */
7521 sp = perf_user_stack_pointer(regs);
7522 rem = __output_copy_user(handle, (void *) sp, dump_size);
7523 dyn_size = dump_size - rem;
7524
7525 perf_output_skip(handle, rem);
7526
7527 /* Dynamic size. */
7528 perf_output_put(handle, dyn_size);
7529 }
7530}
7531
a4faf00d
AS
7532static unsigned long perf_prepare_sample_aux(struct perf_event *event,
7533 struct perf_sample_data *data,
7534 size_t size)
7535{
7536 struct perf_event *sampler = event->aux_event;
56de4e8f 7537 struct perf_buffer *rb;
a4faf00d
AS
7538
7539 data->aux_size = 0;
7540
7541 if (!sampler)
7542 goto out;
7543
7544 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
7545 goto out;
7546
7547 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
7548 goto out;
7549
961c3912 7550 rb = ring_buffer_get(sampler);
a4faf00d
AS
7551 if (!rb)
7552 goto out;
7553
7554 /*
7555 * If this is an NMI hit inside sampling code, don't take
7556 * the sample. See also perf_aux_sample_output().
7557 */
7558 if (READ_ONCE(rb->aux_in_sampling)) {
7559 data->aux_size = 0;
7560 } else {
7561 size = min_t(size_t, size, perf_aux_size(rb));
7562 data->aux_size = ALIGN(size, sizeof(u64));
7563 }
7564 ring_buffer_put(rb);
7565
7566out:
7567 return data->aux_size;
7568}
7569
32961aec
HX
7570static long perf_pmu_snapshot_aux(struct perf_buffer *rb,
7571 struct perf_event *event,
7572 struct perf_output_handle *handle,
7573 unsigned long size)
a4faf00d
AS
7574{
7575 unsigned long flags;
7576 long ret;
7577
7578 /*
7579 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
7580 * paths. If we start calling them in NMI context, they may race with
7581 * the IRQ ones, that is, for example, re-starting an event that's just
7582 * been stopped, which is why we're using a separate callback that
7583 * doesn't change the event state.
7584 *
7585 * IRQs need to be disabled to prevent IPIs from racing with us.
7586 */
7587 local_irq_save(flags);
7588 /*
7589 * Guard against NMI hits inside the critical section;
7590 * see also perf_prepare_sample_aux().
7591 */
7592 WRITE_ONCE(rb->aux_in_sampling, 1);
7593 barrier();
7594
7595 ret = event->pmu->snapshot_aux(event, handle, size);
7596
7597 barrier();
7598 WRITE_ONCE(rb->aux_in_sampling, 0);
7599 local_irq_restore(flags);
7600
7601 return ret;
7602}
7603
7604static void perf_aux_sample_output(struct perf_event *event,
7605 struct perf_output_handle *handle,
7606 struct perf_sample_data *data)
7607{
7608 struct perf_event *sampler = event->aux_event;
56de4e8f 7609 struct perf_buffer *rb;
a4faf00d 7610 unsigned long pad;
a4faf00d
AS
7611 long size;
7612
7613 if (WARN_ON_ONCE(!sampler || !data->aux_size))
7614 return;
7615
961c3912 7616 rb = ring_buffer_get(sampler);
a4faf00d
AS
7617 if (!rb)
7618 return;
7619
7620 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
7621
7622 /*
7623 * An error here means that perf_output_copy() failed (returned a
7624 * non-zero surplus that it didn't copy), which in its current
7625 * enlightened implementation is not possible. If that changes, we'd
7626 * like to know.
7627 */
7628 if (WARN_ON_ONCE(size < 0))
7629 goto out_put;
7630
7631 /*
7632 * The pad comes from ALIGN()ing data->aux_size up to u64 in
7633 * perf_prepare_sample_aux(), so should not be more than that.
7634 */
7635 pad = data->aux_size - size;
7636 if (WARN_ON_ONCE(pad >= sizeof(u64)))
7637 pad = 8;
7638
7639 if (pad) {
7640 u64 zero = 0;
7641 perf_output_copy(handle, &zero, pad);
7642 }
7643
7644out_put:
7645 ring_buffer_put(rb);
7646}
7647
bb447c27
NK
7648/*
7649 * A set of common sample data types saved even for non-sample records
7650 * when event->attr.sample_id_all is set.
7651 */
7652#define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \
7653 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \
7654 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER)
7655
a7c8d0da 7656static void __perf_event_header__init_id(struct perf_sample_data *data,
3aac580d
KL
7657 struct perf_event *event,
7658 u64 sample_type)
6844c09d 7659{
3aac580d 7660 data->type = event->attr.sample_type;
bb447c27 7661 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL;
6844c09d
ACM
7662
7663 if (sample_type & PERF_SAMPLE_TID) {
7664 /* namespace issues */
7665 data->tid_entry.pid = perf_event_pid(event, current);
7666 data->tid_entry.tid = perf_event_tid(event, current);
7667 }
7668
7669 if (sample_type & PERF_SAMPLE_TIME)
34f43927 7670 data->time = perf_event_clock(event);
6844c09d 7671
ff3d527c 7672 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6844c09d
ACM
7673 data->id = primary_event_id(event);
7674
7675 if (sample_type & PERF_SAMPLE_STREAM_ID)
7676 data->stream_id = event->id;
7677
7678 if (sample_type & PERF_SAMPLE_CPU) {
7679 data->cpu_entry.cpu = raw_smp_processor_id();
7680 data->cpu_entry.reserved = 0;
7681 }
7682}
7683
76369139
FW
7684void perf_event_header__init_id(struct perf_event_header *header,
7685 struct perf_sample_data *data,
7686 struct perf_event *event)
c980d109 7687{
a7c8d0da
NK
7688 if (event->attr.sample_id_all) {
7689 header->size += event->id_header_size;
7690 __perf_event_header__init_id(data, event, event->attr.sample_type);
7691 }
c980d109
ACM
7692}
7693
7694static void __perf_event__output_id_sample(struct perf_output_handle *handle,
7695 struct perf_sample_data *data)
7696{
7697 u64 sample_type = data->type;
7698
7699 if (sample_type & PERF_SAMPLE_TID)
7700 perf_output_put(handle, data->tid_entry);
7701
7702 if (sample_type & PERF_SAMPLE_TIME)
7703 perf_output_put(handle, data->time);
7704
7705 if (sample_type & PERF_SAMPLE_ID)
7706 perf_output_put(handle, data->id);
7707
7708 if (sample_type & PERF_SAMPLE_STREAM_ID)
7709 perf_output_put(handle, data->stream_id);
7710
7711 if (sample_type & PERF_SAMPLE_CPU)
7712 perf_output_put(handle, data->cpu_entry);
ff3d527c
AH
7713
7714 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7715 perf_output_put(handle, data->id);
c980d109
ACM
7716}
7717
76369139
FW
7718void perf_event__output_id_sample(struct perf_event *event,
7719 struct perf_output_handle *handle,
7720 struct perf_sample_data *sample)
c980d109
ACM
7721{
7722 if (event->attr.sample_id_all)
7723 __perf_event__output_id_sample(handle, sample);
7724}
7725
3dab77fb 7726static void perf_output_read_one(struct perf_output_handle *handle,
eed01528
SE
7727 struct perf_event *event,
7728 u64 enabled, u64 running)
3dab77fb 7729{
cdd6c482 7730 u64 read_format = event->attr.read_format;
119a784c 7731 u64 values[5];
3dab77fb
PZ
7732 int n = 0;
7733
7e8b2556 7734 values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr));
3dab77fb 7735 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
eed01528 7736 values[n++] = enabled +
cdd6c482 7737 atomic64_read(&event->child_total_time_enabled);
3dab77fb
PZ
7738 }
7739 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
eed01528 7740 values[n++] = running +
cdd6c482 7741 atomic64_read(&event->child_total_time_running);
3dab77fb
PZ
7742 }
7743 if (read_format & PERF_FORMAT_ID)
cdd6c482 7744 values[n++] = primary_event_id(event);
119a784c
NK
7745 if (read_format & PERF_FORMAT_LOST)
7746 values[n++] = atomic64_read(&event->lost_samples);
3dab77fb 7747
76369139 7748 __output_copy(handle, values, n * sizeof(u64));
3dab77fb
PZ
7749}
7750
3dab77fb 7751static void perf_output_read_group(struct perf_output_handle *handle,
7e8b2556
BG
7752 struct perf_event *event,
7753 u64 enabled, u64 running)
3dab77fb 7754{
cdd6c482
IM
7755 struct perf_event *leader = event->group_leader, *sub;
7756 u64 read_format = event->attr.read_format;
6b959ba2 7757 unsigned long flags;
119a784c 7758 u64 values[6];
3dab77fb 7759 int n = 0;
7e8b2556 7760 bool self = has_inherit_and_sample_read(&event->attr);
3dab77fb 7761
6b959ba2
YJ
7762 /*
7763 * Disabling interrupts avoids all counter scheduling
7764 * (context switches, timer based rotation and IPIs).
7765 */
7766 local_irq_save(flags);
7767
3dab77fb
PZ
7768 values[n++] = 1 + leader->nr_siblings;
7769
7770 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
eed01528 7771 values[n++] = enabled;
3dab77fb
PZ
7772
7773 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
eed01528 7774 values[n++] = running;
3dab77fb 7775
8ce939a0
PZI
7776 if ((leader != event) && !handle->skip_read)
7777 perf_pmu_read(leader);
3dab77fb 7778
7e8b2556 7779 values[n++] = perf_event_count(leader, self);
3dab77fb 7780 if (read_format & PERF_FORMAT_ID)
cdd6c482 7781 values[n++] = primary_event_id(leader);
119a784c
NK
7782 if (read_format & PERF_FORMAT_LOST)
7783 values[n++] = atomic64_read(&leader->lost_samples);
3dab77fb 7784
76369139 7785 __output_copy(handle, values, n * sizeof(u64));
3dab77fb 7786
edb39592 7787 for_each_sibling_event(sub, leader) {
3dab77fb
PZ
7788 n = 0;
7789
8ce939a0
PZI
7790 if ((sub != event) && !handle->skip_read)
7791 perf_pmu_read(sub);
3dab77fb 7792
7e8b2556 7793 values[n++] = perf_event_count(sub, self);
3dab77fb 7794 if (read_format & PERF_FORMAT_ID)
cdd6c482 7795 values[n++] = primary_event_id(sub);
119a784c
NK
7796 if (read_format & PERF_FORMAT_LOST)
7797 values[n++] = atomic64_read(&sub->lost_samples);
3dab77fb 7798
76369139 7799 __output_copy(handle, values, n * sizeof(u64));
3dab77fb 7800 }
6b959ba2
YJ
7801
7802 local_irq_restore(flags);
3dab77fb
PZ
7803}
7804
eed01528
SE
7805#define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
7806 PERF_FORMAT_TOTAL_TIME_RUNNING)
7807
ba5213ae
PZ
7808/*
7809 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
7810 *
7811 * The problem is that its both hard and excessively expensive to iterate the
7812 * child list, not to mention that its impossible to IPI the children running
7813 * on another CPU, from interrupt/NMI context.
7e8b2556
BG
7814 *
7815 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread
7816 * counts rather than attempting to accumulate some value across all children on
7817 * all cores.
ba5213ae 7818 */
3dab77fb 7819static void perf_output_read(struct perf_output_handle *handle,
cdd6c482 7820 struct perf_event *event)
3dab77fb 7821{
e3f3541c 7822 u64 enabled = 0, running = 0, now;
eed01528
SE
7823 u64 read_format = event->attr.read_format;
7824
7825 /*
7826 * compute total_time_enabled, total_time_running
7827 * based on snapshot values taken when the event
7828 * was last scheduled in.
7829 *
7830 * we cannot simply called update_context_time()
7831 * because of locking issue as we are called in
7832 * NMI context
7833 */
c4794295 7834 if (read_format & PERF_FORMAT_TOTAL_TIMES)
e3f3541c 7835 calc_timer_values(event, &now, &enabled, &running);
eed01528 7836
cdd6c482 7837 if (event->attr.read_format & PERF_FORMAT_GROUP)
eed01528 7838 perf_output_read_group(handle, event, enabled, running);
3dab77fb 7839 else
eed01528 7840 perf_output_read_one(handle, event, enabled, running);
3dab77fb
PZ
7841}
7842
5622f295
MM
7843void perf_output_sample(struct perf_output_handle *handle,
7844 struct perf_event_header *header,
7845 struct perf_sample_data *data,
cdd6c482 7846 struct perf_event *event)
5622f295
MM
7847{
7848 u64 sample_type = data->type;
7849
8ce939a0
PZI
7850 if (data->sample_flags & PERF_SAMPLE_READ)
7851 handle->skip_read = 1;
7852
5622f295
MM
7853 perf_output_put(handle, *header);
7854
ff3d527c
AH
7855 if (sample_type & PERF_SAMPLE_IDENTIFIER)
7856 perf_output_put(handle, data->id);
7857
5622f295
MM
7858 if (sample_type & PERF_SAMPLE_IP)
7859 perf_output_put(handle, data->ip);
7860
7861 if (sample_type & PERF_SAMPLE_TID)
7862 perf_output_put(handle, data->tid_entry);
7863
7864 if (sample_type & PERF_SAMPLE_TIME)
7865 perf_output_put(handle, data->time);
7866
7867 if (sample_type & PERF_SAMPLE_ADDR)
7868 perf_output_put(handle, data->addr);
7869
7870 if (sample_type & PERF_SAMPLE_ID)
7871 perf_output_put(handle, data->id);
7872
7873 if (sample_type & PERF_SAMPLE_STREAM_ID)
7874 perf_output_put(handle, data->stream_id);
7875
7876 if (sample_type & PERF_SAMPLE_CPU)
7877 perf_output_put(handle, data->cpu_entry);
7878
7879 if (sample_type & PERF_SAMPLE_PERIOD)
7880 perf_output_put(handle, data->period);
7881
7882 if (sample_type & PERF_SAMPLE_READ)
cdd6c482 7883 perf_output_read(handle, event);
5622f295
MM
7884
7885 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
99e818cc 7886 int size = 1;
5622f295 7887
99e818cc
JO
7888 size += data->callchain->nr;
7889 size *= sizeof(u64);
7890 __output_copy(handle, data->callchain, size);
5622f295
MM
7891 }
7892
7893 if (sample_type & PERF_SAMPLE_RAW) {
7e3f977e
DB
7894 struct perf_raw_record *raw = data->raw;
7895
7896 if (raw) {
7897 struct perf_raw_frag *frag = &raw->frag;
7898
7899 perf_output_put(handle, raw->size);
7900 do {
7901 if (frag->copy) {
7902 __output_custom(handle, frag->copy,
7903 frag->data, frag->size);
7904 } else {
7905 __output_copy(handle, frag->data,
7906 frag->size);
7907 }
7908 if (perf_raw_frag_last(frag))
7909 break;
7910 frag = frag->next;
7911 } while (1);
7912 if (frag->pad)
7913 __output_skip(handle, NULL, frag->pad);
5622f295
MM
7914 } else {
7915 struct {
7916 u32 size;
7917 u32 data;
7918 } raw = {
7919 .size = sizeof(u32),
7920 .data = 0,
7921 };
7922 perf_output_put(handle, raw);
7923 }
7924 }
a7ac67ea 7925
bce38cd5 7926 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
eb55b455 7927 if (data->br_stack) {
bce38cd5
SE
7928 size_t size;
7929
7930 size = data->br_stack->nr
7931 * sizeof(struct perf_branch_entry);
7932
7933 perf_output_put(handle, data->br_stack->nr);
03b02db9 7934 if (branch_sample_hw_index(event))
bbfd5e4f 7935 perf_output_put(handle, data->br_stack->hw_idx);
bce38cd5 7936 perf_output_copy(handle, data->br_stack->entries, size);
571d91dc
KL
7937 /*
7938 * Add the extension space which is appended
7939 * right after the struct perf_branch_stack.
7940 */
7941 if (data->br_stack_cntr) {
7942 size = data->br_stack->nr * sizeof(u64);
7943 perf_output_copy(handle, data->br_stack_cntr, size);
7944 }
bce38cd5
SE
7945 } else {
7946 /*
7947 * we always store at least the value of nr
7948 */
7949 u64 nr = 0;
7950 perf_output_put(handle, nr);
7951 }
7952 }
4018994f
JO
7953
7954 if (sample_type & PERF_SAMPLE_REGS_USER) {
7955 u64 abi = data->regs_user.abi;
7956
7957 /*
7958 * If there are no regs to dump, notice it through
7959 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7960 */
7961 perf_output_put(handle, abi);
7962
7963 if (abi) {
7964 u64 mask = event->attr.sample_regs_user;
7965 perf_output_sample_regs(handle,
7966 data->regs_user.regs,
7967 mask);
7968 }
7969 }
c5ebcedb 7970
a5cdd40c 7971 if (sample_type & PERF_SAMPLE_STACK_USER) {
c5ebcedb
JO
7972 perf_output_sample_ustack(handle,
7973 data->stack_user_size,
7974 data->regs_user.regs);
a5cdd40c 7975 }
c3feedf2 7976
2a6c6b7d
KL
7977 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE)
7978 perf_output_put(handle, data->weight.full);
d6be9ad6
SE
7979
7980 if (sample_type & PERF_SAMPLE_DATA_SRC)
7981 perf_output_put(handle, data->data_src.val);
a5cdd40c 7982
fdfbbd07
AK
7983 if (sample_type & PERF_SAMPLE_TRANSACTION)
7984 perf_output_put(handle, data->txn);
7985
60e2364e
SE
7986 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7987 u64 abi = data->regs_intr.abi;
7988 /*
7989 * If there are no regs to dump, notice it through
7990 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
7991 */
7992 perf_output_put(handle, abi);
7993
7994 if (abi) {
7995 u64 mask = event->attr.sample_regs_intr;
7996
7997 perf_output_sample_regs(handle,
7998 data->regs_intr.regs,
7999 mask);
8000 }
8001 }
8002
fc7ce9c7
KL
8003 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
8004 perf_output_put(handle, data->phys_addr);
8005
6546b19f
NK
8006 if (sample_type & PERF_SAMPLE_CGROUP)
8007 perf_output_put(handle, data->cgroup);
8008
8d97e718
KL
8009 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)
8010 perf_output_put(handle, data->data_page_size);
8011
995f088e
SE
8012 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)
8013 perf_output_put(handle, data->code_page_size);
8014
a4faf00d
AS
8015 if (sample_type & PERF_SAMPLE_AUX) {
8016 perf_output_put(handle, data->aux_size);
8017
8018 if (data->aux_size)
8019 perf_aux_sample_output(event, handle, data);
8020 }
8021
a5cdd40c
PZ
8022 if (!event->attr.watermark) {
8023 int wakeup_events = event->attr.wakeup_events;
8024
8025 if (wakeup_events) {
56de4e8f 8026 struct perf_buffer *rb = handle->rb;
a5cdd40c
PZ
8027 int events = local_inc_return(&rb->events);
8028
8029 if (events >= wakeup_events) {
8030 local_sub(wakeup_events, &rb->events);
8031 local_inc(&rb->wakeup);
8032 }
8033 }
8034 }
5622f295
MM
8035}
8036
fc7ce9c7
KL
8037static u64 perf_virt_to_phys(u64 virt)
8038{
8039 u64 phys_addr = 0;
fc7ce9c7
KL
8040
8041 if (!virt)
8042 return 0;
8043
8044 if (virt >= TASK_SIZE) {
8045 /* If it's vmalloc()d memory, leave phys_addr as 0 */
8046 if (virt_addr_valid((void *)(uintptr_t)virt) &&
8047 !(virt >= VMALLOC_START && virt < VMALLOC_END))
8048 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
8049 } else {
8050 /*
8051 * Walking the pages tables for user address.
8052 * Interrupts are disabled, so it prevents any tear down
8053 * of the page tables.
dadbb612 8054 * Try IRQ-safe get_user_page_fast_only first.
fc7ce9c7
KL
8055 * If failed, leave phys_addr as 0.
8056 */
d3296fb3 8057 if (current->mm != NULL) {
4716023a
GT
8058 struct page *p;
8059
d3296fb3 8060 pagefault_disable();
4716023a 8061 if (get_user_page_fast_only(virt, 0, &p)) {
d3296fb3 8062 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
4716023a
GT
8063 put_page(p);
8064 }
d3296fb3
JO
8065 pagefault_enable();
8066 }
fc7ce9c7
KL
8067 }
8068
8069 return phys_addr;
8070}
8071
8d97e718 8072/*
8af26be0 8073 * Return the pagetable size of a given virtual address.
8d97e718 8074 */
8af26be0 8075static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr)
8d97e718 8076{
8af26be0 8077 u64 size = 0;
8d97e718 8078
25176ad0 8079#ifdef CONFIG_HAVE_GUP_FAST
8af26be0
PZ
8080 pgd_t *pgdp, pgd;
8081 p4d_t *p4dp, p4d;
8082 pud_t *pudp, pud;
8083 pmd_t *pmdp, pmd;
8084 pte_t *ptep, pte;
8d97e718 8085
8af26be0
PZ
8086 pgdp = pgd_offset(mm, addr);
8087 pgd = READ_ONCE(*pgdp);
8088 if (pgd_none(pgd))
8d97e718
KL
8089 return 0;
8090
8af26be0
PZ
8091 if (pgd_leaf(pgd))
8092 return pgd_leaf_size(pgd);
8d97e718 8093
8af26be0
PZ
8094 p4dp = p4d_offset_lockless(pgdp, pgd, addr);
8095 p4d = READ_ONCE(*p4dp);
8096 if (!p4d_present(p4d))
8d97e718
KL
8097 return 0;
8098
8af26be0
PZ
8099 if (p4d_leaf(p4d))
8100 return p4d_leaf_size(p4d);
8d97e718 8101
8af26be0
PZ
8102 pudp = pud_offset_lockless(p4dp, p4d, addr);
8103 pud = READ_ONCE(*pudp);
8104 if (!pud_present(pud))
8d97e718
KL
8105 return 0;
8106
8af26be0
PZ
8107 if (pud_leaf(pud))
8108 return pud_leaf_size(pud);
8d97e718 8109
8af26be0 8110 pmdp = pmd_offset_lockless(pudp, pud, addr);
a92cbb82 8111again:
1180e732 8112 pmd = pmdp_get_lockless(pmdp);
8af26be0 8113 if (!pmd_present(pmd))
8d97e718 8114 return 0;
8d97e718 8115
8af26be0
PZ
8116 if (pmd_leaf(pmd))
8117 return pmd_leaf_size(pmd);
51b646b2 8118
8af26be0 8119 ptep = pte_offset_map(&pmd, addr);
a92cbb82
HD
8120 if (!ptep)
8121 goto again;
8122
8af26be0
PZ
8123 pte = ptep_get_lockless(ptep);
8124 if (pte_present(pte))
18d095b2 8125 size = __pte_leaf_size(pmd, pte);
8af26be0 8126 pte_unmap(ptep);
25176ad0 8127#endif /* CONFIG_HAVE_GUP_FAST */
8d97e718 8128
8af26be0 8129 return size;
8d97e718
KL
8130}
8131
8d97e718
KL
8132static u64 perf_get_page_size(unsigned long addr)
8133{
8134 struct mm_struct *mm;
8135 unsigned long flags;
8136 u64 size;
8137
8138 if (!addr)
8139 return 0;
8140
8141 /*
8142 * Software page-table walkers must disable IRQs,
8143 * which prevents any tear down of the page tables.
8144 */
8145 local_irq_save(flags);
8146
8147 mm = current->mm;
8148 if (!mm) {
8149 /*
8150 * For kernel threads and the like, use init_mm so that
8151 * we can find kernel memory.
8152 */
8153 mm = &init_mm;
8154 }
8155
8af26be0 8156 size = perf_get_pgtable_size(mm, addr);
8d97e718
KL
8157
8158 local_irq_restore(flags);
8159
8160 return size;
8161}
8162
99e818cc
JO
8163static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
8164
6cbc304f 8165struct perf_callchain_entry *
8cf7e0e2
JO
8166perf_callchain(struct perf_event *event, struct pt_regs *regs)
8167{
8168 bool kernel = !event->attr.exclude_callchain_kernel;
8169 bool user = !event->attr.exclude_callchain_user;
8170 /* Disallow cross-task user callchains. */
8171 bool crosstask = event->ctx->task && event->ctx->task != current;
8172 const u32 max_stack = event->attr.sample_max_stack;
99e818cc 8173 struct perf_callchain_entry *callchain;
8cf7e0e2 8174
4f6fc782
PZ
8175 if (!current->mm)
8176 user = false;
8177
8cf7e0e2 8178 if (!kernel && !user)
99e818cc 8179 return &__empty_callchain;
8cf7e0e2 8180
99e818cc
JO
8181 callchain = get_perf_callchain(regs, 0, kernel, user,
8182 max_stack, crosstask, true);
8183 return callchain ?: &__empty_callchain;
8cf7e0e2
JO
8184}
8185
bb447c27
NK
8186static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d)
8187{
8188 return d * !!(flags & s);
8189}
8190
f6e70715 8191void perf_prepare_sample(struct perf_sample_data *data,
cdd6c482 8192 struct perf_event *event,
5622f295 8193 struct pt_regs *regs)
7b732a75 8194{
cdd6c482 8195 u64 sample_type = event->attr.sample_type;
3aac580d 8196 u64 filtered_sample_type;
7b732a75 8197
3aac580d 8198 /*
bb447c27
NK
8199 * Add the sample flags that are dependent to others. And clear the
8200 * sample flags that have already been done by the PMU driver.
3aac580d 8201 */
bb447c27
NK
8202 filtered_sample_type = sample_type;
8203 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE,
8204 PERF_SAMPLE_IP);
8205 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE |
8206 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR);
8207 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER,
8208 PERF_SAMPLE_REGS_USER);
8209 filtered_sample_type &= ~data->sample_flags;
6844c09d 8210
f6e70715
NK
8211 if (filtered_sample_type == 0) {
8212 /* Make sure it has the correct data->type for output */
8213 data->type = event->attr.sample_type;
8214 return;
394ee076
PZ
8215 }
8216
a7c8d0da 8217 __perf_event_header__init_id(data, event, filtered_sample_type);
7e3f977e 8218
bb447c27 8219 if (filtered_sample_type & PERF_SAMPLE_IP) {
2c47e7a7 8220 data->ip = perf_instruction_pointer(event, regs);
bb447c27
NK
8221 data->sample_flags |= PERF_SAMPLE_IP;
8222 }
7e3f977e 8223
31046500
NK
8224 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN)
8225 perf_sample_save_callchain(data, event, regs);
a044560c 8226
0a9081cf
NK
8227 if (filtered_sample_type & PERF_SAMPLE_RAW) {
8228 data->raw = NULL;
8229 data->dyn_size += sizeof(u64);
8230 data->sample_flags |= PERF_SAMPLE_RAW;
7f453c24 8231 }
bce38cd5 8232
eb55b455
NK
8233 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) {
8234 data->br_stack = NULL;
8235 data->dyn_size += sizeof(u64);
8236 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK;
bce38cd5 8237 }
4018994f 8238
bb447c27 8239 if (filtered_sample_type & PERF_SAMPLE_REGS_USER)
76a4efa8 8240 perf_sample_regs_user(&data->regs_user, regs);
2565711f 8241
bb447c27
NK
8242 /*
8243 * It cannot use the filtered_sample_type here as REGS_USER can be set
8244 * by STACK_USER (using __cond_set() above) and we don't want to update
8245 * the dyn_size if it's not requested by users.
8246 */
8247 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) {
4018994f
JO
8248 /* regs dump ABI info */
8249 int size = sizeof(u64);
8250
4018994f
JO
8251 if (data->regs_user.regs) {
8252 u64 mask = event->attr.sample_regs_user;
8253 size += hweight64(mask) * sizeof(u64);
8254 }
8255
4cf7a136 8256 data->dyn_size += size;
bb447c27 8257 data->sample_flags |= PERF_SAMPLE_REGS_USER;
4018994f 8258 }
c5ebcedb 8259
bb447c27 8260 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) {
c5ebcedb 8261 /*
9f014e3a 8262 * Either we need PERF_SAMPLE_STACK_USER bit to be always
c5ebcedb
JO
8263 * processed as the last one or have additional check added
8264 * in case new sample type is added, because we could eat
8265 * up the rest of the sample size.
8266 */
c5ebcedb 8267 u16 stack_size = event->attr.sample_stack_user;
f6e70715 8268 u16 header_size = perf_sample_data_size(data, event);
c5ebcedb
JO
8269 u16 size = sizeof(u64);
8270
f6e70715 8271 stack_size = perf_sample_ustack_size(stack_size, header_size,
2565711f 8272 data->regs_user.regs);
c5ebcedb
JO
8273
8274 /*
8275 * If there is something to dump, add space for the dump
8276 * itself and for the field that tells the dynamic size,
8277 * which is how many have been actually dumped.
8278 */
8279 if (stack_size)
8280 size += sizeof(u64) + stack_size;
8281
8282 data->stack_user_size = stack_size;
4cf7a136 8283 data->dyn_size += size;
bb447c27 8284 data->sample_flags |= PERF_SAMPLE_STACK_USER;
c5ebcedb 8285 }
60e2364e 8286
bb447c27 8287 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) {
2abe681d 8288 data->weight.full = 0;
bb447c27
NK
8289 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE;
8290 }
2abe681d 8291
bb447c27 8292 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) {
e16fd7f2 8293 data->data_src.val = PERF_MEM_NA;
bb447c27
NK
8294 data->sample_flags |= PERF_SAMPLE_DATA_SRC;
8295 }
e16fd7f2 8296
bb447c27 8297 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) {
ee9db0e1 8298 data->txn = 0;
bb447c27
NK
8299 data->sample_flags |= PERF_SAMPLE_TRANSACTION;
8300 }
ee9db0e1 8301
bb447c27
NK
8302 if (filtered_sample_type & PERF_SAMPLE_ADDR) {
8303 data->addr = 0;
8304 data->sample_flags |= PERF_SAMPLE_ADDR;
7b084630
NK
8305 }
8306
bb447c27 8307 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) {
60e2364e
SE
8308 /* regs dump ABI info */
8309 int size = sizeof(u64);
8310
8311 perf_sample_regs_intr(&data->regs_intr, regs);
8312
8313 if (data->regs_intr.regs) {
8314 u64 mask = event->attr.sample_regs_intr;
8315
8316 size += hweight64(mask) * sizeof(u64);
8317 }
8318
4cf7a136 8319 data->dyn_size += size;
bb447c27 8320 data->sample_flags |= PERF_SAMPLE_REGS_INTR;
60e2364e 8321 }
fc7ce9c7 8322
bb447c27 8323 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) {
fc7ce9c7 8324 data->phys_addr = perf_virt_to_phys(data->addr);
bb447c27
NK
8325 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR;
8326 }
a4faf00d 8327
6546b19f 8328#ifdef CONFIG_CGROUP_PERF
bb447c27 8329 if (filtered_sample_type & PERF_SAMPLE_CGROUP) {
6546b19f
NK
8330 struct cgroup *cgrp;
8331
8332 /* protected by RCU */
8333 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
8334 data->cgroup = cgroup_id(cgrp);
bb447c27 8335 data->sample_flags |= PERF_SAMPLE_CGROUP;
6546b19f
NK
8336 }
8337#endif
8338
8d97e718
KL
8339 /*
8340 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't
8341 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr,
8342 * but the value will not dump to the userspace.
8343 */
bb447c27 8344 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) {
8d97e718 8345 data->data_page_size = perf_get_page_size(data->addr);
bb447c27
NK
8346 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE;
8347 }
8d97e718 8348
bb447c27 8349 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) {
995f088e 8350 data->code_page_size = perf_get_page_size(data->ip);
bb447c27
NK
8351 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE;
8352 }
995f088e 8353
bb447c27 8354 if (filtered_sample_type & PERF_SAMPLE_AUX) {
a4faf00d 8355 u64 size;
f6e70715 8356 u16 header_size = perf_sample_data_size(data, event);
a4faf00d 8357
f6e70715 8358 header_size += sizeof(u64); /* size */
a4faf00d
AS
8359
8360 /*
8361 * Given the 16bit nature of header::size, an AUX sample can
8362 * easily overflow it, what with all the preceding sample bits.
8363 * Make sure this doesn't happen by using up to U16_MAX bytes
8364 * per sample in total (rounded down to 8 byte boundary).
8365 */
f6e70715 8366 size = min_t(size_t, U16_MAX - header_size,
a4faf00d
AS
8367 event->attr.aux_sample_size);
8368 size = rounddown(size, 8);
8369 size = perf_prepare_sample_aux(event, data, size);
8370
f6e70715 8371 WARN_ON_ONCE(size + header_size > U16_MAX);
4cf7a136 8372 data->dyn_size += size + sizeof(u64); /* size above */
bb447c27 8373 data->sample_flags |= PERF_SAMPLE_AUX;
a4faf00d 8374 }
f6e70715 8375}
4cf7a136 8376
f6e70715
NK
8377void perf_prepare_header(struct perf_event_header *header,
8378 struct perf_sample_data *data,
8379 struct perf_event *event,
8380 struct pt_regs *regs)
8381{
8382 header->type = PERF_RECORD_SAMPLE;
8383 header->size = perf_sample_data_size(data, event);
2c47e7a7 8384 header->misc = perf_misc_flags(event, regs);
4cf7a136 8385
a4faf00d
AS
8386 /*
8387 * If you're adding more sample types here, you likely need to do
8388 * something about the overflowing header::size, like repurpose the
8389 * lowest 3 bits of size, which should be always zero at the moment.
8390 * This raises a more important question, do we really need 512k sized
8391 * samples and why, so good argumentation is in order for whatever you
8392 * do here next.
8393 */
8394 WARN_ON_ONCE(header->size & 7);
5622f295 8395}
7f453c24 8396
18d92bb5
AH
8397static void __perf_event_aux_pause(struct perf_event *event, bool pause)
8398{
8399 if (pause) {
8400 if (!event->hw.aux_paused) {
8401 event->hw.aux_paused = 1;
8402 event->pmu->stop(event, PERF_EF_PAUSE);
8403 }
8404 } else {
8405 if (event->hw.aux_paused) {
8406 event->hw.aux_paused = 0;
8407 event->pmu->start(event, PERF_EF_RESUME);
8408 }
8409 }
8410}
8411
8412static void perf_event_aux_pause(struct perf_event *event, bool pause)
8413{
8414 struct perf_buffer *rb;
8415
8416 if (WARN_ON_ONCE(!event))
8417 return;
8418
8419 rb = ring_buffer_get(event);
8420 if (!rb)
8421 return;
8422
8423 scoped_guard (irqsave) {
8424 /*
8425 * Guard against self-recursion here. Another event could trip
8426 * this same from NMI context.
8427 */
8428 if (READ_ONCE(rb->aux_in_pause_resume))
8429 break;
8430
8431 WRITE_ONCE(rb->aux_in_pause_resume, 1);
8432 barrier();
8433 __perf_event_aux_pause(event, pause);
8434 barrier();
8435 WRITE_ONCE(rb->aux_in_pause_resume, 0);
8436 }
8437 ring_buffer_put(rb);
8438}
8439
56201969 8440static __always_inline int
9ecda41a
WN
8441__perf_event_output(struct perf_event *event,
8442 struct perf_sample_data *data,
8443 struct pt_regs *regs,
8444 int (*output_begin)(struct perf_output_handle *,
267fb273 8445 struct perf_sample_data *,
9ecda41a
WN
8446 struct perf_event *,
8447 unsigned int))
5622f295
MM
8448{
8449 struct perf_output_handle handle;
8450 struct perf_event_header header;
56201969 8451 int err;
689802b2 8452
927c7a9e
FW
8453 /* protect the callchain buffers */
8454 rcu_read_lock();
8455
f6e70715
NK
8456 perf_prepare_sample(data, event, regs);
8457 perf_prepare_header(&header, data, event, regs);
5c148194 8458
267fb273 8459 err = output_begin(&handle, data, event, header.size);
56201969 8460 if (err)
927c7a9e 8461 goto exit;
0322cd6e 8462
cdd6c482 8463 perf_output_sample(&handle, &header, data, event);
f413cdb8 8464
8a057d84 8465 perf_output_end(&handle);
927c7a9e
FW
8466
8467exit:
8468 rcu_read_unlock();
56201969 8469 return err;
0322cd6e
PZ
8470}
8471
9ecda41a
WN
8472void
8473perf_event_output_forward(struct perf_event *event,
8474 struct perf_sample_data *data,
8475 struct pt_regs *regs)
8476{
8477 __perf_event_output(event, data, regs, perf_output_begin_forward);
8478}
8479
8480void
8481perf_event_output_backward(struct perf_event *event,
8482 struct perf_sample_data *data,
8483 struct pt_regs *regs)
8484{
8485 __perf_event_output(event, data, regs, perf_output_begin_backward);
8486}
8487
56201969 8488int
9ecda41a
WN
8489perf_event_output(struct perf_event *event,
8490 struct perf_sample_data *data,
8491 struct pt_regs *regs)
8492{
56201969 8493 return __perf_event_output(event, data, regs, perf_output_begin);
9ecda41a
WN
8494}
8495
38b200d6 8496/*
cdd6c482 8497 * read event_id
38b200d6
PZ
8498 */
8499
8500struct perf_read_event {
8501 struct perf_event_header header;
8502
8503 u32 pid;
8504 u32 tid;
38b200d6
PZ
8505};
8506
8507static void
cdd6c482 8508perf_event_read_event(struct perf_event *event,
38b200d6
PZ
8509 struct task_struct *task)
8510{
8511 struct perf_output_handle handle;
c980d109 8512 struct perf_sample_data sample;
dfc65094 8513 struct perf_read_event read_event = {
38b200d6 8514 .header = {
cdd6c482 8515 .type = PERF_RECORD_READ,
38b200d6 8516 .misc = 0,
c320c7b7 8517 .size = sizeof(read_event) + event->read_size,
38b200d6 8518 },
cdd6c482
IM
8519 .pid = perf_event_pid(event, task),
8520 .tid = perf_event_tid(event, task),
38b200d6 8521 };
3dab77fb 8522 int ret;
38b200d6 8523
c980d109 8524 perf_event_header__init_id(&read_event.header, &sample, event);
267fb273 8525 ret = perf_output_begin(&handle, &sample, event, read_event.header.size);
38b200d6
PZ
8526 if (ret)
8527 return;
8528
dfc65094 8529 perf_output_put(&handle, read_event);
cdd6c482 8530 perf_output_read(&handle, event);
c980d109 8531 perf_event__output_id_sample(event, &handle, &sample);
3dab77fb 8532
38b200d6
PZ
8533 perf_output_end(&handle);
8534}
8535
aab5b71e 8536typedef void (perf_iterate_f)(struct perf_event *event, void *data);
52d857a8
JO
8537
8538static void
aab5b71e
PZ
8539perf_iterate_ctx(struct perf_event_context *ctx,
8540 perf_iterate_f output,
b73e4fef 8541 void *data, bool all)
52d857a8
JO
8542{
8543 struct perf_event *event;
8544
8545 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
b73e4fef
AS
8546 if (!all) {
8547 if (event->state < PERF_EVENT_STATE_INACTIVE)
8548 continue;
8549 if (!event_filter_match(event))
8550 continue;
8551 }
8552
67516844 8553 output(event, data);
52d857a8
JO
8554 }
8555}
8556
aab5b71e 8557static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
f2fb6bef
KL
8558{
8559 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
8560 struct perf_event *event;
8561
8562 list_for_each_entry_rcu(event, &pel->list, sb_list) {
0b8f1e2e
PZ
8563 /*
8564 * Skip events that are not fully formed yet; ensure that
8565 * if we observe event->ctx, both event and ctx will be
8566 * complete enough. See perf_install_in_context().
8567 */
8568 if (!smp_load_acquire(&event->ctx))
8569 continue;
8570
f2fb6bef
KL
8571 if (event->state < PERF_EVENT_STATE_INACTIVE)
8572 continue;
8573 if (!event_filter_match(event))
8574 continue;
8575 output(event, data);
8576 }
8577}
8578
aab5b71e
PZ
8579/*
8580 * Iterate all events that need to receive side-band events.
8581 *
8582 * For new callers; ensure that account_pmu_sb_event() includes
8583 * your event, otherwise it might not get delivered.
8584 */
52d857a8 8585static void
aab5b71e 8586perf_iterate_sb(perf_iterate_f output, void *data,
52d857a8
JO
8587 struct perf_event_context *task_ctx)
8588{
52d857a8 8589 struct perf_event_context *ctx;
52d857a8 8590
aab5b71e
PZ
8591 rcu_read_lock();
8592 preempt_disable();
8593
4e93ad60 8594 /*
aab5b71e
PZ
8595 * If we have task_ctx != NULL we only notify the task context itself.
8596 * The task_ctx is set only for EXIT events before releasing task
4e93ad60
JO
8597 * context.
8598 */
8599 if (task_ctx) {
aab5b71e
PZ
8600 perf_iterate_ctx(task_ctx, output, data, false);
8601 goto done;
4e93ad60
JO
8602 }
8603
aab5b71e 8604 perf_iterate_sb_cpu(output, data);
f2fb6bef 8605
bd275681
PZ
8606 ctx = rcu_dereference(current->perf_event_ctxp);
8607 if (ctx)
8608 perf_iterate_ctx(ctx, output, data, false);
aab5b71e 8609done:
f2fb6bef 8610 preempt_enable();
52d857a8 8611 rcu_read_unlock();
95ff4ca2
AS
8612}
8613
375637bc
AS
8614/*
8615 * Clear all file-based filters at exec, they'll have to be
8616 * re-instated when/if these objects are mmapped again.
8617 */
8618static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
8619{
8620 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8621 struct perf_addr_filter *filter;
8622 unsigned int restart = 0, count = 0;
8623 unsigned long flags;
8624
8625 if (!has_addr_filter(event))
8626 return;
8627
8628 raw_spin_lock_irqsave(&ifh->lock, flags);
8629 list_for_each_entry(filter, &ifh->list, entry) {
9511bce9 8630 if (filter->path.dentry) {
c60f83b8
AS
8631 event->addr_filter_ranges[count].start = 0;
8632 event->addr_filter_ranges[count].size = 0;
375637bc
AS
8633 restart++;
8634 }
8635
8636 count++;
8637 }
8638
8639 if (restart)
8640 event->addr_filters_gen++;
8641 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8642
8643 if (restart)
767ae086 8644 perf_event_stop(event, 1);
375637bc
AS
8645}
8646
8647void perf_event_exec(void)
8648{
8649 struct perf_event_context *ctx;
375637bc 8650
bd275681
PZ
8651 ctx = perf_pin_task_context(current);
8652 if (!ctx)
8653 return;
375637bc 8654
bd275681
PZ
8655 perf_event_enable_on_exec(ctx);
8656 perf_event_remove_on_exec(ctx);
0fe8813b
BL
8657 scoped_guard(rcu)
8658 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true);
375637bc 8659
bd275681
PZ
8660 perf_unpin_context(ctx);
8661 put_ctx(ctx);
375637bc
AS
8662}
8663
95ff4ca2 8664struct remote_output {
56de4e8f 8665 struct perf_buffer *rb;
95ff4ca2
AS
8666 int err;
8667};
8668
8669static void __perf_event_output_stop(struct perf_event *event, void *data)
8670{
8671 struct perf_event *parent = event->parent;
8672 struct remote_output *ro = data;
56de4e8f 8673 struct perf_buffer *rb = ro->rb;
375637bc
AS
8674 struct stop_event_data sd = {
8675 .event = event,
8676 };
95ff4ca2
AS
8677
8678 if (!has_aux(event))
8679 return;
8680
8681 if (!parent)
8682 parent = event;
8683
8684 /*
8685 * In case of inheritance, it will be the parent that links to the
767ae086
AS
8686 * ring-buffer, but it will be the child that's actually using it.
8687 *
8688 * We are using event::rb to determine if the event should be stopped,
8689 * however this may race with ring_buffer_attach() (through set_output),
8690 * which will make us skip the event that actually needs to be stopped.
8691 * So ring_buffer_attach() has to stop an aux event before re-assigning
8692 * its rb pointer.
95ff4ca2
AS
8693 */
8694 if (rcu_dereference(parent->rb) == rb)
375637bc 8695 ro->err = __perf_event_stop(&sd);
95ff4ca2
AS
8696}
8697
8698static int __perf_pmu_output_stop(void *info)
8699{
8700 struct perf_event *event = info;
bd275681 8701 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
95ff4ca2
AS
8702 struct remote_output ro = {
8703 .rb = event->rb,
8704 };
8705
8706 rcu_read_lock();
aab5b71e 8707 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
95ff4ca2 8708 if (cpuctx->task_ctx)
aab5b71e 8709 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
b73e4fef 8710 &ro, false);
95ff4ca2
AS
8711 rcu_read_unlock();
8712
8713 return ro.err;
8714}
8715
8716static void perf_pmu_output_stop(struct perf_event *event)
8717{
8718 struct perf_event *iter;
8719 int err, cpu;
8720
8721restart:
8722 rcu_read_lock();
8723 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
8724 /*
8725 * For per-CPU events, we need to make sure that neither they
8726 * nor their children are running; for cpu==-1 events it's
8727 * sufficient to stop the event itself if it's active, since
8728 * it can't have children.
8729 */
8730 cpu = iter->cpu;
8731 if (cpu == -1)
8732 cpu = READ_ONCE(iter->oncpu);
8733
8734 if (cpu == -1)
8735 continue;
8736
8737 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
8738 if (err == -EAGAIN) {
8739 rcu_read_unlock();
8740 goto restart;
8741 }
8742 }
8743 rcu_read_unlock();
52d857a8
JO
8744}
8745
60313ebe 8746/*
9f498cc5
PZ
8747 * task tracking -- fork/exit
8748 *
13d7a241 8749 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
60313ebe
PZ
8750 */
8751
9f498cc5 8752struct perf_task_event {
3a80b4a3 8753 struct task_struct *task;
cdd6c482 8754 struct perf_event_context *task_ctx;
60313ebe
PZ
8755
8756 struct {
8757 struct perf_event_header header;
8758
8759 u32 pid;
8760 u32 ppid;
9f498cc5
PZ
8761 u32 tid;
8762 u32 ptid;
393b2ad8 8763 u64 time;
cdd6c482 8764 } event_id;
60313ebe
PZ
8765};
8766
67516844
JO
8767static int perf_event_task_match(struct perf_event *event)
8768{
13d7a241
SE
8769 return event->attr.comm || event->attr.mmap ||
8770 event->attr.mmap2 || event->attr.mmap_data ||
8771 event->attr.task;
67516844
JO
8772}
8773
cdd6c482 8774static void perf_event_task_output(struct perf_event *event,
52d857a8 8775 void *data)
60313ebe 8776{
52d857a8 8777 struct perf_task_event *task_event = data;
60313ebe 8778 struct perf_output_handle handle;
c980d109 8779 struct perf_sample_data sample;
9f498cc5 8780 struct task_struct *task = task_event->task;
c980d109 8781 int ret, size = task_event->event_id.header.size;
8bb39f9a 8782
67516844
JO
8783 if (!perf_event_task_match(event))
8784 return;
8785
c980d109 8786 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
60313ebe 8787
267fb273 8788 ret = perf_output_begin(&handle, &sample, event,
a7ac67ea 8789 task_event->event_id.header.size);
ef60777c 8790 if (ret)
c980d109 8791 goto out;
60313ebe 8792
cdd6c482 8793 task_event->event_id.pid = perf_event_pid(event, task);
cdd6c482 8794 task_event->event_id.tid = perf_event_tid(event, task);
f3bed55e
IR
8795
8796 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
8797 task_event->event_id.ppid = perf_event_pid(event,
8798 task->real_parent);
8799 task_event->event_id.ptid = perf_event_pid(event,
8800 task->real_parent);
8801 } else { /* PERF_RECORD_FORK */
8802 task_event->event_id.ppid = perf_event_pid(event, current);
8803 task_event->event_id.ptid = perf_event_tid(event, current);
8804 }
9f498cc5 8805
34f43927
PZ
8806 task_event->event_id.time = perf_event_clock(event);
8807
cdd6c482 8808 perf_output_put(&handle, task_event->event_id);
393b2ad8 8809
c980d109
ACM
8810 perf_event__output_id_sample(event, &handle, &sample);
8811
60313ebe 8812 perf_output_end(&handle);
c980d109
ACM
8813out:
8814 task_event->event_id.header.size = size;
60313ebe
PZ
8815}
8816
cdd6c482
IM
8817static void perf_event_task(struct task_struct *task,
8818 struct perf_event_context *task_ctx,
3a80b4a3 8819 int new)
60313ebe 8820{
9f498cc5 8821 struct perf_task_event task_event;
60313ebe 8822
cdd6c482
IM
8823 if (!atomic_read(&nr_comm_events) &&
8824 !atomic_read(&nr_mmap_events) &&
8825 !atomic_read(&nr_task_events))
60313ebe
PZ
8826 return;
8827
9f498cc5 8828 task_event = (struct perf_task_event){
3a80b4a3
PZ
8829 .task = task,
8830 .task_ctx = task_ctx,
cdd6c482 8831 .event_id = {
60313ebe 8832 .header = {
cdd6c482 8833 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
573402db 8834 .misc = 0,
cdd6c482 8835 .size = sizeof(task_event.event_id),
60313ebe 8836 },
573402db
PZ
8837 /* .pid */
8838 /* .ppid */
9f498cc5
PZ
8839 /* .tid */
8840 /* .ptid */
34f43927 8841 /* .time */
60313ebe
PZ
8842 },
8843 };
8844
aab5b71e 8845 perf_iterate_sb(perf_event_task_output,
52d857a8
JO
8846 &task_event,
8847 task_ctx);
9f498cc5
PZ
8848}
8849
506e64e7
KL
8850/*
8851 * Allocate data for a new task when profiling system-wide
8852 * events which require PMU specific data
8853 */
8854static void
8855perf_event_alloc_task_data(struct task_struct *child,
8856 struct task_struct *parent)
8857{
8858 struct kmem_cache *ctx_cache = NULL;
8859 struct perf_ctx_data *cd;
8860
8861 if (!refcount_read(&global_ctx_data_ref))
8862 return;
8863
8864 scoped_guard (rcu) {
8865 cd = rcu_dereference(parent->perf_ctx_data);
8866 if (cd)
8867 ctx_cache = cd->ctx_cache;
8868 }
8869
8870 if (!ctx_cache)
8871 return;
8872
8873 guard(percpu_read)(&global_ctx_data_rwsem);
8874 scoped_guard (rcu) {
8875 cd = rcu_dereference(child->perf_ctx_data);
8876 if (!cd) {
8877 /*
8878 * A system-wide event may be unaccount,
8879 * when attaching the perf_ctx_data.
8880 */
8881 if (!refcount_read(&global_ctx_data_ref))
8882 return;
8883 goto attach;
8884 }
8885
8886 if (!cd->global) {
8887 cd->global = 1;
8888 refcount_inc(&cd->refcount);
8889 }
8890 }
8891
8892 return;
8893attach:
8894 attach_task_ctx_data(child, ctx_cache, true);
8895}
8896
cdd6c482 8897void perf_event_fork(struct task_struct *task)
9f498cc5 8898{
cdd6c482 8899 perf_event_task(task, NULL, 1);
e4222673 8900 perf_event_namespaces(task);
506e64e7 8901 perf_event_alloc_task_data(task, current);
60313ebe
PZ
8902}
8903
8d1b2d93
PZ
8904/*
8905 * comm tracking
8906 */
8907
8908struct perf_comm_event {
22a4f650
IM
8909 struct task_struct *task;
8910 char *comm;
8d1b2d93
PZ
8911 int comm_size;
8912
8913 struct {
8914 struct perf_event_header header;
8915
8916 u32 pid;
8917 u32 tid;
cdd6c482 8918 } event_id;
8d1b2d93
PZ
8919};
8920
67516844
JO
8921static int perf_event_comm_match(struct perf_event *event)
8922{
8923 return event->attr.comm;
8924}
8925
cdd6c482 8926static void perf_event_comm_output(struct perf_event *event,
52d857a8 8927 void *data)
8d1b2d93 8928{
52d857a8 8929 struct perf_comm_event *comm_event = data;
8d1b2d93 8930 struct perf_output_handle handle;
c980d109 8931 struct perf_sample_data sample;
cdd6c482 8932 int size = comm_event->event_id.header.size;
c980d109
ACM
8933 int ret;
8934
67516844
JO
8935 if (!perf_event_comm_match(event))
8936 return;
8937
c980d109 8938 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
267fb273 8939 ret = perf_output_begin(&handle, &sample, event,
a7ac67ea 8940 comm_event->event_id.header.size);
8d1b2d93
PZ
8941
8942 if (ret)
c980d109 8943 goto out;
8d1b2d93 8944
cdd6c482
IM
8945 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
8946 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
709e50cf 8947
cdd6c482 8948 perf_output_put(&handle, comm_event->event_id);
76369139 8949 __output_copy(&handle, comm_event->comm,
8d1b2d93 8950 comm_event->comm_size);
c980d109
ACM
8951
8952 perf_event__output_id_sample(event, &handle, &sample);
8953
8d1b2d93 8954 perf_output_end(&handle);
c980d109
ACM
8955out:
8956 comm_event->event_id.header.size = size;
8d1b2d93
PZ
8957}
8958
cdd6c482 8959static void perf_event_comm_event(struct perf_comm_event *comm_event)
8d1b2d93 8960{
413ee3b4 8961 char comm[TASK_COMM_LEN];
8d1b2d93 8962 unsigned int size;
8d1b2d93 8963
413ee3b4 8964 memset(comm, 0, sizeof(comm));
fd3f5d38 8965 strscpy(comm, comm_event->task->comm);
888fcee0 8966 size = ALIGN(strlen(comm)+1, sizeof(u64));
8d1b2d93
PZ
8967
8968 comm_event->comm = comm;
8969 comm_event->comm_size = size;
8970
cdd6c482 8971 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8dc85d54 8972
aab5b71e 8973 perf_iterate_sb(perf_event_comm_output,
52d857a8
JO
8974 comm_event,
8975 NULL);
8d1b2d93
PZ
8976}
8977
82b89778 8978void perf_event_comm(struct task_struct *task, bool exec)
8d1b2d93 8979{
9ee318a7
PZ
8980 struct perf_comm_event comm_event;
8981
cdd6c482 8982 if (!atomic_read(&nr_comm_events))
9ee318a7 8983 return;
a63eaf34 8984
9ee318a7 8985 comm_event = (struct perf_comm_event){
8d1b2d93 8986 .task = task,
573402db
PZ
8987 /* .comm */
8988 /* .comm_size */
cdd6c482 8989 .event_id = {
573402db 8990 .header = {
cdd6c482 8991 .type = PERF_RECORD_COMM,
82b89778 8992 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
573402db
PZ
8993 /* .size */
8994 },
8995 /* .pid */
8996 /* .tid */
8d1b2d93
PZ
8997 },
8998 };
8999
cdd6c482 9000 perf_event_comm_event(&comm_event);
8d1b2d93
PZ
9001}
9002
e4222673
HB
9003/*
9004 * namespaces tracking
9005 */
9006
9007struct perf_namespaces_event {
9008 struct task_struct *task;
9009
9010 struct {
9011 struct perf_event_header header;
9012
9013 u32 pid;
9014 u32 tid;
9015 u64 nr_namespaces;
9016 struct perf_ns_link_info link_info[NR_NAMESPACES];
9017 } event_id;
9018};
9019
9020static int perf_event_namespaces_match(struct perf_event *event)
9021{
9022 return event->attr.namespaces;
9023}
9024
9025static void perf_event_namespaces_output(struct perf_event *event,
9026 void *data)
9027{
9028 struct perf_namespaces_event *namespaces_event = data;
9029 struct perf_output_handle handle;
9030 struct perf_sample_data sample;
34900ec5 9031 u16 header_size = namespaces_event->event_id.header.size;
e4222673
HB
9032 int ret;
9033
9034 if (!perf_event_namespaces_match(event))
9035 return;
9036
9037 perf_event_header__init_id(&namespaces_event->event_id.header,
9038 &sample, event);
267fb273 9039 ret = perf_output_begin(&handle, &sample, event,
e4222673
HB
9040 namespaces_event->event_id.header.size);
9041 if (ret)
34900ec5 9042 goto out;
e4222673
HB
9043
9044 namespaces_event->event_id.pid = perf_event_pid(event,
9045 namespaces_event->task);
9046 namespaces_event->event_id.tid = perf_event_tid(event,
9047 namespaces_event->task);
9048
9049 perf_output_put(&handle, namespaces_event->event_id);
9050
9051 perf_event__output_id_sample(event, &handle, &sample);
9052
9053 perf_output_end(&handle);
34900ec5
JO
9054out:
9055 namespaces_event->event_id.header.size = header_size;
e4222673
HB
9056}
9057
9058static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
9059 struct task_struct *task,
9060 const struct proc_ns_operations *ns_ops)
9061{
9062 struct path ns_path;
9063 struct inode *ns_inode;
ce623f89 9064 int error;
e4222673
HB
9065
9066 error = ns_get_path(&ns_path, task, ns_ops);
9067 if (!error) {
9068 ns_inode = ns_path.dentry->d_inode;
9069 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
9070 ns_link_info->ino = ns_inode->i_ino;
0e18dd12 9071 path_put(&ns_path);
e4222673
HB
9072 }
9073}
9074
9075void perf_event_namespaces(struct task_struct *task)
9076{
9077 struct perf_namespaces_event namespaces_event;
9078 struct perf_ns_link_info *ns_link_info;
9079
9080 if (!atomic_read(&nr_namespaces_events))
9081 return;
9082
9083 namespaces_event = (struct perf_namespaces_event){
9084 .task = task,
9085 .event_id = {
9086 .header = {
9087 .type = PERF_RECORD_NAMESPACES,
9088 .misc = 0,
9089 .size = sizeof(namespaces_event.event_id),
9090 },
9091 /* .pid */
9092 /* .tid */
9093 .nr_namespaces = NR_NAMESPACES,
9094 /* .link_info[NR_NAMESPACES] */
9095 },
9096 };
9097
9098 ns_link_info = namespaces_event.event_id.link_info;
9099
9100 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
9101 task, &mntns_operations);
9102
9103#ifdef CONFIG_USER_NS
9104 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
9105 task, &userns_operations);
9106#endif
9107#ifdef CONFIG_NET_NS
9108 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
9109 task, &netns_operations);
9110#endif
9111#ifdef CONFIG_UTS_NS
9112 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
9113 task, &utsns_operations);
9114#endif
9115#ifdef CONFIG_IPC_NS
9116 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
9117 task, &ipcns_operations);
9118#endif
9119#ifdef CONFIG_PID_NS
9120 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
9121 task, &pidns_operations);
9122#endif
9123#ifdef CONFIG_CGROUPS
9124 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
9125 task, &cgroupns_operations);
9126#endif
9127
9128 perf_iterate_sb(perf_event_namespaces_output,
9129 &namespaces_event,
9130 NULL);
9131}
9132
96aaab68
NK
9133/*
9134 * cgroup tracking
9135 */
9136#ifdef CONFIG_CGROUP_PERF
9137
9138struct perf_cgroup_event {
9139 char *path;
9140 int path_size;
9141 struct {
9142 struct perf_event_header header;
9143 u64 id;
9144 char path[];
9145 } event_id;
9146};
9147
9148static int perf_event_cgroup_match(struct perf_event *event)
9149{
9150 return event->attr.cgroup;
9151}
9152
9153static void perf_event_cgroup_output(struct perf_event *event, void *data)
9154{
9155 struct perf_cgroup_event *cgroup_event = data;
9156 struct perf_output_handle handle;
9157 struct perf_sample_data sample;
9158 u16 header_size = cgroup_event->event_id.header.size;
9159 int ret;
9160
9161 if (!perf_event_cgroup_match(event))
9162 return;
9163
9164 perf_event_header__init_id(&cgroup_event->event_id.header,
9165 &sample, event);
267fb273 9166 ret = perf_output_begin(&handle, &sample, event,
96aaab68
NK
9167 cgroup_event->event_id.header.size);
9168 if (ret)
9169 goto out;
9170
9171 perf_output_put(&handle, cgroup_event->event_id);
9172 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
9173
9174 perf_event__output_id_sample(event, &handle, &sample);
9175
9176 perf_output_end(&handle);
9177out:
9178 cgroup_event->event_id.header.size = header_size;
9179}
9180
9181static void perf_event_cgroup(struct cgroup *cgrp)
9182{
9183 struct perf_cgroup_event cgroup_event;
9184 char path_enomem[16] = "//enomem";
9185 char *pathname;
9186 size_t size;
9187
9188 if (!atomic_read(&nr_cgroup_events))
9189 return;
9190
9191 cgroup_event = (struct perf_cgroup_event){
9192 .event_id = {
9193 .header = {
9194 .type = PERF_RECORD_CGROUP,
9195 .misc = 0,
9196 .size = sizeof(cgroup_event.event_id),
9197 },
9198 .id = cgroup_id(cgrp),
9199 },
9200 };
9201
9202 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
9203 if (pathname == NULL) {
9204 cgroup_event.path = path_enomem;
9205 } else {
9206 /* just to be sure to have enough space for alignment */
9207 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
9208 cgroup_event.path = pathname;
9209 }
9210
9211 /*
9212 * Since our buffer works in 8 byte units we need to align our string
9213 * size to a multiple of 8. However, we must guarantee the tail end is
9214 * zero'd out to avoid leaking random bits to userspace.
9215 */
9216 size = strlen(cgroup_event.path) + 1;
9217 while (!IS_ALIGNED(size, sizeof(u64)))
9218 cgroup_event.path[size++] = '\0';
9219
9220 cgroup_event.event_id.header.size += size;
9221 cgroup_event.path_size = size;
9222
9223 perf_iterate_sb(perf_event_cgroup_output,
9224 &cgroup_event,
9225 NULL);
9226
9227 kfree(pathname);
9228}
9229
9230#endif
9231
0a4a9391
PZ
9232/*
9233 * mmap tracking
9234 */
9235
9236struct perf_mmap_event {
089dd79d
PZ
9237 struct vm_area_struct *vma;
9238
9239 const char *file_name;
9240 int file_size;
13d7a241
SE
9241 int maj, min;
9242 u64 ino;
9243 u64 ino_generation;
f972eb63 9244 u32 prot, flags;
88a16a13
JO
9245 u8 build_id[BUILD_ID_SIZE_MAX];
9246 u32 build_id_size;
0a4a9391
PZ
9247
9248 struct {
9249 struct perf_event_header header;
9250
9251 u32 pid;
9252 u32 tid;
9253 u64 start;
9254 u64 len;
9255 u64 pgoff;
cdd6c482 9256 } event_id;
0a4a9391
PZ
9257};
9258
67516844
JO
9259static int perf_event_mmap_match(struct perf_event *event,
9260 void *data)
9261{
9262 struct perf_mmap_event *mmap_event = data;
9263 struct vm_area_struct *vma = mmap_event->vma;
9264 int executable = vma->vm_flags & VM_EXEC;
9265
9266 return (!executable && event->attr.mmap_data) ||
13d7a241 9267 (executable && (event->attr.mmap || event->attr.mmap2));
67516844
JO
9268}
9269
cdd6c482 9270static void perf_event_mmap_output(struct perf_event *event,
52d857a8 9271 void *data)
0a4a9391 9272{
52d857a8 9273 struct perf_mmap_event *mmap_event = data;
0a4a9391 9274 struct perf_output_handle handle;
c980d109 9275 struct perf_sample_data sample;
cdd6c482 9276 int size = mmap_event->event_id.header.size;
d9c1bb2f 9277 u32 type = mmap_event->event_id.header.type;
88a16a13 9278 bool use_build_id;
c980d109 9279 int ret;
0a4a9391 9280
67516844
JO
9281 if (!perf_event_mmap_match(event, data))
9282 return;
9283
13d7a241
SE
9284 if (event->attr.mmap2) {
9285 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
9286 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
9287 mmap_event->event_id.header.size += sizeof(mmap_event->min);
9288 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
d008d525 9289 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
f972eb63
PZ
9290 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
9291 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
13d7a241
SE
9292 }
9293
c980d109 9294 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
267fb273 9295 ret = perf_output_begin(&handle, &sample, event,
a7ac67ea 9296 mmap_event->event_id.header.size);
0a4a9391 9297 if (ret)
c980d109 9298 goto out;
0a4a9391 9299
cdd6c482
IM
9300 mmap_event->event_id.pid = perf_event_pid(event, current);
9301 mmap_event->event_id.tid = perf_event_tid(event, current);
709e50cf 9302
88a16a13
JO
9303 use_build_id = event->attr.build_id && mmap_event->build_id_size;
9304
9305 if (event->attr.mmap2 && use_build_id)
9306 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID;
9307
cdd6c482 9308 perf_output_put(&handle, mmap_event->event_id);
13d7a241
SE
9309
9310 if (event->attr.mmap2) {
88a16a13
JO
9311 if (use_build_id) {
9312 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 };
9313
9314 __output_copy(&handle, size, 4);
9315 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX);
9316 } else {
9317 perf_output_put(&handle, mmap_event->maj);
9318 perf_output_put(&handle, mmap_event->min);
9319 perf_output_put(&handle, mmap_event->ino);
9320 perf_output_put(&handle, mmap_event->ino_generation);
9321 }
f972eb63
PZ
9322 perf_output_put(&handle, mmap_event->prot);
9323 perf_output_put(&handle, mmap_event->flags);
13d7a241
SE
9324 }
9325
76369139 9326 __output_copy(&handle, mmap_event->file_name,
0a4a9391 9327 mmap_event->file_size);
c980d109
ACM
9328
9329 perf_event__output_id_sample(event, &handle, &sample);
9330
78d613eb 9331 perf_output_end(&handle);
c980d109
ACM
9332out:
9333 mmap_event->event_id.header.size = size;
d9c1bb2f 9334 mmap_event->event_id.header.type = type;
0a4a9391
PZ
9335}
9336
cdd6c482 9337static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
0a4a9391 9338{
089dd79d
PZ
9339 struct vm_area_struct *vma = mmap_event->vma;
9340 struct file *file = vma->vm_file;
13d7a241
SE
9341 int maj = 0, min = 0;
9342 u64 ino = 0, gen = 0;
f972eb63 9343 u32 prot = 0, flags = 0;
0a4a9391
PZ
9344 unsigned int size;
9345 char tmp[16];
9346 char *buf = NULL;
549f5c77 9347 char *name = NULL;
413ee3b4 9348
0b3589be
PZ
9349 if (vma->vm_flags & VM_READ)
9350 prot |= PROT_READ;
9351 if (vma->vm_flags & VM_WRITE)
9352 prot |= PROT_WRITE;
9353 if (vma->vm_flags & VM_EXEC)
9354 prot |= PROT_EXEC;
9355
9356 if (vma->vm_flags & VM_MAYSHARE)
9357 flags = MAP_SHARED;
9358 else
9359 flags = MAP_PRIVATE;
9360
0b3589be
PZ
9361 if (vma->vm_flags & VM_LOCKED)
9362 flags |= MAP_LOCKED;
03911132 9363 if (is_vm_hugetlb_page(vma))
0b3589be
PZ
9364 flags |= MAP_HUGETLB;
9365
0a4a9391 9366 if (file) {
13d7a241
SE
9367 struct inode *inode;
9368 dev_t dev;
3ea2f2b9 9369
2c42cfbf 9370 buf = kmalloc(PATH_MAX, GFP_KERNEL);
0a4a9391 9371 if (!buf) {
c7e548b4
ON
9372 name = "//enomem";
9373 goto cpy_name;
0a4a9391 9374 }
413ee3b4 9375 /*
3ea2f2b9 9376 * d_path() works from the end of the rb backwards, so we
413ee3b4
AB
9377 * need to add enough zero bytes after the string to handle
9378 * the 64bit alignment we do later.
9379 */
9bf39ab2 9380 name = file_path(file, buf, PATH_MAX - sizeof(u64));
0a4a9391 9381 if (IS_ERR(name)) {
c7e548b4
ON
9382 name = "//toolong";
9383 goto cpy_name;
0a4a9391 9384 }
13d7a241
SE
9385 inode = file_inode(vma->vm_file);
9386 dev = inode->i_sb->s_dev;
9387 ino = inode->i_ino;
9388 gen = inode->i_generation;
9389 maj = MAJOR(dev);
9390 min = MINOR(dev);
f972eb63 9391
c7e548b4 9392 goto got_name;
0a4a9391 9393 } else {
549f5c77 9394 if (vma->vm_ops && vma->vm_ops->name)
fbe26abe 9395 name = (char *) vma->vm_ops->name(vma);
549f5c77
KW
9396 if (!name)
9397 name = (char *)arch_vma_name(vma);
9398 if (!name) {
9399 if (vma_is_initial_heap(vma))
9400 name = "[heap]";
9401 else if (vma_is_initial_stack(vma))
9402 name = "[stack]";
9403 else
9404 name = "//anon";
fbe26abe 9405 }
0a4a9391
PZ
9406 }
9407
c7e548b4 9408cpy_name:
fd3f5d38 9409 strscpy(tmp, name);
c7e548b4 9410 name = tmp;
0a4a9391 9411got_name:
2c42cfbf
PZ
9412 /*
9413 * Since our buffer works in 8 byte units we need to align our string
9414 * size to a multiple of 8. However, we must guarantee the tail end is
9415 * zero'd out to avoid leaking random bits to userspace.
9416 */
9417 size = strlen(name)+1;
9418 while (!IS_ALIGNED(size, sizeof(u64)))
9419 name[size++] = '\0';
0a4a9391
PZ
9420
9421 mmap_event->file_name = name;
9422 mmap_event->file_size = size;
13d7a241
SE
9423 mmap_event->maj = maj;
9424 mmap_event->min = min;
9425 mmap_event->ino = ino;
9426 mmap_event->ino_generation = gen;
f972eb63
PZ
9427 mmap_event->prot = prot;
9428 mmap_event->flags = flags;
0a4a9391 9429
2fe85427
SE
9430 if (!(vma->vm_flags & VM_EXEC))
9431 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
9432
cdd6c482 9433 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
0a4a9391 9434
88a16a13 9435 if (atomic_read(&nr_build_id_events))
45b8fc30 9436 build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size);
88a16a13 9437
aab5b71e 9438 perf_iterate_sb(perf_event_mmap_output,
52d857a8
JO
9439 mmap_event,
9440 NULL);
665c2142 9441
0a4a9391
PZ
9442 kfree(buf);
9443}
9444
375637bc
AS
9445/*
9446 * Check whether inode and address range match filter criteria.
9447 */
9448static bool perf_addr_filter_match(struct perf_addr_filter *filter,
9449 struct file *file, unsigned long offset,
9450 unsigned long size)
9451{
7f635ff1
MP
9452 /* d_inode(NULL) won't be equal to any mapped user-space file */
9453 if (!filter->path.dentry)
9454 return false;
9455
9511bce9 9456 if (d_inode(filter->path.dentry) != file_inode(file))
375637bc
AS
9457 return false;
9458
9459 if (filter->offset > offset + size)
9460 return false;
9461
9462 if (filter->offset + filter->size < offset)
9463 return false;
9464
9465 return true;
9466}
9467
c60f83b8
AS
9468static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
9469 struct vm_area_struct *vma,
9470 struct perf_addr_filter_range *fr)
9471{
9472 unsigned long vma_size = vma->vm_end - vma->vm_start;
9473 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
9474 struct file *file = vma->vm_file;
9475
9476 if (!perf_addr_filter_match(filter, file, off, vma_size))
9477 return false;
9478
9479 if (filter->offset < off) {
9480 fr->start = vma->vm_start;
9481 fr->size = min(vma_size, filter->size - (off - filter->offset));
9482 } else {
9483 fr->start = vma->vm_start + filter->offset - off;
9484 fr->size = min(vma->vm_end - fr->start, filter->size);
9485 }
9486
9487 return true;
9488}
9489
375637bc
AS
9490static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
9491{
9492 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9493 struct vm_area_struct *vma = data;
375637bc
AS
9494 struct perf_addr_filter *filter;
9495 unsigned int restart = 0, count = 0;
c60f83b8 9496 unsigned long flags;
375637bc
AS
9497
9498 if (!has_addr_filter(event))
9499 return;
9500
c60f83b8 9501 if (!vma->vm_file)
375637bc
AS
9502 return;
9503
9504 raw_spin_lock_irqsave(&ifh->lock, flags);
9505 list_for_each_entry(filter, &ifh->list, entry) {
c60f83b8
AS
9506 if (perf_addr_filter_vma_adjust(filter, vma,
9507 &event->addr_filter_ranges[count]))
375637bc 9508 restart++;
375637bc
AS
9509
9510 count++;
9511 }
9512
9513 if (restart)
9514 event->addr_filters_gen++;
9515 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9516
9517 if (restart)
767ae086 9518 perf_event_stop(event, 1);
375637bc
AS
9519}
9520
9521/*
9522 * Adjust all task's events' filters to the new vma
9523 */
9524static void perf_addr_filters_adjust(struct vm_area_struct *vma)
9525{
9526 struct perf_event_context *ctx;
375637bc 9527
12b40a23
MP
9528 /*
9529 * Data tracing isn't supported yet and as such there is no need
9530 * to keep track of anything that isn't related to executable code:
9531 */
9532 if (!(vma->vm_flags & VM_EXEC))
9533 return;
9534
375637bc 9535 rcu_read_lock();
bd275681
PZ
9536 ctx = rcu_dereference(current->perf_event_ctxp);
9537 if (ctx)
aab5b71e 9538 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
375637bc
AS
9539 rcu_read_unlock();
9540}
9541
3af9e859 9542void perf_event_mmap(struct vm_area_struct *vma)
0a4a9391 9543{
9ee318a7
PZ
9544 struct perf_mmap_event mmap_event;
9545
cdd6c482 9546 if (!atomic_read(&nr_mmap_events))
9ee318a7
PZ
9547 return;
9548
9549 mmap_event = (struct perf_mmap_event){
089dd79d 9550 .vma = vma,
573402db
PZ
9551 /* .file_name */
9552 /* .file_size */
cdd6c482 9553 .event_id = {
573402db 9554 .header = {
cdd6c482 9555 .type = PERF_RECORD_MMAP,
39447b38 9556 .misc = PERF_RECORD_MISC_USER,
573402db
PZ
9557 /* .size */
9558 },
9559 /* .pid */
9560 /* .tid */
089dd79d
PZ
9561 .start = vma->vm_start,
9562 .len = vma->vm_end - vma->vm_start,
3a0304e9 9563 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
0a4a9391 9564 },
13d7a241
SE
9565 /* .maj (attr_mmap2 only) */
9566 /* .min (attr_mmap2 only) */
9567 /* .ino (attr_mmap2 only) */
9568 /* .ino_generation (attr_mmap2 only) */
f972eb63
PZ
9569 /* .prot (attr_mmap2 only) */
9570 /* .flags (attr_mmap2 only) */
0a4a9391
PZ
9571 };
9572
375637bc 9573 perf_addr_filters_adjust(vma);
cdd6c482 9574 perf_event_mmap_event(&mmap_event);
0a4a9391
PZ
9575}
9576
68db7e98
AS
9577void perf_event_aux_event(struct perf_event *event, unsigned long head,
9578 unsigned long size, u64 flags)
9579{
9580 struct perf_output_handle handle;
9581 struct perf_sample_data sample;
9582 struct perf_aux_event {
9583 struct perf_event_header header;
9584 u64 offset;
9585 u64 size;
9586 u64 flags;
9587 } rec = {
9588 .header = {
9589 .type = PERF_RECORD_AUX,
9590 .misc = 0,
9591 .size = sizeof(rec),
9592 },
9593 .offset = head,
9594 .size = size,
9595 .flags = flags,
9596 };
9597 int ret;
9598
9599 perf_event_header__init_id(&rec.header, &sample, event);
267fb273 9600 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
68db7e98
AS
9601
9602 if (ret)
9603 return;
9604
9605 perf_output_put(&handle, rec);
9606 perf_event__output_id_sample(event, &handle, &sample);
9607
9608 perf_output_end(&handle);
9609}
9610
f38b0dbb
KL
9611/*
9612 * Lost/dropped samples logging
9613 */
9614void perf_log_lost_samples(struct perf_event *event, u64 lost)
9615{
9616 struct perf_output_handle handle;
9617 struct perf_sample_data sample;
9618 int ret;
9619
9620 struct {
9621 struct perf_event_header header;
9622 u64 lost;
9623 } lost_samples_event = {
9624 .header = {
9625 .type = PERF_RECORD_LOST_SAMPLES,
9626 .misc = 0,
9627 .size = sizeof(lost_samples_event),
9628 },
9629 .lost = lost,
9630 };
9631
9632 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
9633
267fb273 9634 ret = perf_output_begin(&handle, &sample, event,
f38b0dbb
KL
9635 lost_samples_event.header.size);
9636 if (ret)
9637 return;
9638
9639 perf_output_put(&handle, lost_samples_event);
9640 perf_event__output_id_sample(event, &handle, &sample);
9641 perf_output_end(&handle);
9642}
9643
45ac1403
AH
9644/*
9645 * context_switch tracking
9646 */
9647
9648struct perf_switch_event {
9649 struct task_struct *task;
9650 struct task_struct *next_prev;
9651
9652 struct {
9653 struct perf_event_header header;
9654 u32 next_prev_pid;
9655 u32 next_prev_tid;
9656 } event_id;
9657};
9658
9659static int perf_event_switch_match(struct perf_event *event)
9660{
9661 return event->attr.context_switch;
9662}
9663
9664static void perf_event_switch_output(struct perf_event *event, void *data)
9665{
9666 struct perf_switch_event *se = data;
9667 struct perf_output_handle handle;
9668 struct perf_sample_data sample;
9669 int ret;
9670
9671 if (!perf_event_switch_match(event))
9672 return;
9673
9674 /* Only CPU-wide events are allowed to see next/prev pid/tid */
9675 if (event->ctx->task) {
9676 se->event_id.header.type = PERF_RECORD_SWITCH;
9677 se->event_id.header.size = sizeof(se->event_id.header);
9678 } else {
9679 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
9680 se->event_id.header.size = sizeof(se->event_id);
9681 se->event_id.next_prev_pid =
9682 perf_event_pid(event, se->next_prev);
9683 se->event_id.next_prev_tid =
9684 perf_event_tid(event, se->next_prev);
9685 }
9686
9687 perf_event_header__init_id(&se->event_id.header, &sample, event);
9688
267fb273 9689 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size);
45ac1403
AH
9690 if (ret)
9691 return;
9692
9693 if (event->ctx->task)
9694 perf_output_put(&handle, se->event_id.header);
9695 else
9696 perf_output_put(&handle, se->event_id);
9697
9698 perf_event__output_id_sample(event, &handle, &sample);
9699
9700 perf_output_end(&handle);
9701}
9702
9703static void perf_event_switch(struct task_struct *task,
9704 struct task_struct *next_prev, bool sched_in)
9705{
9706 struct perf_switch_event switch_event;
9707
9708 /* N.B. caller checks nr_switch_events != 0 */
9709
9710 switch_event = (struct perf_switch_event){
9711 .task = task,
9712 .next_prev = next_prev,
9713 .event_id = {
9714 .header = {
9715 /* .type */
9716 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
9717 /* .size */
9718 },
9719 /* .next_prev_pid */
9720 /* .next_prev_tid */
9721 },
9722 };
9723
cd9626e9 9724 if (!sched_in && task_is_runnable(task)) {
101592b4
AB
9725 switch_event.event_id.header.misc |=
9726 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
3ba9f93b 9727 }
101592b4 9728
3ba9f93b 9729 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL);
45ac1403
AH
9730}
9731
a78ac325
PZ
9732/*
9733 * IRQ throttle logging
9734 */
9735
cdd6c482 9736static void perf_log_throttle(struct perf_event *event, int enable)
a78ac325
PZ
9737{
9738 struct perf_output_handle handle;
c980d109 9739 struct perf_sample_data sample;
a78ac325
PZ
9740 int ret;
9741
9742 struct {
9743 struct perf_event_header header;
9744 u64 time;
cca3f454 9745 u64 id;
7f453c24 9746 u64 stream_id;
a78ac325
PZ
9747 } throttle_event = {
9748 .header = {
cdd6c482 9749 .type = PERF_RECORD_THROTTLE,
a78ac325
PZ
9750 .misc = 0,
9751 .size = sizeof(throttle_event),
9752 },
34f43927 9753 .time = perf_event_clock(event),
cdd6c482
IM
9754 .id = primary_event_id(event),
9755 .stream_id = event->id,
a78ac325
PZ
9756 };
9757
966ee4d6 9758 if (enable)
cdd6c482 9759 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
966ee4d6 9760
c980d109
ACM
9761 perf_event_header__init_id(&throttle_event.header, &sample, event);
9762
267fb273 9763 ret = perf_output_begin(&handle, &sample, event,
a7ac67ea 9764 throttle_event.header.size);
a78ac325
PZ
9765 if (ret)
9766 return;
9767
9768 perf_output_put(&handle, throttle_event);
c980d109 9769 perf_event__output_id_sample(event, &handle, &sample);
a78ac325
PZ
9770 perf_output_end(&handle);
9771}
9772
76193a94
SL
9773/*
9774 * ksymbol register/unregister tracking
9775 */
9776
9777struct perf_ksymbol_event {
9778 const char *name;
9779 int name_len;
9780 struct {
9781 struct perf_event_header header;
9782 u64 addr;
9783 u32 len;
9784 u16 ksym_type;
9785 u16 flags;
9786 } event_id;
9787};
9788
9789static int perf_event_ksymbol_match(struct perf_event *event)
9790{
9791 return event->attr.ksymbol;
9792}
9793
9794static void perf_event_ksymbol_output(struct perf_event *event, void *data)
9795{
9796 struct perf_ksymbol_event *ksymbol_event = data;
9797 struct perf_output_handle handle;
9798 struct perf_sample_data sample;
9799 int ret;
9800
9801 if (!perf_event_ksymbol_match(event))
9802 return;
9803
9804 perf_event_header__init_id(&ksymbol_event->event_id.header,
9805 &sample, event);
267fb273 9806 ret = perf_output_begin(&handle, &sample, event,
76193a94
SL
9807 ksymbol_event->event_id.header.size);
9808 if (ret)
9809 return;
9810
9811 perf_output_put(&handle, ksymbol_event->event_id);
9812 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
9813 perf_event__output_id_sample(event, &handle, &sample);
9814
9815 perf_output_end(&handle);
9816}
9817
9818void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
9819 const char *sym)
9820{
9821 struct perf_ksymbol_event ksymbol_event;
9822 char name[KSYM_NAME_LEN];
9823 u16 flags = 0;
9824 int name_len;
9825
9826 if (!atomic_read(&nr_ksymbol_events))
9827 return;
9828
9829 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
9830 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
9831 goto err;
9832
fd3f5d38 9833 strscpy(name, sym);
76193a94
SL
9834 name_len = strlen(name) + 1;
9835 while (!IS_ALIGNED(name_len, sizeof(u64)))
9836 name[name_len++] = '\0';
9837 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
9838
9839 if (unregister)
9840 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
9841
9842 ksymbol_event = (struct perf_ksymbol_event){
9843 .name = name,
9844 .name_len = name_len,
9845 .event_id = {
9846 .header = {
9847 .type = PERF_RECORD_KSYMBOL,
9848 .size = sizeof(ksymbol_event.event_id) +
9849 name_len,
9850 },
9851 .addr = addr,
9852 .len = len,
9853 .ksym_type = ksym_type,
9854 .flags = flags,
9855 },
9856 };
9857
9858 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
9859 return;
9860err:
9861 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
9862}
9863
6ee52e2a
SL
9864/*
9865 * bpf program load/unload tracking
9866 */
9867
9868struct perf_bpf_event {
9869 struct bpf_prog *prog;
9870 struct {
9871 struct perf_event_header header;
9872 u16 type;
9873 u16 flags;
9874 u32 id;
9875 u8 tag[BPF_TAG_SIZE];
9876 } event_id;
9877};
9878
9879static int perf_event_bpf_match(struct perf_event *event)
9880{
9881 return event->attr.bpf_event;
9882}
9883
9884static void perf_event_bpf_output(struct perf_event *event, void *data)
9885{
9886 struct perf_bpf_event *bpf_event = data;
9887 struct perf_output_handle handle;
9888 struct perf_sample_data sample;
9889 int ret;
9890
9891 if (!perf_event_bpf_match(event))
9892 return;
9893
9894 perf_event_header__init_id(&bpf_event->event_id.header,
9895 &sample, event);
eb81a2ed 9896 ret = perf_output_begin(&handle, &sample, event,
6ee52e2a
SL
9897 bpf_event->event_id.header.size);
9898 if (ret)
9899 return;
9900
9901 perf_output_put(&handle, bpf_event->event_id);
9902 perf_event__output_id_sample(event, &handle, &sample);
9903
9904 perf_output_end(&handle);
9905}
9906
9907static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
9908 enum perf_bpf_event_type type)
9909{
9910 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
6ee52e2a
SL
9911 int i;
9912
0be9ae54
HT
9913 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
9914 (u64)(unsigned long)prog->bpf_func,
9915 prog->jited_len, unregister,
9916 prog->aux->ksym.name);
9917
9918 for (i = 1; i < prog->aux->func_cnt; i++) {
9919 struct bpf_prog *subprog = prog->aux->func[i];
9920
9921 perf_event_ksymbol(
9922 PERF_RECORD_KSYMBOL_TYPE_BPF,
9923 (u64)(unsigned long)subprog->bpf_func,
9924 subprog->jited_len, unregister,
9925 subprog->aux->ksym.name);
6ee52e2a
SL
9926 }
9927}
9928
9929void perf_event_bpf_event(struct bpf_prog *prog,
9930 enum perf_bpf_event_type type,
9931 u16 flags)
9932{
9933 struct perf_bpf_event bpf_event;
9934
6ee52e2a
SL
9935 switch (type) {
9936 case PERF_BPF_EVENT_PROG_LOAD:
9937 case PERF_BPF_EVENT_PROG_UNLOAD:
9938 if (atomic_read(&nr_ksymbol_events))
9939 perf_event_bpf_emit_ksymbols(prog, type);
9940 break;
9941 default:
aecaa3ed 9942 return;
6ee52e2a
SL
9943 }
9944
9945 if (!atomic_read(&nr_bpf_events))
9946 return;
9947
9948 bpf_event = (struct perf_bpf_event){
9949 .prog = prog,
9950 .event_id = {
9951 .header = {
9952 .type = PERF_RECORD_BPF_EVENT,
9953 .size = sizeof(bpf_event.event_id),
9954 },
9955 .type = type,
9956 .flags = flags,
9957 .id = prog->aux->id,
9958 },
9959 };
9960
9961 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
9962
9963 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
9964 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
9965}
9966
e17d43b9
AH
9967struct perf_text_poke_event {
9968 const void *old_bytes;
9969 const void *new_bytes;
9970 size_t pad;
9971 u16 old_len;
9972 u16 new_len;
9973
9974 struct {
9975 struct perf_event_header header;
9976
9977 u64 addr;
9978 } event_id;
9979};
9980
9981static int perf_event_text_poke_match(struct perf_event *event)
9982{
9983 return event->attr.text_poke;
9984}
9985
9986static void perf_event_text_poke_output(struct perf_event *event, void *data)
9987{
9988 struct perf_text_poke_event *text_poke_event = data;
9989 struct perf_output_handle handle;
9990 struct perf_sample_data sample;
9991 u64 padding = 0;
9992 int ret;
9993
9994 if (!perf_event_text_poke_match(event))
9995 return;
9996
9997 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event);
9998
267fb273
PZ
9999 ret = perf_output_begin(&handle, &sample, event,
10000 text_poke_event->event_id.header.size);
e17d43b9
AH
10001 if (ret)
10002 return;
10003
10004 perf_output_put(&handle, text_poke_event->event_id);
10005 perf_output_put(&handle, text_poke_event->old_len);
10006 perf_output_put(&handle, text_poke_event->new_len);
10007
10008 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len);
10009 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len);
10010
10011 if (text_poke_event->pad)
10012 __output_copy(&handle, &padding, text_poke_event->pad);
10013
10014 perf_event__output_id_sample(event, &handle, &sample);
10015
10016 perf_output_end(&handle);
10017}
10018
10019void perf_event_text_poke(const void *addr, const void *old_bytes,
10020 size_t old_len, const void *new_bytes, size_t new_len)
10021{
10022 struct perf_text_poke_event text_poke_event;
10023 size_t tot, pad;
10024
10025 if (!atomic_read(&nr_text_poke_events))
10026 return;
10027
10028 tot = sizeof(text_poke_event.old_len) + old_len;
10029 tot += sizeof(text_poke_event.new_len) + new_len;
10030 pad = ALIGN(tot, sizeof(u64)) - tot;
10031
10032 text_poke_event = (struct perf_text_poke_event){
10033 .old_bytes = old_bytes,
10034 .new_bytes = new_bytes,
10035 .pad = pad,
10036 .old_len = old_len,
10037 .new_len = new_len,
10038 .event_id = {
10039 .header = {
10040 .type = PERF_RECORD_TEXT_POKE,
10041 .misc = PERF_RECORD_MISC_KERNEL,
10042 .size = sizeof(text_poke_event.event_id) + tot + pad,
10043 },
10044 .addr = (unsigned long)addr,
10045 },
10046 };
10047
10048 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL);
10049}
10050
8d4e6c4c
AS
10051void perf_event_itrace_started(struct perf_event *event)
10052{
d20eb2d5 10053 WRITE_ONCE(event->attach_state, event->attach_state | PERF_ATTACH_ITRACE);
8d4e6c4c
AS
10054}
10055
ec0d7729
AS
10056static void perf_log_itrace_start(struct perf_event *event)
10057{
10058 struct perf_output_handle handle;
10059 struct perf_sample_data sample;
10060 struct perf_aux_event {
10061 struct perf_event_header header;
10062 u32 pid;
10063 u32 tid;
10064 } rec;
10065 int ret;
10066
10067 if (event->parent)
10068 event = event->parent;
10069
10070 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8d4e6c4c 10071 event->attach_state & PERF_ATTACH_ITRACE)
ec0d7729
AS
10072 return;
10073
ec0d7729
AS
10074 rec.header.type = PERF_RECORD_ITRACE_START;
10075 rec.header.misc = 0;
10076 rec.header.size = sizeof(rec);
10077 rec.pid = perf_event_pid(event, current);
10078 rec.tid = perf_event_tid(event, current);
10079
10080 perf_event_header__init_id(&rec.header, &sample, event);
267fb273 10081 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
ec0d7729
AS
10082
10083 if (ret)
10084 return;
10085
10086 perf_output_put(&handle, rec);
10087 perf_event__output_id_sample(event, &handle, &sample);
10088
10089 perf_output_end(&handle);
10090}
10091
8b8ff8cc
AH
10092void perf_report_aux_output_id(struct perf_event *event, u64 hw_id)
10093{
10094 struct perf_output_handle handle;
10095 struct perf_sample_data sample;
10096 struct perf_aux_event {
10097 struct perf_event_header header;
10098 u64 hw_id;
10099 } rec;
10100 int ret;
10101
10102 if (event->parent)
10103 event = event->parent;
10104
10105 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID;
10106 rec.header.misc = 0;
10107 rec.header.size = sizeof(rec);
10108 rec.hw_id = hw_id;
10109
10110 perf_event_header__init_id(&rec.header, &sample, event);
10111 ret = perf_output_begin(&handle, &sample, event, rec.header.size);
10112
10113 if (ret)
10114 return;
10115
10116 perf_output_put(&handle, rec);
10117 perf_event__output_id_sample(event, &handle, &sample);
10118
10119 perf_output_end(&handle);
10120}
7d30d480 10121EXPORT_SYMBOL_GPL(perf_report_aux_output_id);
8b8ff8cc 10122
475113d9
JO
10123static int
10124__perf_event_account_interrupt(struct perf_event *event, int throttle)
f6c7d5fe 10125{
cdd6c482 10126 struct hw_perf_event *hwc = &event->hw;
79f14641 10127 int ret = 0;
475113d9 10128 u64 seq;
96398826 10129
e050e3f0
SE
10130 seq = __this_cpu_read(perf_throttled_seq);
10131 if (seq != hwc->interrupts_seq) {
10132 hwc->interrupts_seq = seq;
10133 hwc->interrupts = 1;
10134 } else {
10135 hwc->interrupts++;
f51972e6
QW
10136 }
10137
10138 if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) {
10139 __this_cpu_inc(perf_throttled_count);
10140 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
9734e25f 10141 perf_event_throttle_group(event);
f51972e6 10142 ret = 1;
e050e3f0 10143 }
60db5e09 10144
cdd6c482 10145 if (event->attr.freq) {
def0a9b2 10146 u64 now = perf_clock();
abd50713 10147 s64 delta = now - hwc->freq_time_stamp;
bd2b5b12 10148
abd50713 10149 hwc->freq_time_stamp = now;
bd2b5b12 10150
abd50713 10151 if (delta > 0 && delta < 2*TICK_NSEC)
f39d47ff 10152 perf_adjust_period(event, delta, hwc->last_period, true);
bd2b5b12
PZ
10153 }
10154
475113d9
JO
10155 return ret;
10156}
10157
10158int perf_event_account_interrupt(struct perf_event *event)
10159{
10160 return __perf_event_account_interrupt(event, 1);
10161}
10162
030a976e
PZ
10163static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs)
10164{
10165 /*
10166 * Due to interrupt latency (AKA "skid"), we may enter the
10167 * kernel before taking an overflow, even if the PMU is only
10168 * counting user events.
10169 */
10170 if (event->attr.exclude_kernel && !user_mode(regs))
10171 return false;
10172
10173 return true;
10174}
10175
4c03fe11 10176#ifdef CONFIG_BPF_SYSCALL
f11f10bf
KH
10177static int bpf_overflow_handler(struct perf_event *event,
10178 struct perf_sample_data *data,
10179 struct pt_regs *regs)
4c03fe11
KH
10180{
10181 struct bpf_perf_event_data_kern ctx = {
10182 .data = data,
10183 .event = event,
10184 };
10185 struct bpf_prog *prog;
10186 int ret = 0;
10187
10188 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
10189 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
10190 goto out;
10191 rcu_read_lock();
10192 prog = READ_ONCE(event->prog);
10193 if (prog) {
10194 perf_prepare_sample(data, event, regs);
10195 ret = bpf_prog_run(prog, &ctx);
10196 }
10197 rcu_read_unlock();
10198out:
10199 __this_cpu_dec(bpf_prog_active);
4c03fe11 10200
f11f10bf 10201 return ret;
4c03fe11
KH
10202}
10203
854dd99b
IM
10204static inline int perf_event_set_bpf_handler(struct perf_event *event,
10205 struct bpf_prog *prog,
10206 u64 bpf_cookie)
4c03fe11
KH
10207{
10208 if (event->overflow_handler_context)
10209 /* hw breakpoint or kernel counter */
10210 return -EINVAL;
10211
10212 if (event->prog)
10213 return -EEXIST;
10214
10215 if (prog->type != BPF_PROG_TYPE_PERF_EVENT)
10216 return -EINVAL;
10217
10218 if (event->attr.precise_ip &&
10219 prog->call_get_stack &&
10220 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) ||
10221 event->attr.exclude_callchain_kernel ||
10222 event->attr.exclude_callchain_user)) {
10223 /*
10224 * On perf_event with precise_ip, calling bpf_get_stack()
10225 * may trigger unwinder warnings and occasional crashes.
10226 * bpf_get_[stack|stackid] works around this issue by using
10227 * callchain attached to perf_sample_data. If the
10228 * perf_event does not full (kernel and user) callchain
10229 * attached to perf_sample_data, do not allow attaching BPF
10230 * program that calls bpf_get_[stack|stackid].
10231 */
10232 return -EPROTO;
10233 }
10234
10235 event->prog = prog;
10236 event->bpf_cookie = bpf_cookie;
4c03fe11
KH
10237 return 0;
10238}
10239
854dd99b 10240static inline void perf_event_free_bpf_handler(struct perf_event *event)
4c03fe11
KH
10241{
10242 struct bpf_prog *prog = event->prog;
10243
10244 if (!prog)
10245 return;
10246
4c03fe11
KH
10247 event->prog = NULL;
10248 bpf_prog_put(prog);
10249}
10250#else
93d3fde7
IM
10251static inline int bpf_overflow_handler(struct perf_event *event,
10252 struct perf_sample_data *data,
10253 struct pt_regs *regs)
924d9343 10254{
f11f10bf 10255 return 1;
924d9343
KH
10256}
10257
93d3fde7
IM
10258static inline int perf_event_set_bpf_handler(struct perf_event *event,
10259 struct bpf_prog *prog,
10260 u64 bpf_cookie)
4c03fe11
KH
10261{
10262 return -EOPNOTSUPP;
10263}
10264
93d3fde7 10265static inline void perf_event_free_bpf_handler(struct perf_event *event)
4c03fe11
KH
10266{
10267}
10268#endif
10269
475113d9
JO
10270/*
10271 * Generic event overflow handling, sampling.
10272 */
10273
10274static int __perf_event_overflow(struct perf_event *event,
ca6c2132
PZ
10275 int throttle, struct perf_sample_data *data,
10276 struct pt_regs *regs)
475113d9
JO
10277{
10278 int events = atomic_read(&event->event_limit);
10279 int ret = 0;
10280
10281 /*
10282 * Non-sampling counters might still use the PMI to fold short
10283 * hardware counters, ignore those.
10284 */
10285 if (unlikely(!is_sampling_event(event)))
10286 return 0;
10287
10288 ret = __perf_event_account_interrupt(event, throttle);
cc1582c2 10289
18d92bb5
AH
10290 if (event->attr.aux_pause)
10291 perf_event_aux_pause(event->aux_event, true);
10292
100bff23
KH
10293 if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT &&
10294 !bpf_overflow_handler(event, data, regs))
18d92bb5 10295 goto out;
c4fcc7d1 10296
2023b359
PZ
10297 /*
10298 * XXX event_limit might not quite work as expected on inherited
cdd6c482 10299 * events
2023b359
PZ
10300 */
10301
cdd6c482
IM
10302 event->pending_kill = POLL_IN;
10303 if (events && atomic_dec_and_test(&event->event_limit)) {
79f14641 10304 ret = 1;
cdd6c482 10305 event->pending_kill = POLL_HUP;
5aab90ce 10306 perf_event_disable_inatomic(event);
79f14641
PZ
10307 }
10308
ca6c2132 10309 if (event->attr.sigtrap) {
030a976e
PZ
10310 /*
10311 * The desired behaviour of sigtrap vs invalid samples is a bit
10312 * tricky; on the one hand, one should not loose the SIGTRAP if
10313 * it is the first event, on the other hand, we should also not
10314 * trigger the WARN or override the data address.
10315 */
10316 bool valid_sample = sample_is_allowed(event, regs);
bb88f969 10317 unsigned int pending_id = 1;
c5d93d23 10318 enum task_work_notify_mode notify_mode;
bb88f969
ME
10319
10320 if (regs)
10321 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1;
c5d93d23
SAS
10322
10323 notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME;
10324
10325 if (!event->pending_work &&
10326 !task_work_add(current, &event->pending_task, notify_mode)) {
10327 event->pending_work = pending_id;
79bd2330 10328 local_inc(&event->ctx->nr_no_switch_fast);
56799bc0 10329 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount));
058244c6
SAS
10330
10331 event->pending_addr = 0;
10332 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR))
10333 event->pending_addr = data->addr;
c5d93d23 10334
030a976e 10335 } else if (event->attr.exclude_kernel && valid_sample) {
bb88f969
ME
10336 /*
10337 * Should not be able to return to user space without
c5d93d23 10338 * consuming pending_work; with exceptions:
bb88f969
ME
10339 *
10340 * 1. Where !exclude_kernel, events can overflow again
10341 * in the kernel without returning to user space.
10342 *
10343 * 2. Events that can overflow again before the IRQ-
10344 * work without user space progress (e.g. hrtimer).
10345 * To approximate progress (with false negatives),
10346 * check 32-bit hash of the current IP.
10347 */
c5d93d23 10348 WARN_ON_ONCE(event->pending_work != pending_id);
ca6c2132 10349 }
ca6c2132
PZ
10350 }
10351
c4fcc7d1 10352 READ_ONCE(event->overflow_handler)(event, data, regs);
453f19ee 10353
fed66e2c 10354 if (*perf_event_fasync(event) && event->pending_kill) {
a8b0ca17 10355 event->pending_wakeup = 1;
ca6c2132 10356 irq_work_queue(&event->pending_irq);
f506b3dc 10357 }
18d92bb5
AH
10358out:
10359 if (event->attr.aux_resume)
10360 perf_event_aux_pause(event->aux_event, false);
f506b3dc 10361
79f14641 10362 return ret;
f6c7d5fe
PZ
10363}
10364
a8b0ca17 10365int perf_event_overflow(struct perf_event *event,
ca6c2132
PZ
10366 struct perf_sample_data *data,
10367 struct pt_regs *regs)
850bc73f 10368{
a8b0ca17 10369 return __perf_event_overflow(event, 1, data, regs);
850bc73f
PZ
10370}
10371
15dbf27c 10372/*
cdd6c482 10373 * Generic software event infrastructure
15dbf27c
PZ
10374 */
10375
b28ab83c
PZ
10376struct swevent_htable {
10377 struct swevent_hlist *swevent_hlist;
10378 struct mutex hlist_mutex;
10379 int hlist_refcount;
b28ab83c 10380};
b28ab83c
PZ
10381static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
10382
7b4b6658 10383/*
cdd6c482
IM
10384 * We directly increment event->count and keep a second value in
10385 * event->hw.period_left to count intervals. This period event
7b4b6658
PZ
10386 * is kept in the range [-sample_period, 0] so that we can use the
10387 * sign as trigger.
10388 */
10389
ab573844 10390u64 perf_swevent_set_period(struct perf_event *event)
15dbf27c 10391{
cdd6c482 10392 struct hw_perf_event *hwc = &event->hw;
7b4b6658
PZ
10393 u64 period = hwc->last_period;
10394 u64 nr, offset;
10395 s64 old, val;
10396
10397 hwc->last_period = hwc->sample_period;
15dbf27c 10398
28fd85a1
UB
10399 old = local64_read(&hwc->period_left);
10400 do {
10401 val = old;
10402 if (val < 0)
10403 return 0;
15dbf27c 10404
28fd85a1
UB
10405 nr = div64_u64(period + val, period);
10406 offset = nr * period;
10407 val -= offset;
10408 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val));
15dbf27c 10409
7b4b6658 10410 return nr;
15dbf27c
PZ
10411}
10412
0cff784a 10413static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
a8b0ca17 10414 struct perf_sample_data *data,
5622f295 10415 struct pt_regs *regs)
15dbf27c 10416{
cdd6c482 10417 struct hw_perf_event *hwc = &event->hw;
850bc73f 10418 int throttle = 0;
15dbf27c 10419
0cff784a
PZ
10420 if (!overflow)
10421 overflow = perf_swevent_set_period(event);
15dbf27c 10422
7b4b6658
PZ
10423 if (hwc->interrupts == MAX_INTERRUPTS)
10424 return;
15dbf27c 10425
7b4b6658 10426 for (; overflow; overflow--) {
a8b0ca17 10427 if (__perf_event_overflow(event, throttle,
5622f295 10428 data, regs)) {
7b4b6658
PZ
10429 /*
10430 * We inhibit the overflow from happening when
10431 * hwc->interrupts == MAX_INTERRUPTS.
10432 */
10433 break;
10434 }
cf450a73 10435 throttle = 1;
7b4b6658 10436 }
15dbf27c
PZ
10437}
10438
a4eaf7f1 10439static void perf_swevent_event(struct perf_event *event, u64 nr,
a8b0ca17 10440 struct perf_sample_data *data,
5622f295 10441 struct pt_regs *regs)
7b4b6658 10442{
cdd6c482 10443 struct hw_perf_event *hwc = &event->hw;
d6d020e9 10444
e7850595 10445 local64_add(nr, &event->count);
d6d020e9 10446
0cff784a
PZ
10447 if (!regs)
10448 return;
10449
6c7e550f 10450 if (!is_sampling_event(event))
7b4b6658 10451 return;
d6d020e9 10452
5d81e5cf
AV
10453 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
10454 data->period = nr;
10455 return perf_swevent_overflow(event, 1, data, regs);
10456 } else
10457 data->period = event->hw.last_period;
10458
0cff784a 10459 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
a8b0ca17 10460 return perf_swevent_overflow(event, 1, data, regs);
0cff784a 10461
e7850595 10462 if (local64_add_negative(nr, &hwc->period_left))
7b4b6658 10463 return;
df1a132b 10464
a8b0ca17 10465 perf_swevent_overflow(event, 0, data, regs);
d6d020e9
PZ
10466}
10467
6057b90e 10468int perf_exclude_event(struct perf_event *event, struct pt_regs *regs)
f5ffe02e 10469{
a4eaf7f1 10470 if (event->hw.state & PERF_HES_STOPPED)
91b2f482 10471 return 1;
a4eaf7f1 10472
f5ffe02e
FW
10473 if (regs) {
10474 if (event->attr.exclude_user && user_mode(regs))
10475 return 1;
10476
10477 if (event->attr.exclude_kernel && !user_mode(regs))
10478 return 1;
10479 }
10480
10481 return 0;
10482}
10483
cdd6c482 10484static int perf_swevent_match(struct perf_event *event,
1c432d89 10485 enum perf_type_id type,
6fb2915d
LZ
10486 u32 event_id,
10487 struct perf_sample_data *data,
10488 struct pt_regs *regs)
15dbf27c 10489{
cdd6c482 10490 if (event->attr.type != type)
a21ca2ca 10491 return 0;
f5ffe02e 10492
cdd6c482 10493 if (event->attr.config != event_id)
15dbf27c
PZ
10494 return 0;
10495
f5ffe02e
FW
10496 if (perf_exclude_event(event, regs))
10497 return 0;
15dbf27c
PZ
10498
10499 return 1;
10500}
10501
76e1d904
FW
10502static inline u64 swevent_hash(u64 type, u32 event_id)
10503{
10504 u64 val = event_id | (type << 32);
10505
10506 return hash_64(val, SWEVENT_HLIST_BITS);
10507}
10508
49f135ed
FW
10509static inline struct hlist_head *
10510__find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
76e1d904 10511{
49f135ed
FW
10512 u64 hash = swevent_hash(type, event_id);
10513
10514 return &hlist->heads[hash];
10515}
76e1d904 10516
49f135ed
FW
10517/* For the read side: events when they trigger */
10518static inline struct hlist_head *
b28ab83c 10519find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
49f135ed
FW
10520{
10521 struct swevent_hlist *hlist;
76e1d904 10522
b28ab83c 10523 hlist = rcu_dereference(swhash->swevent_hlist);
76e1d904
FW
10524 if (!hlist)
10525 return NULL;
10526
49f135ed
FW
10527 return __find_swevent_head(hlist, type, event_id);
10528}
10529
10530/* For the event head insertion and removal in the hlist */
10531static inline struct hlist_head *
b28ab83c 10532find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
49f135ed
FW
10533{
10534 struct swevent_hlist *hlist;
10535 u32 event_id = event->attr.config;
10536 u64 type = event->attr.type;
10537
10538 /*
10539 * Event scheduling is always serialized against hlist allocation
10540 * and release. Which makes the protected version suitable here.
10541 * The context lock guarantees that.
10542 */
b28ab83c 10543 hlist = rcu_dereference_protected(swhash->swevent_hlist,
49f135ed
FW
10544 lockdep_is_held(&event->ctx->lock));
10545 if (!hlist)
10546 return NULL;
10547
10548 return __find_swevent_head(hlist, type, event_id);
76e1d904
FW
10549}
10550
10551static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
a8b0ca17 10552 u64 nr,
76e1d904
FW
10553 struct perf_sample_data *data,
10554 struct pt_regs *regs)
15dbf27c 10555{
4a32fea9 10556 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
cdd6c482 10557 struct perf_event *event;
76e1d904 10558 struct hlist_head *head;
15dbf27c 10559
76e1d904 10560 rcu_read_lock();
b28ab83c 10561 head = find_swevent_head_rcu(swhash, type, event_id);
76e1d904
FW
10562 if (!head)
10563 goto end;
10564
b67bfe0d 10565 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6fb2915d 10566 if (perf_swevent_match(event, type, event_id, data, regs))
a8b0ca17 10567 perf_swevent_event(event, nr, data, regs);
15dbf27c 10568 }
76e1d904
FW
10569end:
10570 rcu_read_unlock();
15dbf27c
PZ
10571}
10572
86038c5e
PZI
10573DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
10574
4ed7c92d 10575int perf_swevent_get_recursion_context(void)
96f6d444 10576{
0d40a6d8 10577 return get_recursion_context(current->perf_recursion);
96f6d444 10578}
645e8cc0 10579EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
96f6d444 10580
98b5c2c6 10581void perf_swevent_put_recursion_context(int rctx)
15dbf27c 10582{
0d40a6d8 10583 put_recursion_context(current->perf_recursion, rctx);
ce71b9df 10584}
15dbf27c 10585
86038c5e 10586void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
b8e83514 10587{
a4234bfc 10588 struct perf_sample_data data;
4ed7c92d 10589
86038c5e 10590 if (WARN_ON_ONCE(!regs))
4ed7c92d 10591 return;
a4234bfc 10592
fd0d000b 10593 perf_sample_data_init(&data, addr, 0);
a8b0ca17 10594 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
86038c5e
PZI
10595}
10596
10597void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
10598{
10599 int rctx;
10600
10601 preempt_disable_notrace();
10602 rctx = perf_swevent_get_recursion_context();
10603 if (unlikely(rctx < 0))
10604 goto fail;
10605
10606 ___perf_sw_event(event_id, nr, regs, addr);
4ed7c92d
PZ
10607
10608 perf_swevent_put_recursion_context(rctx);
86038c5e 10609fail:
1c024eca 10610 preempt_enable_notrace();
b8e83514
PZ
10611}
10612
cdd6c482 10613static void perf_swevent_read(struct perf_event *event)
15dbf27c 10614{
15dbf27c
PZ
10615}
10616
a4eaf7f1 10617static int perf_swevent_add(struct perf_event *event, int flags)
15dbf27c 10618{
4a32fea9 10619 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
cdd6c482 10620 struct hw_perf_event *hwc = &event->hw;
76e1d904
FW
10621 struct hlist_head *head;
10622
6c7e550f 10623 if (is_sampling_event(event)) {
7b4b6658 10624 hwc->last_period = hwc->sample_period;
cdd6c482 10625 perf_swevent_set_period(event);
7b4b6658 10626 }
76e1d904 10627
a4eaf7f1
PZ
10628 hwc->state = !(flags & PERF_EF_START);
10629
b28ab83c 10630 head = find_swevent_head(swhash, event);
12ca6ad2 10631 if (WARN_ON_ONCE(!head))
76e1d904
FW
10632 return -EINVAL;
10633
10634 hlist_add_head_rcu(&event->hlist_entry, head);
6a694a60 10635 perf_event_update_userpage(event);
76e1d904 10636
15dbf27c
PZ
10637 return 0;
10638}
10639
a4eaf7f1 10640static void perf_swevent_del(struct perf_event *event, int flags)
15dbf27c 10641{
76e1d904 10642 hlist_del_rcu(&event->hlist_entry);
15dbf27c
PZ
10643}
10644
a4eaf7f1 10645static void perf_swevent_start(struct perf_event *event, int flags)
5c92d124 10646{
a4eaf7f1 10647 event->hw.state = 0;
d6d020e9 10648}
aa9c4c0f 10649
a4eaf7f1 10650static void perf_swevent_stop(struct perf_event *event, int flags)
d6d020e9 10651{
a4eaf7f1 10652 event->hw.state = PERF_HES_STOPPED;
bae43c99
IM
10653}
10654
49f135ed
FW
10655/* Deref the hlist from the update side */
10656static inline struct swevent_hlist *
b28ab83c 10657swevent_hlist_deref(struct swevent_htable *swhash)
49f135ed 10658{
b28ab83c
PZ
10659 return rcu_dereference_protected(swhash->swevent_hlist,
10660 lockdep_is_held(&swhash->hlist_mutex));
49f135ed
FW
10661}
10662
b28ab83c 10663static void swevent_hlist_release(struct swevent_htable *swhash)
76e1d904 10664{
b28ab83c 10665 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
76e1d904 10666
49f135ed 10667 if (!hlist)
76e1d904
FW
10668 return;
10669
70691d4a 10670 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
fa4bbc4c 10671 kfree_rcu(hlist, rcu_head);
76e1d904
FW
10672}
10673
3b364d7b 10674static void swevent_hlist_put_cpu(int cpu)
76e1d904 10675{
b28ab83c 10676 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
76e1d904 10677
b28ab83c 10678 mutex_lock(&swhash->hlist_mutex);
76e1d904 10679
b28ab83c
PZ
10680 if (!--swhash->hlist_refcount)
10681 swevent_hlist_release(swhash);
76e1d904 10682
b28ab83c 10683 mutex_unlock(&swhash->hlist_mutex);
76e1d904
FW
10684}
10685
3b364d7b 10686static void swevent_hlist_put(void)
76e1d904
FW
10687{
10688 int cpu;
10689
76e1d904 10690 for_each_possible_cpu(cpu)
3b364d7b 10691 swevent_hlist_put_cpu(cpu);
76e1d904
FW
10692}
10693
3b364d7b 10694static int swevent_hlist_get_cpu(int cpu)
76e1d904 10695{
b28ab83c 10696 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
76e1d904
FW
10697 int err = 0;
10698
b28ab83c 10699 mutex_lock(&swhash->hlist_mutex);
a63fbed7
TG
10700 if (!swevent_hlist_deref(swhash) &&
10701 cpumask_test_cpu(cpu, perf_online_mask)) {
76e1d904
FW
10702 struct swevent_hlist *hlist;
10703
10704 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
10705 if (!hlist) {
10706 err = -ENOMEM;
10707 goto exit;
10708 }
b28ab83c 10709 rcu_assign_pointer(swhash->swevent_hlist, hlist);
76e1d904 10710 }
b28ab83c 10711 swhash->hlist_refcount++;
9ed6060d 10712exit:
b28ab83c 10713 mutex_unlock(&swhash->hlist_mutex);
76e1d904
FW
10714
10715 return err;
10716}
10717
3b364d7b 10718static int swevent_hlist_get(void)
76e1d904 10719{
3b364d7b 10720 int err, cpu, failed_cpu;
76e1d904 10721
a63fbed7 10722 mutex_lock(&pmus_lock);
76e1d904 10723 for_each_possible_cpu(cpu) {
3b364d7b 10724 err = swevent_hlist_get_cpu(cpu);
76e1d904
FW
10725 if (err) {
10726 failed_cpu = cpu;
10727 goto fail;
10728 }
10729 }
a63fbed7 10730 mutex_unlock(&pmus_lock);
76e1d904 10731 return 0;
9ed6060d 10732fail:
76e1d904
FW
10733 for_each_possible_cpu(cpu) {
10734 if (cpu == failed_cpu)
10735 break;
3b364d7b 10736 swevent_hlist_put_cpu(cpu);
76e1d904 10737 }
a63fbed7 10738 mutex_unlock(&pmus_lock);
76e1d904
FW
10739 return err;
10740}
10741
c5905afb 10742struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
95476b64 10743
b0a873eb
PZ
10744static void sw_perf_event_destroy(struct perf_event *event)
10745{
10746 u64 event_id = event->attr.config;
95476b64 10747
b0a873eb
PZ
10748 WARN_ON(event->parent);
10749
c5905afb 10750 static_key_slow_dec(&perf_swevent_enabled[event_id]);
3b364d7b 10751 swevent_hlist_put();
b0a873eb
PZ
10752}
10753
0d6d062c
RB
10754static struct pmu perf_cpu_clock; /* fwd declaration */
10755static struct pmu perf_task_clock;
10756
b0a873eb
PZ
10757static int perf_swevent_init(struct perf_event *event)
10758{
8176cced 10759 u64 event_id = event->attr.config;
b0a873eb
PZ
10760
10761 if (event->attr.type != PERF_TYPE_SOFTWARE)
10762 return -ENOENT;
10763
2481c5fa
SE
10764 /*
10765 * no branch sampling for software events
10766 */
10767 if (has_branch_stack(event))
10768 return -EOPNOTSUPP;
10769
b0a873eb
PZ
10770 switch (event_id) {
10771 case PERF_COUNT_SW_CPU_CLOCK:
0d6d062c
RB
10772 event->attr.type = perf_cpu_clock.type;
10773 return -ENOENT;
b0a873eb 10774 case PERF_COUNT_SW_TASK_CLOCK:
0d6d062c 10775 event->attr.type = perf_task_clock.type;
b0a873eb
PZ
10776 return -ENOENT;
10777
10778 default:
10779 break;
10780 }
10781
ce677831 10782 if (event_id >= PERF_COUNT_SW_MAX)
b0a873eb
PZ
10783 return -ENOENT;
10784
10785 if (!event->parent) {
10786 int err;
10787
3b364d7b 10788 err = swevent_hlist_get();
b0a873eb
PZ
10789 if (err)
10790 return err;
10791
c5905afb 10792 static_key_slow_inc(&perf_swevent_enabled[event_id]);
b0a873eb
PZ
10793 event->destroy = sw_perf_event_destroy;
10794 }
10795
10796 return 0;
10797}
10798
10799static struct pmu perf_swevent = {
89a1e187 10800 .task_ctx_nr = perf_sw_context,
95476b64 10801
34f43927
PZ
10802 .capabilities = PERF_PMU_CAP_NO_NMI,
10803
b0a873eb 10804 .event_init = perf_swevent_init,
a4eaf7f1
PZ
10805 .add = perf_swevent_add,
10806 .del = perf_swevent_del,
10807 .start = perf_swevent_start,
10808 .stop = perf_swevent_stop,
1c024eca 10809 .read = perf_swevent_read,
1c024eca
PZ
10810};
10811
b0a873eb
PZ
10812#ifdef CONFIG_EVENT_TRACING
10813
571f97f7
RB
10814static void tp_perf_event_destroy(struct perf_event *event)
10815{
10816 perf_trace_destroy(event);
10817}
10818
10819static int perf_tp_event_init(struct perf_event *event)
10820{
10821 int err;
10822
10823 if (event->attr.type != PERF_TYPE_TRACEPOINT)
10824 return -ENOENT;
10825
10826 /*
10827 * no branch sampling for tracepoint events
10828 */
10829 if (has_branch_stack(event))
10830 return -EOPNOTSUPP;
10831
10832 err = perf_trace_init(event);
10833 if (err)
10834 return err;
10835
10836 event->destroy = tp_perf_event_destroy;
10837
10838 return 0;
10839}
10840
10841static struct pmu perf_tracepoint = {
10842 .task_ctx_nr = perf_sw_context,
10843
10844 .event_init = perf_tp_event_init,
10845 .add = perf_trace_add,
10846 .del = perf_trace_del,
10847 .start = perf_swevent_start,
10848 .stop = perf_swevent_stop,
10849 .read = perf_swevent_read,
10850};
10851
1c024eca 10852static int perf_tp_filter_match(struct perf_event *event,
b9c44b91 10853 struct perf_raw_record *raw)
1c024eca 10854{
b9c44b91 10855 void *record = raw->frag.data;
1c024eca 10856
b71b437e
PZ
10857 /* only top level events have filters set */
10858 if (event->parent)
10859 event = event->parent;
10860
1c024eca
PZ
10861 if (likely(!event->filter) || filter_match_preds(event->filter, record))
10862 return 1;
10863 return 0;
10864}
10865
10866static int perf_tp_event_match(struct perf_event *event,
b9c44b91 10867 struct perf_raw_record *raw,
1c024eca
PZ
10868 struct pt_regs *regs)
10869{
a0f7d0f7
FW
10870 if (event->hw.state & PERF_HES_STOPPED)
10871 return 0;
580d607c 10872 /*
9fd2e48b 10873 * If exclude_kernel, only trace user-space tracepoints (uprobes)
580d607c 10874 */
9fd2e48b 10875 if (event->attr.exclude_kernel && !user_mode(regs))
1c024eca
PZ
10876 return 0;
10877
b9c44b91 10878 if (!perf_tp_filter_match(event, raw))
1c024eca
PZ
10879 return 0;
10880
10881 return 1;
10882}
10883
85b67bcb
AS
10884void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
10885 struct trace_event_call *call, u64 count,
10886 struct pt_regs *regs, struct hlist_head *head,
10887 struct task_struct *task)
10888{
e87c6bc3 10889 if (bpf_prog_array_valid(call)) {
85b67bcb 10890 *(struct pt_regs **)raw_data = regs;
e87c6bc3 10891 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
85b67bcb
AS
10892 perf_swevent_put_recursion_context(rctx);
10893 return;
10894 }
10895 }
10896 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
8fd0fbbe 10897 rctx, task);
85b67bcb
AS
10898}
10899EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
10900
571f97f7
RB
10901static void __perf_tp_event_target_task(u64 count, void *record,
10902 struct pt_regs *regs,
10903 struct perf_sample_data *data,
b9c44b91 10904 struct perf_raw_record *raw,
571f97f7
RB
10905 struct perf_event *event)
10906{
10907 struct trace_entry *entry = record;
10908
10909 if (event->attr.config != entry->type)
10910 return;
10911 /* Cannot deliver synchronous signal to other task. */
10912 if (event->attr.sigtrap)
10913 return;
b9c44b91
YC
10914 if (perf_tp_event_match(event, raw, regs)) {
10915 perf_sample_data_init(data, 0, 0);
10916 perf_sample_save_raw_data(data, event, raw);
571f97f7 10917 perf_swevent_event(event, count, data, regs);
b9c44b91 10918 }
571f97f7
RB
10919}
10920
10921static void perf_tp_event_target_task(u64 count, void *record,
10922 struct pt_regs *regs,
10923 struct perf_sample_data *data,
b9c44b91 10924 struct perf_raw_record *raw,
571f97f7
RB
10925 struct perf_event_context *ctx)
10926{
10927 unsigned int cpu = smp_processor_id();
10928 struct pmu *pmu = &perf_tracepoint;
10929 struct perf_event *event, *sibling;
10930
10931 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) {
b9c44b91 10932 __perf_tp_event_target_task(count, record, regs, data, raw, event);
571f97f7 10933 for_each_sibling_event(sibling, event)
b9c44b91 10934 __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
571f97f7
RB
10935 }
10936
10937 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) {
b9c44b91 10938 __perf_tp_event_target_task(count, record, regs, data, raw, event);
571f97f7 10939 for_each_sibling_event(sibling, event)
b9c44b91 10940 __perf_tp_event_target_task(count, record, regs, data, raw, sibling);
571f97f7
RB
10941 }
10942}
10943
1e1dcd93 10944void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
e6dab5ff 10945 struct pt_regs *regs, struct hlist_head *head, int rctx,
8fd0fbbe 10946 struct task_struct *task)
95476b64
FW
10947{
10948 struct perf_sample_data data;
8fd0fbbe 10949 struct perf_event *event;
1c024eca 10950
95476b64 10951 struct perf_raw_record raw = {
7e3f977e
DB
10952 .frag = {
10953 .size = entry_size,
10954 .data = record,
10955 },
95476b64
FW
10956 };
10957
1e1dcd93
AS
10958 perf_trace_buf_update(record, event_type);
10959
8fd0fbbe 10960 hlist_for_each_entry_rcu(event, head, hlist_entry) {
b9c44b91 10961 if (perf_tp_event_match(event, &raw, regs)) {
1d1bfe30
YJ
10962 /*
10963 * Here use the same on-stack perf_sample_data,
10964 * some members in data are event-specific and
10965 * need to be re-computed for different sweveents.
10966 * Re-initialize data->sample_flags safely to avoid
10967 * the problem that next event skips preparing data
10968 * because data->sample_flags is set.
10969 */
10970 perf_sample_data_init(&data, 0, 0);
b9c44b91
YC
10971 perf_sample_save_raw_data(&data, event, &raw);
10972 perf_swevent_event(event, count, &data, regs);
1d1bfe30 10973 }
4f41c013 10974 }
ecc55f84 10975
e6dab5ff
AV
10976 /*
10977 * If we got specified a target task, also iterate its context and
10978 * deliver this event there too.
10979 */
10980 if (task && task != current) {
10981 struct perf_event_context *ctx;
e6dab5ff
AV
10982
10983 rcu_read_lock();
bd275681 10984 ctx = rcu_dereference(task->perf_event_ctxp);
e6dab5ff
AV
10985 if (!ctx)
10986 goto unlock;
10987
571f97f7 10988 raw_spin_lock(&ctx->lock);
b9c44b91 10989 perf_tp_event_target_task(count, record, regs, &data, &raw, ctx);
571f97f7 10990 raw_spin_unlock(&ctx->lock);
e6dab5ff
AV
10991unlock:
10992 rcu_read_unlock();
10993 }
10994
ecc55f84 10995 perf_swevent_put_recursion_context(rctx);
95476b64
FW
10996}
10997EXPORT_SYMBOL_GPL(perf_tp_event);
10998
33ea4b24 10999#if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
e12f03d7
SL
11000/*
11001 * Flags in config, used by dynamic PMU kprobe and uprobe
11002 * The flags should match following PMU_FORMAT_ATTR().
11003 *
11004 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
11005 * if not set, create kprobe/uprobe
a6ca88b2
SL
11006 *
11007 * The following values specify a reference counter (or semaphore in the
11008 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
11009 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
11010 *
11011 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
11012 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
e12f03d7
SL
11013 */
11014enum perf_probe_config {
11015 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
a6ca88b2
SL
11016 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
11017 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
e12f03d7
SL
11018};
11019
11020PMU_FORMAT_ATTR(retprobe, "config:0");
a6ca88b2 11021#endif
e12f03d7 11022
a6ca88b2
SL
11023#ifdef CONFIG_KPROBE_EVENTS
11024static struct attribute *kprobe_attrs[] = {
e12f03d7
SL
11025 &format_attr_retprobe.attr,
11026 NULL,
11027};
11028
a6ca88b2 11029static struct attribute_group kprobe_format_group = {
e12f03d7 11030 .name = "format",
a6ca88b2 11031 .attrs = kprobe_attrs,
e12f03d7
SL
11032};
11033
a6ca88b2
SL
11034static const struct attribute_group *kprobe_attr_groups[] = {
11035 &kprobe_format_group,
e12f03d7
SL
11036 NULL,
11037};
11038
11039static int perf_kprobe_event_init(struct perf_event *event);
11040static struct pmu perf_kprobe = {
11041 .task_ctx_nr = perf_sw_context,
11042 .event_init = perf_kprobe_event_init,
11043 .add = perf_trace_add,
11044 .del = perf_trace_del,
11045 .start = perf_swevent_start,
11046 .stop = perf_swevent_stop,
11047 .read = perf_swevent_read,
a6ca88b2 11048 .attr_groups = kprobe_attr_groups,
e12f03d7
SL
11049};
11050
11051static int perf_kprobe_event_init(struct perf_event *event)
11052{
11053 int err;
11054 bool is_retprobe;
11055
11056 if (event->attr.type != perf_kprobe.type)
11057 return -ENOENT;
32e6e967 11058
c9e0924e 11059 if (!perfmon_capable())
32e6e967
SL
11060 return -EACCES;
11061
e12f03d7
SL
11062 /*
11063 * no branch sampling for probe events
11064 */
11065 if (has_branch_stack(event))
11066 return -EOPNOTSUPP;
11067
11068 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
11069 err = perf_kprobe_init(event, is_retprobe);
11070 if (err)
11071 return err;
11072
11073 event->destroy = perf_kprobe_destroy;
11074
11075 return 0;
11076}
11077#endif /* CONFIG_KPROBE_EVENTS */
11078
33ea4b24 11079#ifdef CONFIG_UPROBE_EVENTS
a6ca88b2
SL
11080PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
11081
11082static struct attribute *uprobe_attrs[] = {
11083 &format_attr_retprobe.attr,
11084 &format_attr_ref_ctr_offset.attr,
11085 NULL,
11086};
11087
11088static struct attribute_group uprobe_format_group = {
11089 .name = "format",
11090 .attrs = uprobe_attrs,
11091};
11092
11093static const struct attribute_group *uprobe_attr_groups[] = {
11094 &uprobe_format_group,
11095 NULL,
11096};
11097
33ea4b24
SL
11098static int perf_uprobe_event_init(struct perf_event *event);
11099static struct pmu perf_uprobe = {
11100 .task_ctx_nr = perf_sw_context,
11101 .event_init = perf_uprobe_event_init,
11102 .add = perf_trace_add,
11103 .del = perf_trace_del,
11104 .start = perf_swevent_start,
11105 .stop = perf_swevent_stop,
11106 .read = perf_swevent_read,
a6ca88b2 11107 .attr_groups = uprobe_attr_groups,
33ea4b24
SL
11108};
11109
11110static int perf_uprobe_event_init(struct perf_event *event)
11111{
11112 int err;
a6ca88b2 11113 unsigned long ref_ctr_offset;
33ea4b24
SL
11114 bool is_retprobe;
11115
11116 if (event->attr.type != perf_uprobe.type)
11117 return -ENOENT;
32e6e967 11118
c9e0924e 11119 if (!perfmon_capable())
32e6e967
SL
11120 return -EACCES;
11121
33ea4b24
SL
11122 /*
11123 * no branch sampling for probe events
11124 */
11125 if (has_branch_stack(event))
11126 return -EOPNOTSUPP;
11127
11128 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
a6ca88b2
SL
11129 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
11130 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
33ea4b24
SL
11131 if (err)
11132 return err;
11133
11134 event->destroy = perf_uprobe_destroy;
11135
11136 return 0;
11137}
11138#endif /* CONFIG_UPROBE_EVENTS */
11139
b0a873eb
PZ
11140static inline void perf_tp_register(void)
11141{
2e80a82a 11142 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
e12f03d7
SL
11143#ifdef CONFIG_KPROBE_EVENTS
11144 perf_pmu_register(&perf_kprobe, "kprobe", -1);
11145#endif
33ea4b24
SL
11146#ifdef CONFIG_UPROBE_EVENTS
11147 perf_pmu_register(&perf_uprobe, "uprobe", -1);
11148#endif
e077df4f 11149}
6fb2915d 11150
6fb2915d
LZ
11151static void perf_event_free_filter(struct perf_event *event)
11152{
11153 ftrace_profile_free_filter(event);
11154}
11155
e12f03d7
SL
11156/*
11157 * returns true if the event is a tracepoint, or a kprobe/upprobe created
11158 * with perf_event_open()
11159 */
11160static inline bool perf_event_is_tracing(struct perf_event *event)
11161{
11162 if (event->pmu == &perf_tracepoint)
11163 return true;
11164#ifdef CONFIG_KPROBE_EVENTS
11165 if (event->pmu == &perf_kprobe)
11166 return true;
33ea4b24
SL
11167#endif
11168#ifdef CONFIG_UPROBE_EVENTS
11169 if (event->pmu == &perf_uprobe)
11170 return true;
e12f03d7
SL
11171#endif
11172 return false;
11173}
11174
7ed9138a
PZ
11175static int __perf_event_set_bpf_prog(struct perf_event *event,
11176 struct bpf_prog *prog,
11177 u64 bpf_cookie)
2541517c 11178{
64ad7556 11179 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp;
2541517c 11180
da916e96
PZ
11181 if (event->state <= PERF_EVENT_STATE_REVOKED)
11182 return -ENODEV;
11183
e12f03d7 11184 if (!perf_event_is_tracing(event))
82e6b1ee 11185 return perf_event_set_bpf_handler(event, prog, bpf_cookie);
2541517c 11186
64ad7556
DK
11187 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE;
11188 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE;
98b5c2c6 11189 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
cf5f5cea 11190 is_syscall_tp = is_syscall_trace_event(event->tp_event);
64ad7556 11191 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp)
98b5c2c6 11192 /* bpf programs can only be attached to u/kprobe or tracepoint */
2541517c
AS
11193 return -EINVAL;
11194
64ad7556 11195 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) ||
cf5f5cea 11196 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
652c1b17 11197 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT))
2541517c 11198 return -EINVAL;
2541517c 11199
66c84731 11200 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe)
64ad7556
DK
11201 /* only uprobe programs are allowed to be sleepable */
11202 return -EINVAL;
11203
9802d865 11204 /* Kprobe override only works for kprobes, not uprobes. */
64ad7556 11205 if (prog->kprobe_override && !is_kprobe)
9802d865 11206 return -EINVAL;
9802d865 11207
cf5f5cea 11208 if (is_tracepoint || is_syscall_tp) {
32bbe007
AS
11209 int off = trace_event_get_offsets(event->tp_event);
11210
652c1b17 11211 if (prog->aux->max_ctx_offset > off)
32bbe007 11212 return -EACCES;
32bbe007 11213 }
2541517c 11214
82e6b1ee 11215 return perf_event_attach_bpf_prog(event, prog, bpf_cookie);
2541517c
AS
11216}
11217
7ed9138a
PZ
11218int perf_event_set_bpf_prog(struct perf_event *event,
11219 struct bpf_prog *prog,
11220 u64 bpf_cookie)
11221{
11222 struct perf_event_context *ctx;
11223 int ret;
11224
11225 ctx = perf_event_ctx_lock(event);
11226 ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie);
11227 perf_event_ctx_unlock(event, ctx);
11228
11229 return ret;
11230}
11231
b89fbfbb 11232void perf_event_free_bpf_prog(struct perf_event *event)
2541517c 11233{
c5b96789
PZ
11234 if (!event->prog)
11235 return;
11236
e12f03d7 11237 if (!perf_event_is_tracing(event)) {
0b4c6841 11238 perf_event_free_bpf_handler(event);
2541517c 11239 return;
2541517c 11240 }
e87c6bc3 11241 perf_event_detach_bpf_prog(event);
2541517c
AS
11242}
11243
e077df4f 11244#else
6fb2915d 11245
b0a873eb 11246static inline void perf_tp_register(void)
e077df4f 11247{
e077df4f 11248}
6fb2915d 11249
6fb2915d
LZ
11250static void perf_event_free_filter(struct perf_event *event)
11251{
11252}
11253
7ed9138a
PZ
11254static int __perf_event_set_bpf_prog(struct perf_event *event,
11255 struct bpf_prog *prog,
11256 u64 bpf_cookie)
11257{
11258 return -ENOENT;
11259}
11260
11261int perf_event_set_bpf_prog(struct perf_event *event,
11262 struct bpf_prog *prog,
82e6b1ee 11263 u64 bpf_cookie)
2541517c
AS
11264{
11265 return -ENOENT;
11266}
11267
b89fbfbb 11268void perf_event_free_bpf_prog(struct perf_event *event)
2541517c
AS
11269{
11270}
07b139c8 11271#endif /* CONFIG_EVENT_TRACING */
e077df4f 11272
24f1e32c 11273#ifdef CONFIG_HAVE_HW_BREAKPOINT
f5ffe02e 11274void perf_bp_event(struct perf_event *bp, void *data)
24f1e32c 11275{
f5ffe02e
FW
11276 struct perf_sample_data sample;
11277 struct pt_regs *regs = data;
11278
fd0d000b 11279 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
f5ffe02e 11280
a4eaf7f1 11281 if (!bp->hw.state && !perf_exclude_event(bp, regs))
a8b0ca17 11282 perf_swevent_event(bp, 1, &sample, regs);
24f1e32c
FW
11283}
11284#endif
11285
375637bc
AS
11286/*
11287 * Allocate a new address filter
11288 */
11289static struct perf_addr_filter *
11290perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
11291{
11292 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
11293 struct perf_addr_filter *filter;
11294
11295 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
11296 if (!filter)
11297 return NULL;
11298
11299 INIT_LIST_HEAD(&filter->entry);
11300 list_add_tail(&filter->entry, filters);
11301
11302 return filter;
11303}
11304
11305static void free_filters_list(struct list_head *filters)
11306{
11307 struct perf_addr_filter *filter, *iter;
11308
11309 list_for_each_entry_safe(filter, iter, filters, entry) {
9511bce9 11310 path_put(&filter->path);
375637bc
AS
11311 list_del(&filter->entry);
11312 kfree(filter);
11313 }
11314}
11315
11316/*
11317 * Free existing address filters and optionally install new ones
11318 */
11319static void perf_addr_filters_splice(struct perf_event *event,
11320 struct list_head *head)
11321{
11322 unsigned long flags;
11323 LIST_HEAD(list);
11324
11325 if (!has_addr_filter(event))
11326 return;
11327
11328 /* don't bother with children, they don't have their own filters */
11329 if (event->parent)
11330 return;
11331
11332 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
11333
11334 list_splice_init(&event->addr_filters.list, &list);
11335 if (head)
11336 list_splice(head, &event->addr_filters.list);
11337
11338 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
11339
11340 free_filters_list(&list);
11341}
11342
adc38b4c
PZ
11343static void perf_free_addr_filters(struct perf_event *event)
11344{
11345 /*
11346 * Used during free paths, there is no concurrency.
11347 */
11348 if (list_empty(&event->addr_filters.list))
11349 return;
11350
11351 perf_addr_filters_splice(event, NULL);
11352}
11353
375637bc
AS
11354/*
11355 * Scan through mm's vmas and see if one of them matches the
11356 * @filter; if so, adjust filter's address range.
c1e8d7c6 11357 * Called with mm::mmap_lock down for reading.
375637bc 11358 */
c60f83b8
AS
11359static void perf_addr_filter_apply(struct perf_addr_filter *filter,
11360 struct mm_struct *mm,
11361 struct perf_addr_filter_range *fr)
375637bc
AS
11362{
11363 struct vm_area_struct *vma;
fcb72a58 11364 VMA_ITERATOR(vmi, mm, 0);
375637bc 11365
fcb72a58 11366 for_each_vma(vmi, vma) {
c60f83b8 11367 if (!vma->vm_file)
375637bc
AS
11368 continue;
11369
c60f83b8
AS
11370 if (perf_addr_filter_vma_adjust(filter, vma, fr))
11371 return;
375637bc 11372 }
375637bc
AS
11373}
11374
11375/*
11376 * Update event's address range filters based on the
11377 * task's existing mappings, if any.
11378 */
11379static void perf_event_addr_filters_apply(struct perf_event *event)
11380{
11381 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11382 struct task_struct *task = READ_ONCE(event->ctx->task);
11383 struct perf_addr_filter *filter;
11384 struct mm_struct *mm = NULL;
11385 unsigned int count = 0;
11386 unsigned long flags;
11387
11388 /*
11389 * We may observe TASK_TOMBSTONE, which means that the event tear-down
11390 * will stop on the parent's child_mutex that our caller is also holding
11391 */
11392 if (task == TASK_TOMBSTONE)
11393 return;
11394
52a44f83 11395 if (ifh->nr_file_filters) {
b89a05b2 11396 mm = get_task_mm(task);
52a44f83
AS
11397 if (!mm)
11398 goto restart;
375637bc 11399
d8ed45c5 11400 mmap_read_lock(mm);
52a44f83 11401 }
375637bc
AS
11402
11403 raw_spin_lock_irqsave(&ifh->lock, flags);
11404 list_for_each_entry(filter, &ifh->list, entry) {
52a44f83
AS
11405 if (filter->path.dentry) {
11406 /*
11407 * Adjust base offset if the filter is associated to a
11408 * binary that needs to be mapped:
11409 */
11410 event->addr_filter_ranges[count].start = 0;
11411 event->addr_filter_ranges[count].size = 0;
375637bc 11412
c60f83b8 11413 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
52a44f83
AS
11414 } else {
11415 event->addr_filter_ranges[count].start = filter->offset;
11416 event->addr_filter_ranges[count].size = filter->size;
11417 }
375637bc
AS
11418
11419 count++;
11420 }
11421
11422 event->addr_filters_gen++;
11423 raw_spin_unlock_irqrestore(&ifh->lock, flags);
11424
52a44f83 11425 if (ifh->nr_file_filters) {
d8ed45c5 11426 mmap_read_unlock(mm);
375637bc 11427
52a44f83
AS
11428 mmput(mm);
11429 }
375637bc
AS
11430
11431restart:
767ae086 11432 perf_event_stop(event, 1);
375637bc
AS
11433}
11434
11435/*
11436 * Address range filtering: limiting the data to certain
11437 * instruction address ranges. Filters are ioctl()ed to us from
11438 * userspace as ascii strings.
11439 *
11440 * Filter string format:
11441 *
11442 * ACTION RANGE_SPEC
11443 * where ACTION is one of the
11444 * * "filter": limit the trace to this region
11445 * * "start": start tracing from this address
11446 * * "stop": stop tracing at this address/region;
11447 * RANGE_SPEC is
11448 * * for kernel addresses: <start address>[/<size>]
11449 * * for object files: <start address>[/<size>]@</path/to/object/file>
11450 *
6ed70cf3
AS
11451 * if <size> is not specified or is zero, the range is treated as a single
11452 * address; not valid for ACTION=="filter".
375637bc
AS
11453 */
11454enum {
e96271f3 11455 IF_ACT_NONE = -1,
375637bc
AS
11456 IF_ACT_FILTER,
11457 IF_ACT_START,
11458 IF_ACT_STOP,
11459 IF_SRC_FILE,
11460 IF_SRC_KERNEL,
11461 IF_SRC_FILEADDR,
11462 IF_SRC_KERNELADDR,
11463};
11464
11465enum {
11466 IF_STATE_ACTION = 0,
11467 IF_STATE_SOURCE,
11468 IF_STATE_END,
11469};
11470
11471static const match_table_t if_tokens = {
11472 { IF_ACT_FILTER, "filter" },
11473 { IF_ACT_START, "start" },
11474 { IF_ACT_STOP, "stop" },
11475 { IF_SRC_FILE, "%u/%u@%s" },
11476 { IF_SRC_KERNEL, "%u/%u" },
11477 { IF_SRC_FILEADDR, "%u@%s" },
11478 { IF_SRC_KERNELADDR, "%u" },
e96271f3 11479 { IF_ACT_NONE, NULL },
375637bc
AS
11480};
11481
11482/*
11483 * Address filter string parser
11484 */
11485static int
11486perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
11487 struct list_head *filters)
11488{
11489 struct perf_addr_filter *filter = NULL;
11490 char *start, *orig, *filename = NULL;
375637bc
AS
11491 substring_t args[MAX_OPT_ARGS];
11492 int state = IF_STATE_ACTION, token;
11493 unsigned int kernel = 0;
11494 int ret = -EINVAL;
11495
11496 orig = fstr = kstrdup(fstr, GFP_KERNEL);
11497 if (!fstr)
11498 return -ENOMEM;
11499
11500 while ((start = strsep(&fstr, " ,\n")) != NULL) {
6ed70cf3
AS
11501 static const enum perf_addr_filter_action_t actions[] = {
11502 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
11503 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
11504 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
11505 };
375637bc
AS
11506 ret = -EINVAL;
11507
11508 if (!*start)
11509 continue;
11510
11511 /* filter definition begins */
11512 if (state == IF_STATE_ACTION) {
11513 filter = perf_addr_filter_new(event, filters);
11514 if (!filter)
11515 goto fail;
11516 }
11517
11518 token = match_token(start, if_tokens, args);
11519 switch (token) {
11520 case IF_ACT_FILTER:
11521 case IF_ACT_START:
375637bc
AS
11522 case IF_ACT_STOP:
11523 if (state != IF_STATE_ACTION)
11524 goto fail;
11525
6ed70cf3 11526 filter->action = actions[token];
375637bc
AS
11527 state = IF_STATE_SOURCE;
11528 break;
11529
11530 case IF_SRC_KERNELADDR:
11531 case IF_SRC_KERNEL:
11532 kernel = 1;
df561f66 11533 fallthrough;
375637bc
AS
11534
11535 case IF_SRC_FILEADDR:
11536 case IF_SRC_FILE:
11537 if (state != IF_STATE_SOURCE)
11538 goto fail;
11539
375637bc
AS
11540 *args[0].to = 0;
11541 ret = kstrtoul(args[0].from, 0, &filter->offset);
11542 if (ret)
11543 goto fail;
11544
6ed70cf3 11545 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
375637bc
AS
11546 *args[1].to = 0;
11547 ret = kstrtoul(args[1].from, 0, &filter->size);
11548 if (ret)
11549 goto fail;
11550 }
11551
4059ffd0 11552 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
6ed70cf3 11553 int fpos = token == IF_SRC_FILE ? 2 : 1;
4059ffd0 11554
7bdb157c 11555 kfree(filename);
4059ffd0 11556 filename = match_strdup(&args[fpos]);
375637bc
AS
11557 if (!filename) {
11558 ret = -ENOMEM;
11559 goto fail;
11560 }
11561 }
11562
11563 state = IF_STATE_END;
11564 break;
11565
11566 default:
11567 goto fail;
11568 }
11569
11570 /*
11571 * Filter definition is fully parsed, validate and install it.
11572 * Make sure that it doesn't contradict itself or the event's
11573 * attribute.
11574 */
11575 if (state == IF_STATE_END) {
9ccbfbb1 11576 ret = -EINVAL;
375637bc 11577
6ed70cf3
AS
11578 /*
11579 * ACTION "filter" must have a non-zero length region
11580 * specified.
11581 */
11582 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
11583 !filter->size)
11584 goto fail;
11585
375637bc
AS
11586 if (!kernel) {
11587 if (!filename)
11588 goto fail;
11589
6ce77bfd
AS
11590 /*
11591 * For now, we only support file-based filters
11592 * in per-task events; doing so for CPU-wide
11593 * events requires additional context switching
11594 * trickery, since same object code will be
11595 * mapped at different virtual addresses in
11596 * different processes.
11597 */
11598 ret = -EOPNOTSUPP;
11599 if (!event->ctx->task)
7bdb157c 11600 goto fail;
6ce77bfd 11601
375637bc 11602 /* look up the path and grab its inode */
9511bce9
SL
11603 ret = kern_path(filename, LOOKUP_FOLLOW,
11604 &filter->path);
375637bc 11605 if (ret)
7bdb157c 11606 goto fail;
375637bc
AS
11607
11608 ret = -EINVAL;
9511bce9
SL
11609 if (!filter->path.dentry ||
11610 !S_ISREG(d_inode(filter->path.dentry)
11611 ->i_mode))
375637bc 11612 goto fail;
6ce77bfd
AS
11613
11614 event->addr_filters.nr_file_filters++;
375637bc
AS
11615 }
11616
11617 /* ready to consume more filters */
d680ff24
AH
11618 kfree(filename);
11619 filename = NULL;
375637bc
AS
11620 state = IF_STATE_ACTION;
11621 filter = NULL;
d680ff24 11622 kernel = 0;
375637bc
AS
11623 }
11624 }
11625
11626 if (state != IF_STATE_ACTION)
11627 goto fail;
11628
7bdb157c 11629 kfree(filename);
375637bc
AS
11630 kfree(orig);
11631
11632 return 0;
11633
375637bc 11634fail:
7bdb157c 11635 kfree(filename);
375637bc
AS
11636 free_filters_list(filters);
11637 kfree(orig);
11638
11639 return ret;
11640}
11641
11642static int
11643perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
11644{
11645 LIST_HEAD(filters);
11646 int ret;
11647
11648 /*
11649 * Since this is called in perf_ioctl() path, we're already holding
11650 * ctx::mutex.
11651 */
11652 lockdep_assert_held(&event->ctx->mutex);
11653
11654 if (WARN_ON_ONCE(event->parent))
11655 return -EINVAL;
11656
375637bc
AS
11657 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
11658 if (ret)
6ce77bfd 11659 goto fail_clear_files;
375637bc
AS
11660
11661 ret = event->pmu->addr_filters_validate(&filters);
6ce77bfd
AS
11662 if (ret)
11663 goto fail_free_filters;
375637bc
AS
11664
11665 /* remove existing filters, if any */
11666 perf_addr_filters_splice(event, &filters);
11667
11668 /* install new filters */
11669 perf_event_for_each_child(event, perf_event_addr_filters_apply);
11670
6ce77bfd
AS
11671 return ret;
11672
11673fail_free_filters:
11674 free_filters_list(&filters);
11675
11676fail_clear_files:
11677 event->addr_filters.nr_file_filters = 0;
11678
375637bc
AS
11679 return ret;
11680}
11681
c796bbbe
AS
11682static int perf_event_set_filter(struct perf_event *event, void __user *arg)
11683{
c796bbbe 11684 int ret = -EINVAL;
e12f03d7 11685 char *filter_str;
c796bbbe
AS
11686
11687 filter_str = strndup_user(arg, PAGE_SIZE);
11688 if (IS_ERR(filter_str))
11689 return PTR_ERR(filter_str);
11690
e12f03d7
SL
11691#ifdef CONFIG_EVENT_TRACING
11692 if (perf_event_is_tracing(event)) {
11693 struct perf_event_context *ctx = event->ctx;
11694
11695 /*
11696 * Beware, here be dragons!!
11697 *
11698 * the tracepoint muck will deadlock against ctx->mutex, but
11699 * the tracepoint stuff does not actually need it. So
11700 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
11701 * already have a reference on ctx.
11702 *
11703 * This can result in event getting moved to a different ctx,
11704 * but that does not affect the tracepoint state.
11705 */
11706 mutex_unlock(&ctx->mutex);
11707 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
11708 mutex_lock(&ctx->mutex);
11709 } else
11710#endif
11711 if (has_addr_filter(event))
375637bc 11712 ret = perf_event_set_addr_filter(event, filter_str);
c796bbbe
AS
11713
11714 kfree(filter_str);
11715 return ret;
11716}
11717
b0a873eb
PZ
11718/*
11719 * hrtimer based swevent callback
11720 */
f29ac756 11721
b0a873eb 11722static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
f29ac756 11723{
b0a873eb
PZ
11724 enum hrtimer_restart ret = HRTIMER_RESTART;
11725 struct perf_sample_data data;
11726 struct pt_regs *regs;
11727 struct perf_event *event;
11728 u64 period;
f29ac756 11729
b0a873eb 11730 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
ba3dd36c
PZ
11731
11732 if (event->state != PERF_EVENT_STATE_ACTIVE)
11733 return HRTIMER_NORESTART;
11734
b0a873eb 11735 event->pmu->read(event);
f344011c 11736
fd0d000b 11737 perf_sample_data_init(&data, 0, event->hw.last_period);
b0a873eb
PZ
11738 regs = get_irq_regs();
11739
11740 if (regs && !perf_exclude_event(event, regs)) {
77aeeebd 11741 if (!(event->attr.exclude_idle && is_idle_task(current)))
33b07b8b 11742 if (__perf_event_overflow(event, 1, &data, regs))
b0a873eb
PZ
11743 ret = HRTIMER_NORESTART;
11744 }
24f1e32c 11745
b0a873eb
PZ
11746 period = max_t(u64, 10000, event->hw.sample_period);
11747 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
24f1e32c 11748
b0a873eb 11749 return ret;
f29ac756
PZ
11750}
11751
b0a873eb 11752static void perf_swevent_start_hrtimer(struct perf_event *event)
5c92d124 11753{
b0a873eb 11754 struct hw_perf_event *hwc = &event->hw;
5d508e82
FBH
11755 s64 period;
11756
11757 if (!is_sampling_event(event))
11758 return;
f5ffe02e 11759
5d508e82
FBH
11760 period = local64_read(&hwc->period_left);
11761 if (period) {
11762 if (period < 0)
11763 period = 10000;
fa407f35 11764
5d508e82
FBH
11765 local64_set(&hwc->period_left, 0);
11766 } else {
11767 period = max_t(u64, 10000, hwc->sample_period);
11768 }
3497d206 11769 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
30f9028b 11770 HRTIMER_MODE_REL_PINNED_HARD);
24f1e32c 11771}
b0a873eb
PZ
11772
11773static void perf_swevent_cancel_hrtimer(struct perf_event *event)
24f1e32c 11774{
b0a873eb
PZ
11775 struct hw_perf_event *hwc = &event->hw;
11776
bc4394e5
KL
11777 /*
11778 * The throttle can be triggered in the hrtimer handler.
11779 * The HRTIMER_NORESTART should be used to stop the timer,
11780 * rather than hrtimer_cancel(). See perf_swevent_hrtimer()
11781 */
11782 if (is_sampling_event(event) && (hwc->interrupts != MAX_INTERRUPTS)) {
b0a873eb 11783 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
fa407f35 11784 local64_set(&hwc->period_left, ktime_to_ns(remaining));
b0a873eb
PZ
11785
11786 hrtimer_cancel(&hwc->hrtimer);
11787 }
24f1e32c
FW
11788}
11789
ba3dd36c
PZ
11790static void perf_swevent_init_hrtimer(struct perf_event *event)
11791{
11792 struct hw_perf_event *hwc = &event->hw;
11793
11794 if (!is_sampling_event(event))
11795 return;
11796
022a2235 11797 hrtimer_setup(&hwc->hrtimer, perf_swevent_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
ba3dd36c
PZ
11798
11799 /*
11800 * Since hrtimers have a fixed rate, we can do a static freq->period
11801 * mapping and avoid the whole period adjust feedback stuff.
11802 */
11803 if (event->attr.freq) {
11804 long freq = event->attr.sample_freq;
11805
11806 event->attr.sample_period = NSEC_PER_SEC / freq;
11807 hwc->sample_period = event->attr.sample_period;
11808 local64_set(&hwc->period_left, hwc->sample_period);
778141e3 11809 hwc->last_period = hwc->sample_period;
ba3dd36c
PZ
11810 event->attr.freq = 0;
11811 }
11812}
11813
b0a873eb
PZ
11814/*
11815 * Software event: cpu wall time clock
11816 */
11817
11818static void cpu_clock_event_update(struct perf_event *event)
24f1e32c 11819{
b0a873eb
PZ
11820 s64 prev;
11821 u64 now;
11822
a4eaf7f1 11823 now = local_clock();
b0a873eb
PZ
11824 prev = local64_xchg(&event->hw.prev_count, now);
11825 local64_add(now - prev, &event->count);
24f1e32c 11826}
24f1e32c 11827
a4eaf7f1 11828static void cpu_clock_event_start(struct perf_event *event, int flags)
b0a873eb 11829{
a4eaf7f1 11830 local64_set(&event->hw.prev_count, local_clock());
b0a873eb 11831 perf_swevent_start_hrtimer(event);
b0a873eb
PZ
11832}
11833
a4eaf7f1 11834static void cpu_clock_event_stop(struct perf_event *event, int flags)
f29ac756 11835{
b0a873eb 11836 perf_swevent_cancel_hrtimer(event);
bc4394e5
KL
11837 if (flags & PERF_EF_UPDATE)
11838 cpu_clock_event_update(event);
b0a873eb 11839}
f29ac756 11840
a4eaf7f1
PZ
11841static int cpu_clock_event_add(struct perf_event *event, int flags)
11842{
11843 if (flags & PERF_EF_START)
11844 cpu_clock_event_start(event, flags);
6a694a60 11845 perf_event_update_userpage(event);
a4eaf7f1
PZ
11846
11847 return 0;
11848}
11849
11850static void cpu_clock_event_del(struct perf_event *event, int flags)
11851{
11852 cpu_clock_event_stop(event, flags);
11853}
11854
b0a873eb
PZ
11855static void cpu_clock_event_read(struct perf_event *event)
11856{
11857 cpu_clock_event_update(event);
11858}
f344011c 11859
b0a873eb
PZ
11860static int cpu_clock_event_init(struct perf_event *event)
11861{
0d6d062c 11862 if (event->attr.type != perf_cpu_clock.type)
b0a873eb
PZ
11863 return -ENOENT;
11864
11865 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
11866 return -ENOENT;
11867
2481c5fa
SE
11868 /*
11869 * no branch sampling for software events
11870 */
11871 if (has_branch_stack(event))
11872 return -EOPNOTSUPP;
11873
ba3dd36c
PZ
11874 perf_swevent_init_hrtimer(event);
11875
b0a873eb 11876 return 0;
f29ac756
PZ
11877}
11878
b0a873eb 11879static struct pmu perf_cpu_clock = {
89a1e187
PZ
11880 .task_ctx_nr = perf_sw_context,
11881
34f43927 11882 .capabilities = PERF_PMU_CAP_NO_NMI,
0d6d062c 11883 .dev = PMU_NULL_DEV,
34f43927 11884
b0a873eb 11885 .event_init = cpu_clock_event_init,
a4eaf7f1
PZ
11886 .add = cpu_clock_event_add,
11887 .del = cpu_clock_event_del,
11888 .start = cpu_clock_event_start,
11889 .stop = cpu_clock_event_stop,
b0a873eb
PZ
11890 .read = cpu_clock_event_read,
11891};
11892
11893/*
11894 * Software event: task time clock
11895 */
11896
11897static void task_clock_event_update(struct perf_event *event, u64 now)
5c92d124 11898{
b0a873eb
PZ
11899 u64 prev;
11900 s64 delta;
5c92d124 11901
b0a873eb
PZ
11902 prev = local64_xchg(&event->hw.prev_count, now);
11903 delta = now - prev;
11904 local64_add(delta, &event->count);
11905}
5c92d124 11906
a4eaf7f1 11907static void task_clock_event_start(struct perf_event *event, int flags)
b0a873eb 11908{
a4eaf7f1 11909 local64_set(&event->hw.prev_count, event->ctx->time);
b0a873eb 11910 perf_swevent_start_hrtimer(event);
b0a873eb
PZ
11911}
11912
a4eaf7f1 11913static void task_clock_event_stop(struct perf_event *event, int flags)
b0a873eb
PZ
11914{
11915 perf_swevent_cancel_hrtimer(event);
bc4394e5
KL
11916 if (flags & PERF_EF_UPDATE)
11917 task_clock_event_update(event, event->ctx->time);
a4eaf7f1
PZ
11918}
11919
11920static int task_clock_event_add(struct perf_event *event, int flags)
11921{
11922 if (flags & PERF_EF_START)
11923 task_clock_event_start(event, flags);
6a694a60 11924 perf_event_update_userpage(event);
b0a873eb 11925
a4eaf7f1
PZ
11926 return 0;
11927}
11928
11929static void task_clock_event_del(struct perf_event *event, int flags)
11930{
11931 task_clock_event_stop(event, PERF_EF_UPDATE);
b0a873eb
PZ
11932}
11933
11934static void task_clock_event_read(struct perf_event *event)
11935{
768a06e2
PZ
11936 u64 now = perf_clock();
11937 u64 delta = now - event->ctx->timestamp;
11938 u64 time = event->ctx->time + delta;
b0a873eb
PZ
11939
11940 task_clock_event_update(event, time);
11941}
11942
11943static int task_clock_event_init(struct perf_event *event)
6fb2915d 11944{
0d6d062c 11945 if (event->attr.type != perf_task_clock.type)
b0a873eb
PZ
11946 return -ENOENT;
11947
11948 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
11949 return -ENOENT;
11950
2481c5fa
SE
11951 /*
11952 * no branch sampling for software events
11953 */
11954 if (has_branch_stack(event))
11955 return -EOPNOTSUPP;
11956
ba3dd36c
PZ
11957 perf_swevent_init_hrtimer(event);
11958
b0a873eb 11959 return 0;
6fb2915d
LZ
11960}
11961
b0a873eb 11962static struct pmu perf_task_clock = {
89a1e187
PZ
11963 .task_ctx_nr = perf_sw_context,
11964
34f43927 11965 .capabilities = PERF_PMU_CAP_NO_NMI,
0d6d062c 11966 .dev = PMU_NULL_DEV,
34f43927 11967
b0a873eb 11968 .event_init = task_clock_event_init,
a4eaf7f1
PZ
11969 .add = task_clock_event_add,
11970 .del = task_clock_event_del,
11971 .start = task_clock_event_start,
11972 .stop = task_clock_event_stop,
b0a873eb
PZ
11973 .read = task_clock_event_read,
11974};
6fb2915d 11975
ad5133b7 11976static void perf_pmu_nop_void(struct pmu *pmu)
e077df4f 11977{
e077df4f 11978}
6fb2915d 11979
fbbe0701
SB
11980static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
11981{
11982}
11983
ad5133b7 11984static int perf_pmu_nop_int(struct pmu *pmu)
6fb2915d 11985{
ad5133b7 11986 return 0;
6fb2915d
LZ
11987}
11988
81ec3f3c
JO
11989static int perf_event_nop_int(struct perf_event *event, u64 value)
11990{
11991 return 0;
11992}
11993
18ab2cd3 11994static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
fbbe0701
SB
11995
11996static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
6fb2915d 11997{
fbbe0701
SB
11998 __this_cpu_write(nop_txn_flags, flags);
11999
12000 if (flags & ~PERF_PMU_TXN_ADD)
12001 return;
12002
ad5133b7 12003 perf_pmu_disable(pmu);
6fb2915d
LZ
12004}
12005
ad5133b7
PZ
12006static int perf_pmu_commit_txn(struct pmu *pmu)
12007{
fbbe0701
SB
12008 unsigned int flags = __this_cpu_read(nop_txn_flags);
12009
12010 __this_cpu_write(nop_txn_flags, 0);
12011
12012 if (flags & ~PERF_PMU_TXN_ADD)
12013 return 0;
12014
ad5133b7
PZ
12015 perf_pmu_enable(pmu);
12016 return 0;
12017}
e077df4f 12018
ad5133b7 12019static void perf_pmu_cancel_txn(struct pmu *pmu)
24f1e32c 12020{
fbbe0701
SB
12021 unsigned int flags = __this_cpu_read(nop_txn_flags);
12022
12023 __this_cpu_write(nop_txn_flags, 0);
12024
12025 if (flags & ~PERF_PMU_TXN_ADD)
12026 return;
12027
ad5133b7 12028 perf_pmu_enable(pmu);
24f1e32c
FW
12029}
12030
35edc2a5
PZ
12031static int perf_event_idx_default(struct perf_event *event)
12032{
c719f560 12033 return 0;
35edc2a5
PZ
12034}
12035
8dc85d54 12036/*
6e855cd4 12037 * Let userspace know that this PMU supports address range filtering:
8dc85d54 12038 */
6e855cd4
AS
12039static ssize_t nr_addr_filters_show(struct device *dev,
12040 struct device_attribute *attr,
12041 char *page)
24f1e32c 12042{
6e855cd4
AS
12043 struct pmu *pmu = dev_get_drvdata(dev);
12044
b6ecb57f 12045 return sysfs_emit(page, "%d\n", pmu->nr_addr_filters);
6e855cd4
AS
12046}
12047DEVICE_ATTR_RO(nr_addr_filters);
12048
2e80a82a 12049static struct idr pmu_idr;
d6d020e9 12050
abe43400
PZ
12051static ssize_t
12052type_show(struct device *dev, struct device_attribute *attr, char *page)
12053{
12054 struct pmu *pmu = dev_get_drvdata(dev);
12055
b6ecb57f 12056 return sysfs_emit(page, "%d\n", pmu->type);
abe43400 12057}
90826ca7 12058static DEVICE_ATTR_RO(type);
abe43400 12059
62b85639
SE
12060static ssize_t
12061perf_event_mux_interval_ms_show(struct device *dev,
12062 struct device_attribute *attr,
12063 char *page)
12064{
12065 struct pmu *pmu = dev_get_drvdata(dev);
12066
b6ecb57f 12067 return sysfs_emit(page, "%d\n", pmu->hrtimer_interval_ms);
62b85639
SE
12068}
12069
272325c4
PZ
12070static DEFINE_MUTEX(mux_interval_mutex);
12071
62b85639
SE
12072static ssize_t
12073perf_event_mux_interval_ms_store(struct device *dev,
12074 struct device_attribute *attr,
12075 const char *buf, size_t count)
12076{
12077 struct pmu *pmu = dev_get_drvdata(dev);
12078 int timer, cpu, ret;
12079
12080 ret = kstrtoint(buf, 0, &timer);
12081 if (ret)
12082 return ret;
12083
12084 if (timer < 1)
12085 return -EINVAL;
12086
12087 /* same value, noting to do */
12088 if (timer == pmu->hrtimer_interval_ms)
12089 return count;
12090
272325c4 12091 mutex_lock(&mux_interval_mutex);
62b85639
SE
12092 pmu->hrtimer_interval_ms = timer;
12093
12094 /* update all cpuctx for this PMU */
a63fbed7 12095 cpus_read_lock();
272325c4 12096 for_each_online_cpu(cpu) {
bd275681 12097 struct perf_cpu_pmu_context *cpc;
4eabf533 12098 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
bd275681 12099 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
62b85639 12100
1af6239d 12101 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc);
62b85639 12102 }
a63fbed7 12103 cpus_read_unlock();
272325c4 12104 mutex_unlock(&mux_interval_mutex);
62b85639
SE
12105
12106 return count;
12107}
90826ca7 12108static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
62b85639 12109
4ba4f1af
KL
12110static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu)
12111{
12112 switch (scope) {
12113 case PERF_PMU_SCOPE_CORE:
12114 return topology_sibling_cpumask(cpu);
12115 case PERF_PMU_SCOPE_DIE:
12116 return topology_die_cpumask(cpu);
12117 case PERF_PMU_SCOPE_CLUSTER:
12118 return topology_cluster_cpumask(cpu);
12119 case PERF_PMU_SCOPE_PKG:
12120 return topology_core_cpumask(cpu);
12121 case PERF_PMU_SCOPE_SYS_WIDE:
12122 return cpu_online_mask;
12123 }
12124
12125 return NULL;
12126}
12127
12128static inline struct cpumask *perf_scope_cpumask(unsigned int scope)
12129{
12130 switch (scope) {
12131 case PERF_PMU_SCOPE_CORE:
12132 return perf_online_core_mask;
12133 case PERF_PMU_SCOPE_DIE:
12134 return perf_online_die_mask;
12135 case PERF_PMU_SCOPE_CLUSTER:
12136 return perf_online_cluster_mask;
12137 case PERF_PMU_SCOPE_PKG:
12138 return perf_online_pkg_mask;
12139 case PERF_PMU_SCOPE_SYS_WIDE:
12140 return perf_online_sys_mask;
12141 }
12142
12143 return NULL;
12144}
12145
12146static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr,
12147 char *buf)
12148{
12149 struct pmu *pmu = dev_get_drvdata(dev);
12150 struct cpumask *mask = perf_scope_cpumask(pmu->scope);
12151
12152 if (mask)
12153 return cpumap_print_to_pagebuf(true, buf, mask);
12154 return 0;
12155}
12156
12157static DEVICE_ATTR_RO(cpumask);
12158
90826ca7
GKH
12159static struct attribute *pmu_dev_attrs[] = {
12160 &dev_attr_type.attr,
12161 &dev_attr_perf_event_mux_interval_ms.attr,
652ffc21 12162 &dev_attr_nr_addr_filters.attr,
4ba4f1af 12163 &dev_attr_cpumask.attr,
652ffc21
GK
12164 NULL,
12165};
12166
12167static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
12168{
12169 struct device *dev = kobj_to_dev(kobj);
12170 struct pmu *pmu = dev_get_drvdata(dev);
12171
388a1fb7 12172 if (n == 2 && !pmu->nr_addr_filters)
652ffc21
GK
12173 return 0;
12174
4ba4f1af
KL
12175 /* cpumask */
12176 if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE)
12177 return 0;
12178
652ffc21 12179 return a->mode;
652ffc21
GK
12180}
12181
12182static struct attribute_group pmu_dev_attr_group = {
12183 .is_visible = pmu_dev_is_visible,
12184 .attrs = pmu_dev_attrs,
12185};
12186
12187static const struct attribute_group *pmu_dev_groups[] = {
12188 &pmu_dev_attr_group,
90826ca7 12189 NULL,
abe43400
PZ
12190};
12191
12192static int pmu_bus_running;
12193static struct bus_type pmu_bus = {
12194 .name = "event_source",
90826ca7 12195 .dev_groups = pmu_dev_groups,
abe43400
PZ
12196};
12197
12198static void pmu_dev_release(struct device *dev)
12199{
12200 kfree(dev);
12201}
12202
12203static int pmu_dev_alloc(struct pmu *pmu)
12204{
12205 int ret = -ENOMEM;
12206
12207 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
12208 if (!pmu->dev)
12209 goto out;
12210
0c9d42ed 12211 pmu->dev->groups = pmu->attr_groups;
abe43400 12212 device_initialize(pmu->dev);
abe43400
PZ
12213
12214 dev_set_drvdata(pmu->dev, pmu);
12215 pmu->dev->bus = &pmu_bus;
143f83e2 12216 pmu->dev->parent = pmu->parent;
abe43400 12217 pmu->dev->release = pmu_dev_release;
e8d7a90c
CZ
12218
12219 ret = dev_set_name(pmu->dev, "%s", pmu->name);
12220 if (ret)
12221 goto free_dev;
12222
abe43400
PZ
12223 ret = device_add(pmu->dev);
12224 if (ret)
12225 goto free_dev;
12226
652ffc21 12227 if (pmu->attr_update) {
f3a3a825 12228 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
652ffc21
GK
12229 if (ret)
12230 goto del_dev;
12231 }
f3a3a825 12232
abe43400
PZ
12233out:
12234 return ret;
12235
6e855cd4
AS
12236del_dev:
12237 device_del(pmu->dev);
12238
abe43400
PZ
12239free_dev:
12240 put_device(pmu->dev);
8f4c4963 12241 pmu->dev = NULL;
abe43400
PZ
12242 goto out;
12243}
12244
547e9fd7 12245static struct lock_class_key cpuctx_mutex;
facc4307 12246static struct lock_class_key cpuctx_lock;
547e9fd7 12247
003659fe
PZ
12248static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new)
12249{
12250 void *tmp, *val = idr_find(idr, id);
12251
12252 if (val != old)
12253 return false;
12254
12255 tmp = idr_replace(idr, new, id);
12256 if (IS_ERR(tmp))
12257 return false;
12258
12259 WARN_ON_ONCE(tmp != val);
12260 return true;
12261}
12262
8f4c4963
PZ
12263static void perf_pmu_free(struct pmu *pmu)
12264{
8f4c4963
PZ
12265 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) {
12266 if (pmu->nr_addr_filters)
12267 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
12268 device_del(pmu->dev);
12269 put_device(pmu->dev);
12270 }
4eabf533
PZ
12271
12272 if (pmu->cpu_pmu_context) {
12273 int cpu;
12274
12275 for_each_possible_cpu(cpu) {
12276 struct perf_cpu_pmu_context *cpc;
12277
12278 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu);
12279 if (!cpc)
12280 continue;
12281 if (cpc->epc.embedded) {
12282 /* refcount managed */
12283 put_pmu_ctx(&cpc->epc);
12284 continue;
12285 }
12286 kfree(cpc);
12287 }
12288 free_percpu(pmu->cpu_pmu_context);
12289 }
8f4c4963
PZ
12290}
12291
6c8b0b83
PZ
12292DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T))
12293
12294int perf_pmu_register(struct pmu *_pmu, const char *name, int type)
24f1e32c 12295{
6c8b0b83 12296 int cpu, max = PERF_TYPE_MAX;
24f1e32c 12297
6c8b0b83
PZ
12298 struct pmu *pmu __free(pmu_unregister) = _pmu;
12299 guard(mutex)(&pmus_lock);
8f4c4963 12300
6c8b0b83
PZ
12301 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n"))
12302 return -EINVAL;
0d6d062c 12303
6c8b0b83
PZ
12304 if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE,
12305 "Can not register a pmu with an invalid scope.\n"))
12306 return -EINVAL;
4ba4f1af 12307
2e80a82a
PZ
12308 pmu->name = name;
12309
0d6d062c
RB
12310 if (type >= 0)
12311 max = type;
66d258c5 12312
6c8b0b83
PZ
12313 CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL);
12314 if (pmu_type.id < 0)
12315 return pmu_type.id;
66d258c5 12316
6c8b0b83 12317 WARN_ON(type >= 0 && pmu_type.id != type);
66d258c5 12318
6c8b0b83 12319 pmu->type = pmu_type.id;
003659fe 12320 atomic_set(&pmu->exclusive_cnt, 0);
2e80a82a 12321
0d6d062c 12322 if (pmu_bus_running && !pmu->dev) {
6c8b0b83 12323 int ret = pmu_dev_alloc(pmu);
abe43400 12324 if (ret)
6c8b0b83 12325 return ret;
abe43400
PZ
12326 }
12327
4eabf533 12328 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *);
bd275681 12329 if (!pmu->cpu_pmu_context)
6c8b0b83 12330 return -ENOMEM;
f344011c 12331
108b02cf 12332 for_each_possible_cpu(cpu) {
4eabf533
PZ
12333 struct perf_cpu_pmu_context *cpc =
12334 kmalloc_node(sizeof(struct perf_cpu_pmu_context),
12335 GFP_KERNEL | __GFP_ZERO,
12336 cpu_to_node(cpu));
12337
12338 if (!cpc)
12339 return -ENOMEM;
9e630205 12340
4eabf533 12341 *per_cpu_ptr(pmu->cpu_pmu_context, cpu) = cpc;
bd275681
PZ
12342 __perf_init_event_pmu_context(&cpc->epc, pmu);
12343 __perf_mux_hrtimer_init(cpc, cpu);
108b02cf 12344 }
76e1d904 12345
ad5133b7
PZ
12346 if (!pmu->start_txn) {
12347 if (pmu->pmu_enable) {
12348 /*
12349 * If we have pmu_enable/pmu_disable calls, install
12350 * transaction stubs that use that to try and batch
12351 * hardware accesses.
12352 */
12353 pmu->start_txn = perf_pmu_start_txn;
12354 pmu->commit_txn = perf_pmu_commit_txn;
12355 pmu->cancel_txn = perf_pmu_cancel_txn;
12356 } else {
fbbe0701 12357 pmu->start_txn = perf_pmu_nop_txn;
ad5133b7
PZ
12358 pmu->commit_txn = perf_pmu_nop_int;
12359 pmu->cancel_txn = perf_pmu_nop_void;
f344011c 12360 }
5c92d124 12361 }
15dbf27c 12362
ad5133b7
PZ
12363 if (!pmu->pmu_enable) {
12364 pmu->pmu_enable = perf_pmu_nop_void;
12365 pmu->pmu_disable = perf_pmu_nop_void;
12366 }
12367
81ec3f3c
JO
12368 if (!pmu->check_period)
12369 pmu->check_period = perf_event_nop_int;
12370
35edc2a5
PZ
12371 if (!pmu->event_idx)
12372 pmu->event_idx = perf_event_idx_default;
12373
da916e96
PZ
12374 INIT_LIST_HEAD(&pmu->events);
12375 spin_lock_init(&pmu->events_lock);
12376
003659fe
PZ
12377 /*
12378 * Now that the PMU is complete, make it visible to perf_try_init_event().
12379 */
6c8b0b83
PZ
12380 if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu))
12381 return -EINVAL;
0d6d062c 12382 list_add_rcu(&pmu->entry, &pmus);
003659fe 12383
6c8b0b83
PZ
12384 take_idr_id(pmu_type);
12385 _pmu = no_free_ptr(pmu); // let it rip
12386 return 0;
f29ac756 12387}
c464c76e 12388EXPORT_SYMBOL_GPL(perf_pmu_register);
f29ac756 12389
da916e96
PZ
12390static void __pmu_detach_event(struct pmu *pmu, struct perf_event *event,
12391 struct perf_event_context *ctx)
12392{
12393 /*
12394 * De-schedule the event and mark it REVOKED.
12395 */
12396 perf_event_exit_event(event, ctx, true);
12397
12398 /*
12399 * All _free_event() bits that rely on event->pmu:
12400 *
12401 * Notably, perf_mmap() relies on the ordering here.
12402 */
12403 scoped_guard (mutex, &event->mmap_mutex) {
12404 WARN_ON_ONCE(pmu->event_unmapped);
12405 /*
12406 * Mostly an empty lock sequence, such that perf_mmap(), which
12407 * relies on mmap_mutex, is sure to observe the state change.
12408 */
12409 }
12410
12411 perf_event_free_bpf_prog(event);
12412 perf_free_addr_filters(event);
12413
12414 if (event->destroy) {
12415 event->destroy(event);
12416 event->destroy = NULL;
12417 }
12418
12419 if (event->pmu_ctx) {
12420 put_pmu_ctx(event->pmu_ctx);
12421 event->pmu_ctx = NULL;
12422 }
12423
12424 exclusive_event_destroy(event);
12425 module_put(pmu->module);
12426
12427 event->pmu = NULL; /* force fault instead of UAF */
12428}
12429
12430static void pmu_detach_event(struct pmu *pmu, struct perf_event *event)
12431{
12432 struct perf_event_context *ctx;
12433
12434 ctx = perf_event_ctx_lock(event);
12435 __pmu_detach_event(pmu, event, ctx);
12436 perf_event_ctx_unlock(event, ctx);
12437
12438 scoped_guard (spinlock, &pmu->events_lock)
12439 list_del(&event->pmu_list);
12440}
12441
12442static struct perf_event *pmu_get_event(struct pmu *pmu)
12443{
12444 struct perf_event *event;
12445
12446 guard(spinlock)(&pmu->events_lock);
12447 list_for_each_entry(event, &pmu->events, pmu_list) {
12448 if (atomic_long_inc_not_zero(&event->refcount))
12449 return event;
12450 }
12451
12452 return NULL;
12453}
12454
12455static bool pmu_empty(struct pmu *pmu)
12456{
12457 guard(spinlock)(&pmu->events_lock);
12458 return list_empty(&pmu->events);
12459}
12460
12461static void pmu_detach_events(struct pmu *pmu)
12462{
12463 struct perf_event *event;
12464
12465 for (;;) {
12466 event = pmu_get_event(pmu);
12467 if (!event)
12468 break;
12469
12470 pmu_detach_event(pmu, event);
12471 put_event(event);
12472 }
12473
12474 /*
12475 * wait for pending _free_event()s
12476 */
12477 wait_var_event(pmu, pmu_empty(pmu));
12478}
12479
12480int perf_pmu_unregister(struct pmu *pmu)
5c92d124 12481{
6c8b0b83 12482 scoped_guard (mutex, &pmus_lock) {
da916e96
PZ
12483 if (!idr_cmpxchg(&pmu_idr, pmu->type, pmu, NULL))
12484 return -EINVAL;
12485
6c8b0b83 12486 list_del_rcu(&pmu->entry);
6c8b0b83 12487 }
5c92d124 12488
0475f9ea 12489 /*
cde8e884
PZ
12490 * We dereference the pmu list under both SRCU and regular RCU, so
12491 * synchronize against both of those.
da916e96
PZ
12492 *
12493 * Notably, the entirety of event creation, from perf_init_event()
12494 * (which will now fail, because of the above) until
12495 * perf_install_in_context() should be under SRCU such that
12496 * this synchronizes against event creation. This avoids trying to
12497 * detach events that are not fully formed.
0475f9ea 12498 */
b0a873eb 12499 synchronize_srcu(&pmus_srcu);
cde8e884 12500 synchronize_rcu();
d6d020e9 12501
da916e96
PZ
12502 if (pmu->event_unmapped && !pmu_empty(pmu)) {
12503 /*
12504 * Can't force remove events when pmu::event_unmapped()
12505 * is used in perf_mmap_close().
12506 */
12507 guard(mutex)(&pmus_lock);
12508 idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu);
12509 list_add_rcu(&pmu->entry, &pmus);
12510 return -EBUSY;
12511 }
12512
12513 scoped_guard (mutex, &pmus_lock)
12514 idr_remove(&pmu_idr, pmu->type);
12515
12516 /*
12517 * PMU is removed from the pmus list, so no new events will
12518 * be created, now take care of the existing ones.
12519 */
12520 pmu_detach_events(pmu);
12521
12522 /*
12523 * PMU is unused, make it go away.
12524 */
8f4c4963 12525 perf_pmu_free(pmu);
da916e96 12526 return 0;
b0a873eb 12527}
c464c76e 12528EXPORT_SYMBOL_GPL(perf_pmu_unregister);
d6d020e9 12529
e321d02d
KL
12530static inline bool has_extended_regs(struct perf_event *event)
12531{
12532 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
12533 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
12534}
12535
cc34b98b
MR
12536static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
12537{
ccd41c86 12538 struct perf_event_context *ctx = NULL;
cc34b98b
MR
12539 int ret;
12540
12541 if (!try_module_get(pmu->module))
12542 return -ENODEV;
ccd41c86 12543
0c7296ca
PZ
12544 /*
12545 * A number of pmu->event_init() methods iterate the sibling_list to,
12546 * for example, validate if the group fits on the PMU. Therefore,
12547 * if this is a sibling event, acquire the ctx->mutex to protect
12548 * the sibling_list.
12549 */
12550 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
8b10c5e2
PZ
12551 /*
12552 * This ctx->mutex can nest when we're called through
12553 * inheritance. See the perf_event_ctx_lock_nested() comment.
12554 */
12555 ctx = perf_event_ctx_lock_nested(event->group_leader,
12556 SINGLE_DEPTH_NESTING);
ccd41c86
PZ
12557 BUG_ON(!ctx);
12558 }
12559
cc34b98b
MR
12560 event->pmu = pmu;
12561 ret = pmu->event_init(event);
ccd41c86
PZ
12562
12563 if (ctx)
12564 perf_event_ctx_unlock(event->group_leader, ctx);
12565
da02f54e
PZ
12566 if (ret)
12567 goto err_pmu;
e321d02d 12568
da02f54e
PZ
12569 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
12570 has_extended_regs(event)) {
12571 ret = -EOPNOTSUPP;
12572 goto err_destroy;
12573 }
e321d02d 12574
da02f54e
PZ
12575 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
12576 event_has_any_exclude_flag(event)) {
12577 ret = -EINVAL;
12578 goto err_destroy;
12579 }
4ba4f1af 12580
da02f54e
PZ
12581 if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) {
12582 const struct cpumask *cpumask;
12583 struct cpumask *pmu_cpumask;
12584 int cpu;
12585
12586 cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu);
12587 pmu_cpumask = perf_scope_cpumask(pmu->scope);
12588
12589 ret = -ENODEV;
12590 if (!pmu_cpumask || !cpumask)
12591 goto err_destroy;
12592
12593 cpu = cpumask_any_and(pmu_cpumask, cpumask);
12594 if (cpu >= nr_cpu_ids)
12595 goto err_destroy;
12596
12597 event->event_caps |= PERF_EV_CAP_READ_SCOPE;
cc6795ae
AM
12598 }
12599
da02f54e
PZ
12600 return 0;
12601
12602err_destroy:
12603 if (event->destroy) {
12604 event->destroy(event);
12605 event->destroy = NULL;
c70ca298 12606 }
cc34b98b 12607
da02f54e
PZ
12608err_pmu:
12609 event->pmu = NULL;
12610 module_put(pmu->module);
cc34b98b
MR
12611 return ret;
12612}
12613
18ab2cd3 12614static struct pmu *perf_init_event(struct perf_event *event)
b0a873eb 12615{
55bcf6ef 12616 bool extended_type = false;
85c617ab 12617 struct pmu *pmu;
caf8b765 12618 int type, ret;
b0a873eb 12619
da916e96 12620 guard(srcu)(&pmus_srcu); /* pmu idr/list access */
2e80a82a 12621
0d6d062c
RB
12622 /*
12623 * Save original type before calling pmu->event_init() since certain
12624 * pmus overwrites event->attr.type to forward event to another pmu.
12625 */
12626 event->orig_type = event->attr.type;
12627
40999312
KL
12628 /* Try parent's PMU first: */
12629 if (event->parent && event->parent->pmu) {
12630 pmu = event->parent->pmu;
12631 ret = perf_try_init_event(pmu, event);
12632 if (!ret)
caf8b765 12633 return pmu;
40999312
KL
12634 }
12635
66d258c5
PZ
12636 /*
12637 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
12638 * are often aliases for PERF_TYPE_RAW.
12639 */
12640 type = event->attr.type;
55bcf6ef
KL
12641 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) {
12642 type = event->attr.config >> PERF_PMU_TYPE_SHIFT;
12643 if (!type) {
12644 type = PERF_TYPE_RAW;
12645 } else {
12646 extended_type = true;
12647 event->attr.config &= PERF_HW_EVENT_MASK;
12648 }
12649 }
66d258c5
PZ
12650
12651again:
caf8b765
PZ
12652 scoped_guard (rcu)
12653 pmu = idr_find(&pmu_idr, type);
940c5b29 12654 if (pmu) {
55bcf6ef
KL
12655 if (event->attr.type != type && type != PERF_TYPE_RAW &&
12656 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE))
caf8b765 12657 return ERR_PTR(-ENOENT);
55bcf6ef 12658
cc34b98b 12659 ret = perf_try_init_event(pmu, event);
55bcf6ef 12660 if (ret == -ENOENT && event->attr.type != type && !extended_type) {
66d258c5
PZ
12661 type = event->attr.type;
12662 goto again;
12663 }
12664
940c5b29 12665 if (ret)
caf8b765 12666 return ERR_PTR(ret);
66d258c5 12667
caf8b765 12668 return pmu;
940c5b29 12669 }
2e80a82a 12670
9f0bff11 12671 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
cc34b98b 12672 ret = perf_try_init_event(pmu, event);
b0a873eb 12673 if (!ret)
caf8b765 12674 return pmu;
76e1d904 12675
caf8b765
PZ
12676 if (ret != -ENOENT)
12677 return ERR_PTR(ret);
5c92d124 12678 }
15dbf27c 12679
caf8b765 12680 return ERR_PTR(-ENOENT);
5c92d124
IM
12681}
12682
f2fb6bef
KL
12683static void attach_sb_event(struct perf_event *event)
12684{
12685 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
12686
12687 raw_spin_lock(&pel->lock);
12688 list_add_rcu(&event->sb_list, &pel->list);
12689 raw_spin_unlock(&pel->lock);
12690}
12691
aab5b71e
PZ
12692/*
12693 * We keep a list of all !task (and therefore per-cpu) events
12694 * that need to receive side-band records.
12695 *
12696 * This avoids having to scan all the various PMU per-cpu contexts
12697 * looking for them.
12698 */
f2fb6bef
KL
12699static void account_pmu_sb_event(struct perf_event *event)
12700{
a4f144eb 12701 if (is_sb_event(event))
f2fb6bef
KL
12702 attach_sb_event(event);
12703}
12704
555e0c1e
FW
12705/* Freq events need the tick to stay alive (see perf_event_task_tick). */
12706static void account_freq_event_nohz(void)
12707{
12708#ifdef CONFIG_NO_HZ_FULL
12709 /* Lock so we don't race with concurrent unaccount */
12710 spin_lock(&nr_freq_lock);
12711 if (atomic_inc_return(&nr_freq_events) == 1)
12712 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
12713 spin_unlock(&nr_freq_lock);
12714#endif
12715}
12716
12717static void account_freq_event(void)
12718{
12719 if (tick_nohz_full_enabled())
12720 account_freq_event_nohz();
12721 else
12722 atomic_inc(&nr_freq_events);
12723}
12724
12725
766d6c07
FW
12726static void account_event(struct perf_event *event)
12727{
25432ae9
PZ
12728 bool inc = false;
12729
4beb31f3
FW
12730 if (event->parent)
12731 return;
12732
a5398bff 12733 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB))
25432ae9 12734 inc = true;
766d6c07
FW
12735 if (event->attr.mmap || event->attr.mmap_data)
12736 atomic_inc(&nr_mmap_events);
88a16a13
JO
12737 if (event->attr.build_id)
12738 atomic_inc(&nr_build_id_events);
766d6c07
FW
12739 if (event->attr.comm)
12740 atomic_inc(&nr_comm_events);
e4222673
HB
12741 if (event->attr.namespaces)
12742 atomic_inc(&nr_namespaces_events);
96aaab68
NK
12743 if (event->attr.cgroup)
12744 atomic_inc(&nr_cgroup_events);
766d6c07
FW
12745 if (event->attr.task)
12746 atomic_inc(&nr_task_events);
555e0c1e
FW
12747 if (event->attr.freq)
12748 account_freq_event();
45ac1403
AH
12749 if (event->attr.context_switch) {
12750 atomic_inc(&nr_switch_events);
25432ae9 12751 inc = true;
45ac1403 12752 }
4beb31f3 12753 if (has_branch_stack(event))
25432ae9 12754 inc = true;
4beb31f3 12755 if (is_cgroup_event(event))
25432ae9 12756 inc = true;
76193a94
SL
12757 if (event->attr.ksymbol)
12758 atomic_inc(&nr_ksymbol_events);
6ee52e2a
SL
12759 if (event->attr.bpf_event)
12760 atomic_inc(&nr_bpf_events);
e17d43b9
AH
12761 if (event->attr.text_poke)
12762 atomic_inc(&nr_text_poke_events);
25432ae9 12763
9107c89e 12764 if (inc) {
5bce9db1
AS
12765 /*
12766 * We need the mutex here because static_branch_enable()
12767 * must complete *before* the perf_sched_count increment
12768 * becomes visible.
12769 */
9107c89e
PZ
12770 if (atomic_inc_not_zero(&perf_sched_count))
12771 goto enabled;
12772
12773 mutex_lock(&perf_sched_mutex);
12774 if (!atomic_read(&perf_sched_count)) {
12775 static_branch_enable(&perf_sched_events);
12776 /*
12777 * Guarantee that all CPUs observe they key change and
12778 * call the perf scheduling hooks before proceeding to
12779 * install events that need them.
12780 */
0809d954 12781 synchronize_rcu();
9107c89e
PZ
12782 }
12783 /*
12784 * Now that we have waited for the sync_sched(), allow further
12785 * increments to by-pass the mutex.
12786 */
12787 atomic_inc(&perf_sched_count);
12788 mutex_unlock(&perf_sched_mutex);
12789 }
12790enabled:
4beb31f3 12791
f2fb6bef 12792 account_pmu_sb_event(event);
766d6c07
FW
12793}
12794
0793a61d 12795/*
788faab7 12796 * Allocate and initialize an event structure
0793a61d 12797 */
cdd6c482 12798static struct perf_event *
c3f00c70 12799perf_event_alloc(struct perf_event_attr *attr, int cpu,
d580ff86
PZ
12800 struct task_struct *task,
12801 struct perf_event *group_leader,
12802 struct perf_event *parent_event,
4dc0da86 12803 perf_overflow_handler_t overflow_handler,
79dff51e 12804 void *context, int cgroup_fd)
0793a61d 12805{
51b0fe39 12806 struct pmu *pmu;
cdd6c482 12807 struct hw_perf_event *hwc;
90983b16 12808 long err = -EINVAL;
ff65338e 12809 int node;
0793a61d 12810
66832eb4
ON
12811 if ((unsigned)cpu >= nr_cpu_ids) {
12812 if (!task || cpu != -1)
12813 return ERR_PTR(-EINVAL);
12814 }
97ba62b2
ME
12815 if (attr->sigtrap && !task) {
12816 /* Requires a task: avoid signalling random tasks. */
12817 return ERR_PTR(-EINVAL);
12818 }
66832eb4 12819
ff65338e 12820 node = (cpu >= 0) ? cpu_to_node(cpu) : -1;
8f2221f5
PZ
12821 struct perf_event *event __free(__free_event) =
12822 kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node);
cdd6c482 12823 if (!event)
d5d2bc0d 12824 return ERR_PTR(-ENOMEM);
0793a61d 12825
04289bb9 12826 /*
cdd6c482 12827 * Single events are their own group leaders, with an
04289bb9
IM
12828 * empty sibling list:
12829 */
12830 if (!group_leader)
cdd6c482 12831 group_leader = event;
04289bb9 12832
cdd6c482
IM
12833 mutex_init(&event->child_mutex);
12834 INIT_LIST_HEAD(&event->child_list);
fccc714b 12835
cdd6c482
IM
12836 INIT_LIST_HEAD(&event->event_entry);
12837 INIT_LIST_HEAD(&event->sibling_list);
6668128a 12838 INIT_LIST_HEAD(&event->active_list);
8e1a2031 12839 init_event_group(event);
10c6db11 12840 INIT_LIST_HEAD(&event->rb_entry);
71ad88ef 12841 INIT_LIST_HEAD(&event->active_entry);
375637bc 12842 INIT_LIST_HEAD(&event->addr_filters.list);
f3ae75de 12843 INIT_HLIST_NODE(&event->hlist_entry);
da916e96 12844 INIT_LIST_HEAD(&event->pmu_list);
f3ae75de 12845
10c6db11 12846
cdd6c482 12847 init_waitqueue_head(&event->waitq);
ca6c2132 12848 init_irq_work(&event->pending_irq, perf_pending_irq);
2b84def9 12849 event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable);
ca6c2132 12850 init_task_work(&event->pending_task, perf_pending_task);
0793a61d 12851
cdd6c482 12852 mutex_init(&event->mmap_mutex);
375637bc 12853 raw_spin_lock_init(&event->addr_filters.lock);
7b732a75 12854
a6fa941d 12855 atomic_long_set(&event->refcount, 1);
cdd6c482
IM
12856 event->cpu = cpu;
12857 event->attr = *attr;
12858 event->group_leader = group_leader;
12859 event->pmu = NULL;
cdd6c482 12860 event->oncpu = -1;
a96bbc16 12861
cdd6c482 12862 event->parent = parent_event;
b84fbc9f 12863
17cf22c3 12864 event->ns = get_pid_ns(task_active_pid_ns(current));
cdd6c482 12865 event->id = atomic64_inc_return(&perf_event_id);
a96bbc16 12866
cdd6c482 12867 event->state = PERF_EVENT_STATE_INACTIVE;
329d876d 12868
e3265a43
NK
12869 if (parent_event)
12870 event->event_caps = parent_event->event_caps;
12871
d580ff86
PZ
12872 if (task) {
12873 event->attach_state = PERF_ATTACH_TASK;
d580ff86 12874 /*
50f16a8b
PZ
12875 * XXX pmu::event_init needs to know what task to account to
12876 * and we cannot use the ctx information because we need the
12877 * pmu before we get a ctx.
d580ff86 12878 */
7b3c92b8 12879 event->hw.target = get_task_struct(task);
d580ff86
PZ
12880 }
12881
34f43927
PZ
12882 event->clock = &local_clock;
12883 if (parent_event)
12884 event->clock = parent_event->clock;
12885
4dc0da86 12886 if (!overflow_handler && parent_event) {
b326e956 12887 overflow_handler = parent_event->overflow_handler;
4dc0da86 12888 context = parent_event->overflow_handler_context;
f1e4ba5b 12889#if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
f11f10bf 12890 if (parent_event->prog) {
85192dbf 12891 struct bpf_prog *prog = parent_event->prog;
aa6a5f3c 12892
85192dbf 12893 bpf_prog_inc(prog);
aa6a5f3c 12894 event->prog = prog;
aa6a5f3c
AS
12895 }
12896#endif
4dc0da86 12897 }
66832eb4 12898
1879445d
WN
12899 if (overflow_handler) {
12900 event->overflow_handler = overflow_handler;
12901 event->overflow_handler_context = context;
9ecda41a
WN
12902 } else if (is_write_backward(event)){
12903 event->overflow_handler = perf_event_output_backward;
12904 event->overflow_handler_context = NULL;
1879445d 12905 } else {
9ecda41a 12906 event->overflow_handler = perf_event_output_forward;
1879445d
WN
12907 event->overflow_handler_context = NULL;
12908 }
97eaf530 12909
0231bb53 12910 perf_event__state_init(event);
a86ed508 12911
4aeb0b42 12912 pmu = NULL;
b8e83514 12913
cdd6c482 12914 hwc = &event->hw;
bd2b5b12 12915 hwc->sample_period = attr->sample_period;
ca559503 12916 if (is_event_in_freq_mode(event))
bd2b5b12 12917 hwc->sample_period = 1;
eced1dfc 12918 hwc->last_period = hwc->sample_period;
bd2b5b12 12919
e7850595 12920 local64_set(&hwc->period_left, hwc->sample_period);
60db5e09 12921
2023b359 12922 /*
7e8b2556
BG
12923 * We do not support PERF_SAMPLE_READ on inherited events unless
12924 * PERF_SAMPLE_TID is also selected, which allows inherited events to
12925 * collect per-thread samples.
ba5213ae 12926 * See perf_output_read().
2023b359 12927 */
7e8b2556 12928 if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID))
8f2221f5 12929 return ERR_PTR(-EINVAL);
a46a2300
YZ
12930
12931 if (!has_branch_stack(event))
12932 event->attr.branch_sample_type = 0;
2023b359 12933
b0a873eb 12934 pmu = perf_init_event(event);
8f2221f5
PZ
12935 if (IS_ERR(pmu))
12936 return (void*)pmu;
d5d2bc0d 12937
506e64e7
KL
12938 /*
12939 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config().
12940 * The attach should be right after the perf_init_event().
12941 * Otherwise, the __free_event() would mistakenly detach the non-exist
12942 * perf_ctx_data because of the other errors between them.
12943 */
12944 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
12945 err = attach_perf_ctx_data(event);
12946 if (err)
12947 return ERR_PTR(err);
12948 }
12949
09f4e8f0 12950 /*
bd275681
PZ
12951 * Disallow uncore-task events. Similarly, disallow uncore-cgroup
12952 * events (they don't make sense as the cgroup will be different
12953 * on other CPUs in the uncore mask).
09f4e8f0 12954 */
8f2221f5
PZ
12955 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1))
12956 return ERR_PTR(-EINVAL);
09f4e8f0 12957
ab43762e 12958 if (event->attr.aux_output &&
18d92bb5 12959 (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) ||
8f2221f5
PZ
12960 event->attr.aux_pause || event->attr.aux_resume))
12961 return ERR_PTR(-EOPNOTSUPP);
ab43762e 12962
8f2221f5
PZ
12963 if (event->attr.aux_pause && event->attr.aux_resume)
12964 return ERR_PTR(-EINVAL);
18d92bb5
AH
12965
12966 if (event->attr.aux_start_paused) {
8f2221f5
PZ
12967 if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE))
12968 return ERR_PTR(-EOPNOTSUPP);
18d92bb5
AH
12969 event->hw.aux_paused = 1;
12970 }
12971
98add2af
PZ
12972 if (cgroup_fd != -1) {
12973 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
12974 if (err)
8f2221f5 12975 return ERR_PTR(err);
98add2af
PZ
12976 }
12977
bed5b25a
AS
12978 err = exclusive_event_init(event);
12979 if (err)
8f2221f5 12980 return ERR_PTR(err);
bed5b25a 12981
375637bc 12982 if (has_addr_filter(event)) {
c60f83b8
AS
12983 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
12984 sizeof(struct perf_addr_filter_range),
12985 GFP_KERNEL);
8f2221f5
PZ
12986 if (!event->addr_filter_ranges)
12987 return ERR_PTR(-ENOMEM);
375637bc 12988
18736eef
AS
12989 /*
12990 * Clone the parent's vma offsets: they are valid until exec()
12991 * even if the mm is not shared with the parent.
12992 */
12993 if (event->parent) {
12994 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
12995
12996 raw_spin_lock_irq(&ifh->lock);
c60f83b8
AS
12997 memcpy(event->addr_filter_ranges,
12998 event->parent->addr_filter_ranges,
12999 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
18736eef
AS
13000 raw_spin_unlock_irq(&ifh->lock);
13001 }
13002
375637bc
AS
13003 /* force hw sync on the address filters */
13004 event->addr_filters_gen = 1;
13005 }
13006
cdd6c482 13007 if (!event->parent) {
927c7a9e 13008 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
97c79a38 13009 err = get_callchain_buffers(attr->sample_max_stack);
90983b16 13010 if (err)
8f2221f5 13011 return ERR_PTR(err);
c70ca298 13012 event->attach_state |= PERF_ATTACH_CALLCHAIN;
d010b332 13013 }
f344011c 13014 }
9ee318a7 13015
da97e184
JFG
13016 err = security_perf_event_alloc(event);
13017 if (err)
8f2221f5 13018 return ERR_PTR(err);
da97e184 13019
927a5570
AS
13020 /* symmetric to unaccount_event() in _free_event() */
13021 account_event(event);
13022
da916e96
PZ
13023 /*
13024 * Event creation should be under SRCU, see perf_pmu_unregister().
13025 */
13026 lockdep_assert_held(&pmus_srcu);
13027 scoped_guard (spinlock, &pmu->events_lock)
13028 list_add(&event->pmu_list, &pmu->events);
13029
8f2221f5 13030 return_ptr(event);
0793a61d
TG
13031}
13032
cdd6c482
IM
13033static int perf_copy_attr(struct perf_event_attr __user *uattr,
13034 struct perf_event_attr *attr)
974802ea 13035{
974802ea 13036 u32 size;
cdf8073d 13037 int ret;
974802ea 13038
c2ba8f41 13039 /* Zero the full structure, so that a short copy will be nice. */
974802ea
PZ
13040 memset(attr, 0, sizeof(*attr));
13041
13042 ret = get_user(size, &uattr->size);
13043 if (ret)
13044 return ret;
13045
c2ba8f41
AS
13046 /* ABI compatibility quirk: */
13047 if (!size)
974802ea 13048 size = PERF_ATTR_SIZE_VER0;
c2ba8f41 13049 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
974802ea
PZ
13050 goto err_size;
13051
c2ba8f41
AS
13052 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
13053 if (ret) {
13054 if (ret == -E2BIG)
13055 goto err_size;
13056 return ret;
974802ea
PZ
13057 }
13058
f12f42ac
MX
13059 attr->size = size;
13060
a4faf00d 13061 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
974802ea
PZ
13062 return -EINVAL;
13063
13064 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
13065 return -EINVAL;
13066
13067 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
13068 return -EINVAL;
13069
bce38cd5
SE
13070 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
13071 u64 mask = attr->branch_sample_type;
13072
13073 /* only using defined bits */
13074 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
13075 return -EINVAL;
13076
13077 /* at least one branch bit must be set */
13078 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
13079 return -EINVAL;
13080
bce38cd5
SE
13081 /* propagate priv level, when not set for branch */
13082 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
13083
13084 /* exclude_kernel checked on syscall entry */
13085 if (!attr->exclude_kernel)
13086 mask |= PERF_SAMPLE_BRANCH_KERNEL;
13087
13088 if (!attr->exclude_user)
13089 mask |= PERF_SAMPLE_BRANCH_USER;
13090
13091 if (!attr->exclude_hv)
13092 mask |= PERF_SAMPLE_BRANCH_HV;
13093 /*
13094 * adjust user setting (for HW filter setup)
13095 */
13096 attr->branch_sample_type = mask;
13097 }
e712209a 13098 /* privileged levels capture (kernel, hv): check permissions */
da97e184 13099 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
9ec84f79 13100 ret = perf_allow_kernel();
da97e184
JFG
13101 if (ret)
13102 return ret;
13103 }
bce38cd5 13104 }
4018994f 13105
c5ebcedb 13106 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
4018994f 13107 ret = perf_reg_validate(attr->sample_regs_user);
c5ebcedb
JO
13108 if (ret)
13109 return ret;
13110 }
13111
13112 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
13113 if (!arch_perf_have_user_stack_dump())
13114 return -ENOSYS;
13115
13116 /*
13117 * We have __u32 type for the size, but so far
13118 * we can only use __u16 as maximum due to the
13119 * __u16 sample size limit.
13120 */
13121 if (attr->sample_stack_user >= USHRT_MAX)
78b562fb 13122 return -EINVAL;
c5ebcedb 13123 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
78b562fb 13124 return -EINVAL;
c5ebcedb 13125 }
4018994f 13126
5f970521
JO
13127 if (!attr->sample_max_stack)
13128 attr->sample_max_stack = sysctl_perf_event_max_stack;
13129
60e2364e
SE
13130 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
13131 ret = perf_reg_validate(attr->sample_regs_intr);
6546b19f
NK
13132
13133#ifndef CONFIG_CGROUP_PERF
13134 if (attr->sample_type & PERF_SAMPLE_CGROUP)
13135 return -EINVAL;
13136#endif
2a6c6b7d
KL
13137 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) &&
13138 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT))
13139 return -EINVAL;
6546b19f 13140
2b26f0aa
ME
13141 if (!attr->inherit && attr->inherit_thread)
13142 return -EINVAL;
13143
2e498d0a
ME
13144 if (attr->remove_on_exec && attr->enable_on_exec)
13145 return -EINVAL;
13146
97ba62b2
ME
13147 if (attr->sigtrap && !attr->remove_on_exec)
13148 return -EINVAL;
13149
974802ea
PZ
13150out:
13151 return ret;
13152
13153err_size:
13154 put_user(sizeof(*attr), &uattr->size);
13155 ret = -E2BIG;
13156 goto out;
13157}
13158
68e3c698
PZ
13159static void mutex_lock_double(struct mutex *a, struct mutex *b)
13160{
13161 if (b < a)
13162 swap(a, b);
13163
13164 mutex_lock(a);
13165 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
13166}
13167
ac9721f3
PZ
13168static int
13169perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
a4be7c27 13170{
56de4e8f 13171 struct perf_buffer *rb = NULL;
a4be7c27
PZ
13172 int ret = -EINVAL;
13173
68e3c698
PZ
13174 if (!output_event) {
13175 mutex_lock(&event->mmap_mutex);
a4be7c27 13176 goto set;
68e3c698 13177 }
a4be7c27 13178
ac9721f3
PZ
13179 /* don't allow circular references */
13180 if (event == output_event)
a4be7c27
PZ
13181 goto out;
13182
0f139300
PZ
13183 /*
13184 * Don't allow cross-cpu buffers
13185 */
13186 if (output_event->cpu != event->cpu)
13187 goto out;
13188
13189 /*
76369139 13190 * If its not a per-cpu rb, it must be the same task.
0f139300 13191 */
24d3ae2f 13192 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
0f139300
PZ
13193 goto out;
13194
34f43927
PZ
13195 /*
13196 * Mixing clocks in the same buffer is trouble you don't need.
13197 */
13198 if (output_event->clock != event->clock)
13199 goto out;
13200
9ecda41a
WN
13201 /*
13202 * Either writing ring buffer from beginning or from end.
13203 * Mixing is not allowed.
13204 */
13205 if (is_write_backward(output_event) != is_write_backward(event))
13206 goto out;
13207
45bfb2e5
PZ
13208 /*
13209 * If both events generate aux data, they must be on the same PMU
13210 */
13211 if (has_aux(event) && has_aux(output_event) &&
13212 event->pmu != output_event->pmu)
13213 goto out;
13214
68e3c698
PZ
13215 /*
13216 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
13217 * output_event is already on rb->event_list, and the list iteration
13218 * restarts after every removal, it is guaranteed this new event is
13219 * observed *OR* if output_event is already removed, it's guaranteed we
13220 * observe !rb->mmap_count.
13221 */
13222 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
a4be7c27 13223set:
ac9721f3
PZ
13224 /* Can't redirect output if we've got an active mmap() */
13225 if (atomic_read(&event->mmap_count))
13226 goto unlock;
a4be7c27 13227
ac9721f3 13228 if (output_event) {
da916e96
PZ
13229 if (output_event->state <= PERF_EVENT_STATE_REVOKED)
13230 goto unlock;
13231
76369139
FW
13232 /* get the rb we want to redirect to */
13233 rb = ring_buffer_get(output_event);
13234 if (!rb)
ac9721f3 13235 goto unlock;
68e3c698
PZ
13236
13237 /* did we race against perf_mmap_close() */
13238 if (!atomic_read(&rb->mmap_count)) {
13239 ring_buffer_put(rb);
13240 goto unlock;
13241 }
a4be7c27
PZ
13242 }
13243
b69cf536 13244 ring_buffer_attach(event, rb);
9bb5d40c 13245
a4be7c27 13246 ret = 0;
ac9721f3
PZ
13247unlock:
13248 mutex_unlock(&event->mmap_mutex);
68e3c698
PZ
13249 if (output_event)
13250 mutex_unlock(&output_event->mmap_mutex);
ac9721f3 13251
a4be7c27 13252out:
a4be7c27
PZ
13253 return ret;
13254}
13255
34f43927
PZ
13256static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
13257{
13258 bool nmi_safe = false;
13259
13260 switch (clk_id) {
13261 case CLOCK_MONOTONIC:
13262 event->clock = &ktime_get_mono_fast_ns;
13263 nmi_safe = true;
13264 break;
13265
13266 case CLOCK_MONOTONIC_RAW:
13267 event->clock = &ktime_get_raw_fast_ns;
13268 nmi_safe = true;
13269 break;
13270
13271 case CLOCK_REALTIME:
13272 event->clock = &ktime_get_real_ns;
13273 break;
13274
13275 case CLOCK_BOOTTIME:
9285ec4c 13276 event->clock = &ktime_get_boottime_ns;
34f43927
PZ
13277 break;
13278
13279 case CLOCK_TAI:
9285ec4c 13280 event->clock = &ktime_get_clocktai_ns;
34f43927
PZ
13281 break;
13282
13283 default:
13284 return -EINVAL;
13285 }
13286
13287 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
13288 return -EINVAL;
13289
13290 return 0;
13291}
13292
b068fc04
ME
13293static bool
13294perf_check_permission(struct perf_event_attr *attr, struct task_struct *task)
13295{
13296 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS;
13297 bool is_capable = perfmon_capable();
13298
13299 if (attr->sigtrap) {
13300 /*
13301 * perf_event_attr::sigtrap sends signals to the other task.
13302 * Require the current task to also have CAP_KILL.
13303 */
13304 rcu_read_lock();
13305 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL);
13306 rcu_read_unlock();
13307
13308 /*
13309 * If the required capabilities aren't available, checks for
13310 * ptrace permissions: upgrade to ATTACH, since sending signals
13311 * can effectively change the target task.
13312 */
13313 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS;
13314 }
13315
13316 /*
13317 * Preserve ptrace permission check for backwards compatibility. The
13318 * ptrace check also includes checks that the current task and other
13319 * task have matching uids, and is therefore not done here explicitly.
13320 */
13321 return is_capable || ptrace_may_access(task, ptrace_mode);
13322}
13323
0793a61d 13324/**
cdd6c482 13325 * sys_perf_event_open - open a performance event, associate it to a task/cpu
9f66a381 13326 *
cdd6c482 13327 * @attr_uptr: event_id type attributes for monitoring/sampling
0793a61d 13328 * @pid: target pid
9f66a381 13329 * @cpu: target cpu
cdd6c482 13330 * @group_fd: group leader event fd
a1ddf524 13331 * @flags: perf event open flags
0793a61d 13332 */
cdd6c482
IM
13333SYSCALL_DEFINE5(perf_event_open,
13334 struct perf_event_attr __user *, attr_uptr,
2743a5b0 13335 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
0793a61d 13336{
b04243ef 13337 struct perf_event *group_leader = NULL, *output_event = NULL;
bd275681 13338 struct perf_event_pmu_context *pmu_ctx;
b04243ef 13339 struct perf_event *event, *sibling;
cdd6c482 13340 struct perf_event_attr attr;
bd275681 13341 struct perf_event_context *ctx;
cdd6c482 13342 struct file *event_file = NULL;
38a81da2 13343 struct task_struct *task = NULL;
89a1e187 13344 struct pmu *pmu;
ea635c64 13345 int event_fd;
b04243ef 13346 int move_group = 0;
dc86cabe 13347 int err;
a21b0b35 13348 int f_flags = O_RDWR;
79dff51e 13349 int cgroup_fd = -1;
0793a61d 13350
2743a5b0 13351 /* for future expandability... */
e5d1367f 13352 if (flags & ~PERF_FLAG_ALL)
2743a5b0
PM
13353 return -EINVAL;
13354
0a041ebc 13355 err = perf_copy_attr(attr_uptr, &attr);
da97e184
JFG
13356 if (err)
13357 return err;
13358
0a041ebc 13359 /* Do we allow access to perf_event_open(2) ? */
9ec84f79 13360 err = security_perf_event_open(PERF_SECURITY_OPEN);
dc86cabe
IM
13361 if (err)
13362 return err;
eab656ae 13363
0764771d 13364 if (!attr.exclude_kernel) {
9ec84f79 13365 err = perf_allow_kernel();
da97e184
JFG
13366 if (err)
13367 return err;
0764771d
PZ
13368 }
13369
e4222673 13370 if (attr.namespaces) {
18aa1856 13371 if (!perfmon_capable())
e4222673
HB
13372 return -EACCES;
13373 }
13374
df58ab24 13375 if (attr.freq) {
cdd6c482 13376 if (attr.sample_freq > sysctl_perf_event_sample_rate)
df58ab24 13377 return -EINVAL;
0819b2e3
PZ
13378 } else {
13379 if (attr.sample_period & (1ULL << 63))
13380 return -EINVAL;
df58ab24
PZ
13381 }
13382
fc7ce9c7 13383 /* Only privileged users can get physical addresses */
da97e184 13384 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
9ec84f79 13385 err = perf_allow_kernel();
da97e184
JFG
13386 if (err)
13387 return err;
13388 }
fc7ce9c7 13389
08ef1af4
OM
13390 /* REGS_INTR can leak data, lockdown must prevent this */
13391 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
13392 err = security_locked_down(LOCKDOWN_PERF);
13393 if (err)
13394 return err;
13395 }
b0c8fdc7 13396
e5d1367f
SE
13397 /*
13398 * In cgroup mode, the pid argument is used to pass the fd
13399 * opened to the cgroup directory in cgroupfs. The cpu argument
13400 * designates the cpu on which to monitor threads from that
13401 * cgroup.
13402 */
13403 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
13404 return -EINVAL;
13405
a21b0b35
YD
13406 if (flags & PERF_FLAG_FD_CLOEXEC)
13407 f_flags |= O_CLOEXEC;
13408
13409 event_fd = get_unused_fd_flags(f_flags);
ea635c64
AV
13410 if (event_fd < 0)
13411 return event_fd;
13412
da916e96
PZ
13413 /*
13414 * Event creation should be under SRCU, see perf_pmu_unregister().
13415 */
13416 guard(srcu)(&pmus_srcu);
13417
4dd53b84 13418 CLASS(fd, group)(group_fd); // group_fd == -1 => empty
ac9721f3 13419 if (group_fd != -1) {
4dd53b84
AV
13420 if (!is_perf_file(group)) {
13421 err = -EBADF;
d14b12d7 13422 goto err_fd;
4dd53b84 13423 }
1da91ea8 13424 group_leader = fd_file(group)->private_data;
da916e96
PZ
13425 if (group_leader->state <= PERF_EVENT_STATE_REVOKED) {
13426 err = -ENODEV;
13427 goto err_fd;
13428 }
ac9721f3
PZ
13429 if (flags & PERF_FLAG_FD_OUTPUT)
13430 output_event = group_leader;
13431 if (flags & PERF_FLAG_FD_NO_GROUP)
13432 group_leader = NULL;
13433 }
13434
e5d1367f 13435 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
c6be5a5c
PZ
13436 task = find_lively_task_by_vpid(pid);
13437 if (IS_ERR(task)) {
13438 err = PTR_ERR(task);
4dd53b84 13439 goto err_fd;
c6be5a5c
PZ
13440 }
13441 }
13442
1f4ee503
PZ
13443 if (task && group_leader &&
13444 group_leader->attr.inherit != attr.inherit) {
13445 err = -EINVAL;
13446 goto err_task;
13447 }
13448
79dff51e
MF
13449 if (flags & PERF_FLAG_PID_CGROUP)
13450 cgroup_fd = pid;
13451
4dc0da86 13452 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
79dff51e 13453 NULL, NULL, cgroup_fd);
d14b12d7
SE
13454 if (IS_ERR(event)) {
13455 err = PTR_ERR(event);
78af4dc9 13456 goto err_task;
d14b12d7
SE
13457 }
13458
53b25335
VW
13459 if (is_sampling_event(event)) {
13460 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
a1396555 13461 err = -EOPNOTSUPP;
53b25335
VW
13462 goto err_alloc;
13463 }
13464 }
13465
89a1e187
PZ
13466 /*
13467 * Special case software events and allow them to be part of
13468 * any hardware group.
13469 */
13470 pmu = event->pmu;
b04243ef 13471
34f43927
PZ
13472 if (attr.use_clockid) {
13473 err = perf_event_set_clock(event, attr.clockid);
13474 if (err)
13475 goto err_alloc;
13476 }
13477
4ff6a8de
DCC
13478 if (pmu->task_ctx_nr == perf_sw_context)
13479 event->event_caps |= PERF_EV_CAP_SOFTWARE;
13480
bd275681
PZ
13481 if (task) {
13482 err = down_read_interruptible(&task->signal->exec_update_lock);
13483 if (err)
13484 goto err_alloc;
13485
13486 /*
13487 * We must hold exec_update_lock across this and any potential
13488 * perf_install_in_context() call for this new event to
13489 * serialize against exec() altering our credentials (and the
13490 * perf_event_exit_task() that could imply).
13491 */
13492 err = -EACCES;
13493 if (!perf_check_permission(&attr, task))
13494 goto err_cred;
b04243ef 13495 }
89a1e187
PZ
13496
13497 /*
13498 * Get the target context (task or percpu):
13499 */
bd275681 13500 ctx = find_get_context(task, event);
89a1e187
PZ
13501 if (IS_ERR(ctx)) {
13502 err = PTR_ERR(ctx);
bd275681
PZ
13503 goto err_cred;
13504 }
13505
13506 mutex_lock(&ctx->mutex);
13507
13508 if (ctx->task == TASK_TOMBSTONE) {
13509 err = -ESRCH;
13510 goto err_locked;
13511 }
13512
13513 if (!task) {
13514 /*
13515 * Check if the @cpu we're creating an event for is online.
13516 *
13517 * We use the perf_cpu_context::ctx::mutex to serialize against
13518 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13519 */
13520 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu);
13521
13522 if (!cpuctx->online) {
13523 err = -ENODEV;
13524 goto err_locked;
13525 }
89a1e187
PZ
13526 }
13527
ac9721f3 13528 if (group_leader) {
dc86cabe 13529 err = -EINVAL;
04289bb9 13530
04289bb9 13531 /*
ccff286d
IM
13532 * Do not allow a recursive hierarchy (this new sibling
13533 * becoming part of another group-sibling):
13534 */
13535 if (group_leader->group_leader != group_leader)
bd275681 13536 goto err_locked;
34f43927
PZ
13537
13538 /* All events in a group should have the same clock */
13539 if (group_leader->clock != event->clock)
bd275681 13540 goto err_locked;
34f43927 13541
ccff286d 13542 /*
64aee2a9
MR
13543 * Make sure we're both events for the same CPU;
13544 * grouping events for different CPUs is broken; since
13545 * you can never concurrently schedule them anyhow.
04289bb9 13546 */
64aee2a9 13547 if (group_leader->cpu != event->cpu)
bd275681 13548 goto err_locked;
64aee2a9
MR
13549
13550 /*
bd275681 13551 * Make sure we're both on the same context; either task or cpu.
64aee2a9 13552 */
bd275681
PZ
13553 if (group_leader->ctx != ctx)
13554 goto err_locked;
b04243ef 13555
3b6f9e5c
PM
13556 /*
13557 * Only a group leader can be exclusive or pinned
13558 */
0d48696f 13559 if (attr.exclusive || attr.pinned)
84c4e620 13560 goto err_locked;
321027c1 13561
bd275681
PZ
13562 if (is_software_event(event) &&
13563 !in_software_context(group_leader)) {
321027c1 13564 /*
bd275681
PZ
13565 * If the event is a sw event, but the group_leader
13566 * is on hw context.
13567 *
13568 * Allow the addition of software events to hw
13569 * groups, this is safe because software events
13570 * never fail to schedule.
13571 *
13572 * Note the comment that goes with struct
13573 * perf_event_pmu_context.
321027c1 13574 */
bd275681 13575 pmu = group_leader->pmu_ctx->pmu;
bf480f93
RB
13576 } else if (!is_software_event(event)) {
13577 if (is_software_event(group_leader) &&
13578 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
13579 /*
13580 * In case the group is a pure software group, and we
13581 * try to add a hardware event, move the whole group to
13582 * the hardware context.
13583 */
13584 move_group = 1;
321027c1 13585 }
8a58ddae 13586
bf480f93
RB
13587 /* Don't allow group of multiple hw events from different pmus */
13588 if (!in_software_context(group_leader) &&
13589 group_leader->pmu_ctx->pmu != pmu)
8a58ddae
AS
13590 goto err_locked;
13591 }
f55fc2a5
PZ
13592 }
13593
bd275681
PZ
13594 /*
13595 * Now that we're certain of the pmu; find the pmu_ctx.
13596 */
13597 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
13598 if (IS_ERR(pmu_ctx)) {
13599 err = PTR_ERR(pmu_ctx);
84c4e620
PZ
13600 goto err_locked;
13601 }
bd275681 13602 event->pmu_ctx = pmu_ctx;
84c4e620 13603
bd275681
PZ
13604 if (output_event) {
13605 err = perf_event_set_output(event, output_event);
13606 if (err)
13607 goto err_context;
a723968c
PZ
13608 }
13609
bd275681
PZ
13610 if (!perf_event_validate_size(event)) {
13611 err = -E2BIG;
13612 goto err_context;
a63fbed7
TG
13613 }
13614
da9ec3d3
MR
13615 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
13616 err = -EINVAL;
bd275681 13617 goto err_context;
da9ec3d3 13618 }
a63fbed7 13619
f55fc2a5
PZ
13620 /*
13621 * Must be under the same ctx::mutex as perf_install_in_context(),
13622 * because we need to serialize with concurrent event creation.
13623 */
13624 if (!exclusive_event_installable(event, ctx)) {
f55fc2a5 13625 err = -EBUSY;
bd275681 13626 goto err_context;
f55fc2a5 13627 }
f63a8daa 13628
f55fc2a5
PZ
13629 WARN_ON_ONCE(ctx->parent_ctx);
13630
bd275681
PZ
13631 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags);
13632 if (IS_ERR(event_file)) {
13633 err = PTR_ERR(event_file);
13634 event_file = NULL;
13635 goto err_context;
13636 }
13637
79c9ce57
PZ
13638 /*
13639 * This is the point on no return; we cannot fail hereafter. This is
13640 * where we start modifying current state.
13641 */
13642
f55fc2a5 13643 if (move_group) {
45a0e07a 13644 perf_remove_from_context(group_leader, 0);
bd275681 13645 put_pmu_ctx(group_leader->pmu_ctx);
0231bb53 13646
edb39592 13647 for_each_sibling_event(sibling, group_leader) {
45a0e07a 13648 perf_remove_from_context(sibling, 0);
bd275681 13649 put_pmu_ctx(sibling->pmu_ctx);
b04243ef 13650 }
b04243ef 13651
8f95b435
PZI
13652 /*
13653 * Install the group siblings before the group leader.
13654 *
13655 * Because a group leader will try and install the entire group
13656 * (through the sibling list, which is still in-tact), we can
13657 * end up with siblings installed in the wrong context.
13658 *
13659 * By installing siblings first we NO-OP because they're not
13660 * reachable through the group lists.
13661 */
edb39592 13662 for_each_sibling_event(sibling, group_leader) {
bd275681
PZ
13663 sibling->pmu_ctx = pmu_ctx;
13664 get_pmu_ctx(pmu_ctx);
8f95b435 13665 perf_event__state_init(sibling);
9fc81d87 13666 perf_install_in_context(ctx, sibling, sibling->cpu);
b04243ef 13667 }
8f95b435
PZI
13668
13669 /*
13670 * Removing from the context ends up with disabled
13671 * event. What we want here is event in the initial
13672 * startup state, ready to be add into new context.
13673 */
bd275681
PZ
13674 group_leader->pmu_ctx = pmu_ctx;
13675 get_pmu_ctx(pmu_ctx);
8f95b435
PZI
13676 perf_event__state_init(group_leader);
13677 perf_install_in_context(ctx, group_leader, group_leader->cpu);
bed5b25a
AS
13678 }
13679
f73e22ab
PZ
13680 /*
13681 * Precalculate sample_data sizes; do while holding ctx::mutex such
13682 * that we're serialized against further additions and before
13683 * perf_install_in_context() which is the point the event is active and
13684 * can use these values.
13685 */
13686 perf_event__header_size(event);
13687 perf_event__id_header_size(event);
13688
78cd2c74
PZ
13689 event->owner = current;
13690
e2d37cd2 13691 perf_install_in_context(ctx, event, event->cpu);
fe4b04fa 13692 perf_unpin_context(ctx);
f63a8daa 13693
d859e29f 13694 mutex_unlock(&ctx->mutex);
9b51f66d 13695
79c9ce57 13696 if (task) {
f7cfd871 13697 up_read(&task->signal->exec_update_lock);
79c9ce57
PZ
13698 put_task_struct(task);
13699 }
13700
cdd6c482
IM
13701 mutex_lock(&current->perf_event_mutex);
13702 list_add_tail(&event->owner_entry, &current->perf_event_list);
13703 mutex_unlock(&current->perf_event_mutex);
082ff5a2 13704
8a49542c 13705 /*
4dd53b84
AV
13706 * File reference in group guarantees that group_leader has been
13707 * kept alive until we place the new event on the sibling_list.
13708 * This ensures destruction of the group leader will find
13709 * the pointer to itself in perf_group_detach().
8a49542c 13710 */
ea635c64
AV
13711 fd_install(event_fd, event_file);
13712 return event_fd;
0793a61d 13713
bd275681 13714err_context:
a551844e
PZ
13715 put_pmu_ctx(event->pmu_ctx);
13716 event->pmu_ctx = NULL; /* _free_event() */
f55fc2a5 13717err_locked:
f55fc2a5 13718 mutex_unlock(&ctx->mutex);
bd275681
PZ
13719 perf_unpin_context(ctx);
13720 put_ctx(ctx);
78af4dc9 13721err_cred:
13722 if (task)
d01e7f10 13723 up_read(&task->signal->exec_update_lock);
c6be5a5c 13724err_alloc:
da916e96 13725 put_event(event);
1f4ee503 13726err_task:
e7d0bc04
PZ
13727 if (task)
13728 put_task_struct(task);
ea635c64
AV
13729err_fd:
13730 put_unused_fd(event_fd);
dc86cabe 13731 return err;
0793a61d
TG
13732}
13733
fb0459d7
AV
13734/**
13735 * perf_event_create_kernel_counter
13736 *
13737 * @attr: attributes of the counter to create
13738 * @cpu: cpu in which the counter is bound
38a81da2 13739 * @task: task to profile (NULL for percpu)
a1ddf524
HX
13740 * @overflow_handler: callback to trigger when we hit the event
13741 * @context: context data could be used in overflow_handler callback
fb0459d7
AV
13742 */
13743struct perf_event *
13744perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
38a81da2 13745 struct task_struct *task,
4dc0da86
AK
13746 perf_overflow_handler_t overflow_handler,
13747 void *context)
fb0459d7 13748{
bd275681 13749 struct perf_event_pmu_context *pmu_ctx;
fb0459d7 13750 struct perf_event_context *ctx;
c3f00c70 13751 struct perf_event *event;
bd275681 13752 struct pmu *pmu;
fb0459d7 13753 int err;
d859e29f 13754
dce5affb
AS
13755 /*
13756 * Grouping is not supported for kernel events, neither is 'AUX',
13757 * make sure the caller's intentions are adjusted.
13758 */
18d92bb5 13759 if (attr->aux_output || attr->aux_action)
dce5affb
AS
13760 return ERR_PTR(-EINVAL);
13761
da916e96
PZ
13762 /*
13763 * Event creation should be under SRCU, see perf_pmu_unregister().
13764 */
13765 guard(srcu)(&pmus_srcu);
13766
4dc0da86 13767 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
79dff51e 13768 overflow_handler, context, -1);
c3f00c70
PZ
13769 if (IS_ERR(event)) {
13770 err = PTR_ERR(event);
13771 goto err;
13772 }
d859e29f 13773
f8697762 13774 /* Mark owner so we could distinguish it from user events. */
63b6da39 13775 event->owner = TASK_TOMBSTONE;
bd275681
PZ
13776 pmu = event->pmu;
13777
13778 if (pmu->task_ctx_nr == perf_sw_context)
13779 event->event_caps |= PERF_EV_CAP_SOFTWARE;
f8697762 13780
f25d8ba9
AS
13781 /*
13782 * Get the target context (task or percpu):
13783 */
bd275681 13784 ctx = find_get_context(task, event);
c6567f64
FW
13785 if (IS_ERR(ctx)) {
13786 err = PTR_ERR(ctx);
bd275681 13787 goto err_alloc;
d859e29f 13788 }
fb0459d7 13789
fb0459d7
AV
13790 WARN_ON_ONCE(ctx->parent_ctx);
13791 mutex_lock(&ctx->mutex);
84c4e620
PZ
13792 if (ctx->task == TASK_TOMBSTONE) {
13793 err = -ESRCH;
13794 goto err_unlock;
13795 }
13796
bd275681
PZ
13797 pmu_ctx = find_get_pmu_context(pmu, ctx, event);
13798 if (IS_ERR(pmu_ctx)) {
13799 err = PTR_ERR(pmu_ctx);
13800 goto err_unlock;
13801 }
13802 event->pmu_ctx = pmu_ctx;
13803
a63fbed7
TG
13804 if (!task) {
13805 /*
13806 * Check if the @cpu we're creating an event for is online.
13807 *
13808 * We use the perf_cpu_context::ctx::mutex to serialize against
13809 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
13810 */
13811 struct perf_cpu_context *cpuctx =
13812 container_of(ctx, struct perf_cpu_context, ctx);
13813 if (!cpuctx->online) {
13814 err = -ENODEV;
bd275681 13815 goto err_pmu_ctx;
a63fbed7
TG
13816 }
13817 }
13818
bed5b25a 13819 if (!exclusive_event_installable(event, ctx)) {
bed5b25a 13820 err = -EBUSY;
bd275681 13821 goto err_pmu_ctx;
bed5b25a
AS
13822 }
13823
4ce54af8 13824 perf_install_in_context(ctx, event, event->cpu);
fe4b04fa 13825 perf_unpin_context(ctx);
fb0459d7
AV
13826 mutex_unlock(&ctx->mutex);
13827
fb0459d7
AV
13828 return event;
13829
bd275681
PZ
13830err_pmu_ctx:
13831 put_pmu_ctx(pmu_ctx);
a551844e 13832 event->pmu_ctx = NULL; /* _free_event() */
84c4e620
PZ
13833err_unlock:
13834 mutex_unlock(&ctx->mutex);
13835 perf_unpin_context(ctx);
13836 put_ctx(ctx);
bd275681 13837err_alloc:
da916e96 13838 put_event(event);
c3f00c70 13839err:
c6567f64 13840 return ERR_PTR(err);
9b51f66d 13841}
fb0459d7 13842EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
9b51f66d 13843
bd275681
PZ
13844static void __perf_pmu_remove(struct perf_event_context *ctx,
13845 int cpu, struct pmu *pmu,
13846 struct perf_event_groups *groups,
13847 struct list_head *events)
0cda4c02 13848{
bd275681 13849 struct perf_event *event, *sibling;
0cda4c02 13850
bd275681 13851 perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) {
45a0e07a 13852 perf_remove_from_context(event, 0);
bd275681
PZ
13853 put_pmu_ctx(event->pmu_ctx);
13854 list_add(&event->migrate_entry, events);
13855
13856 for_each_sibling_event(sibling, event) {
13857 perf_remove_from_context(sibling, 0);
bd275681
PZ
13858 put_pmu_ctx(sibling->pmu_ctx);
13859 list_add(&sibling->migrate_entry, events);
13860 }
0cda4c02 13861 }
bd275681 13862}
0cda4c02 13863
bd275681
PZ
13864static void __perf_pmu_install_event(struct pmu *pmu,
13865 struct perf_event_context *ctx,
13866 int cpu, struct perf_event *event)
13867{
13868 struct perf_event_pmu_context *epc;
889c58b3
PZ
13869 struct perf_event_context *old_ctx = event->ctx;
13870
13871 get_ctx(ctx); /* normally find_get_context() */
bd275681
PZ
13872
13873 event->cpu = cpu;
13874 epc = find_get_pmu_context(pmu, ctx, event);
13875 event->pmu_ctx = epc;
13876
13877 if (event->state >= PERF_EVENT_STATE_OFF)
13878 event->state = PERF_EVENT_STATE_INACTIVE;
bd275681 13879 perf_install_in_context(ctx, event, cpu);
889c58b3
PZ
13880
13881 /*
13882 * Now that event->ctx is updated and visible, put the old ctx.
13883 */
13884 put_ctx(old_ctx);
bd275681
PZ
13885}
13886
13887static void __perf_pmu_install(struct perf_event_context *ctx,
13888 int cpu, struct pmu *pmu, struct list_head *events)
13889{
13890 struct perf_event *event, *tmp;
0cda4c02 13891
8f95b435
PZI
13892 /*
13893 * Re-instate events in 2 passes.
13894 *
13895 * Skip over group leaders and only install siblings on this first
13896 * pass, siblings will not get enabled without a leader, however a
13897 * leader will enable its siblings, even if those are still on the old
13898 * context.
13899 */
bd275681 13900 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
8f95b435
PZI
13901 if (event->group_leader == event)
13902 continue;
13903
13904 list_del(&event->migrate_entry);
bd275681 13905 __perf_pmu_install_event(pmu, ctx, cpu, event);
8f95b435
PZI
13906 }
13907
13908 /*
13909 * Once all the siblings are setup properly, install the group leaders
13910 * to make it go.
13911 */
bd275681 13912 list_for_each_entry_safe(event, tmp, events, migrate_entry) {
9886167d 13913 list_del(&event->migrate_entry);
bd275681 13914 __perf_pmu_install_event(pmu, ctx, cpu, event);
0cda4c02 13915 }
bd275681
PZ
13916}
13917
13918void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
13919{
13920 struct perf_event_context *src_ctx, *dst_ctx;
13921 LIST_HEAD(events);
13922
889c58b3
PZ
13923 /*
13924 * Since per-cpu context is persistent, no need to grab an extra
13925 * reference.
13926 */
bd275681
PZ
13927 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx;
13928 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx;
13929
13930 /*
13931 * See perf_event_ctx_lock() for comments on the details
13932 * of swizzling perf_event::ctx.
13933 */
13934 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
13935
13936 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events);
13937 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events);
13938
b1680989
PZ
13939 if (!list_empty(&events)) {
13940 /*
13941 * Wait for the events to quiesce before re-instating them.
13942 */
13943 synchronize_rcu();
bd275681 13944
b1680989
PZ
13945 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events);
13946 }
bd275681 13947
0cda4c02 13948 mutex_unlock(&dst_ctx->mutex);
f63a8daa 13949 mutex_unlock(&src_ctx->mutex);
0cda4c02
YZ
13950}
13951EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
13952
ef54c1a4 13953static void sync_child_event(struct perf_event *child_event)
d859e29f 13954{
cdd6c482 13955 struct perf_event *parent_event = child_event->parent;
8bc20959 13956 u64 child_val;
d859e29f 13957
ef54c1a4
PZ
13958 if (child_event->attr.inherit_stat) {
13959 struct task_struct *task = child_event->ctx->task;
13960
13961 if (task && task != TASK_TOMBSTONE)
13962 perf_event_read_event(child_event, task);
13963 }
38b200d6 13964
7e8b2556 13965 child_val = perf_event_count(child_event, false);
d859e29f
PM
13966
13967 /*
13968 * Add back the child's count to the parent's count:
13969 */
a6e6dea6 13970 atomic64_add(child_val, &parent_event->child_count);
cdd6c482
IM
13971 atomic64_add(child_event->total_time_enabled,
13972 &parent_event->child_total_time_enabled);
13973 atomic64_add(child_event->total_time_running,
13974 &parent_event->child_total_time_running);
d859e29f
PM
13975}
13976
9b51f66d 13977static void
da916e96
PZ
13978perf_event_exit_event(struct perf_event *event,
13979 struct perf_event_context *ctx, bool revoke)
9b51f66d 13980{
ef54c1a4 13981 struct perf_event *parent_event = event->parent;
da916e96 13982 unsigned long detach_flags = DETACH_EXIT;
d20eb2d5 13983 unsigned int attach_state;
8ba289b8 13984
ef54c1a4
PZ
13985 if (parent_event) {
13986 /*
13987 * Do not destroy the 'original' grouping; because of the
13988 * context switch optimization the original events could've
13989 * ended up in a random child task.
13990 *
13991 * If we were to destroy the original group, all group related
13992 * operations would cease to function properly after this
13993 * random child dies.
13994 *
13995 * Do destroy all inherited groups, we don't care about those
13996 * and being thorough is better.
13997 */
da916e96 13998 detach_flags |= DETACH_GROUP | DETACH_CHILD;
ef54c1a4 13999 mutex_lock(&parent_event->child_mutex);
d20eb2d5
FW
14000 /* PERF_ATTACH_ITRACE might be set concurrently */
14001 attach_state = READ_ONCE(event->attach_state);
ef54c1a4 14002 }
32132a3d 14003
da916e96
PZ
14004 if (revoke)
14005 detach_flags |= DETACH_GROUP | DETACH_REVOKE;
0cc0c027 14006
da916e96 14007 perf_remove_from_context(event, detach_flags);
9b51f66d 14008 /*
ef54c1a4 14009 * Child events can be freed.
9b51f66d 14010 */
d20eb2d5
FW
14011 if (parent_event) {
14012 mutex_unlock(&parent_event->child_mutex);
14013
14014 /*
14015 * Match the refcount initialization. Make sure it doesn't happen
14016 * twice if pmu_detach_event() calls it on an already exited task.
14017 */
14018 if (attach_state & PERF_ATTACH_CHILD) {
da916e96
PZ
14019 /*
14020 * Kick perf_poll() for is_event_hup();
14021 */
14022 perf_event_wakeup(parent_event);
14023 /*
14024 * pmu_detach_event() will have an extra refcount.
d20eb2d5 14025 * perf_pending_task() might have one too.
da916e96
PZ
14026 */
14027 put_event(event);
14028 }
d20eb2d5 14029
8ba289b8 14030 return;
4bcf349a 14031 }
8ba289b8
PZ
14032
14033 /*
ef54c1a4 14034 * Parent events are governed by their filedesc, retain them.
8ba289b8 14035 */
ef54c1a4 14036 perf_event_wakeup(event);
9b51f66d
IM
14037}
14038
4da0600e 14039static void perf_event_exit_task_context(struct task_struct *task, bool exit)
9b51f66d 14040{
4da0600e 14041 struct perf_event_context *ctx, *clone_ctx = NULL;
63b6da39 14042 struct perf_event *child_event, *next;
63b6da39 14043
4da0600e
PZ
14044 ctx = perf_pin_task_context(task);
14045 if (!ctx)
9b51f66d
IM
14046 return;
14047
ad3a37de 14048 /*
6a3351b6
PZ
14049 * In order to reduce the amount of tricky in ctx tear-down, we hold
14050 * ctx::mutex over the entire thing. This serializes against almost
14051 * everything that wants to access the ctx.
14052 *
14053 * The exception is sys_perf_event_open() /
14054 * perf_event_create_kernel_count() which does find_get_context()
14055 * without ctx::mutex (it cannot because of the move_group double mutex
14056 * lock thing). See the comments in perf_install_in_context().
ad3a37de 14057 */
4da0600e 14058 mutex_lock(&ctx->mutex);
c93f7669
PM
14059
14060 /*
6a3351b6
PZ
14061 * In a single ctx::lock section, de-schedule the events and detach the
14062 * context from the task such that we cannot ever get it scheduled back
14063 * in.
c93f7669 14064 */
4da0600e 14065 raw_spin_lock_irq(&ctx->lock);
90661365 14066 if (exit)
4da0600e 14067 task_ctx_sched_out(ctx, NULL, EVENT_ALL);
4a1c0f26 14068
71a851b4 14069 /*
63b6da39
PZ
14070 * Now that the context is inactive, destroy the task <-> ctx relation
14071 * and mark the context dead.
71a851b4 14072 */
4da0600e
PZ
14073 RCU_INIT_POINTER(task->perf_event_ctxp, NULL);
14074 put_ctx(ctx); /* cannot be last */
14075 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
14076 put_task_struct(task); /* cannot be last */
4a1c0f26 14077
4da0600e
PZ
14078 clone_ctx = unclone_ctx(ctx);
14079 raw_spin_unlock_irq(&ctx->lock);
9f498cc5 14080
211de6eb
PZ
14081 if (clone_ctx)
14082 put_ctx(clone_ctx);
4a1c0f26 14083
9f498cc5 14084 /*
cdd6c482
IM
14085 * Report the task dead after unscheduling the events so that we
14086 * won't get any samples after PERF_RECORD_EXIT. We can however still
14087 * get a few PERF_RECORD_READ events.
9f498cc5 14088 */
90661365 14089 if (exit)
4da0600e 14090 perf_event_task(task, ctx, 0);
a63eaf34 14091
4da0600e 14092 list_for_each_entry_safe(child_event, next, &ctx->event_list, event_entry)
da916e96 14093 perf_event_exit_event(child_event, ctx, false);
8bc20959 14094
4da0600e 14095 mutex_unlock(&ctx->mutex);
a63eaf34 14096
90661365
PZ
14097 if (!exit) {
14098 /*
14099 * perf_event_release_kernel() could still have a reference on
14100 * this context. In that case we must wait for these events to
14101 * have been freed (in particular all their references to this
14102 * task must've been dropped).
14103 *
14104 * Without this copy_process() will unconditionally free this
14105 * task (irrespective of its reference count) and
14106 * _free_event()'s put_task_struct(event->hw.target) will be a
14107 * use-after-free.
14108 *
14109 * Wait for all events to drop their context reference.
14110 */
4da0600e
PZ
14111 wait_var_event(&ctx->refcount,
14112 refcount_read(&ctx->refcount) == 1);
90661365 14113 }
4da0600e 14114 put_ctx(ctx);
9b51f66d
IM
14115}
14116
8dc85d54 14117/*
4da0600e 14118 * When a task exits, feed back event values to parent events.
79c9ce57 14119 *
f7cfd871 14120 * Can be called with exec_update_lock held when called from
96ecee29 14121 * setup_new_exec().
8dc85d54 14122 */
4da0600e 14123void perf_event_exit_task(struct task_struct *task)
8dc85d54 14124{
8882135b 14125 struct perf_event *event, *tmp;
8dc85d54 14126
4da0600e
PZ
14127 WARN_ON_ONCE(task != current);
14128
14129 mutex_lock(&task->perf_event_mutex);
14130 list_for_each_entry_safe(event, tmp, &task->perf_event_list,
8882135b
PZ
14131 owner_entry) {
14132 list_del_init(&event->owner_entry);
14133
14134 /*
14135 * Ensure the list deletion is visible before we clear
14136 * the owner, closes a race against perf_release() where
14137 * we need to serialize on the owner->perf_event_mutex.
14138 */
f47c02c0 14139 smp_store_release(&event->owner, NULL);
8882135b 14140 }
4da0600e 14141 mutex_unlock(&task->perf_event_mutex);
8882135b 14142
4da0600e 14143 perf_event_exit_task_context(task, true);
4e93ad60
JO
14144
14145 /*
14146 * The perf_event_exit_task_context calls perf_event_task
4da0600e
PZ
14147 * with task's task_ctx, which generates EXIT events for
14148 * task contexts and sets task->perf_event_ctxp[] to NULL.
4e93ad60
JO
14149 * At this point we need to send EXIT events to cpu contexts.
14150 */
4da0600e 14151 perf_event_task(task, NULL, 0);
506e64e7
KL
14152
14153 /*
14154 * Detach the perf_ctx_data for the system-wide event.
14155 */
14156 guard(percpu_read)(&global_ctx_data_rwsem);
4da0600e 14157 detach_task_ctx_data(task);
8dc85d54
PZ
14158}
14159
bbbee908 14160/*
1cf8dfe8
PZ
14161 * Free a context as created by inheritance by perf_event_init_task() below,
14162 * used by fork() in case of fail.
652884fe 14163 *
1cf8dfe8
PZ
14164 * Even though the task has never lived, the context and events have been
14165 * exposed through the child_list, so we must take care tearing it all down.
bbbee908 14166 */
cdd6c482 14167void perf_event_free_task(struct task_struct *task)
bbbee908 14168{
90661365 14169 perf_event_exit_task_context(task, false);
889ff015
FW
14170}
14171
4e231c79
PZ
14172void perf_event_delayed_put(struct task_struct *task)
14173{
bd275681 14174 WARN_ON_ONCE(task->perf_event_ctxp);
4e231c79
PZ
14175}
14176
e03e7ee3 14177struct file *perf_event_get(unsigned int fd)
ffe8690c 14178{
02e5ad97 14179 struct file *file = fget(fd);
e03e7ee3
AS
14180 if (!file)
14181 return ERR_PTR(-EBADF);
ffe8690c 14182
e03e7ee3
AS
14183 if (file->f_op != &perf_fops) {
14184 fput(file);
14185 return ERR_PTR(-EBADF);
14186 }
ffe8690c 14187
e03e7ee3 14188 return file;
ffe8690c
KX
14189}
14190
f8d959a5
YS
14191const struct perf_event *perf_get_event(struct file *file)
14192{
14193 if (file->f_op != &perf_fops)
14194 return ERR_PTR(-EINVAL);
14195
14196 return file->private_data;
14197}
14198
ffe8690c
KX
14199const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
14200{
14201 if (!event)
14202 return ERR_PTR(-EINVAL);
14203
14204 return &event->attr;
14205}
14206
9ec84f79 14207int perf_allow_kernel(void)
5e9629d0
JC
14208{
14209 if (sysctl_perf_event_paranoid > 1 && !perfmon_capable())
14210 return -EACCES;
14211
9ec84f79 14212 return security_perf_event_open(PERF_SECURITY_KERNEL);
5e9629d0
JC
14213}
14214EXPORT_SYMBOL_GPL(perf_allow_kernel);
14215
97dee4f3 14216/*
788faab7 14217 * Inherit an event from parent task to child task.
d8a8cfc7
PZ
14218 *
14219 * Returns:
14220 * - valid pointer on success
14221 * - NULL for orphaned events
14222 * - IS_ERR() on error
97dee4f3
PZ
14223 */
14224static struct perf_event *
14225inherit_event(struct perf_event *parent_event,
14226 struct task_struct *parent,
14227 struct perf_event_context *parent_ctx,
14228 struct task_struct *child,
14229 struct perf_event *group_leader,
14230 struct perf_event_context *child_ctx)
14231{
8ca2bd41 14232 enum perf_event_state parent_state = parent_event->state;
bd275681 14233 struct perf_event_pmu_context *pmu_ctx;
97dee4f3 14234 struct perf_event *child_event;
cee010ec 14235 unsigned long flags;
97dee4f3
PZ
14236
14237 /*
14238 * Instead of creating recursive hierarchies of events,
14239 * we link inherited events back to the original parent,
14240 * which has a filp for sure, which we use as the reference
14241 * count:
14242 */
14243 if (parent_event->parent)
14244 parent_event = parent_event->parent;
14245
da916e96
PZ
14246 if (parent_event->state <= PERF_EVENT_STATE_REVOKED)
14247 return NULL;
14248
14249 /*
14250 * Event creation should be under SRCU, see perf_pmu_unregister().
14251 */
14252 guard(srcu)(&pmus_srcu);
14253
97dee4f3
PZ
14254 child_event = perf_event_alloc(&parent_event->attr,
14255 parent_event->cpu,
d580ff86 14256 child,
97dee4f3 14257 group_leader, parent_event,
79dff51e 14258 NULL, NULL, -1);
97dee4f3
PZ
14259 if (IS_ERR(child_event))
14260 return child_event;
a6fa941d 14261
0ba3a4ab
GS
14262 get_ctx(child_ctx);
14263 child_event->ctx = child_ctx;
14264
bd275681 14265 pmu_ctx = find_get_pmu_context(child_event->pmu, child_ctx, child_event);
c55bfbb3 14266 if (IS_ERR(pmu_ctx)) {
22d38bab 14267 free_event(child_event);
e2d37148 14268 return ERR_CAST(pmu_ctx);
313ccb96 14269 }
bd275681 14270 child_event->pmu_ctx = pmu_ctx;
313ccb96 14271
c6e5b732
PZ
14272 /*
14273 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
14274 * must be under the same lock in order to serialize against
14275 * perf_event_release_kernel(), such that either we must observe
14276 * is_orphaned_event() or they will observe us on the child_list.
14277 */
14278 mutex_lock(&parent_event->child_mutex);
fadfe7be
JO
14279 if (is_orphaned_event(parent_event) ||
14280 !atomic_long_inc_not_zero(&parent_event->refcount)) {
c6e5b732 14281 mutex_unlock(&parent_event->child_mutex);
22d38bab 14282 free_event(child_event);
a6fa941d
AV
14283 return NULL;
14284 }
14285
97dee4f3
PZ
14286 /*
14287 * Make the child state follow the state of the parent event,
14288 * not its attr.disabled bit. We hold the parent's mutex,
14289 * so we won't race with perf_event_{en, dis}able_family.
14290 */
1929def9 14291 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
97dee4f3
PZ
14292 child_event->state = PERF_EVENT_STATE_INACTIVE;
14293 else
14294 child_event->state = PERF_EVENT_STATE_OFF;
14295
14296 if (parent_event->attr.freq) {
14297 u64 sample_period = parent_event->hw.sample_period;
14298 struct hw_perf_event *hwc = &child_event->hw;
14299
14300 hwc->sample_period = sample_period;
14301 hwc->last_period = sample_period;
14302
14303 local64_set(&hwc->period_left, sample_period);
14304 }
14305
97dee4f3 14306 child_event->overflow_handler = parent_event->overflow_handler;
4dc0da86
AK
14307 child_event->overflow_handler_context
14308 = parent_event->overflow_handler_context;
97dee4f3 14309
614b6780
TG
14310 /*
14311 * Precalculate sample_data sizes
14312 */
14313 perf_event__header_size(child_event);
6844c09d 14314 perf_event__id_header_size(child_event);
614b6780 14315
97dee4f3
PZ
14316 /*
14317 * Link it up in the child's context:
14318 */
cee010ec 14319 raw_spin_lock_irqsave(&child_ctx->lock, flags);
97dee4f3 14320 add_event_to_ctx(child_event, child_ctx);
ef54c1a4 14321 child_event->attach_state |= PERF_ATTACH_CHILD;
cee010ec 14322 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
97dee4f3 14323
97dee4f3
PZ
14324 /*
14325 * Link this into the parent event's child list
14326 */
97dee4f3
PZ
14327 list_add_tail(&child_event->child_list, &parent_event->child_list);
14328 mutex_unlock(&parent_event->child_mutex);
14329
14330 return child_event;
14331}
14332
d8a8cfc7
PZ
14333/*
14334 * Inherits an event group.
14335 *
14336 * This will quietly suppress orphaned events; !inherit_event() is not an error.
14337 * This matches with perf_event_release_kernel() removing all child events.
14338 *
14339 * Returns:
14340 * - 0 on success
14341 * - <0 on error
14342 */
97dee4f3
PZ
14343static int inherit_group(struct perf_event *parent_event,
14344 struct task_struct *parent,
14345 struct perf_event_context *parent_ctx,
14346 struct task_struct *child,
14347 struct perf_event_context *child_ctx)
14348{
14349 struct perf_event *leader;
14350 struct perf_event *sub;
14351 struct perf_event *child_ctr;
14352
14353 leader = inherit_event(parent_event, parent, parent_ctx,
14354 child, NULL, child_ctx);
14355 if (IS_ERR(leader))
14356 return PTR_ERR(leader);
d8a8cfc7
PZ
14357 /*
14358 * @leader can be NULL here because of is_orphaned_event(). In this
14359 * case inherit_event() will create individual events, similar to what
14360 * perf_group_detach() would do anyway.
14361 */
edb39592 14362 for_each_sibling_event(sub, parent_event) {
97dee4f3
PZ
14363 child_ctr = inherit_event(sub, parent, parent_ctx,
14364 child, leader, child_ctx);
14365 if (IS_ERR(child_ctr))
14366 return PTR_ERR(child_ctr);
f733c6b5 14367
00496fe5 14368 if (sub->aux_event == parent_event && child_ctr &&
f733c6b5
AS
14369 !perf_get_aux_event(child_ctr, leader))
14370 return -EINVAL;
97dee4f3 14371 }
a71ef314
PZ
14372 if (leader)
14373 leader->group_generation = parent_event->group_generation;
97dee4f3 14374 return 0;
889ff015
FW
14375}
14376
d8a8cfc7
PZ
14377/*
14378 * Creates the child task context and tries to inherit the event-group.
14379 *
14380 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
14381 * inherited_all set when we 'fail' to inherit an orphaned event; this is
14382 * consistent with perf_event_release_kernel() removing all child events.
14383 *
14384 * Returns:
14385 * - 0 on success
14386 * - <0 on error
14387 */
889ff015
FW
14388static int
14389inherit_task_group(struct perf_event *event, struct task_struct *parent,
14390 struct perf_event_context *parent_ctx,
bd275681 14391 struct task_struct *child,
2b26f0aa 14392 u64 clone_flags, int *inherited_all)
889ff015 14393{
8dc85d54 14394 struct perf_event_context *child_ctx;
bd275681 14395 int ret;
889ff015 14396
2b26f0aa 14397 if (!event->attr.inherit ||
97ba62b2
ME
14398 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) ||
14399 /* Do not inherit if sigtrap and signal handlers were cleared. */
14400 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) {
889ff015
FW
14401 *inherited_all = 0;
14402 return 0;
bbbee908
PZ
14403 }
14404
bd275681 14405 child_ctx = child->perf_event_ctxp;
889ff015
FW
14406 if (!child_ctx) {
14407 /*
14408 * This is executed from the parent task context, so
14409 * inherit events that have been marked for cloning.
14410 * First allocate and initialize a context for the
14411 * child.
14412 */
bd275681 14413 child_ctx = alloc_perf_context(child);
889ff015
FW
14414 if (!child_ctx)
14415 return -ENOMEM;
bbbee908 14416
bd275681 14417 child->perf_event_ctxp = child_ctx;
889ff015
FW
14418 }
14419
bd275681 14420 ret = inherit_group(event, parent, parent_ctx, child, child_ctx);
889ff015
FW
14421 if (ret)
14422 *inherited_all = 0;
14423
14424 return ret;
bbbee908
PZ
14425}
14426
9b51f66d 14427/*
cdd6c482 14428 * Initialize the perf_event context in task_struct
9b51f66d 14429 */
bd275681 14430static int perf_event_init_context(struct task_struct *child, u64 clone_flags)
9b51f66d 14431{
889ff015 14432 struct perf_event_context *child_ctx, *parent_ctx;
cdd6c482
IM
14433 struct perf_event_context *cloned_ctx;
14434 struct perf_event *event;
9b51f66d 14435 struct task_struct *parent = current;
564c2b21 14436 int inherited_all = 1;
dddd3379 14437 unsigned long flags;
6ab423e0 14438 int ret = 0;
9b51f66d 14439
bd275681 14440 if (likely(!parent->perf_event_ctxp))
6ab423e0
PZ
14441 return 0;
14442
ad3a37de 14443 /*
25346b93
PM
14444 * If the parent's context is a clone, pin it so it won't get
14445 * swapped under us.
ad3a37de 14446 */
bd275681 14447 parent_ctx = perf_pin_task_context(parent);
ffb4ef21
PZ
14448 if (!parent_ctx)
14449 return 0;
25346b93 14450
ad3a37de
PM
14451 /*
14452 * No need to check if parent_ctx != NULL here; since we saw
14453 * it non-NULL earlier, the only reason for it to become NULL
14454 * is if we exit, and since we're currently in the middle of
14455 * a fork we can't be exiting at the same time.
14456 */
ad3a37de 14457
9b51f66d
IM
14458 /*
14459 * Lock the parent list. No need to lock the child - not PID
14460 * hashed yet and not running, so nobody can access it.
14461 */
d859e29f 14462 mutex_lock(&parent_ctx->mutex);
9b51f66d
IM
14463
14464 /*
14465 * We dont have to disable NMIs - we are only looking at
14466 * the list, not manipulating it:
14467 */
6e6804d2 14468 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
8dc85d54 14469 ret = inherit_task_group(event, parent, parent_ctx,
bd275681 14470 child, clone_flags, &inherited_all);
889ff015 14471 if (ret)
e7cc4865 14472 goto out_unlock;
889ff015 14473 }
b93f7978 14474
dddd3379
TG
14475 /*
14476 * We can't hold ctx->lock when iterating the ->flexible_group list due
14477 * to allocations, but we need to prevent rotation because
14478 * rotate_ctx() will change the list from interrupt context.
14479 */
14480 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
14481 parent_ctx->rotate_disable = 1;
14482 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
14483
6e6804d2 14484 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
8dc85d54 14485 ret = inherit_task_group(event, parent, parent_ctx,
bd275681 14486 child, clone_flags, &inherited_all);
889ff015 14487 if (ret)
e7cc4865 14488 goto out_unlock;
564c2b21
PM
14489 }
14490
dddd3379
TG
14491 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
14492 parent_ctx->rotate_disable = 0;
dddd3379 14493
bd275681 14494 child_ctx = child->perf_event_ctxp;
889ff015 14495
05cbaa28 14496 if (child_ctx && inherited_all) {
564c2b21
PM
14497 /*
14498 * Mark the child context as a clone of the parent
14499 * context, or of whatever the parent is a clone of.
c5ed5145
PZ
14500 *
14501 * Note that if the parent is a clone, the holding of
14502 * parent_ctx->lock avoids it from being uncloned.
564c2b21 14503 */
c5ed5145 14504 cloned_ctx = parent_ctx->parent_ctx;
ad3a37de
PM
14505 if (cloned_ctx) {
14506 child_ctx->parent_ctx = cloned_ctx;
25346b93 14507 child_ctx->parent_gen = parent_ctx->parent_gen;
564c2b21
PM
14508 } else {
14509 child_ctx->parent_ctx = parent_ctx;
14510 child_ctx->parent_gen = parent_ctx->generation;
14511 }
14512 get_ctx(child_ctx->parent_ctx);
9b51f66d
IM
14513 }
14514
c5ed5145 14515 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
e7cc4865 14516out_unlock:
d859e29f 14517 mutex_unlock(&parent_ctx->mutex);
6ab423e0 14518
25346b93 14519 perf_unpin_context(parent_ctx);
fe4b04fa 14520 put_ctx(parent_ctx);
ad3a37de 14521
6ab423e0 14522 return ret;
9b51f66d
IM
14523}
14524
8dc85d54
PZ
14525/*
14526 * Initialize the perf_event context in task_struct
14527 */
2b26f0aa 14528int perf_event_init_task(struct task_struct *child, u64 clone_flags)
8dc85d54 14529{
bd275681 14530 int ret;
8dc85d54 14531
0d40a6d8 14532 memset(child->perf_recursion, 0, sizeof(child->perf_recursion));
bd275681 14533 child->perf_event_ctxp = NULL;
8550d7cb
ON
14534 mutex_init(&child->perf_event_mutex);
14535 INIT_LIST_HEAD(&child->perf_event_list);
cb436912 14536 child->perf_ctx_data = NULL;
8550d7cb 14537
bd275681
PZ
14538 ret = perf_event_init_context(child, clone_flags);
14539 if (ret) {
14540 perf_event_free_task(child);
14541 return ret;
8dc85d54
PZ
14542 }
14543
14544 return 0;
14545}
14546
220b140b
PM
14547static void __init perf_event_init_all_cpus(void)
14548{
b28ab83c 14549 struct swevent_htable *swhash;
bd275681 14550 struct perf_cpu_context *cpuctx;
220b140b 14551 int cpu;
220b140b 14552
a63fbed7 14553 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
4ba4f1af
KL
14554 zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL);
14555 zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL);
14556 zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL);
14557 zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL);
14558 zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL);
14559
a63fbed7 14560
220b140b 14561 for_each_possible_cpu(cpu) {
b28ab83c
PZ
14562 swhash = &per_cpu(swevent_htable, cpu);
14563 mutex_init(&swhash->hlist_mutex);
f2fb6bef
KL
14564
14565 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
14566 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
e48c1788 14567
a5398bff 14568 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
bd275681
PZ
14569
14570 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14571 __perf_event_init_context(&cpuctx->ctx);
14572 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
14573 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
14574 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
14575 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
14576 cpuctx->heap = cpuctx->heap_default;
220b140b
PM
14577 }
14578}
14579
d18bf422 14580static void perf_swevent_init_cpu(unsigned int cpu)
0793a61d 14581{
108b02cf 14582 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
0793a61d 14583
b28ab83c 14584 mutex_lock(&swhash->hlist_mutex);
059fcd8c 14585 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
76e1d904
FW
14586 struct swevent_hlist *hlist;
14587
b28ab83c
PZ
14588 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
14589 WARN_ON(!hlist);
14590 rcu_assign_pointer(swhash->swevent_hlist, hlist);
76e1d904 14591 }
b28ab83c 14592 mutex_unlock(&swhash->hlist_mutex);
0793a61d
TG
14593}
14594
2965faa5 14595#if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
108b02cf 14596static void __perf_event_exit_context(void *__info)
0793a61d 14597{
bd275681 14598 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context);
108b02cf 14599 struct perf_event_context *ctx = __info;
fae3fde6 14600 struct perf_event *event;
0793a61d 14601
fae3fde6 14602 raw_spin_lock(&ctx->lock);
2d17cf1a 14603 ctx_sched_out(ctx, NULL, EVENT_TIME);
fae3fde6 14604 list_for_each_entry(event, &ctx->event_list, event_entry)
45a0e07a 14605 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
fae3fde6 14606 raw_spin_unlock(&ctx->lock);
0793a61d 14607}
108b02cf 14608
4ba4f1af
KL
14609static void perf_event_clear_cpumask(unsigned int cpu)
14610{
14611 int target[PERF_PMU_MAX_SCOPE];
14612 unsigned int scope;
14613 struct pmu *pmu;
14614
14615 cpumask_clear_cpu(cpu, perf_online_mask);
14616
14617 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14618 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
14619 struct cpumask *pmu_cpumask = perf_scope_cpumask(scope);
14620
14621 target[scope] = -1;
14622 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
14623 continue;
14624
14625 if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask))
14626 continue;
14627 target[scope] = cpumask_any_but(cpumask, cpu);
14628 if (target[scope] < nr_cpu_ids)
14629 cpumask_set_cpu(target[scope], pmu_cpumask);
14630 }
14631
14632 /* migrate */
e3dfd64c 14633 list_for_each_entry(pmu, &pmus, entry) {
4ba4f1af
KL
14634 if (pmu->scope == PERF_PMU_SCOPE_NONE ||
14635 WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE))
14636 continue;
14637
14638 if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids)
14639 perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]);
14640 }
14641}
14642
108b02cf
PZ
14643static void perf_event_exit_cpu_context(int cpu)
14644{
a63fbed7 14645 struct perf_cpu_context *cpuctx;
108b02cf 14646 struct perf_event_context *ctx;
108b02cf 14647
bd275681 14648 // XXX simplify cpuctx->online
a63fbed7 14649 mutex_lock(&pmus_lock);
4ba4f1af
KL
14650 /*
14651 * Clear the cpumasks, and migrate to other CPUs if possible.
14652 * Must be invoked before the __perf_event_exit_context.
14653 */
14654 perf_event_clear_cpumask(cpu);
bd275681
PZ
14655 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14656 ctx = &cpuctx->ctx;
108b02cf 14657
bd275681
PZ
14658 mutex_lock(&ctx->mutex);
14659 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
14660 cpuctx->online = 0;
14661 mutex_unlock(&ctx->mutex);
a63fbed7 14662 mutex_unlock(&pmus_lock);
108b02cf 14663}
00e16c3d
TG
14664#else
14665
14666static void perf_event_exit_cpu_context(int cpu) { }
14667
14668#endif
108b02cf 14669
4ba4f1af
KL
14670static void perf_event_setup_cpumask(unsigned int cpu)
14671{
14672 struct cpumask *pmu_cpumask;
14673 unsigned int scope;
14674
4ba4f1af
KL
14675 /*
14676 * Early boot stage, the cpumask hasn't been set yet.
14677 * The perf_online_<domain>_masks includes the first CPU of each domain.
673a5009 14678 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks.
4ba4f1af 14679 */
673a5009 14680 if (cpumask_empty(perf_online_mask)) {
4ba4f1af
KL
14681 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14682 pmu_cpumask = perf_scope_cpumask(scope);
14683 if (WARN_ON_ONCE(!pmu_cpumask))
14684 continue;
14685 cpumask_set_cpu(cpu, pmu_cpumask);
14686 }
673a5009 14687 goto end;
4ba4f1af
KL
14688 }
14689
14690 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) {
14691 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu);
14692
14693 pmu_cpumask = perf_scope_cpumask(scope);
14694
14695 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask))
14696 continue;
14697
14698 if (!cpumask_empty(cpumask) &&
14699 cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids)
14700 cpumask_set_cpu(cpu, pmu_cpumask);
14701 }
673a5009
KL
14702end:
14703 cpumask_set_cpu(cpu, perf_online_mask);
4ba4f1af
KL
14704}
14705
a63fbed7
TG
14706int perf_event_init_cpu(unsigned int cpu)
14707{
14708 struct perf_cpu_context *cpuctx;
14709 struct perf_event_context *ctx;
a63fbed7
TG
14710
14711 perf_swevent_init_cpu(cpu);
14712
14713 mutex_lock(&pmus_lock);
4ba4f1af 14714 perf_event_setup_cpumask(cpu);
bd275681
PZ
14715 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu);
14716 ctx = &cpuctx->ctx;
a63fbed7 14717
bd275681
PZ
14718 mutex_lock(&ctx->mutex);
14719 cpuctx->online = 1;
14720 mutex_unlock(&ctx->mutex);
a63fbed7
TG
14721 mutex_unlock(&pmus_lock);
14722
14723 return 0;
14724}
14725
00e16c3d 14726int perf_event_exit_cpu(unsigned int cpu)
0793a61d 14727{
e3703f8c 14728 perf_event_exit_cpu_context(cpu);
00e16c3d 14729 return 0;
0793a61d 14730}
0793a61d 14731
c277443c
PZ
14732static int
14733perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
14734{
14735 int cpu;
14736
14737 for_each_online_cpu(cpu)
14738 perf_event_exit_cpu(cpu);
14739
14740 return NOTIFY_OK;
14741}
14742
14743/*
14744 * Run the perf reboot notifier at the very last possible moment so that
14745 * the generic watchdog code runs as long as possible.
14746 */
14747static struct notifier_block perf_reboot_notifier = {
14748 .notifier_call = perf_reboot,
14749 .priority = INT_MIN,
14750};
14751
cdd6c482 14752void __init perf_event_init(void)
0793a61d 14753{
3c502e7a
JW
14754 int ret;
14755
2e80a82a
PZ
14756 idr_init(&pmu_idr);
14757
220b140b 14758 perf_event_init_all_cpus();
b0a873eb 14759 init_srcu_struct(&pmus_srcu);
2e80a82a 14760 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
0d6d062c
RB
14761 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1);
14762 perf_pmu_register(&perf_task_clock, "task_clock", -1);
b0a873eb 14763 perf_tp_register();
00e16c3d 14764 perf_event_init_cpu(smp_processor_id());
c277443c 14765 register_reboot_notifier(&perf_reboot_notifier);
3c502e7a
JW
14766
14767 ret = init_hw_breakpoint();
14768 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
b2029520 14769
bdacfaf2
NK
14770 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC);
14771
b01c3a00
JO
14772 /*
14773 * Build time assertion that we keep the data_head at the intended
14774 * location. IOW, validation we got the __reserved[] size right.
14775 */
14776 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
14777 != 1024);
0793a61d 14778}
abe43400 14779
fd979c01
CS
14780ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
14781 char *page)
14782{
14783 struct perf_pmu_events_attr *pmu_attr =
14784 container_of(attr, struct perf_pmu_events_attr, attr);
14785
14786 if (pmu_attr->event_str)
14787 return sprintf(page, "%s\n", pmu_attr->event_str);
14788
14789 return 0;
14790}
675965b0 14791EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
fd979c01 14792
abe43400
PZ
14793static int __init perf_event_sysfs_init(void)
14794{
14795 struct pmu *pmu;
14796 int ret;
14797
14798 mutex_lock(&pmus_lock);
14799
14800 ret = bus_register(&pmu_bus);
14801 if (ret)
14802 goto unlock;
14803
14804 list_for_each_entry(pmu, &pmus, entry) {
0d6d062c 14805 if (pmu->dev)
abe43400
PZ
14806 continue;
14807
14808 ret = pmu_dev_alloc(pmu);
14809 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
14810 }
14811 pmu_bus_running = 1;
14812 ret = 0;
14813
14814unlock:
14815 mutex_unlock(&pmus_lock);
14816
14817 return ret;
14818}
14819device_initcall(perf_event_sysfs_init);
e5d1367f
SE
14820
14821#ifdef CONFIG_CGROUP_PERF
eb95419b
TH
14822static struct cgroup_subsys_state *
14823perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
e5d1367f
SE
14824{
14825 struct perf_cgroup *jc;
e5d1367f 14826
1b15d055 14827 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
e5d1367f
SE
14828 if (!jc)
14829 return ERR_PTR(-ENOMEM);
14830
e5d1367f
SE
14831 jc->info = alloc_percpu(struct perf_cgroup_info);
14832 if (!jc->info) {
14833 kfree(jc);
14834 return ERR_PTR(-ENOMEM);
14835 }
14836
e5d1367f
SE
14837 return &jc->css;
14838}
14839
eb95419b 14840static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
e5d1367f 14841{
eb95419b
TH
14842 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
14843
e5d1367f
SE
14844 free_percpu(jc->info);
14845 kfree(jc);
14846}
14847
96aaab68
NK
14848static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
14849{
14850 perf_event_cgroup(css->cgroup);
14851 return 0;
14852}
14853
e5d1367f
SE
14854static int __perf_cgroup_move(void *info)
14855{
14856 struct task_struct *task = info;
bd275681
PZ
14857
14858 preempt_disable();
f841b682 14859 perf_cgroup_switch(task);
bd275681
PZ
14860 preempt_enable();
14861
e5d1367f
SE
14862 return 0;
14863}
14864
1f7dd3e5 14865static void perf_cgroup_attach(struct cgroup_taskset *tset)
e5d1367f 14866{
bb9d97b6 14867 struct task_struct *task;
1f7dd3e5 14868 struct cgroup_subsys_state *css;
bb9d97b6 14869
1f7dd3e5 14870 cgroup_taskset_for_each(task, css, tset)
bb9d97b6 14871 task_function_call(task, __perf_cgroup_move, task);
e5d1367f
SE
14872}
14873
073219e9 14874struct cgroup_subsys perf_event_cgrp_subsys = {
92fb9748
TH
14875 .css_alloc = perf_cgroup_css_alloc,
14876 .css_free = perf_cgroup_css_free,
96aaab68 14877 .css_online = perf_cgroup_css_online,
bb9d97b6 14878 .attach = perf_cgroup_attach,
968ebff1
TH
14879 /*
14880 * Implicitly enable on dfl hierarchy so that perf events can
14881 * always be filtered by cgroup2 path as long as perf_event
14882 * controller is not mounted on a legacy hierarchy.
14883 */
14884 .implicit_on_dfl = true,
8cfd8147 14885 .threaded = true,
e5d1367f
SE
14886};
14887#endif /* CONFIG_CGROUP_PERF */
c22ac2a3
SL
14888
14889DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t);