Merge tag 'for_v5.7-rc1' of git://git.kernel.org/pub/scm/linux/kernel/git/jack/linux-fs
[linux-block.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
PZ
30#include <linux/hardirq.h>
31#include <linux/rculist.h>
0793a61d
TG
32#include <linux/uaccess.h>
33#include <linux/syscalls.h>
34#include <linux/anon_inodes.h>
aa9c4c0f 35#include <linux/kernel_stat.h>
39bed6cb 36#include <linux/cgroup.h>
cdd6c482 37#include <linux/perf_event.h>
af658dca 38#include <linux/trace_events.h>
3c502e7a 39#include <linux/hw_breakpoint.h>
c5ebcedb 40#include <linux/mm_types.h>
c464c76e 41#include <linux/module.h>
f972eb63 42#include <linux/mman.h>
b3f20785 43#include <linux/compat.h>
2541517c
AS
44#include <linux/bpf.h>
45#include <linux/filter.h>
375637bc
AS
46#include <linux/namei.h>
47#include <linux/parser.h>
e6017571 48#include <linux/sched/clock.h>
6e84f315 49#include <linux/sched/mm.h>
e4222673
HB
50#include <linux/proc_ns.h>
51#include <linux/mount.h>
6eef8a71 52#include <linux/min_heap.h>
0793a61d 53
76369139
FW
54#include "internal.h"
55
4e193bd4
TB
56#include <asm/irq_regs.h>
57
272325c4
PZ
58typedef int (*remote_function_f)(void *);
59
fe4b04fa 60struct remote_function_call {
e7e7ee2e 61 struct task_struct *p;
272325c4 62 remote_function_f func;
e7e7ee2e
IM
63 void *info;
64 int ret;
fe4b04fa
PZ
65};
66
67static void remote_function(void *data)
68{
69 struct remote_function_call *tfc = data;
70 struct task_struct *p = tfc->p;
71
72 if (p) {
0da4cf3e
PZ
73 /* -EAGAIN */
74 if (task_cpu(p) != smp_processor_id())
75 return;
76
77 /*
78 * Now that we're on right CPU with IRQs disabled, we can test
79 * if we hit the right task without races.
80 */
81
82 tfc->ret = -ESRCH; /* No such (running) process */
83 if (p != current)
fe4b04fa
PZ
84 return;
85 }
86
87 tfc->ret = tfc->func(tfc->info);
88}
89
90/**
91 * task_function_call - call a function on the cpu on which a task runs
92 * @p: the task to evaluate
93 * @func: the function to be called
94 * @info: the function call argument
95 *
96 * Calls the function @func when the task is currently running. This might
97 * be on the current CPU, which just calls the function directly
98 *
99 * returns: @func return value, or
100 * -ESRCH - when the process isn't running
101 * -EAGAIN - when the process moved away
102 */
103static int
272325c4 104task_function_call(struct task_struct *p, remote_function_f func, void *info)
fe4b04fa
PZ
105{
106 struct remote_function_call data = {
e7e7ee2e
IM
107 .p = p,
108 .func = func,
109 .info = info,
0da4cf3e 110 .ret = -EAGAIN,
fe4b04fa 111 };
0da4cf3e 112 int ret;
fe4b04fa 113
0da4cf3e
PZ
114 do {
115 ret = smp_call_function_single(task_cpu(p), remote_function, &data, 1);
116 if (!ret)
117 ret = data.ret;
118 } while (ret == -EAGAIN);
fe4b04fa 119
0da4cf3e 120 return ret;
fe4b04fa
PZ
121}
122
123/**
124 * cpu_function_call - call a function on the cpu
125 * @func: the function to be called
126 * @info: the function call argument
127 *
128 * Calls the function @func on the remote cpu.
129 *
130 * returns: @func return value or -ENXIO when the cpu is offline
131 */
272325c4 132static int cpu_function_call(int cpu, remote_function_f func, void *info)
fe4b04fa
PZ
133{
134 struct remote_function_call data = {
e7e7ee2e
IM
135 .p = NULL,
136 .func = func,
137 .info = info,
138 .ret = -ENXIO, /* No such CPU */
fe4b04fa
PZ
139 };
140
141 smp_call_function_single(cpu, remote_function, &data, 1);
142
143 return data.ret;
144}
145
fae3fde6
PZ
146static inline struct perf_cpu_context *
147__get_cpu_context(struct perf_event_context *ctx)
148{
149 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
150}
151
152static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
153 struct perf_event_context *ctx)
0017960f 154{
fae3fde6
PZ
155 raw_spin_lock(&cpuctx->ctx.lock);
156 if (ctx)
157 raw_spin_lock(&ctx->lock);
158}
159
160static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
161 struct perf_event_context *ctx)
162{
163 if (ctx)
164 raw_spin_unlock(&ctx->lock);
165 raw_spin_unlock(&cpuctx->ctx.lock);
166}
167
63b6da39
PZ
168#define TASK_TOMBSTONE ((void *)-1L)
169
170static bool is_kernel_event(struct perf_event *event)
171{
f47c02c0 172 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
63b6da39
PZ
173}
174
39a43640
PZ
175/*
176 * On task ctx scheduling...
177 *
178 * When !ctx->nr_events a task context will not be scheduled. This means
179 * we can disable the scheduler hooks (for performance) without leaving
180 * pending task ctx state.
181 *
182 * This however results in two special cases:
183 *
184 * - removing the last event from a task ctx; this is relatively straight
185 * forward and is done in __perf_remove_from_context.
186 *
187 * - adding the first event to a task ctx; this is tricky because we cannot
188 * rely on ctx->is_active and therefore cannot use event_function_call().
189 * See perf_install_in_context().
190 *
39a43640
PZ
191 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
192 */
193
fae3fde6
PZ
194typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
195 struct perf_event_context *, void *);
196
197struct event_function_struct {
198 struct perf_event *event;
199 event_f func;
200 void *data;
201};
202
203static int event_function(void *info)
204{
205 struct event_function_struct *efs = info;
206 struct perf_event *event = efs->event;
0017960f 207 struct perf_event_context *ctx = event->ctx;
fae3fde6
PZ
208 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
209 struct perf_event_context *task_ctx = cpuctx->task_ctx;
63b6da39 210 int ret = 0;
fae3fde6 211
16444645 212 lockdep_assert_irqs_disabled();
fae3fde6 213
63b6da39 214 perf_ctx_lock(cpuctx, task_ctx);
fae3fde6
PZ
215 /*
216 * Since we do the IPI call without holding ctx->lock things can have
217 * changed, double check we hit the task we set out to hit.
fae3fde6
PZ
218 */
219 if (ctx->task) {
63b6da39 220 if (ctx->task != current) {
0da4cf3e 221 ret = -ESRCH;
63b6da39
PZ
222 goto unlock;
223 }
fae3fde6 224
fae3fde6
PZ
225 /*
226 * We only use event_function_call() on established contexts,
227 * and event_function() is only ever called when active (or
228 * rather, we'll have bailed in task_function_call() or the
229 * above ctx->task != current test), therefore we must have
230 * ctx->is_active here.
231 */
232 WARN_ON_ONCE(!ctx->is_active);
233 /*
234 * And since we have ctx->is_active, cpuctx->task_ctx must
235 * match.
236 */
63b6da39
PZ
237 WARN_ON_ONCE(task_ctx != ctx);
238 } else {
239 WARN_ON_ONCE(&cpuctx->ctx != ctx);
fae3fde6 240 }
63b6da39 241
fae3fde6 242 efs->func(event, cpuctx, ctx, efs->data);
63b6da39 243unlock:
fae3fde6
PZ
244 perf_ctx_unlock(cpuctx, task_ctx);
245
63b6da39 246 return ret;
fae3fde6
PZ
247}
248
fae3fde6 249static void event_function_call(struct perf_event *event, event_f func, void *data)
0017960f
PZ
250{
251 struct perf_event_context *ctx = event->ctx;
63b6da39 252 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
fae3fde6
PZ
253 struct event_function_struct efs = {
254 .event = event,
255 .func = func,
256 .data = data,
257 };
0017960f 258
c97f4736
PZ
259 if (!event->parent) {
260 /*
261 * If this is a !child event, we must hold ctx::mutex to
262 * stabilize the the event->ctx relation. See
263 * perf_event_ctx_lock().
264 */
265 lockdep_assert_held(&ctx->mutex);
266 }
0017960f
PZ
267
268 if (!task) {
fae3fde6 269 cpu_function_call(event->cpu, event_function, &efs);
0017960f
PZ
270 return;
271 }
272
63b6da39
PZ
273 if (task == TASK_TOMBSTONE)
274 return;
275
a096309b 276again:
fae3fde6 277 if (!task_function_call(task, event_function, &efs))
0017960f
PZ
278 return;
279
280 raw_spin_lock_irq(&ctx->lock);
63b6da39
PZ
281 /*
282 * Reload the task pointer, it might have been changed by
283 * a concurrent perf_event_context_sched_out().
284 */
285 task = ctx->task;
a096309b
PZ
286 if (task == TASK_TOMBSTONE) {
287 raw_spin_unlock_irq(&ctx->lock);
288 return;
0017960f 289 }
a096309b
PZ
290 if (ctx->is_active) {
291 raw_spin_unlock_irq(&ctx->lock);
292 goto again;
293 }
294 func(event, NULL, ctx, data);
0017960f
PZ
295 raw_spin_unlock_irq(&ctx->lock);
296}
297
cca20946
PZ
298/*
299 * Similar to event_function_call() + event_function(), but hard assumes IRQs
300 * are already disabled and we're on the right CPU.
301 */
302static void event_function_local(struct perf_event *event, event_f func, void *data)
303{
304 struct perf_event_context *ctx = event->ctx;
305 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
306 struct task_struct *task = READ_ONCE(ctx->task);
307 struct perf_event_context *task_ctx = NULL;
308
16444645 309 lockdep_assert_irqs_disabled();
cca20946
PZ
310
311 if (task) {
312 if (task == TASK_TOMBSTONE)
313 return;
314
315 task_ctx = ctx;
316 }
317
318 perf_ctx_lock(cpuctx, task_ctx);
319
320 task = ctx->task;
321 if (task == TASK_TOMBSTONE)
322 goto unlock;
323
324 if (task) {
325 /*
326 * We must be either inactive or active and the right task,
327 * otherwise we're screwed, since we cannot IPI to somewhere
328 * else.
329 */
330 if (ctx->is_active) {
331 if (WARN_ON_ONCE(task != current))
332 goto unlock;
333
334 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
335 goto unlock;
336 }
337 } else {
338 WARN_ON_ONCE(&cpuctx->ctx != ctx);
339 }
340
341 func(event, cpuctx, ctx, data);
342unlock:
343 perf_ctx_unlock(cpuctx, task_ctx);
344}
345
e5d1367f
SE
346#define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
347 PERF_FLAG_FD_OUTPUT |\
a21b0b35
YD
348 PERF_FLAG_PID_CGROUP |\
349 PERF_FLAG_FD_CLOEXEC)
e5d1367f 350
bce38cd5
SE
351/*
352 * branch priv levels that need permission checks
353 */
354#define PERF_SAMPLE_BRANCH_PERM_PLM \
355 (PERF_SAMPLE_BRANCH_KERNEL |\
356 PERF_SAMPLE_BRANCH_HV)
357
0b3fcf17
SE
358enum event_type_t {
359 EVENT_FLEXIBLE = 0x1,
360 EVENT_PINNED = 0x2,
3cbaa590 361 EVENT_TIME = 0x4,
487f05e1
AS
362 /* see ctx_resched() for details */
363 EVENT_CPU = 0x8,
0b3fcf17
SE
364 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
365};
366
e5d1367f
SE
367/*
368 * perf_sched_events : >0 events exist
369 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
370 */
9107c89e
PZ
371
372static void perf_sched_delayed(struct work_struct *work);
373DEFINE_STATIC_KEY_FALSE(perf_sched_events);
374static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
375static DEFINE_MUTEX(perf_sched_mutex);
376static atomic_t perf_sched_count;
377
e5d1367f 378static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
ba532500 379static DEFINE_PER_CPU(int, perf_sched_cb_usages);
f2fb6bef 380static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
e5d1367f 381
cdd6c482
IM
382static atomic_t nr_mmap_events __read_mostly;
383static atomic_t nr_comm_events __read_mostly;
e4222673 384static atomic_t nr_namespaces_events __read_mostly;
cdd6c482 385static atomic_t nr_task_events __read_mostly;
948b26b6 386static atomic_t nr_freq_events __read_mostly;
45ac1403 387static atomic_t nr_switch_events __read_mostly;
76193a94 388static atomic_t nr_ksymbol_events __read_mostly;
6ee52e2a 389static atomic_t nr_bpf_events __read_mostly;
96aaab68 390static atomic_t nr_cgroup_events __read_mostly;
9ee318a7 391
108b02cf
PZ
392static LIST_HEAD(pmus);
393static DEFINE_MUTEX(pmus_lock);
394static struct srcu_struct pmus_srcu;
a63fbed7 395static cpumask_var_t perf_online_mask;
108b02cf 396
0764771d 397/*
cdd6c482 398 * perf event paranoia level:
0fbdea19
IM
399 * -1 - not paranoid at all
400 * 0 - disallow raw tracepoint access for unpriv
cdd6c482 401 * 1 - disallow cpu events for unpriv
0fbdea19 402 * 2 - disallow kernel profiling for unpriv
0764771d 403 */
0161028b 404int sysctl_perf_event_paranoid __read_mostly = 2;
0764771d 405
20443384
FW
406/* Minimum for 512 kiB + 1 user control page */
407int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
df58ab24
PZ
408
409/*
cdd6c482 410 * max perf event sample rate
df58ab24 411 */
14c63f17
DH
412#define DEFAULT_MAX_SAMPLE_RATE 100000
413#define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
414#define DEFAULT_CPU_TIME_MAX_PERCENT 25
415
416int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
417
418static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
419static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
420
d9494cb4
PZ
421static int perf_sample_allowed_ns __read_mostly =
422 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
14c63f17 423
18ab2cd3 424static void update_perf_cpu_limits(void)
14c63f17
DH
425{
426 u64 tmp = perf_sample_period_ns;
427
428 tmp *= sysctl_perf_cpu_time_max_percent;
91a612ee
PZ
429 tmp = div_u64(tmp, 100);
430 if (!tmp)
431 tmp = 1;
432
433 WRITE_ONCE(perf_sample_allowed_ns, tmp);
14c63f17 434}
163ec435 435
8d5bce0c 436static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
9e630205 437
163ec435
PZ
438int perf_proc_update_handler(struct ctl_table *table, int write,
439 void __user *buffer, size_t *lenp,
440 loff_t *ppos)
441{
1a51c5da
SE
442 int ret;
443 int perf_cpu = sysctl_perf_cpu_time_max_percent;
ab7fdefb
KL
444 /*
445 * If throttling is disabled don't allow the write:
446 */
1a51c5da 447 if (write && (perf_cpu == 100 || perf_cpu == 0))
ab7fdefb
KL
448 return -EINVAL;
449
1a51c5da
SE
450 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
451 if (ret || !write)
452 return ret;
453
163ec435 454 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
14c63f17
DH
455 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
456 update_perf_cpu_limits();
457
458 return 0;
459}
460
461int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
462
463int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
464 void __user *buffer, size_t *lenp,
465 loff_t *ppos)
466{
1572e45a 467 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
14c63f17
DH
468
469 if (ret || !write)
470 return ret;
471
b303e7c1
PZ
472 if (sysctl_perf_cpu_time_max_percent == 100 ||
473 sysctl_perf_cpu_time_max_percent == 0) {
91a612ee
PZ
474 printk(KERN_WARNING
475 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
476 WRITE_ONCE(perf_sample_allowed_ns, 0);
477 } else {
478 update_perf_cpu_limits();
479 }
163ec435
PZ
480
481 return 0;
482}
1ccd1549 483
14c63f17
DH
484/*
485 * perf samples are done in some very critical code paths (NMIs).
486 * If they take too much CPU time, the system can lock up and not
487 * get any real work done. This will drop the sample rate when
488 * we detect that events are taking too long.
489 */
490#define NR_ACCUMULATED_SAMPLES 128
d9494cb4 491static DEFINE_PER_CPU(u64, running_sample_length);
14c63f17 492
91a612ee
PZ
493static u64 __report_avg;
494static u64 __report_allowed;
495
6a02ad66 496static void perf_duration_warn(struct irq_work *w)
14c63f17 497{
0d87d7ec 498 printk_ratelimited(KERN_INFO
91a612ee
PZ
499 "perf: interrupt took too long (%lld > %lld), lowering "
500 "kernel.perf_event_max_sample_rate to %d\n",
501 __report_avg, __report_allowed,
502 sysctl_perf_event_sample_rate);
6a02ad66
PZ
503}
504
505static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
506
507void perf_sample_event_took(u64 sample_len_ns)
508{
91a612ee
PZ
509 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
510 u64 running_len;
511 u64 avg_len;
512 u32 max;
14c63f17 513
91a612ee 514 if (max_len == 0)
14c63f17
DH
515 return;
516
91a612ee
PZ
517 /* Decay the counter by 1 average sample. */
518 running_len = __this_cpu_read(running_sample_length);
519 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
520 running_len += sample_len_ns;
521 __this_cpu_write(running_sample_length, running_len);
14c63f17
DH
522
523 /*
91a612ee
PZ
524 * Note: this will be biased artifically low until we have
525 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
14c63f17
DH
526 * from having to maintain a count.
527 */
91a612ee
PZ
528 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
529 if (avg_len <= max_len)
14c63f17
DH
530 return;
531
91a612ee
PZ
532 __report_avg = avg_len;
533 __report_allowed = max_len;
14c63f17 534
91a612ee
PZ
535 /*
536 * Compute a throttle threshold 25% below the current duration.
537 */
538 avg_len += avg_len / 4;
539 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
540 if (avg_len < max)
541 max /= (u32)avg_len;
542 else
543 max = 1;
14c63f17 544
91a612ee
PZ
545 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
546 WRITE_ONCE(max_samples_per_tick, max);
547
548 sysctl_perf_event_sample_rate = max * HZ;
549 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
6a02ad66 550
cd578abb 551 if (!irq_work_queue(&perf_duration_work)) {
91a612ee 552 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
cd578abb 553 "kernel.perf_event_max_sample_rate to %d\n",
91a612ee 554 __report_avg, __report_allowed,
cd578abb
PZ
555 sysctl_perf_event_sample_rate);
556 }
14c63f17
DH
557}
558
cdd6c482 559static atomic64_t perf_event_id;
a96bbc16 560
0b3fcf17
SE
561static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
562 enum event_type_t event_type);
563
564static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
e5d1367f
SE
565 enum event_type_t event_type,
566 struct task_struct *task);
567
568static void update_context_time(struct perf_event_context *ctx);
569static u64 perf_event_time(struct perf_event *event);
0b3fcf17 570
cdd6c482 571void __weak perf_event_print_debug(void) { }
0793a61d 572
84c79910 573extern __weak const char *perf_pmu_name(void)
0793a61d 574{
84c79910 575 return "pmu";
0793a61d
TG
576}
577
0b3fcf17
SE
578static inline u64 perf_clock(void)
579{
580 return local_clock();
581}
582
34f43927
PZ
583static inline u64 perf_event_clock(struct perf_event *event)
584{
585 return event->clock();
586}
587
0d3d73aa
PZ
588/*
589 * State based event timekeeping...
590 *
591 * The basic idea is to use event->state to determine which (if any) time
592 * fields to increment with the current delta. This means we only need to
593 * update timestamps when we change state or when they are explicitly requested
594 * (read).
595 *
596 * Event groups make things a little more complicated, but not terribly so. The
597 * rules for a group are that if the group leader is OFF the entire group is
598 * OFF, irrespecive of what the group member states are. This results in
599 * __perf_effective_state().
600 *
601 * A futher ramification is that when a group leader flips between OFF and
602 * !OFF, we need to update all group member times.
603 *
604 *
605 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
606 * need to make sure the relevant context time is updated before we try and
607 * update our timestamps.
608 */
609
610static __always_inline enum perf_event_state
611__perf_effective_state(struct perf_event *event)
612{
613 struct perf_event *leader = event->group_leader;
614
615 if (leader->state <= PERF_EVENT_STATE_OFF)
616 return leader->state;
617
618 return event->state;
619}
620
621static __always_inline void
622__perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
623{
624 enum perf_event_state state = __perf_effective_state(event);
625 u64 delta = now - event->tstamp;
626
627 *enabled = event->total_time_enabled;
628 if (state >= PERF_EVENT_STATE_INACTIVE)
629 *enabled += delta;
630
631 *running = event->total_time_running;
632 if (state >= PERF_EVENT_STATE_ACTIVE)
633 *running += delta;
634}
635
636static void perf_event_update_time(struct perf_event *event)
637{
638 u64 now = perf_event_time(event);
639
640 __perf_update_times(event, now, &event->total_time_enabled,
641 &event->total_time_running);
642 event->tstamp = now;
643}
644
645static void perf_event_update_sibling_time(struct perf_event *leader)
646{
647 struct perf_event *sibling;
648
edb39592 649 for_each_sibling_event(sibling, leader)
0d3d73aa
PZ
650 perf_event_update_time(sibling);
651}
652
653static void
654perf_event_set_state(struct perf_event *event, enum perf_event_state state)
655{
656 if (event->state == state)
657 return;
658
659 perf_event_update_time(event);
660 /*
661 * If a group leader gets enabled/disabled all its siblings
662 * are affected too.
663 */
664 if ((event->state < 0) ^ (state < 0))
665 perf_event_update_sibling_time(event);
666
667 WRITE_ONCE(event->state, state);
668}
669
e5d1367f
SE
670#ifdef CONFIG_CGROUP_PERF
671
e5d1367f
SE
672static inline bool
673perf_cgroup_match(struct perf_event *event)
674{
675 struct perf_event_context *ctx = event->ctx;
676 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
677
ef824fa1
TH
678 /* @event doesn't care about cgroup */
679 if (!event->cgrp)
680 return true;
681
682 /* wants specific cgroup scope but @cpuctx isn't associated with any */
683 if (!cpuctx->cgrp)
684 return false;
685
686 /*
687 * Cgroup scoping is recursive. An event enabled for a cgroup is
688 * also enabled for all its descendant cgroups. If @cpuctx's
689 * cgroup is a descendant of @event's (the test covers identity
690 * case), it's a match.
691 */
692 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
693 event->cgrp->css.cgroup);
e5d1367f
SE
694}
695
e5d1367f
SE
696static inline void perf_detach_cgroup(struct perf_event *event)
697{
4e2ba650 698 css_put(&event->cgrp->css);
e5d1367f
SE
699 event->cgrp = NULL;
700}
701
702static inline int is_cgroup_event(struct perf_event *event)
703{
704 return event->cgrp != NULL;
705}
706
707static inline u64 perf_cgroup_event_time(struct perf_event *event)
708{
709 struct perf_cgroup_info *t;
710
711 t = per_cpu_ptr(event->cgrp->info, event->cpu);
712 return t->time;
713}
714
715static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
716{
717 struct perf_cgroup_info *info;
718 u64 now;
719
720 now = perf_clock();
721
722 info = this_cpu_ptr(cgrp->info);
723
724 info->time += now - info->timestamp;
725 info->timestamp = now;
726}
727
728static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
729{
c917e0f2
SL
730 struct perf_cgroup *cgrp = cpuctx->cgrp;
731 struct cgroup_subsys_state *css;
732
733 if (cgrp) {
734 for (css = &cgrp->css; css; css = css->parent) {
735 cgrp = container_of(css, struct perf_cgroup, css);
736 __update_cgrp_time(cgrp);
737 }
738 }
e5d1367f
SE
739}
740
741static inline void update_cgrp_time_from_event(struct perf_event *event)
742{
3f7cce3c
SE
743 struct perf_cgroup *cgrp;
744
e5d1367f 745 /*
3f7cce3c
SE
746 * ensure we access cgroup data only when needed and
747 * when we know the cgroup is pinned (css_get)
e5d1367f 748 */
3f7cce3c 749 if (!is_cgroup_event(event))
e5d1367f
SE
750 return;
751
614e4c4e 752 cgrp = perf_cgroup_from_task(current, event->ctx);
3f7cce3c
SE
753 /*
754 * Do not update time when cgroup is not active
755 */
28fa741c 756 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
3f7cce3c 757 __update_cgrp_time(event->cgrp);
e5d1367f
SE
758}
759
760static inline void
3f7cce3c
SE
761perf_cgroup_set_timestamp(struct task_struct *task,
762 struct perf_event_context *ctx)
e5d1367f
SE
763{
764 struct perf_cgroup *cgrp;
765 struct perf_cgroup_info *info;
c917e0f2 766 struct cgroup_subsys_state *css;
e5d1367f 767
3f7cce3c
SE
768 /*
769 * ctx->lock held by caller
770 * ensure we do not access cgroup data
771 * unless we have the cgroup pinned (css_get)
772 */
773 if (!task || !ctx->nr_cgroups)
e5d1367f
SE
774 return;
775
614e4c4e 776 cgrp = perf_cgroup_from_task(task, ctx);
c917e0f2
SL
777
778 for (css = &cgrp->css; css; css = css->parent) {
779 cgrp = container_of(css, struct perf_cgroup, css);
780 info = this_cpu_ptr(cgrp->info);
781 info->timestamp = ctx->timestamp;
782 }
e5d1367f
SE
783}
784
058fe1c0
DCC
785static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
786
e5d1367f
SE
787#define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
788#define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
789
790/*
791 * reschedule events based on the cgroup constraint of task.
792 *
793 * mode SWOUT : schedule out everything
794 * mode SWIN : schedule in based on cgroup for next
795 */
18ab2cd3 796static void perf_cgroup_switch(struct task_struct *task, int mode)
e5d1367f
SE
797{
798 struct perf_cpu_context *cpuctx;
058fe1c0 799 struct list_head *list;
e5d1367f
SE
800 unsigned long flags;
801
802 /*
058fe1c0
DCC
803 * Disable interrupts and preemption to avoid this CPU's
804 * cgrp_cpuctx_entry to change under us.
e5d1367f
SE
805 */
806 local_irq_save(flags);
807
058fe1c0
DCC
808 list = this_cpu_ptr(&cgrp_cpuctx_list);
809 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) {
810 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
e5d1367f 811
058fe1c0
DCC
812 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
813 perf_pmu_disable(cpuctx->ctx.pmu);
e5d1367f 814
058fe1c0
DCC
815 if (mode & PERF_CGROUP_SWOUT) {
816 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
817 /*
818 * must not be done before ctxswout due
819 * to event_filter_match() in event_sched_out()
820 */
821 cpuctx->cgrp = NULL;
822 }
e5d1367f 823
058fe1c0
DCC
824 if (mode & PERF_CGROUP_SWIN) {
825 WARN_ON_ONCE(cpuctx->cgrp);
826 /*
827 * set cgrp before ctxsw in to allow
828 * event_filter_match() to not have to pass
829 * task around
830 * we pass the cpuctx->ctx to perf_cgroup_from_task()
831 * because cgorup events are only per-cpu
832 */
833 cpuctx->cgrp = perf_cgroup_from_task(task,
834 &cpuctx->ctx);
835 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
e5d1367f 836 }
058fe1c0
DCC
837 perf_pmu_enable(cpuctx->ctx.pmu);
838 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
e5d1367f
SE
839 }
840
e5d1367f
SE
841 local_irq_restore(flags);
842}
843
a8d757ef
SE
844static inline void perf_cgroup_sched_out(struct task_struct *task,
845 struct task_struct *next)
e5d1367f 846{
a8d757ef
SE
847 struct perf_cgroup *cgrp1;
848 struct perf_cgroup *cgrp2 = NULL;
849
ddaaf4e2 850 rcu_read_lock();
a8d757ef
SE
851 /*
852 * we come here when we know perf_cgroup_events > 0
614e4c4e
SE
853 * we do not need to pass the ctx here because we know
854 * we are holding the rcu lock
a8d757ef 855 */
614e4c4e 856 cgrp1 = perf_cgroup_from_task(task, NULL);
70a01657 857 cgrp2 = perf_cgroup_from_task(next, NULL);
a8d757ef
SE
858
859 /*
860 * only schedule out current cgroup events if we know
861 * that we are switching to a different cgroup. Otherwise,
862 * do no touch the cgroup events.
863 */
864 if (cgrp1 != cgrp2)
865 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
ddaaf4e2
SE
866
867 rcu_read_unlock();
e5d1367f
SE
868}
869
a8d757ef
SE
870static inline void perf_cgroup_sched_in(struct task_struct *prev,
871 struct task_struct *task)
e5d1367f 872{
a8d757ef
SE
873 struct perf_cgroup *cgrp1;
874 struct perf_cgroup *cgrp2 = NULL;
875
ddaaf4e2 876 rcu_read_lock();
a8d757ef
SE
877 /*
878 * we come here when we know perf_cgroup_events > 0
614e4c4e
SE
879 * we do not need to pass the ctx here because we know
880 * we are holding the rcu lock
a8d757ef 881 */
614e4c4e 882 cgrp1 = perf_cgroup_from_task(task, NULL);
614e4c4e 883 cgrp2 = perf_cgroup_from_task(prev, NULL);
a8d757ef
SE
884
885 /*
886 * only need to schedule in cgroup events if we are changing
887 * cgroup during ctxsw. Cgroup events were not scheduled
888 * out of ctxsw out if that was not the case.
889 */
890 if (cgrp1 != cgrp2)
891 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
ddaaf4e2
SE
892
893 rcu_read_unlock();
e5d1367f
SE
894}
895
c2283c93
IR
896static int perf_cgroup_ensure_storage(struct perf_event *event,
897 struct cgroup_subsys_state *css)
898{
899 struct perf_cpu_context *cpuctx;
900 struct perf_event **storage;
901 int cpu, heap_size, ret = 0;
902
903 /*
904 * Allow storage to have sufficent space for an iterator for each
905 * possibly nested cgroup plus an iterator for events with no cgroup.
906 */
907 for (heap_size = 1; css; css = css->parent)
908 heap_size++;
909
910 for_each_possible_cpu(cpu) {
911 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu);
912 if (heap_size <= cpuctx->heap_size)
913 continue;
914
915 storage = kmalloc_node(heap_size * sizeof(struct perf_event *),
916 GFP_KERNEL, cpu_to_node(cpu));
917 if (!storage) {
918 ret = -ENOMEM;
919 break;
920 }
921
922 raw_spin_lock_irq(&cpuctx->ctx.lock);
923 if (cpuctx->heap_size < heap_size) {
924 swap(cpuctx->heap, storage);
925 if (storage == cpuctx->heap_default)
926 storage = NULL;
927 cpuctx->heap_size = heap_size;
928 }
929 raw_spin_unlock_irq(&cpuctx->ctx.lock);
930
931 kfree(storage);
932 }
933
934 return ret;
935}
936
e5d1367f
SE
937static inline int perf_cgroup_connect(int fd, struct perf_event *event,
938 struct perf_event_attr *attr,
939 struct perf_event *group_leader)
940{
941 struct perf_cgroup *cgrp;
942 struct cgroup_subsys_state *css;
2903ff01
AV
943 struct fd f = fdget(fd);
944 int ret = 0;
e5d1367f 945
2903ff01 946 if (!f.file)
e5d1367f
SE
947 return -EBADF;
948
b583043e 949 css = css_tryget_online_from_dir(f.file->f_path.dentry,
ec903c0c 950 &perf_event_cgrp_subsys);
3db272c0
LZ
951 if (IS_ERR(css)) {
952 ret = PTR_ERR(css);
953 goto out;
954 }
e5d1367f 955
c2283c93
IR
956 ret = perf_cgroup_ensure_storage(event, css);
957 if (ret)
958 goto out;
959
e5d1367f
SE
960 cgrp = container_of(css, struct perf_cgroup, css);
961 event->cgrp = cgrp;
962
963 /*
964 * all events in a group must monitor
965 * the same cgroup because a task belongs
966 * to only one perf cgroup at a time
967 */
968 if (group_leader && group_leader->cgrp != cgrp) {
969 perf_detach_cgroup(event);
970 ret = -EINVAL;
e5d1367f 971 }
3db272c0 972out:
2903ff01 973 fdput(f);
e5d1367f
SE
974 return ret;
975}
976
977static inline void
978perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
979{
980 struct perf_cgroup_info *t;
981 t = per_cpu_ptr(event->cgrp->info, event->cpu);
982 event->shadow_ctx_time = now - t->timestamp;
983}
984
db4a8356
DCC
985/*
986 * Update cpuctx->cgrp so that it is set when first cgroup event is added and
987 * cleared when last cgroup event is removed.
988 */
989static inline void
990list_update_cgroup_event(struct perf_event *event,
991 struct perf_event_context *ctx, bool add)
992{
993 struct perf_cpu_context *cpuctx;
058fe1c0 994 struct list_head *cpuctx_entry;
db4a8356
DCC
995
996 if (!is_cgroup_event(event))
997 return;
998
db4a8356
DCC
999 /*
1000 * Because cgroup events are always per-cpu events,
07c59729 1001 * @ctx == &cpuctx->ctx.
db4a8356 1002 */
07c59729 1003 cpuctx = container_of(ctx, struct perf_cpu_context, ctx);
33801b94 1004
1005 /*
1006 * Since setting cpuctx->cgrp is conditional on the current @cgrp
1007 * matching the event's cgroup, we must do this for every new event,
1008 * because if the first would mismatch, the second would not try again
1009 * and we would leave cpuctx->cgrp unset.
1010 */
1011 if (add && !cpuctx->cgrp) {
be96b316
TH
1012 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
1013
be96b316
TH
1014 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
1015 cpuctx->cgrp = cgrp;
058fe1c0 1016 }
33801b94 1017
1018 if (add && ctx->nr_cgroups++)
1019 return;
1020 else if (!add && --ctx->nr_cgroups)
1021 return;
1022
1023 /* no cgroup running */
1024 if (!add)
1025 cpuctx->cgrp = NULL;
1026
1027 cpuctx_entry = &cpuctx->cgrp_cpuctx_entry;
1028 if (add)
07c59729
SL
1029 list_add(cpuctx_entry,
1030 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu));
33801b94 1031 else
1032 list_del(cpuctx_entry);
db4a8356
DCC
1033}
1034
e5d1367f
SE
1035#else /* !CONFIG_CGROUP_PERF */
1036
1037static inline bool
1038perf_cgroup_match(struct perf_event *event)
1039{
1040 return true;
1041}
1042
1043static inline void perf_detach_cgroup(struct perf_event *event)
1044{}
1045
1046static inline int is_cgroup_event(struct perf_event *event)
1047{
1048 return 0;
1049}
1050
e5d1367f
SE
1051static inline void update_cgrp_time_from_event(struct perf_event *event)
1052{
1053}
1054
1055static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1056{
1057}
1058
a8d757ef
SE
1059static inline void perf_cgroup_sched_out(struct task_struct *task,
1060 struct task_struct *next)
e5d1367f
SE
1061{
1062}
1063
a8d757ef
SE
1064static inline void perf_cgroup_sched_in(struct task_struct *prev,
1065 struct task_struct *task)
e5d1367f
SE
1066{
1067}
1068
1069static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1070 struct perf_event_attr *attr,
1071 struct perf_event *group_leader)
1072{
1073 return -EINVAL;
1074}
1075
1076static inline void
3f7cce3c
SE
1077perf_cgroup_set_timestamp(struct task_struct *task,
1078 struct perf_event_context *ctx)
e5d1367f
SE
1079{
1080}
1081
d00dbd29 1082static inline void
e5d1367f
SE
1083perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1084{
1085}
1086
1087static inline void
1088perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1089{
1090}
1091
1092static inline u64 perf_cgroup_event_time(struct perf_event *event)
1093{
1094 return 0;
1095}
1096
db4a8356
DCC
1097static inline void
1098list_update_cgroup_event(struct perf_event *event,
1099 struct perf_event_context *ctx, bool add)
1100{
1101}
1102
e5d1367f
SE
1103#endif
1104
9e630205
SE
1105/*
1106 * set default to be dependent on timer tick just
1107 * like original code
1108 */
1109#define PERF_CPU_HRTIMER (1000 / HZ)
1110/*
8a1115ff 1111 * function must be called with interrupts disabled
9e630205 1112 */
272325c4 1113static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
9e630205
SE
1114{
1115 struct perf_cpu_context *cpuctx;
8d5bce0c 1116 bool rotations;
9e630205 1117
16444645 1118 lockdep_assert_irqs_disabled();
9e630205
SE
1119
1120 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
9e630205
SE
1121 rotations = perf_rotate_context(cpuctx);
1122
4cfafd30
PZ
1123 raw_spin_lock(&cpuctx->hrtimer_lock);
1124 if (rotations)
9e630205 1125 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
4cfafd30
PZ
1126 else
1127 cpuctx->hrtimer_active = 0;
1128 raw_spin_unlock(&cpuctx->hrtimer_lock);
9e630205 1129
4cfafd30 1130 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
9e630205
SE
1131}
1132
272325c4 1133static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
9e630205 1134{
272325c4 1135 struct hrtimer *timer = &cpuctx->hrtimer;
9e630205 1136 struct pmu *pmu = cpuctx->ctx.pmu;
272325c4 1137 u64 interval;
9e630205
SE
1138
1139 /* no multiplexing needed for SW PMU */
1140 if (pmu->task_ctx_nr == perf_sw_context)
1141 return;
1142
62b85639
SE
1143 /*
1144 * check default is sane, if not set then force to
1145 * default interval (1/tick)
1146 */
272325c4
PZ
1147 interval = pmu->hrtimer_interval_ms;
1148 if (interval < 1)
1149 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
62b85639 1150
272325c4 1151 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
9e630205 1152
4cfafd30 1153 raw_spin_lock_init(&cpuctx->hrtimer_lock);
30f9028b 1154 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
272325c4 1155 timer->function = perf_mux_hrtimer_handler;
9e630205
SE
1156}
1157
272325c4 1158static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
9e630205 1159{
272325c4 1160 struct hrtimer *timer = &cpuctx->hrtimer;
9e630205 1161 struct pmu *pmu = cpuctx->ctx.pmu;
4cfafd30 1162 unsigned long flags;
9e630205
SE
1163
1164 /* not for SW PMU */
1165 if (pmu->task_ctx_nr == perf_sw_context)
272325c4 1166 return 0;
9e630205 1167
4cfafd30
PZ
1168 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1169 if (!cpuctx->hrtimer_active) {
1170 cpuctx->hrtimer_active = 1;
1171 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
30f9028b 1172 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
4cfafd30
PZ
1173 }
1174 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
9e630205 1175
272325c4 1176 return 0;
9e630205
SE
1177}
1178
33696fc0 1179void perf_pmu_disable(struct pmu *pmu)
9e35ad38 1180{
33696fc0
PZ
1181 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1182 if (!(*count)++)
1183 pmu->pmu_disable(pmu);
9e35ad38 1184}
9e35ad38 1185
33696fc0 1186void perf_pmu_enable(struct pmu *pmu)
9e35ad38 1187{
33696fc0
PZ
1188 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1189 if (!--(*count))
1190 pmu->pmu_enable(pmu);
9e35ad38 1191}
9e35ad38 1192
2fde4f94 1193static DEFINE_PER_CPU(struct list_head, active_ctx_list);
e9d2b064
PZ
1194
1195/*
2fde4f94
MR
1196 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1197 * perf_event_task_tick() are fully serialized because they're strictly cpu
1198 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1199 * disabled, while perf_event_task_tick is called from IRQ context.
e9d2b064 1200 */
2fde4f94 1201static void perf_event_ctx_activate(struct perf_event_context *ctx)
9e35ad38 1202{
2fde4f94 1203 struct list_head *head = this_cpu_ptr(&active_ctx_list);
b5ab4cd5 1204
16444645 1205 lockdep_assert_irqs_disabled();
b5ab4cd5 1206
2fde4f94
MR
1207 WARN_ON(!list_empty(&ctx->active_ctx_list));
1208
1209 list_add(&ctx->active_ctx_list, head);
1210}
1211
1212static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1213{
16444645 1214 lockdep_assert_irqs_disabled();
2fde4f94
MR
1215
1216 WARN_ON(list_empty(&ctx->active_ctx_list));
1217
1218 list_del_init(&ctx->active_ctx_list);
9e35ad38 1219}
9e35ad38 1220
cdd6c482 1221static void get_ctx(struct perf_event_context *ctx)
a63eaf34 1222{
8c94abbb 1223 refcount_inc(&ctx->refcount);
a63eaf34
PM
1224}
1225
4af57ef2
YZ
1226static void free_ctx(struct rcu_head *head)
1227{
1228 struct perf_event_context *ctx;
1229
1230 ctx = container_of(head, struct perf_event_context, rcu_head);
1231 kfree(ctx->task_ctx_data);
1232 kfree(ctx);
1233}
1234
cdd6c482 1235static void put_ctx(struct perf_event_context *ctx)
a63eaf34 1236{
8c94abbb 1237 if (refcount_dec_and_test(&ctx->refcount)) {
564c2b21
PM
1238 if (ctx->parent_ctx)
1239 put_ctx(ctx->parent_ctx);
63b6da39 1240 if (ctx->task && ctx->task != TASK_TOMBSTONE)
c93f7669 1241 put_task_struct(ctx->task);
4af57ef2 1242 call_rcu(&ctx->rcu_head, free_ctx);
564c2b21 1243 }
a63eaf34
PM
1244}
1245
f63a8daa
PZ
1246/*
1247 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1248 * perf_pmu_migrate_context() we need some magic.
1249 *
1250 * Those places that change perf_event::ctx will hold both
1251 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1252 *
8b10c5e2
PZ
1253 * Lock ordering is by mutex address. There are two other sites where
1254 * perf_event_context::mutex nests and those are:
1255 *
1256 * - perf_event_exit_task_context() [ child , 0 ]
8ba289b8
PZ
1257 * perf_event_exit_event()
1258 * put_event() [ parent, 1 ]
8b10c5e2
PZ
1259 *
1260 * - perf_event_init_context() [ parent, 0 ]
1261 * inherit_task_group()
1262 * inherit_group()
1263 * inherit_event()
1264 * perf_event_alloc()
1265 * perf_init_event()
1266 * perf_try_init_event() [ child , 1 ]
1267 *
1268 * While it appears there is an obvious deadlock here -- the parent and child
1269 * nesting levels are inverted between the two. This is in fact safe because
1270 * life-time rules separate them. That is an exiting task cannot fork, and a
1271 * spawning task cannot (yet) exit.
1272 *
1273 * But remember that that these are parent<->child context relations, and
1274 * migration does not affect children, therefore these two orderings should not
1275 * interact.
f63a8daa
PZ
1276 *
1277 * The change in perf_event::ctx does not affect children (as claimed above)
1278 * because the sys_perf_event_open() case will install a new event and break
1279 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1280 * concerned with cpuctx and that doesn't have children.
1281 *
1282 * The places that change perf_event::ctx will issue:
1283 *
1284 * perf_remove_from_context();
1285 * synchronize_rcu();
1286 * perf_install_in_context();
1287 *
1288 * to affect the change. The remove_from_context() + synchronize_rcu() should
1289 * quiesce the event, after which we can install it in the new location. This
1290 * means that only external vectors (perf_fops, prctl) can perturb the event
1291 * while in transit. Therefore all such accessors should also acquire
1292 * perf_event_context::mutex to serialize against this.
1293 *
1294 * However; because event->ctx can change while we're waiting to acquire
1295 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1296 * function.
1297 *
1298 * Lock order:
69143038 1299 * exec_update_mutex
f63a8daa
PZ
1300 * task_struct::perf_event_mutex
1301 * perf_event_context::mutex
f63a8daa 1302 * perf_event::child_mutex;
07c4a776 1303 * perf_event_context::lock
f63a8daa
PZ
1304 * perf_event::mmap_mutex
1305 * mmap_sem
18736eef 1306 * perf_addr_filters_head::lock
82d94856
PZ
1307 *
1308 * cpu_hotplug_lock
1309 * pmus_lock
1310 * cpuctx->mutex / perf_event_context::mutex
f63a8daa 1311 */
a83fe28e
PZ
1312static struct perf_event_context *
1313perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
f63a8daa
PZ
1314{
1315 struct perf_event_context *ctx;
1316
1317again:
1318 rcu_read_lock();
6aa7de05 1319 ctx = READ_ONCE(event->ctx);
8c94abbb 1320 if (!refcount_inc_not_zero(&ctx->refcount)) {
f63a8daa
PZ
1321 rcu_read_unlock();
1322 goto again;
1323 }
1324 rcu_read_unlock();
1325
a83fe28e 1326 mutex_lock_nested(&ctx->mutex, nesting);
f63a8daa
PZ
1327 if (event->ctx != ctx) {
1328 mutex_unlock(&ctx->mutex);
1329 put_ctx(ctx);
1330 goto again;
1331 }
1332
1333 return ctx;
1334}
1335
a83fe28e
PZ
1336static inline struct perf_event_context *
1337perf_event_ctx_lock(struct perf_event *event)
1338{
1339 return perf_event_ctx_lock_nested(event, 0);
1340}
1341
f63a8daa
PZ
1342static void perf_event_ctx_unlock(struct perf_event *event,
1343 struct perf_event_context *ctx)
1344{
1345 mutex_unlock(&ctx->mutex);
1346 put_ctx(ctx);
1347}
1348
211de6eb
PZ
1349/*
1350 * This must be done under the ctx->lock, such as to serialize against
1351 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1352 * calling scheduler related locks and ctx->lock nests inside those.
1353 */
1354static __must_check struct perf_event_context *
1355unclone_ctx(struct perf_event_context *ctx)
71a851b4 1356{
211de6eb
PZ
1357 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1358
1359 lockdep_assert_held(&ctx->lock);
1360
1361 if (parent_ctx)
71a851b4 1362 ctx->parent_ctx = NULL;
5a3126d4 1363 ctx->generation++;
211de6eb
PZ
1364
1365 return parent_ctx;
71a851b4
PZ
1366}
1367
1d953111
ON
1368static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1369 enum pid_type type)
6844c09d 1370{
1d953111 1371 u32 nr;
6844c09d
ACM
1372 /*
1373 * only top level events have the pid namespace they were created in
1374 */
1375 if (event->parent)
1376 event = event->parent;
1377
1d953111
ON
1378 nr = __task_pid_nr_ns(p, type, event->ns);
1379 /* avoid -1 if it is idle thread or runs in another ns */
1380 if (!nr && !pid_alive(p))
1381 nr = -1;
1382 return nr;
6844c09d
ACM
1383}
1384
1d953111 1385static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
6844c09d 1386{
6883f81a 1387 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1d953111 1388}
6844c09d 1389
1d953111
ON
1390static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1391{
1392 return perf_event_pid_type(event, p, PIDTYPE_PID);
6844c09d
ACM
1393}
1394
7f453c24 1395/*
cdd6c482 1396 * If we inherit events we want to return the parent event id
7f453c24
PZ
1397 * to userspace.
1398 */
cdd6c482 1399static u64 primary_event_id(struct perf_event *event)
7f453c24 1400{
cdd6c482 1401 u64 id = event->id;
7f453c24 1402
cdd6c482
IM
1403 if (event->parent)
1404 id = event->parent->id;
7f453c24
PZ
1405
1406 return id;
1407}
1408
25346b93 1409/*
cdd6c482 1410 * Get the perf_event_context for a task and lock it.
63b6da39 1411 *
25346b93
PM
1412 * This has to cope with with the fact that until it is locked,
1413 * the context could get moved to another task.
1414 */
cdd6c482 1415static struct perf_event_context *
8dc85d54 1416perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
25346b93 1417{
cdd6c482 1418 struct perf_event_context *ctx;
25346b93 1419
9ed6060d 1420retry:
058ebd0e
PZ
1421 /*
1422 * One of the few rules of preemptible RCU is that one cannot do
1423 * rcu_read_unlock() while holding a scheduler (or nested) lock when
2fd59077 1424 * part of the read side critical section was irqs-enabled -- see
058ebd0e
PZ
1425 * rcu_read_unlock_special().
1426 *
1427 * Since ctx->lock nests under rq->lock we must ensure the entire read
2fd59077 1428 * side critical section has interrupts disabled.
058ebd0e 1429 */
2fd59077 1430 local_irq_save(*flags);
058ebd0e 1431 rcu_read_lock();
8dc85d54 1432 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
25346b93
PM
1433 if (ctx) {
1434 /*
1435 * If this context is a clone of another, it might
1436 * get swapped for another underneath us by
cdd6c482 1437 * perf_event_task_sched_out, though the
25346b93
PM
1438 * rcu_read_lock() protects us from any context
1439 * getting freed. Lock the context and check if it
1440 * got swapped before we could get the lock, and retry
1441 * if so. If we locked the right context, then it
1442 * can't get swapped on us any more.
1443 */
2fd59077 1444 raw_spin_lock(&ctx->lock);
8dc85d54 1445 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
2fd59077 1446 raw_spin_unlock(&ctx->lock);
058ebd0e 1447 rcu_read_unlock();
2fd59077 1448 local_irq_restore(*flags);
25346b93
PM
1449 goto retry;
1450 }
b49a9e7e 1451
63b6da39 1452 if (ctx->task == TASK_TOMBSTONE ||
8c94abbb 1453 !refcount_inc_not_zero(&ctx->refcount)) {
2fd59077 1454 raw_spin_unlock(&ctx->lock);
b49a9e7e 1455 ctx = NULL;
828b6f0e
PZ
1456 } else {
1457 WARN_ON_ONCE(ctx->task != task);
b49a9e7e 1458 }
25346b93
PM
1459 }
1460 rcu_read_unlock();
2fd59077
PM
1461 if (!ctx)
1462 local_irq_restore(*flags);
25346b93
PM
1463 return ctx;
1464}
1465
1466/*
1467 * Get the context for a task and increment its pin_count so it
1468 * can't get swapped to another task. This also increments its
1469 * reference count so that the context can't get freed.
1470 */
8dc85d54
PZ
1471static struct perf_event_context *
1472perf_pin_task_context(struct task_struct *task, int ctxn)
25346b93 1473{
cdd6c482 1474 struct perf_event_context *ctx;
25346b93
PM
1475 unsigned long flags;
1476
8dc85d54 1477 ctx = perf_lock_task_context(task, ctxn, &flags);
25346b93
PM
1478 if (ctx) {
1479 ++ctx->pin_count;
e625cce1 1480 raw_spin_unlock_irqrestore(&ctx->lock, flags);
25346b93
PM
1481 }
1482 return ctx;
1483}
1484
cdd6c482 1485static void perf_unpin_context(struct perf_event_context *ctx)
25346b93
PM
1486{
1487 unsigned long flags;
1488
e625cce1 1489 raw_spin_lock_irqsave(&ctx->lock, flags);
25346b93 1490 --ctx->pin_count;
e625cce1 1491 raw_spin_unlock_irqrestore(&ctx->lock, flags);
25346b93
PM
1492}
1493
f67218c3
PZ
1494/*
1495 * Update the record of the current time in a context.
1496 */
1497static void update_context_time(struct perf_event_context *ctx)
1498{
1499 u64 now = perf_clock();
1500
1501 ctx->time += now - ctx->timestamp;
1502 ctx->timestamp = now;
1503}
1504
4158755d
SE
1505static u64 perf_event_time(struct perf_event *event)
1506{
1507 struct perf_event_context *ctx = event->ctx;
e5d1367f
SE
1508
1509 if (is_cgroup_event(event))
1510 return perf_cgroup_event_time(event);
1511
4158755d
SE
1512 return ctx ? ctx->time : 0;
1513}
1514
487f05e1
AS
1515static enum event_type_t get_event_type(struct perf_event *event)
1516{
1517 struct perf_event_context *ctx = event->ctx;
1518 enum event_type_t event_type;
1519
1520 lockdep_assert_held(&ctx->lock);
1521
3bda69c1
AS
1522 /*
1523 * It's 'group type', really, because if our group leader is
1524 * pinned, so are we.
1525 */
1526 if (event->group_leader != event)
1527 event = event->group_leader;
1528
487f05e1
AS
1529 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1530 if (!ctx->task)
1531 event_type |= EVENT_CPU;
1532
1533 return event_type;
1534}
1535
8e1a2031 1536/*
161c85fa 1537 * Helper function to initialize event group nodes.
8e1a2031 1538 */
161c85fa 1539static void init_event_group(struct perf_event *event)
8e1a2031
AB
1540{
1541 RB_CLEAR_NODE(&event->group_node);
1542 event->group_index = 0;
1543}
1544
1545/*
1546 * Extract pinned or flexible groups from the context
161c85fa 1547 * based on event attrs bits.
8e1a2031
AB
1548 */
1549static struct perf_event_groups *
1550get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
889ff015
FW
1551{
1552 if (event->attr.pinned)
1553 return &ctx->pinned_groups;
1554 else
1555 return &ctx->flexible_groups;
1556}
1557
8e1a2031 1558/*
161c85fa 1559 * Helper function to initializes perf_event_group trees.
8e1a2031 1560 */
161c85fa 1561static void perf_event_groups_init(struct perf_event_groups *groups)
8e1a2031
AB
1562{
1563 groups->tree = RB_ROOT;
1564 groups->index = 0;
1565}
1566
1567/*
1568 * Compare function for event groups;
161c85fa
PZ
1569 *
1570 * Implements complex key that first sorts by CPU and then by virtual index
1571 * which provides ordering when rotating groups for the same CPU.
8e1a2031 1572 */
161c85fa
PZ
1573static bool
1574perf_event_groups_less(struct perf_event *left, struct perf_event *right)
8e1a2031 1575{
161c85fa
PZ
1576 if (left->cpu < right->cpu)
1577 return true;
1578 if (left->cpu > right->cpu)
1579 return false;
1580
95ed6c70
IR
1581#ifdef CONFIG_CGROUP_PERF
1582 if (left->cgrp != right->cgrp) {
1583 if (!left->cgrp || !left->cgrp->css.cgroup) {
1584 /*
1585 * Left has no cgroup but right does, no cgroups come
1586 * first.
1587 */
1588 return true;
1589 }
a6763625 1590 if (!right->cgrp || !right->cgrp->css.cgroup) {
95ed6c70
IR
1591 /*
1592 * Right has no cgroup but left does, no cgroups come
1593 * first.
1594 */
1595 return false;
1596 }
1597 /* Two dissimilar cgroups, order by id. */
1598 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id)
1599 return true;
1600
1601 return false;
1602 }
1603#endif
1604
161c85fa
PZ
1605 if (left->group_index < right->group_index)
1606 return true;
1607 if (left->group_index > right->group_index)
1608 return false;
1609
1610 return false;
8e1a2031
AB
1611}
1612
1613/*
161c85fa
PZ
1614 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1615 * key (see perf_event_groups_less). This places it last inside the CPU
1616 * subtree.
8e1a2031
AB
1617 */
1618static void
1619perf_event_groups_insert(struct perf_event_groups *groups,
161c85fa 1620 struct perf_event *event)
8e1a2031
AB
1621{
1622 struct perf_event *node_event;
1623 struct rb_node *parent;
1624 struct rb_node **node;
1625
1626 event->group_index = ++groups->index;
1627
1628 node = &groups->tree.rb_node;
1629 parent = *node;
1630
1631 while (*node) {
1632 parent = *node;
161c85fa 1633 node_event = container_of(*node, struct perf_event, group_node);
8e1a2031
AB
1634
1635 if (perf_event_groups_less(event, node_event))
1636 node = &parent->rb_left;
1637 else
1638 node = &parent->rb_right;
1639 }
1640
1641 rb_link_node(&event->group_node, parent, node);
1642 rb_insert_color(&event->group_node, &groups->tree);
1643}
1644
1645/*
161c85fa 1646 * Helper function to insert event into the pinned or flexible groups.
8e1a2031
AB
1647 */
1648static void
1649add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1650{
1651 struct perf_event_groups *groups;
1652
1653 groups = get_event_groups(event, ctx);
1654 perf_event_groups_insert(groups, event);
1655}
1656
1657/*
161c85fa 1658 * Delete a group from a tree.
8e1a2031
AB
1659 */
1660static void
1661perf_event_groups_delete(struct perf_event_groups *groups,
161c85fa 1662 struct perf_event *event)
8e1a2031 1663{
161c85fa
PZ
1664 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1665 RB_EMPTY_ROOT(&groups->tree));
8e1a2031 1666
161c85fa 1667 rb_erase(&event->group_node, &groups->tree);
8e1a2031
AB
1668 init_event_group(event);
1669}
1670
1671/*
161c85fa 1672 * Helper function to delete event from its groups.
8e1a2031
AB
1673 */
1674static void
1675del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1676{
1677 struct perf_event_groups *groups;
1678
1679 groups = get_event_groups(event, ctx);
1680 perf_event_groups_delete(groups, event);
1681}
1682
1683/*
95ed6c70 1684 * Get the leftmost event in the cpu/cgroup subtree.
8e1a2031
AB
1685 */
1686static struct perf_event *
95ed6c70
IR
1687perf_event_groups_first(struct perf_event_groups *groups, int cpu,
1688 struct cgroup *cgrp)
8e1a2031
AB
1689{
1690 struct perf_event *node_event = NULL, *match = NULL;
1691 struct rb_node *node = groups->tree.rb_node;
95ed6c70
IR
1692#ifdef CONFIG_CGROUP_PERF
1693 u64 node_cgrp_id, cgrp_id = 0;
1694
1695 if (cgrp)
1696 cgrp_id = cgrp->kn->id;
1697#endif
8e1a2031
AB
1698
1699 while (node) {
161c85fa 1700 node_event = container_of(node, struct perf_event, group_node);
8e1a2031
AB
1701
1702 if (cpu < node_event->cpu) {
1703 node = node->rb_left;
95ed6c70
IR
1704 continue;
1705 }
1706 if (cpu > node_event->cpu) {
8e1a2031 1707 node = node->rb_right;
95ed6c70
IR
1708 continue;
1709 }
1710#ifdef CONFIG_CGROUP_PERF
1711 node_cgrp_id = 0;
1712 if (node_event->cgrp && node_event->cgrp->css.cgroup)
1713 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id;
1714
1715 if (cgrp_id < node_cgrp_id) {
8e1a2031 1716 node = node->rb_left;
95ed6c70
IR
1717 continue;
1718 }
1719 if (cgrp_id > node_cgrp_id) {
1720 node = node->rb_right;
1721 continue;
8e1a2031 1722 }
95ed6c70
IR
1723#endif
1724 match = node_event;
1725 node = node->rb_left;
8e1a2031
AB
1726 }
1727
1728 return match;
1729}
1730
1cac7b1a
PZ
1731/*
1732 * Like rb_entry_next_safe() for the @cpu subtree.
1733 */
1734static struct perf_event *
1735perf_event_groups_next(struct perf_event *event)
1736{
1737 struct perf_event *next;
95ed6c70
IR
1738#ifdef CONFIG_CGROUP_PERF
1739 u64 curr_cgrp_id = 0;
1740 u64 next_cgrp_id = 0;
1741#endif
1cac7b1a
PZ
1742
1743 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
95ed6c70
IR
1744 if (next == NULL || next->cpu != event->cpu)
1745 return NULL;
1746
1747#ifdef CONFIG_CGROUP_PERF
1748 if (event->cgrp && event->cgrp->css.cgroup)
1749 curr_cgrp_id = event->cgrp->css.cgroup->kn->id;
1cac7b1a 1750
95ed6c70
IR
1751 if (next->cgrp && next->cgrp->css.cgroup)
1752 next_cgrp_id = next->cgrp->css.cgroup->kn->id;
1753
1754 if (curr_cgrp_id != next_cgrp_id)
1755 return NULL;
1756#endif
1757 return next;
1cac7b1a
PZ
1758}
1759
8e1a2031 1760/*
161c85fa 1761 * Iterate through the whole groups tree.
8e1a2031 1762 */
6e6804d2
PZ
1763#define perf_event_groups_for_each(event, groups) \
1764 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1765 typeof(*event), group_node); event; \
1766 event = rb_entry_safe(rb_next(&event->group_node), \
1767 typeof(*event), group_node))
8e1a2031 1768
fccc714b 1769/*
788faab7 1770 * Add an event from the lists for its context.
fccc714b
PZ
1771 * Must be called with ctx->mutex and ctx->lock held.
1772 */
04289bb9 1773static void
cdd6c482 1774list_add_event(struct perf_event *event, struct perf_event_context *ctx)
04289bb9 1775{
c994d613
PZ
1776 lockdep_assert_held(&ctx->lock);
1777
8a49542c
PZ
1778 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1779 event->attach_state |= PERF_ATTACH_CONTEXT;
04289bb9 1780
0d3d73aa
PZ
1781 event->tstamp = perf_event_time(event);
1782
04289bb9 1783 /*
8a49542c
PZ
1784 * If we're a stand alone event or group leader, we go to the context
1785 * list, group events are kept attached to the group so that
1786 * perf_group_detach can, at all times, locate all siblings.
04289bb9 1787 */
8a49542c 1788 if (event->group_leader == event) {
4ff6a8de 1789 event->group_caps = event->event_caps;
8e1a2031 1790 add_event_to_groups(event, ctx);
5c148194 1791 }
592903cd 1792
db4a8356 1793 list_update_cgroup_event(event, ctx, true);
e5d1367f 1794
cdd6c482
IM
1795 list_add_rcu(&event->event_entry, &ctx->event_list);
1796 ctx->nr_events++;
1797 if (event->attr.inherit_stat)
bfbd3381 1798 ctx->nr_stat++;
5a3126d4
PZ
1799
1800 ctx->generation++;
04289bb9
IM
1801}
1802
0231bb53
JO
1803/*
1804 * Initialize event state based on the perf_event_attr::disabled.
1805 */
1806static inline void perf_event__state_init(struct perf_event *event)
1807{
1808 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1809 PERF_EVENT_STATE_INACTIVE;
1810}
1811
a723968c 1812static void __perf_event_read_size(struct perf_event *event, int nr_siblings)
c320c7b7
ACM
1813{
1814 int entry = sizeof(u64); /* value */
1815 int size = 0;
1816 int nr = 1;
1817
1818 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1819 size += sizeof(u64);
1820
1821 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1822 size += sizeof(u64);
1823
1824 if (event->attr.read_format & PERF_FORMAT_ID)
1825 entry += sizeof(u64);
1826
1827 if (event->attr.read_format & PERF_FORMAT_GROUP) {
a723968c 1828 nr += nr_siblings;
c320c7b7
ACM
1829 size += sizeof(u64);
1830 }
1831
1832 size += entry * nr;
1833 event->read_size = size;
1834}
1835
a723968c 1836static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
c320c7b7
ACM
1837{
1838 struct perf_sample_data *data;
c320c7b7
ACM
1839 u16 size = 0;
1840
c320c7b7
ACM
1841 if (sample_type & PERF_SAMPLE_IP)
1842 size += sizeof(data->ip);
1843
6844c09d
ACM
1844 if (sample_type & PERF_SAMPLE_ADDR)
1845 size += sizeof(data->addr);
1846
1847 if (sample_type & PERF_SAMPLE_PERIOD)
1848 size += sizeof(data->period);
1849
c3feedf2
AK
1850 if (sample_type & PERF_SAMPLE_WEIGHT)
1851 size += sizeof(data->weight);
1852
6844c09d
ACM
1853 if (sample_type & PERF_SAMPLE_READ)
1854 size += event->read_size;
1855
d6be9ad6
SE
1856 if (sample_type & PERF_SAMPLE_DATA_SRC)
1857 size += sizeof(data->data_src.val);
1858
fdfbbd07
AK
1859 if (sample_type & PERF_SAMPLE_TRANSACTION)
1860 size += sizeof(data->txn);
1861
fc7ce9c7
KL
1862 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1863 size += sizeof(data->phys_addr);
1864
6546b19f
NK
1865 if (sample_type & PERF_SAMPLE_CGROUP)
1866 size += sizeof(data->cgroup);
1867
6844c09d
ACM
1868 event->header_size = size;
1869}
1870
a723968c
PZ
1871/*
1872 * Called at perf_event creation and when events are attached/detached from a
1873 * group.
1874 */
1875static void perf_event__header_size(struct perf_event *event)
1876{
1877 __perf_event_read_size(event,
1878 event->group_leader->nr_siblings);
1879 __perf_event_header_size(event, event->attr.sample_type);
1880}
1881
6844c09d
ACM
1882static void perf_event__id_header_size(struct perf_event *event)
1883{
1884 struct perf_sample_data *data;
1885 u64 sample_type = event->attr.sample_type;
1886 u16 size = 0;
1887
c320c7b7
ACM
1888 if (sample_type & PERF_SAMPLE_TID)
1889 size += sizeof(data->tid_entry);
1890
1891 if (sample_type & PERF_SAMPLE_TIME)
1892 size += sizeof(data->time);
1893
ff3d527c
AH
1894 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1895 size += sizeof(data->id);
1896
c320c7b7
ACM
1897 if (sample_type & PERF_SAMPLE_ID)
1898 size += sizeof(data->id);
1899
1900 if (sample_type & PERF_SAMPLE_STREAM_ID)
1901 size += sizeof(data->stream_id);
1902
1903 if (sample_type & PERF_SAMPLE_CPU)
1904 size += sizeof(data->cpu_entry);
1905
6844c09d 1906 event->id_header_size = size;
c320c7b7
ACM
1907}
1908
a723968c
PZ
1909static bool perf_event_validate_size(struct perf_event *event)
1910{
1911 /*
1912 * The values computed here will be over-written when we actually
1913 * attach the event.
1914 */
1915 __perf_event_read_size(event, event->group_leader->nr_siblings + 1);
1916 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ);
1917 perf_event__id_header_size(event);
1918
1919 /*
1920 * Sum the lot; should not exceed the 64k limit we have on records.
1921 * Conservative limit to allow for callchains and other variable fields.
1922 */
1923 if (event->read_size + event->header_size +
1924 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024)
1925 return false;
1926
1927 return true;
1928}
1929
8a49542c
PZ
1930static void perf_group_attach(struct perf_event *event)
1931{
c320c7b7 1932 struct perf_event *group_leader = event->group_leader, *pos;
8a49542c 1933
a76a82a3
PZ
1934 lockdep_assert_held(&event->ctx->lock);
1935
74c3337c
PZ
1936 /*
1937 * We can have double attach due to group movement in perf_event_open.
1938 */
1939 if (event->attach_state & PERF_ATTACH_GROUP)
1940 return;
1941
8a49542c
PZ
1942 event->attach_state |= PERF_ATTACH_GROUP;
1943
1944 if (group_leader == event)
1945 return;
1946
652884fe
PZ
1947 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1948
4ff6a8de 1949 group_leader->group_caps &= event->event_caps;
8a49542c 1950
8343aae6 1951 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
8a49542c 1952 group_leader->nr_siblings++;
c320c7b7
ACM
1953
1954 perf_event__header_size(group_leader);
1955
edb39592 1956 for_each_sibling_event(pos, group_leader)
c320c7b7 1957 perf_event__header_size(pos);
8a49542c
PZ
1958}
1959
a63eaf34 1960/*
788faab7 1961 * Remove an event from the lists for its context.
fccc714b 1962 * Must be called with ctx->mutex and ctx->lock held.
a63eaf34 1963 */
04289bb9 1964static void
cdd6c482 1965list_del_event(struct perf_event *event, struct perf_event_context *ctx)
04289bb9 1966{
652884fe
PZ
1967 WARN_ON_ONCE(event->ctx != ctx);
1968 lockdep_assert_held(&ctx->lock);
1969
8a49542c
PZ
1970 /*
1971 * We can have double detach due to exit/hot-unplug + close.
1972 */
1973 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
a63eaf34 1974 return;
8a49542c
PZ
1975
1976 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1977
db4a8356 1978 list_update_cgroup_event(event, ctx, false);
e5d1367f 1979
cdd6c482
IM
1980 ctx->nr_events--;
1981 if (event->attr.inherit_stat)
bfbd3381 1982 ctx->nr_stat--;
8bc20959 1983
cdd6c482 1984 list_del_rcu(&event->event_entry);
04289bb9 1985
8a49542c 1986 if (event->group_leader == event)
8e1a2031 1987 del_event_from_groups(event, ctx);
5c148194 1988
b2e74a26
SE
1989 /*
1990 * If event was in error state, then keep it
1991 * that way, otherwise bogus counts will be
1992 * returned on read(). The only way to get out
1993 * of error state is by explicit re-enabling
1994 * of the event
1995 */
1996 if (event->state > PERF_EVENT_STATE_OFF)
0d3d73aa 1997 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
5a3126d4
PZ
1998
1999 ctx->generation++;
050735b0
PZ
2000}
2001
ab43762e
AS
2002static int
2003perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
2004{
2005 if (!has_aux(aux_event))
2006 return 0;
2007
2008 if (!event->pmu->aux_output_match)
2009 return 0;
2010
2011 return event->pmu->aux_output_match(aux_event);
2012}
2013
2014static void put_event(struct perf_event *event);
2015static void event_sched_out(struct perf_event *event,
2016 struct perf_cpu_context *cpuctx,
2017 struct perf_event_context *ctx);
2018
2019static void perf_put_aux_event(struct perf_event *event)
2020{
2021 struct perf_event_context *ctx = event->ctx;
2022 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2023 struct perf_event *iter;
2024
2025 /*
2026 * If event uses aux_event tear down the link
2027 */
2028 if (event->aux_event) {
2029 iter = event->aux_event;
2030 event->aux_event = NULL;
2031 put_event(iter);
2032 return;
2033 }
2034
2035 /*
2036 * If the event is an aux_event, tear down all links to
2037 * it from other events.
2038 */
2039 for_each_sibling_event(iter, event->group_leader) {
2040 if (iter->aux_event != event)
2041 continue;
2042
2043 iter->aux_event = NULL;
2044 put_event(event);
2045
2046 /*
2047 * If it's ACTIVE, schedule it out and put it into ERROR
2048 * state so that we don't try to schedule it again. Note
2049 * that perf_event_enable() will clear the ERROR status.
2050 */
2051 event_sched_out(iter, cpuctx, ctx);
2052 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
2053 }
2054}
2055
a4faf00d
AS
2056static bool perf_need_aux_event(struct perf_event *event)
2057{
2058 return !!event->attr.aux_output || !!event->attr.aux_sample_size;
2059}
2060
ab43762e
AS
2061static int perf_get_aux_event(struct perf_event *event,
2062 struct perf_event *group_leader)
2063{
2064 /*
2065 * Our group leader must be an aux event if we want to be
2066 * an aux_output. This way, the aux event will precede its
2067 * aux_output events in the group, and therefore will always
2068 * schedule first.
2069 */
2070 if (!group_leader)
2071 return 0;
2072
a4faf00d
AS
2073 /*
2074 * aux_output and aux_sample_size are mutually exclusive.
2075 */
2076 if (event->attr.aux_output && event->attr.aux_sample_size)
2077 return 0;
2078
2079 if (event->attr.aux_output &&
2080 !perf_aux_output_match(event, group_leader))
2081 return 0;
2082
2083 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux)
ab43762e
AS
2084 return 0;
2085
2086 if (!atomic_long_inc_not_zero(&group_leader->refcount))
2087 return 0;
2088
2089 /*
2090 * Link aux_outputs to their aux event; this is undone in
2091 * perf_group_detach() by perf_put_aux_event(). When the
2092 * group in torn down, the aux_output events loose their
2093 * link to the aux_event and can't schedule any more.
2094 */
2095 event->aux_event = group_leader;
2096
2097 return 1;
2098}
2099
ab6f824c
PZ
2100static inline struct list_head *get_event_list(struct perf_event *event)
2101{
2102 struct perf_event_context *ctx = event->ctx;
2103 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active;
2104}
2105
8a49542c 2106static void perf_group_detach(struct perf_event *event)
050735b0
PZ
2107{
2108 struct perf_event *sibling, *tmp;
6668128a 2109 struct perf_event_context *ctx = event->ctx;
8a49542c 2110
6668128a 2111 lockdep_assert_held(&ctx->lock);
a76a82a3 2112
8a49542c
PZ
2113 /*
2114 * We can have double detach due to exit/hot-unplug + close.
2115 */
2116 if (!(event->attach_state & PERF_ATTACH_GROUP))
2117 return;
2118
2119 event->attach_state &= ~PERF_ATTACH_GROUP;
2120
ab43762e
AS
2121 perf_put_aux_event(event);
2122
8a49542c
PZ
2123 /*
2124 * If this is a sibling, remove it from its group.
2125 */
2126 if (event->group_leader != event) {
8343aae6 2127 list_del_init(&event->sibling_list);
8a49542c 2128 event->group_leader->nr_siblings--;
c320c7b7 2129 goto out;
8a49542c
PZ
2130 }
2131
04289bb9 2132 /*
cdd6c482
IM
2133 * If this was a group event with sibling events then
2134 * upgrade the siblings to singleton events by adding them
8a49542c 2135 * to whatever list we are on.
04289bb9 2136 */
8343aae6 2137 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
8e1a2031 2138
04289bb9 2139 sibling->group_leader = sibling;
24868367 2140 list_del_init(&sibling->sibling_list);
d6f962b5
FW
2141
2142 /* Inherit group flags from the previous leader */
4ff6a8de 2143 sibling->group_caps = event->group_caps;
652884fe 2144
8e1a2031 2145 if (!RB_EMPTY_NODE(&event->group_node)) {
8e1a2031 2146 add_event_to_groups(sibling, event->ctx);
6668128a 2147
ab6f824c
PZ
2148 if (sibling->state == PERF_EVENT_STATE_ACTIVE)
2149 list_add_tail(&sibling->active_list, get_event_list(sibling));
8e1a2031
AB
2150 }
2151
652884fe 2152 WARN_ON_ONCE(sibling->ctx != event->ctx);
04289bb9 2153 }
c320c7b7
ACM
2154
2155out:
2156 perf_event__header_size(event->group_leader);
2157
edb39592 2158 for_each_sibling_event(tmp, event->group_leader)
c320c7b7 2159 perf_event__header_size(tmp);
04289bb9
IM
2160}
2161
fadfe7be
JO
2162static bool is_orphaned_event(struct perf_event *event)
2163{
a69b0ca4 2164 return event->state == PERF_EVENT_STATE_DEAD;
fadfe7be
JO
2165}
2166
2c81a647 2167static inline int __pmu_filter_match(struct perf_event *event)
66eb579e
MR
2168{
2169 struct pmu *pmu = event->pmu;
2170 return pmu->filter_match ? pmu->filter_match(event) : 1;
2171}
2172
2c81a647
MR
2173/*
2174 * Check whether we should attempt to schedule an event group based on
2175 * PMU-specific filtering. An event group can consist of HW and SW events,
2176 * potentially with a SW leader, so we must check all the filters, to
2177 * determine whether a group is schedulable:
2178 */
2179static inline int pmu_filter_match(struct perf_event *event)
2180{
edb39592 2181 struct perf_event *sibling;
2c81a647
MR
2182
2183 if (!__pmu_filter_match(event))
2184 return 0;
2185
edb39592
PZ
2186 for_each_sibling_event(sibling, event) {
2187 if (!__pmu_filter_match(sibling))
2c81a647
MR
2188 return 0;
2189 }
2190
2191 return 1;
2192}
2193
fa66f07a
SE
2194static inline int
2195event_filter_match(struct perf_event *event)
2196{
0b8f1e2e
PZ
2197 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2198 perf_cgroup_match(event) && pmu_filter_match(event);
fa66f07a
SE
2199}
2200
9ffcfa6f
SE
2201static void
2202event_sched_out(struct perf_event *event,
3b6f9e5c 2203 struct perf_cpu_context *cpuctx,
cdd6c482 2204 struct perf_event_context *ctx)
3b6f9e5c 2205{
0d3d73aa 2206 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
652884fe
PZ
2207
2208 WARN_ON_ONCE(event->ctx != ctx);
2209 lockdep_assert_held(&ctx->lock);
2210
cdd6c482 2211 if (event->state != PERF_EVENT_STATE_ACTIVE)
9ffcfa6f 2212 return;
3b6f9e5c 2213
6668128a
PZ
2214 /*
2215 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2216 * we can schedule events _OUT_ individually through things like
2217 * __perf_remove_from_context().
2218 */
2219 list_del_init(&event->active_list);
2220
44377277
AS
2221 perf_pmu_disable(event->pmu);
2222
28a967c3
PZ
2223 event->pmu->del(event, 0);
2224 event->oncpu = -1;
0d3d73aa 2225
1d54ad94
PZ
2226 if (READ_ONCE(event->pending_disable) >= 0) {
2227 WRITE_ONCE(event->pending_disable, -1);
0d3d73aa 2228 state = PERF_EVENT_STATE_OFF;
970892a9 2229 }
0d3d73aa 2230 perf_event_set_state(event, state);
3b6f9e5c 2231
cdd6c482 2232 if (!is_software_event(event))
3b6f9e5c 2233 cpuctx->active_oncpu--;
2fde4f94
MR
2234 if (!--ctx->nr_active)
2235 perf_event_ctx_deactivate(ctx);
0f5a2601
PZ
2236 if (event->attr.freq && event->attr.sample_freq)
2237 ctx->nr_freq--;
cdd6c482 2238 if (event->attr.exclusive || !cpuctx->active_oncpu)
3b6f9e5c 2239 cpuctx->exclusive = 0;
44377277
AS
2240
2241 perf_pmu_enable(event->pmu);
3b6f9e5c
PM
2242}
2243
d859e29f 2244static void
cdd6c482 2245group_sched_out(struct perf_event *group_event,
d859e29f 2246 struct perf_cpu_context *cpuctx,
cdd6c482 2247 struct perf_event_context *ctx)
d859e29f 2248{
cdd6c482 2249 struct perf_event *event;
0d3d73aa
PZ
2250
2251 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2252 return;
d859e29f 2253
3f005e7d
MR
2254 perf_pmu_disable(ctx->pmu);
2255
cdd6c482 2256 event_sched_out(group_event, cpuctx, ctx);
d859e29f
PM
2257
2258 /*
2259 * Schedule out siblings (if any):
2260 */
edb39592 2261 for_each_sibling_event(event, group_event)
cdd6c482 2262 event_sched_out(event, cpuctx, ctx);
d859e29f 2263
3f005e7d
MR
2264 perf_pmu_enable(ctx->pmu);
2265
0d3d73aa 2266 if (group_event->attr.exclusive)
d859e29f
PM
2267 cpuctx->exclusive = 0;
2268}
2269
45a0e07a 2270#define DETACH_GROUP 0x01UL
0017960f 2271
0793a61d 2272/*
cdd6c482 2273 * Cross CPU call to remove a performance event
0793a61d 2274 *
cdd6c482 2275 * We disable the event on the hardware level first. After that we
0793a61d
TG
2276 * remove it from the context list.
2277 */
fae3fde6
PZ
2278static void
2279__perf_remove_from_context(struct perf_event *event,
2280 struct perf_cpu_context *cpuctx,
2281 struct perf_event_context *ctx,
2282 void *info)
0793a61d 2283{
45a0e07a 2284 unsigned long flags = (unsigned long)info;
0793a61d 2285
3c5c8711
PZ
2286 if (ctx->is_active & EVENT_TIME) {
2287 update_context_time(ctx);
2288 update_cgrp_time_from_cpuctx(cpuctx);
2289 }
2290
cdd6c482 2291 event_sched_out(event, cpuctx, ctx);
45a0e07a 2292 if (flags & DETACH_GROUP)
46ce0fe9 2293 perf_group_detach(event);
cdd6c482 2294 list_del_event(event, ctx);
39a43640
PZ
2295
2296 if (!ctx->nr_events && ctx->is_active) {
64ce3126 2297 ctx->is_active = 0;
90c91dfb 2298 ctx->rotate_necessary = 0;
39a43640
PZ
2299 if (ctx->task) {
2300 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2301 cpuctx->task_ctx = NULL;
2302 }
64ce3126 2303 }
0793a61d
TG
2304}
2305
0793a61d 2306/*
cdd6c482 2307 * Remove the event from a task's (or a CPU's) list of events.
0793a61d 2308 *
cdd6c482
IM
2309 * If event->ctx is a cloned context, callers must make sure that
2310 * every task struct that event->ctx->task could possibly point to
c93f7669
PM
2311 * remains valid. This is OK when called from perf_release since
2312 * that only calls us on the top-level context, which can't be a clone.
cdd6c482 2313 * When called from perf_event_exit_task, it's OK because the
c93f7669 2314 * context has been detached from its task.
0793a61d 2315 */
45a0e07a 2316static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
0793a61d 2317{
a76a82a3
PZ
2318 struct perf_event_context *ctx = event->ctx;
2319
2320 lockdep_assert_held(&ctx->mutex);
0793a61d 2321
45a0e07a 2322 event_function_call(event, __perf_remove_from_context, (void *)flags);
a76a82a3
PZ
2323
2324 /*
2325 * The above event_function_call() can NO-OP when it hits
2326 * TASK_TOMBSTONE. In that case we must already have been detached
2327 * from the context (by perf_event_exit_event()) but the grouping
2328 * might still be in-tact.
2329 */
2330 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2331 if ((flags & DETACH_GROUP) &&
2332 (event->attach_state & PERF_ATTACH_GROUP)) {
2333 /*
2334 * Since in that case we cannot possibly be scheduled, simply
2335 * detach now.
2336 */
2337 raw_spin_lock_irq(&ctx->lock);
2338 perf_group_detach(event);
2339 raw_spin_unlock_irq(&ctx->lock);
2340 }
0793a61d
TG
2341}
2342
d859e29f 2343/*
cdd6c482 2344 * Cross CPU call to disable a performance event
d859e29f 2345 */
fae3fde6
PZ
2346static void __perf_event_disable(struct perf_event *event,
2347 struct perf_cpu_context *cpuctx,
2348 struct perf_event_context *ctx,
2349 void *info)
7b648018 2350{
fae3fde6
PZ
2351 if (event->state < PERF_EVENT_STATE_INACTIVE)
2352 return;
7b648018 2353
3c5c8711
PZ
2354 if (ctx->is_active & EVENT_TIME) {
2355 update_context_time(ctx);
2356 update_cgrp_time_from_event(event);
2357 }
2358
fae3fde6
PZ
2359 if (event == event->group_leader)
2360 group_sched_out(event, cpuctx, ctx);
2361 else
2362 event_sched_out(event, cpuctx, ctx);
0d3d73aa
PZ
2363
2364 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
7b648018
PZ
2365}
2366
d859e29f 2367/*
788faab7 2368 * Disable an event.
c93f7669 2369 *
cdd6c482
IM
2370 * If event->ctx is a cloned context, callers must make sure that
2371 * every task struct that event->ctx->task could possibly point to
9f014e3a 2372 * remains valid. This condition is satisfied when called through
cdd6c482
IM
2373 * perf_event_for_each_child or perf_event_for_each because they
2374 * hold the top-level event's child_mutex, so any descendant that
8ba289b8
PZ
2375 * goes to exit will block in perf_event_exit_event().
2376 *
cdd6c482 2377 * When called from perf_pending_event it's OK because event->ctx
c93f7669 2378 * is the current context on this CPU and preemption is disabled,
cdd6c482 2379 * hence we can't get into perf_event_task_sched_out for this context.
d859e29f 2380 */
f63a8daa 2381static void _perf_event_disable(struct perf_event *event)
d859e29f 2382{
cdd6c482 2383 struct perf_event_context *ctx = event->ctx;
d859e29f 2384
e625cce1 2385 raw_spin_lock_irq(&ctx->lock);
7b648018 2386 if (event->state <= PERF_EVENT_STATE_OFF) {
e625cce1 2387 raw_spin_unlock_irq(&ctx->lock);
7b648018 2388 return;
53cfbf59 2389 }
e625cce1 2390 raw_spin_unlock_irq(&ctx->lock);
7b648018 2391
fae3fde6
PZ
2392 event_function_call(event, __perf_event_disable, NULL);
2393}
2394
2395void perf_event_disable_local(struct perf_event *event)
2396{
2397 event_function_local(event, __perf_event_disable, NULL);
d859e29f 2398}
f63a8daa
PZ
2399
2400/*
2401 * Strictly speaking kernel users cannot create groups and therefore this
2402 * interface does not need the perf_event_ctx_lock() magic.
2403 */
2404void perf_event_disable(struct perf_event *event)
2405{
2406 struct perf_event_context *ctx;
2407
2408 ctx = perf_event_ctx_lock(event);
2409 _perf_event_disable(event);
2410 perf_event_ctx_unlock(event, ctx);
2411}
dcfce4a0 2412EXPORT_SYMBOL_GPL(perf_event_disable);
d859e29f 2413
5aab90ce
JO
2414void perf_event_disable_inatomic(struct perf_event *event)
2415{
1d54ad94
PZ
2416 WRITE_ONCE(event->pending_disable, smp_processor_id());
2417 /* can fail, see perf_pending_event_disable() */
5aab90ce
JO
2418 irq_work_queue(&event->pending);
2419}
2420
e5d1367f 2421static void perf_set_shadow_time(struct perf_event *event,
0d3d73aa 2422 struct perf_event_context *ctx)
e5d1367f
SE
2423{
2424 /*
2425 * use the correct time source for the time snapshot
2426 *
2427 * We could get by without this by leveraging the
2428 * fact that to get to this function, the caller
2429 * has most likely already called update_context_time()
2430 * and update_cgrp_time_xx() and thus both timestamp
2431 * are identical (or very close). Given that tstamp is,
2432 * already adjusted for cgroup, we could say that:
2433 * tstamp - ctx->timestamp
2434 * is equivalent to
2435 * tstamp - cgrp->timestamp.
2436 *
2437 * Then, in perf_output_read(), the calculation would
2438 * work with no changes because:
2439 * - event is guaranteed scheduled in
2440 * - no scheduled out in between
2441 * - thus the timestamp would be the same
2442 *
2443 * But this is a bit hairy.
2444 *
2445 * So instead, we have an explicit cgroup call to remain
2446 * within the time time source all along. We believe it
2447 * is cleaner and simpler to understand.
2448 */
2449 if (is_cgroup_event(event))
0d3d73aa 2450 perf_cgroup_set_shadow_time(event, event->tstamp);
e5d1367f 2451 else
0d3d73aa 2452 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
e5d1367f
SE
2453}
2454
4fe757dd
PZ
2455#define MAX_INTERRUPTS (~0ULL)
2456
2457static void perf_log_throttle(struct perf_event *event, int enable);
ec0d7729 2458static void perf_log_itrace_start(struct perf_event *event);
4fe757dd 2459
235c7fc7 2460static int
9ffcfa6f 2461event_sched_in(struct perf_event *event,
235c7fc7 2462 struct perf_cpu_context *cpuctx,
6e37738a 2463 struct perf_event_context *ctx)
235c7fc7 2464{
44377277 2465 int ret = 0;
4158755d 2466
ab6f824c
PZ
2467 WARN_ON_ONCE(event->ctx != ctx);
2468
63342411
PZ
2469 lockdep_assert_held(&ctx->lock);
2470
cdd6c482 2471 if (event->state <= PERF_EVENT_STATE_OFF)
235c7fc7
IM
2472 return 0;
2473
95ff4ca2
AS
2474 WRITE_ONCE(event->oncpu, smp_processor_id());
2475 /*
0c1cbc18
PZ
2476 * Order event::oncpu write to happen before the ACTIVE state is
2477 * visible. This allows perf_event_{stop,read}() to observe the correct
2478 * ->oncpu if it sees ACTIVE.
95ff4ca2
AS
2479 */
2480 smp_wmb();
0d3d73aa 2481 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
4fe757dd
PZ
2482
2483 /*
2484 * Unthrottle events, since we scheduled we might have missed several
2485 * ticks already, also for a heavily scheduling task there is little
2486 * guarantee it'll get a tick in a timely manner.
2487 */
2488 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2489 perf_log_throttle(event, 1);
2490 event->hw.interrupts = 0;
2491 }
2492
44377277
AS
2493 perf_pmu_disable(event->pmu);
2494
0d3d73aa 2495 perf_set_shadow_time(event, ctx);
72f669c0 2496
ec0d7729
AS
2497 perf_log_itrace_start(event);
2498
a4eaf7f1 2499 if (event->pmu->add(event, PERF_EF_START)) {
0d3d73aa 2500 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
cdd6c482 2501 event->oncpu = -1;
44377277
AS
2502 ret = -EAGAIN;
2503 goto out;
235c7fc7
IM
2504 }
2505
cdd6c482 2506 if (!is_software_event(event))
3b6f9e5c 2507 cpuctx->active_oncpu++;
2fde4f94
MR
2508 if (!ctx->nr_active++)
2509 perf_event_ctx_activate(ctx);
0f5a2601
PZ
2510 if (event->attr.freq && event->attr.sample_freq)
2511 ctx->nr_freq++;
235c7fc7 2512
cdd6c482 2513 if (event->attr.exclusive)
3b6f9e5c
PM
2514 cpuctx->exclusive = 1;
2515
44377277
AS
2516out:
2517 perf_pmu_enable(event->pmu);
2518
2519 return ret;
235c7fc7
IM
2520}
2521
6751b71e 2522static int
cdd6c482 2523group_sched_in(struct perf_event *group_event,
6751b71e 2524 struct perf_cpu_context *cpuctx,
6e37738a 2525 struct perf_event_context *ctx)
6751b71e 2526{
6bde9b6c 2527 struct perf_event *event, *partial_group = NULL;
4a234593 2528 struct pmu *pmu = ctx->pmu;
6751b71e 2529
cdd6c482 2530 if (group_event->state == PERF_EVENT_STATE_OFF)
6751b71e
PM
2531 return 0;
2532
fbbe0701 2533 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
6bde9b6c 2534
9ffcfa6f 2535 if (event_sched_in(group_event, cpuctx, ctx)) {
ad5133b7 2536 pmu->cancel_txn(pmu);
272325c4 2537 perf_mux_hrtimer_restart(cpuctx);
6751b71e 2538 return -EAGAIN;
90151c35 2539 }
6751b71e
PM
2540
2541 /*
2542 * Schedule in siblings as one group (if any):
2543 */
edb39592 2544 for_each_sibling_event(event, group_event) {
9ffcfa6f 2545 if (event_sched_in(event, cpuctx, ctx)) {
cdd6c482 2546 partial_group = event;
6751b71e
PM
2547 goto group_error;
2548 }
2549 }
2550
9ffcfa6f 2551 if (!pmu->commit_txn(pmu))
6e85158c 2552 return 0;
9ffcfa6f 2553
6751b71e
PM
2554group_error:
2555 /*
2556 * Groups can be scheduled in as one unit only, so undo any
2557 * partial group before returning:
0d3d73aa 2558 * The events up to the failed event are scheduled out normally.
6751b71e 2559 */
edb39592 2560 for_each_sibling_event(event, group_event) {
cdd6c482 2561 if (event == partial_group)
0d3d73aa 2562 break;
d7842da4 2563
0d3d73aa 2564 event_sched_out(event, cpuctx, ctx);
6751b71e 2565 }
9ffcfa6f 2566 event_sched_out(group_event, cpuctx, ctx);
6751b71e 2567
ad5133b7 2568 pmu->cancel_txn(pmu);
90151c35 2569
272325c4 2570 perf_mux_hrtimer_restart(cpuctx);
9e630205 2571
6751b71e
PM
2572 return -EAGAIN;
2573}
2574
3b6f9e5c 2575/*
cdd6c482 2576 * Work out whether we can put this event group on the CPU now.
3b6f9e5c 2577 */
cdd6c482 2578static int group_can_go_on(struct perf_event *event,
3b6f9e5c
PM
2579 struct perf_cpu_context *cpuctx,
2580 int can_add_hw)
2581{
2582 /*
cdd6c482 2583 * Groups consisting entirely of software events can always go on.
3b6f9e5c 2584 */
4ff6a8de 2585 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
3b6f9e5c
PM
2586 return 1;
2587 /*
2588 * If an exclusive group is already on, no other hardware
cdd6c482 2589 * events can go on.
3b6f9e5c
PM
2590 */
2591 if (cpuctx->exclusive)
2592 return 0;
2593 /*
2594 * If this group is exclusive and there are already
cdd6c482 2595 * events on the CPU, it can't go on.
3b6f9e5c 2596 */
cdd6c482 2597 if (event->attr.exclusive && cpuctx->active_oncpu)
3b6f9e5c
PM
2598 return 0;
2599 /*
2600 * Otherwise, try to add it if all previous groups were able
2601 * to go on.
2602 */
2603 return can_add_hw;
2604}
2605
cdd6c482
IM
2606static void add_event_to_ctx(struct perf_event *event,
2607 struct perf_event_context *ctx)
53cfbf59 2608{
cdd6c482 2609 list_add_event(event, ctx);
8a49542c 2610 perf_group_attach(event);
53cfbf59
PM
2611}
2612
bd2afa49
PZ
2613static void ctx_sched_out(struct perf_event_context *ctx,
2614 struct perf_cpu_context *cpuctx,
2615 enum event_type_t event_type);
2c29ef0f
PZ
2616static void
2617ctx_sched_in(struct perf_event_context *ctx,
2618 struct perf_cpu_context *cpuctx,
2619 enum event_type_t event_type,
2620 struct task_struct *task);
fe4b04fa 2621
bd2afa49 2622static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
487f05e1
AS
2623 struct perf_event_context *ctx,
2624 enum event_type_t event_type)
bd2afa49
PZ
2625{
2626 if (!cpuctx->task_ctx)
2627 return;
2628
2629 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2630 return;
2631
487f05e1 2632 ctx_sched_out(ctx, cpuctx, event_type);
bd2afa49
PZ
2633}
2634
dce5855b
PZ
2635static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2636 struct perf_event_context *ctx,
2637 struct task_struct *task)
2638{
2639 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2640 if (ctx)
2641 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2642 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2643 if (ctx)
2644 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2645}
2646
487f05e1
AS
2647/*
2648 * We want to maintain the following priority of scheduling:
2649 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2650 * - task pinned (EVENT_PINNED)
2651 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2652 * - task flexible (EVENT_FLEXIBLE).
2653 *
2654 * In order to avoid unscheduling and scheduling back in everything every
2655 * time an event is added, only do it for the groups of equal priority and
2656 * below.
2657 *
2658 * This can be called after a batch operation on task events, in which case
2659 * event_type is a bit mask of the types of events involved. For CPU events,
2660 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2661 */
3e349507 2662static void ctx_resched(struct perf_cpu_context *cpuctx,
487f05e1
AS
2663 struct perf_event_context *task_ctx,
2664 enum event_type_t event_type)
0017960f 2665{
bd903afe 2666 enum event_type_t ctx_event_type;
487f05e1
AS
2667 bool cpu_event = !!(event_type & EVENT_CPU);
2668
2669 /*
2670 * If pinned groups are involved, flexible groups also need to be
2671 * scheduled out.
2672 */
2673 if (event_type & EVENT_PINNED)
2674 event_type |= EVENT_FLEXIBLE;
2675
bd903afe
SL
2676 ctx_event_type = event_type & EVENT_ALL;
2677
3e349507
PZ
2678 perf_pmu_disable(cpuctx->ctx.pmu);
2679 if (task_ctx)
487f05e1
AS
2680 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2681
2682 /*
2683 * Decide which cpu ctx groups to schedule out based on the types
2684 * of events that caused rescheduling:
2685 * - EVENT_CPU: schedule out corresponding groups;
2686 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2687 * - otherwise, do nothing more.
2688 */
2689 if (cpu_event)
2690 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2691 else if (ctx_event_type & EVENT_PINNED)
2692 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2693
3e349507
PZ
2694 perf_event_sched_in(cpuctx, task_ctx, current);
2695 perf_pmu_enable(cpuctx->ctx.pmu);
0017960f
PZ
2696}
2697
c68d224e
SE
2698void perf_pmu_resched(struct pmu *pmu)
2699{
2700 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2701 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2702
2703 perf_ctx_lock(cpuctx, task_ctx);
2704 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2705 perf_ctx_unlock(cpuctx, task_ctx);
2706}
2707
0793a61d 2708/*
cdd6c482 2709 * Cross CPU call to install and enable a performance event
682076ae 2710 *
a096309b
PZ
2711 * Very similar to remote_function() + event_function() but cannot assume that
2712 * things like ctx->is_active and cpuctx->task_ctx are set.
0793a61d 2713 */
fe4b04fa 2714static int __perf_install_in_context(void *info)
0793a61d 2715{
a096309b
PZ
2716 struct perf_event *event = info;
2717 struct perf_event_context *ctx = event->ctx;
108b02cf 2718 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2c29ef0f 2719 struct perf_event_context *task_ctx = cpuctx->task_ctx;
63cae12b 2720 bool reprogram = true;
a096309b 2721 int ret = 0;
0793a61d 2722
63b6da39 2723 raw_spin_lock(&cpuctx->ctx.lock);
39a43640 2724 if (ctx->task) {
b58f6b0d
PZ
2725 raw_spin_lock(&ctx->lock);
2726 task_ctx = ctx;
a096309b 2727
63cae12b 2728 reprogram = (ctx->task == current);
b58f6b0d 2729
39a43640 2730 /*
63cae12b
PZ
2731 * If the task is running, it must be running on this CPU,
2732 * otherwise we cannot reprogram things.
2733 *
2734 * If its not running, we don't care, ctx->lock will
2735 * serialize against it becoming runnable.
39a43640 2736 */
63cae12b
PZ
2737 if (task_curr(ctx->task) && !reprogram) {
2738 ret = -ESRCH;
2739 goto unlock;
2740 }
a096309b 2741
63cae12b 2742 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
63b6da39
PZ
2743 } else if (task_ctx) {
2744 raw_spin_lock(&task_ctx->lock);
2c29ef0f 2745 }
b58f6b0d 2746
33801b94 2747#ifdef CONFIG_CGROUP_PERF
2748 if (is_cgroup_event(event)) {
2749 /*
2750 * If the current cgroup doesn't match the event's
2751 * cgroup, we should not try to schedule it.
2752 */
2753 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2754 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2755 event->cgrp->css.cgroup);
2756 }
2757#endif
2758
63cae12b 2759 if (reprogram) {
a096309b
PZ
2760 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2761 add_event_to_ctx(event, ctx);
487f05e1 2762 ctx_resched(cpuctx, task_ctx, get_event_type(event));
a096309b
PZ
2763 } else {
2764 add_event_to_ctx(event, ctx);
2765 }
2766
63b6da39 2767unlock:
2c29ef0f 2768 perf_ctx_unlock(cpuctx, task_ctx);
fe4b04fa 2769
a096309b 2770 return ret;
0793a61d
TG
2771}
2772
8a58ddae
AS
2773static bool exclusive_event_installable(struct perf_event *event,
2774 struct perf_event_context *ctx);
2775
0793a61d 2776/*
a096309b
PZ
2777 * Attach a performance event to a context.
2778 *
2779 * Very similar to event_function_call, see comment there.
0793a61d
TG
2780 */
2781static void
cdd6c482
IM
2782perf_install_in_context(struct perf_event_context *ctx,
2783 struct perf_event *event,
0793a61d
TG
2784 int cpu)
2785{
a096309b 2786 struct task_struct *task = READ_ONCE(ctx->task);
39a43640 2787
fe4b04fa
PZ
2788 lockdep_assert_held(&ctx->mutex);
2789
8a58ddae
AS
2790 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2791
0cda4c02
YZ
2792 if (event->cpu != -1)
2793 event->cpu = cpu;
c3f00c70 2794
0b8f1e2e
PZ
2795 /*
2796 * Ensures that if we can observe event->ctx, both the event and ctx
2797 * will be 'complete'. See perf_iterate_sb_cpu().
2798 */
2799 smp_store_release(&event->ctx, ctx);
2800
db0503e4
PZ
2801 /*
2802 * perf_event_attr::disabled events will not run and can be initialized
2803 * without IPI. Except when this is the first event for the context, in
2804 * that case we need the magic of the IPI to set ctx->is_active.
2805 *
2806 * The IOC_ENABLE that is sure to follow the creation of a disabled
2807 * event will issue the IPI and reprogram the hardware.
2808 */
2809 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) {
2810 raw_spin_lock_irq(&ctx->lock);
2811 if (ctx->task == TASK_TOMBSTONE) {
2812 raw_spin_unlock_irq(&ctx->lock);
2813 return;
2814 }
2815 add_event_to_ctx(event, ctx);
2816 raw_spin_unlock_irq(&ctx->lock);
2817 return;
2818 }
2819
a096309b
PZ
2820 if (!task) {
2821 cpu_function_call(cpu, __perf_install_in_context, event);
2822 return;
2823 }
2824
2825 /*
2826 * Should not happen, we validate the ctx is still alive before calling.
2827 */
2828 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2829 return;
2830
39a43640
PZ
2831 /*
2832 * Installing events is tricky because we cannot rely on ctx->is_active
2833 * to be set in case this is the nr_events 0 -> 1 transition.
63cae12b
PZ
2834 *
2835 * Instead we use task_curr(), which tells us if the task is running.
2836 * However, since we use task_curr() outside of rq::lock, we can race
2837 * against the actual state. This means the result can be wrong.
2838 *
2839 * If we get a false positive, we retry, this is harmless.
2840 *
2841 * If we get a false negative, things are complicated. If we are after
2842 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2843 * value must be correct. If we're before, it doesn't matter since
2844 * perf_event_context_sched_in() will program the counter.
2845 *
2846 * However, this hinges on the remote context switch having observed
2847 * our task->perf_event_ctxp[] store, such that it will in fact take
2848 * ctx::lock in perf_event_context_sched_in().
2849 *
2850 * We do this by task_function_call(), if the IPI fails to hit the task
2851 * we know any future context switch of task must see the
2852 * perf_event_ctpx[] store.
39a43640 2853 */
63cae12b 2854
63b6da39 2855 /*
63cae12b
PZ
2856 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2857 * task_cpu() load, such that if the IPI then does not find the task
2858 * running, a future context switch of that task must observe the
2859 * store.
63b6da39 2860 */
63cae12b
PZ
2861 smp_mb();
2862again:
2863 if (!task_function_call(task, __perf_install_in_context, event))
a096309b
PZ
2864 return;
2865
2866 raw_spin_lock_irq(&ctx->lock);
2867 task = ctx->task;
84c4e620 2868 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
a096309b
PZ
2869 /*
2870 * Cannot happen because we already checked above (which also
2871 * cannot happen), and we hold ctx->mutex, which serializes us
2872 * against perf_event_exit_task_context().
2873 */
63b6da39
PZ
2874 raw_spin_unlock_irq(&ctx->lock);
2875 return;
2876 }
39a43640 2877 /*
63cae12b
PZ
2878 * If the task is not running, ctx->lock will avoid it becoming so,
2879 * thus we can safely install the event.
39a43640 2880 */
63cae12b
PZ
2881 if (task_curr(task)) {
2882 raw_spin_unlock_irq(&ctx->lock);
2883 goto again;
2884 }
2885 add_event_to_ctx(event, ctx);
2886 raw_spin_unlock_irq(&ctx->lock);
0793a61d
TG
2887}
2888
d859e29f 2889/*
cdd6c482 2890 * Cross CPU call to enable a performance event
d859e29f 2891 */
fae3fde6
PZ
2892static void __perf_event_enable(struct perf_event *event,
2893 struct perf_cpu_context *cpuctx,
2894 struct perf_event_context *ctx,
2895 void *info)
04289bb9 2896{
cdd6c482 2897 struct perf_event *leader = event->group_leader;
fae3fde6 2898 struct perf_event_context *task_ctx;
04289bb9 2899
6e801e01
PZ
2900 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2901 event->state <= PERF_EVENT_STATE_ERROR)
fae3fde6 2902 return;
3cbed429 2903
bd2afa49
PZ
2904 if (ctx->is_active)
2905 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2906
0d3d73aa 2907 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
04289bb9 2908
fae3fde6
PZ
2909 if (!ctx->is_active)
2910 return;
2911
e5d1367f 2912 if (!event_filter_match(event)) {
bd2afa49 2913 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
fae3fde6 2914 return;
e5d1367f 2915 }
f4c4176f 2916
04289bb9 2917 /*
cdd6c482 2918 * If the event is in a group and isn't the group leader,
d859e29f 2919 * then don't put it on unless the group is on.
04289bb9 2920 */
bd2afa49
PZ
2921 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2922 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
fae3fde6 2923 return;
bd2afa49 2924 }
fe4b04fa 2925
fae3fde6
PZ
2926 task_ctx = cpuctx->task_ctx;
2927 if (ctx->task)
2928 WARN_ON_ONCE(task_ctx != ctx);
d859e29f 2929
487f05e1 2930 ctx_resched(cpuctx, task_ctx, get_event_type(event));
7b648018
PZ
2931}
2932
d859e29f 2933/*
788faab7 2934 * Enable an event.
c93f7669 2935 *
cdd6c482
IM
2936 * If event->ctx is a cloned context, callers must make sure that
2937 * every task struct that event->ctx->task could possibly point to
c93f7669 2938 * remains valid. This condition is satisfied when called through
cdd6c482
IM
2939 * perf_event_for_each_child or perf_event_for_each as described
2940 * for perf_event_disable.
d859e29f 2941 */
f63a8daa 2942static void _perf_event_enable(struct perf_event *event)
d859e29f 2943{
cdd6c482 2944 struct perf_event_context *ctx = event->ctx;
d859e29f 2945
7b648018 2946 raw_spin_lock_irq(&ctx->lock);
6e801e01
PZ
2947 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2948 event->state < PERF_EVENT_STATE_ERROR) {
7b648018 2949 raw_spin_unlock_irq(&ctx->lock);
d859e29f
PM
2950 return;
2951 }
2952
d859e29f 2953 /*
cdd6c482 2954 * If the event is in error state, clear that first.
7b648018
PZ
2955 *
2956 * That way, if we see the event in error state below, we know that it
2957 * has gone back into error state, as distinct from the task having
2958 * been scheduled away before the cross-call arrived.
d859e29f 2959 */
cdd6c482
IM
2960 if (event->state == PERF_EVENT_STATE_ERROR)
2961 event->state = PERF_EVENT_STATE_OFF;
e625cce1 2962 raw_spin_unlock_irq(&ctx->lock);
fe4b04fa 2963
fae3fde6 2964 event_function_call(event, __perf_event_enable, NULL);
d859e29f 2965}
f63a8daa
PZ
2966
2967/*
2968 * See perf_event_disable();
2969 */
2970void perf_event_enable(struct perf_event *event)
2971{
2972 struct perf_event_context *ctx;
2973
2974 ctx = perf_event_ctx_lock(event);
2975 _perf_event_enable(event);
2976 perf_event_ctx_unlock(event, ctx);
2977}
dcfce4a0 2978EXPORT_SYMBOL_GPL(perf_event_enable);
d859e29f 2979
375637bc
AS
2980struct stop_event_data {
2981 struct perf_event *event;
2982 unsigned int restart;
2983};
2984
95ff4ca2
AS
2985static int __perf_event_stop(void *info)
2986{
375637bc
AS
2987 struct stop_event_data *sd = info;
2988 struct perf_event *event = sd->event;
95ff4ca2 2989
375637bc 2990 /* if it's already INACTIVE, do nothing */
95ff4ca2
AS
2991 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2992 return 0;
2993
2994 /* matches smp_wmb() in event_sched_in() */
2995 smp_rmb();
2996
2997 /*
2998 * There is a window with interrupts enabled before we get here,
2999 * so we need to check again lest we try to stop another CPU's event.
3000 */
3001 if (READ_ONCE(event->oncpu) != smp_processor_id())
3002 return -EAGAIN;
3003
3004 event->pmu->stop(event, PERF_EF_UPDATE);
3005
375637bc
AS
3006 /*
3007 * May race with the actual stop (through perf_pmu_output_stop()),
3008 * but it is only used for events with AUX ring buffer, and such
3009 * events will refuse to restart because of rb::aux_mmap_count==0,
3010 * see comments in perf_aux_output_begin().
3011 *
788faab7 3012 * Since this is happening on an event-local CPU, no trace is lost
375637bc
AS
3013 * while restarting.
3014 */
3015 if (sd->restart)
c9bbdd48 3016 event->pmu->start(event, 0);
375637bc 3017
95ff4ca2
AS
3018 return 0;
3019}
3020
767ae086 3021static int perf_event_stop(struct perf_event *event, int restart)
375637bc
AS
3022{
3023 struct stop_event_data sd = {
3024 .event = event,
767ae086 3025 .restart = restart,
375637bc
AS
3026 };
3027 int ret = 0;
3028
3029 do {
3030 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
3031 return 0;
3032
3033 /* matches smp_wmb() in event_sched_in() */
3034 smp_rmb();
3035
3036 /*
3037 * We only want to restart ACTIVE events, so if the event goes
3038 * inactive here (event->oncpu==-1), there's nothing more to do;
3039 * fall through with ret==-ENXIO.
3040 */
3041 ret = cpu_function_call(READ_ONCE(event->oncpu),
3042 __perf_event_stop, &sd);
3043 } while (ret == -EAGAIN);
3044
3045 return ret;
3046}
3047
3048/*
3049 * In order to contain the amount of racy and tricky in the address filter
3050 * configuration management, it is a two part process:
3051 *
3052 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
3053 * we update the addresses of corresponding vmas in
c60f83b8 3054 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
375637bc
AS
3055 * (p2) when an event is scheduled in (pmu::add), it calls
3056 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
3057 * if the generation has changed since the previous call.
3058 *
3059 * If (p1) happens while the event is active, we restart it to force (p2).
3060 *
3061 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
3062 * pre-existing mappings, called once when new filters arrive via SET_FILTER
3063 * ioctl;
3064 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
3065 * registered mapping, called for every new mmap(), with mm::mmap_sem down
3066 * for reading;
3067 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
3068 * of exec.
3069 */
3070void perf_event_addr_filters_sync(struct perf_event *event)
3071{
3072 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
3073
3074 if (!has_addr_filter(event))
3075 return;
3076
3077 raw_spin_lock(&ifh->lock);
3078 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
3079 event->pmu->addr_filters_sync(event);
3080 event->hw.addr_filters_gen = event->addr_filters_gen;
3081 }
3082 raw_spin_unlock(&ifh->lock);
3083}
3084EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
3085
f63a8daa 3086static int _perf_event_refresh(struct perf_event *event, int refresh)
79f14641 3087{
2023b359 3088 /*
cdd6c482 3089 * not supported on inherited events
2023b359 3090 */
2e939d1d 3091 if (event->attr.inherit || !is_sampling_event(event))
2023b359
PZ
3092 return -EINVAL;
3093
cdd6c482 3094 atomic_add(refresh, &event->event_limit);
f63a8daa 3095 _perf_event_enable(event);
2023b359
PZ
3096
3097 return 0;
79f14641 3098}
f63a8daa
PZ
3099
3100/*
3101 * See perf_event_disable()
3102 */
3103int perf_event_refresh(struct perf_event *event, int refresh)
3104{
3105 struct perf_event_context *ctx;
3106 int ret;
3107
3108 ctx = perf_event_ctx_lock(event);
3109 ret = _perf_event_refresh(event, refresh);
3110 perf_event_ctx_unlock(event, ctx);
3111
3112 return ret;
3113}
26ca5c11 3114EXPORT_SYMBOL_GPL(perf_event_refresh);
79f14641 3115
32ff77e8
MC
3116static int perf_event_modify_breakpoint(struct perf_event *bp,
3117 struct perf_event_attr *attr)
3118{
3119 int err;
3120
3121 _perf_event_disable(bp);
3122
3123 err = modify_user_hw_breakpoint_check(bp, attr, true);
32ff77e8 3124
bf06278c 3125 if (!bp->attr.disabled)
32ff77e8 3126 _perf_event_enable(bp);
bf06278c
JO
3127
3128 return err;
32ff77e8
MC
3129}
3130
3131static int perf_event_modify_attr(struct perf_event *event,
3132 struct perf_event_attr *attr)
3133{
3134 if (event->attr.type != attr->type)
3135 return -EINVAL;
3136
3137 switch (event->attr.type) {
3138 case PERF_TYPE_BREAKPOINT:
3139 return perf_event_modify_breakpoint(event, attr);
3140 default:
3141 /* Place holder for future additions. */
3142 return -EOPNOTSUPP;
3143 }
3144}
3145
5b0311e1
FW
3146static void ctx_sched_out(struct perf_event_context *ctx,
3147 struct perf_cpu_context *cpuctx,
3148 enum event_type_t event_type)
235c7fc7 3149{
6668128a 3150 struct perf_event *event, *tmp;
db24d33e 3151 int is_active = ctx->is_active;
235c7fc7 3152
c994d613 3153 lockdep_assert_held(&ctx->lock);
235c7fc7 3154
39a43640
PZ
3155 if (likely(!ctx->nr_events)) {
3156 /*
3157 * See __perf_remove_from_context().
3158 */
3159 WARN_ON_ONCE(ctx->is_active);
3160 if (ctx->task)
3161 WARN_ON_ONCE(cpuctx->task_ctx);
facc4307 3162 return;
39a43640
PZ
3163 }
3164
db24d33e 3165 ctx->is_active &= ~event_type;
3cbaa590
PZ
3166 if (!(ctx->is_active & EVENT_ALL))
3167 ctx->is_active = 0;
3168
63e30d3e
PZ
3169 if (ctx->task) {
3170 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3171 if (!ctx->is_active)
3172 cpuctx->task_ctx = NULL;
3173 }
facc4307 3174
8fdc6539
PZ
3175 /*
3176 * Always update time if it was set; not only when it changes.
3177 * Otherwise we can 'forget' to update time for any but the last
3178 * context we sched out. For example:
3179 *
3180 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3181 * ctx_sched_out(.event_type = EVENT_PINNED)
3182 *
3183 * would only update time for the pinned events.
3184 */
3cbaa590
PZ
3185 if (is_active & EVENT_TIME) {
3186 /* update (and stop) ctx time */
3187 update_context_time(ctx);
3188 update_cgrp_time_from_cpuctx(cpuctx);
3189 }
3190
8fdc6539
PZ
3191 is_active ^= ctx->is_active; /* changed bits */
3192
3cbaa590 3193 if (!ctx->nr_active || !(is_active & EVENT_ALL))
facc4307 3194 return;
5b0311e1 3195
075e0b00 3196 perf_pmu_disable(ctx->pmu);
3cbaa590 3197 if (is_active & EVENT_PINNED) {
6668128a 3198 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
889ff015 3199 group_sched_out(event, cpuctx, ctx);
9ed6060d 3200 }
889ff015 3201
3cbaa590 3202 if (is_active & EVENT_FLEXIBLE) {
6668128a 3203 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
8c9ed8e1 3204 group_sched_out(event, cpuctx, ctx);
90c91dfb
PZ
3205
3206 /*
3207 * Since we cleared EVENT_FLEXIBLE, also clear
3208 * rotate_necessary, is will be reset by
3209 * ctx_flexible_sched_in() when needed.
3210 */
3211 ctx->rotate_necessary = 0;
9ed6060d 3212 }
1b9a644f 3213 perf_pmu_enable(ctx->pmu);
235c7fc7
IM
3214}
3215
564c2b21 3216/*
5a3126d4
PZ
3217 * Test whether two contexts are equivalent, i.e. whether they have both been
3218 * cloned from the same version of the same context.
3219 *
3220 * Equivalence is measured using a generation number in the context that is
3221 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3222 * and list_del_event().
564c2b21 3223 */
cdd6c482
IM
3224static int context_equiv(struct perf_event_context *ctx1,
3225 struct perf_event_context *ctx2)
564c2b21 3226{
211de6eb
PZ
3227 lockdep_assert_held(&ctx1->lock);
3228 lockdep_assert_held(&ctx2->lock);
3229
5a3126d4
PZ
3230 /* Pinning disables the swap optimization */
3231 if (ctx1->pin_count || ctx2->pin_count)
3232 return 0;
3233
3234 /* If ctx1 is the parent of ctx2 */
3235 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3236 return 1;
3237
3238 /* If ctx2 is the parent of ctx1 */
3239 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3240 return 1;
3241
3242 /*
3243 * If ctx1 and ctx2 have the same parent; we flatten the parent
3244 * hierarchy, see perf_event_init_context().
3245 */
3246 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3247 ctx1->parent_gen == ctx2->parent_gen)
3248 return 1;
3249
3250 /* Unmatched */
3251 return 0;
564c2b21
PM
3252}
3253
cdd6c482
IM
3254static void __perf_event_sync_stat(struct perf_event *event,
3255 struct perf_event *next_event)
bfbd3381
PZ
3256{
3257 u64 value;
3258
cdd6c482 3259 if (!event->attr.inherit_stat)
bfbd3381
PZ
3260 return;
3261
3262 /*
cdd6c482 3263 * Update the event value, we cannot use perf_event_read()
bfbd3381
PZ
3264 * because we're in the middle of a context switch and have IRQs
3265 * disabled, which upsets smp_call_function_single(), however
cdd6c482 3266 * we know the event must be on the current CPU, therefore we
bfbd3381
PZ
3267 * don't need to use it.
3268 */
0d3d73aa 3269 if (event->state == PERF_EVENT_STATE_ACTIVE)
3dbebf15 3270 event->pmu->read(event);
bfbd3381 3271
0d3d73aa 3272 perf_event_update_time(event);
bfbd3381
PZ
3273
3274 /*
cdd6c482 3275 * In order to keep per-task stats reliable we need to flip the event
bfbd3381
PZ
3276 * values when we flip the contexts.
3277 */
e7850595
PZ
3278 value = local64_read(&next_event->count);
3279 value = local64_xchg(&event->count, value);
3280 local64_set(&next_event->count, value);
bfbd3381 3281
cdd6c482
IM
3282 swap(event->total_time_enabled, next_event->total_time_enabled);
3283 swap(event->total_time_running, next_event->total_time_running);
19d2e755 3284
bfbd3381 3285 /*
19d2e755 3286 * Since we swizzled the values, update the user visible data too.
bfbd3381 3287 */
cdd6c482
IM
3288 perf_event_update_userpage(event);
3289 perf_event_update_userpage(next_event);
bfbd3381
PZ
3290}
3291
cdd6c482
IM
3292static void perf_event_sync_stat(struct perf_event_context *ctx,
3293 struct perf_event_context *next_ctx)
bfbd3381 3294{
cdd6c482 3295 struct perf_event *event, *next_event;
bfbd3381
PZ
3296
3297 if (!ctx->nr_stat)
3298 return;
3299
02ffdbc8
PZ
3300 update_context_time(ctx);
3301
cdd6c482
IM
3302 event = list_first_entry(&ctx->event_list,
3303 struct perf_event, event_entry);
bfbd3381 3304
cdd6c482
IM
3305 next_event = list_first_entry(&next_ctx->event_list,
3306 struct perf_event, event_entry);
bfbd3381 3307
cdd6c482
IM
3308 while (&event->event_entry != &ctx->event_list &&
3309 &next_event->event_entry != &next_ctx->event_list) {
bfbd3381 3310
cdd6c482 3311 __perf_event_sync_stat(event, next_event);
bfbd3381 3312
cdd6c482
IM
3313 event = list_next_entry(event, event_entry);
3314 next_event = list_next_entry(next_event, event_entry);
bfbd3381
PZ
3315 }
3316}
3317
fe4b04fa
PZ
3318static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3319 struct task_struct *next)
0793a61d 3320{
8dc85d54 3321 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
cdd6c482 3322 struct perf_event_context *next_ctx;
5a3126d4 3323 struct perf_event_context *parent, *next_parent;
108b02cf 3324 struct perf_cpu_context *cpuctx;
c93f7669 3325 int do_switch = 1;
0793a61d 3326
108b02cf
PZ
3327 if (likely(!ctx))
3328 return;
10989fb2 3329
108b02cf
PZ
3330 cpuctx = __get_cpu_context(ctx);
3331 if (!cpuctx->task_ctx)
0793a61d
TG
3332 return;
3333
c93f7669 3334 rcu_read_lock();
8dc85d54 3335 next_ctx = next->perf_event_ctxp[ctxn];
5a3126d4
PZ
3336 if (!next_ctx)
3337 goto unlock;
3338
3339 parent = rcu_dereference(ctx->parent_ctx);
3340 next_parent = rcu_dereference(next_ctx->parent_ctx);
3341
3342 /* If neither context have a parent context; they cannot be clones. */
802c8a61 3343 if (!parent && !next_parent)
5a3126d4
PZ
3344 goto unlock;
3345
3346 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
c93f7669
PM
3347 /*
3348 * Looks like the two contexts are clones, so we might be
3349 * able to optimize the context switch. We lock both
3350 * contexts and check that they are clones under the
3351 * lock (including re-checking that neither has been
3352 * uncloned in the meantime). It doesn't matter which
3353 * order we take the locks because no other cpu could
3354 * be trying to lock both of these tasks.
3355 */
e625cce1
TG
3356 raw_spin_lock(&ctx->lock);
3357 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
c93f7669 3358 if (context_equiv(ctx, next_ctx)) {
c2b98a86
AB
3359 struct pmu *pmu = ctx->pmu;
3360
63b6da39
PZ
3361 WRITE_ONCE(ctx->task, next);
3362 WRITE_ONCE(next_ctx->task, task);
5a158c3c 3363
c2b98a86
AB
3364 /*
3365 * PMU specific parts of task perf context can require
3366 * additional synchronization. As an example of such
3367 * synchronization see implementation details of Intel
3368 * LBR call stack data profiling;
3369 */
3370 if (pmu->swap_task_ctx)
3371 pmu->swap_task_ctx(ctx, next_ctx);
3372 else
3373 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
5a158c3c 3374
63b6da39
PZ
3375 /*
3376 * RCU_INIT_POINTER here is safe because we've not
3377 * modified the ctx and the above modification of
3378 * ctx->task and ctx->task_ctx_data are immaterial
3379 * since those values are always verified under
3380 * ctx->lock which we're now holding.
3381 */
3382 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3383 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3384
c93f7669 3385 do_switch = 0;
bfbd3381 3386
cdd6c482 3387 perf_event_sync_stat(ctx, next_ctx);
c93f7669 3388 }
e625cce1
TG
3389 raw_spin_unlock(&next_ctx->lock);
3390 raw_spin_unlock(&ctx->lock);
564c2b21 3391 }
5a3126d4 3392unlock:
c93f7669 3393 rcu_read_unlock();
564c2b21 3394
c93f7669 3395 if (do_switch) {
facc4307 3396 raw_spin_lock(&ctx->lock);
487f05e1 3397 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
facc4307 3398 raw_spin_unlock(&ctx->lock);
c93f7669 3399 }
0793a61d
TG
3400}
3401
e48c1788
PZ
3402static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3403
ba532500
YZ
3404void perf_sched_cb_dec(struct pmu *pmu)
3405{
e48c1788
PZ
3406 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3407
ba532500 3408 this_cpu_dec(perf_sched_cb_usages);
e48c1788
PZ
3409
3410 if (!--cpuctx->sched_cb_usage)
3411 list_del(&cpuctx->sched_cb_entry);
ba532500
YZ
3412}
3413
e48c1788 3414
ba532500
YZ
3415void perf_sched_cb_inc(struct pmu *pmu)
3416{
e48c1788
PZ
3417 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3418
3419 if (!cpuctx->sched_cb_usage++)
3420 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3421
ba532500
YZ
3422 this_cpu_inc(perf_sched_cb_usages);
3423}
3424
3425/*
3426 * This function provides the context switch callback to the lower code
3427 * layer. It is invoked ONLY when the context switch callback is enabled.
09e61b4f
PZ
3428 *
3429 * This callback is relevant even to per-cpu events; for example multi event
3430 * PEBS requires this to provide PID/TID information. This requires we flush
3431 * all queued PEBS records before we context switch to a new task.
ba532500
YZ
3432 */
3433static void perf_pmu_sched_task(struct task_struct *prev,
3434 struct task_struct *next,
3435 bool sched_in)
3436{
3437 struct perf_cpu_context *cpuctx;
3438 struct pmu *pmu;
ba532500
YZ
3439
3440 if (prev == next)
3441 return;
3442
e48c1788 3443 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
1fd7e416 3444 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
ba532500 3445
e48c1788
PZ
3446 if (WARN_ON_ONCE(!pmu->sched_task))
3447 continue;
ba532500 3448
e48c1788
PZ
3449 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3450 perf_pmu_disable(pmu);
ba532500 3451
e48c1788 3452 pmu->sched_task(cpuctx->task_ctx, sched_in);
ba532500 3453
e48c1788
PZ
3454 perf_pmu_enable(pmu);
3455 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
ba532500 3456 }
ba532500
YZ
3457}
3458
45ac1403
AH
3459static void perf_event_switch(struct task_struct *task,
3460 struct task_struct *next_prev, bool sched_in);
3461
8dc85d54
PZ
3462#define for_each_task_context_nr(ctxn) \
3463 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3464
3465/*
3466 * Called from scheduler to remove the events of the current task,
3467 * with interrupts disabled.
3468 *
3469 * We stop each event and update the event value in event->count.
3470 *
3471 * This does not protect us against NMI, but disable()
3472 * sets the disabled bit in the control field of event _before_
3473 * accessing the event control register. If a NMI hits, then it will
3474 * not restart the event.
3475 */
ab0cce56
JO
3476void __perf_event_task_sched_out(struct task_struct *task,
3477 struct task_struct *next)
8dc85d54
PZ
3478{
3479 int ctxn;
3480
ba532500
YZ
3481 if (__this_cpu_read(perf_sched_cb_usages))
3482 perf_pmu_sched_task(task, next, false);
3483
45ac1403
AH
3484 if (atomic_read(&nr_switch_events))
3485 perf_event_switch(task, next, false);
3486
8dc85d54
PZ
3487 for_each_task_context_nr(ctxn)
3488 perf_event_context_sched_out(task, ctxn, next);
e5d1367f
SE
3489
3490 /*
3491 * if cgroup events exist on this CPU, then we need
3492 * to check if we have to switch out PMU state.
3493 * cgroup event are system-wide mode only
3494 */
4a32fea9 3495 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
a8d757ef 3496 perf_cgroup_sched_out(task, next);
8dc85d54
PZ
3497}
3498
5b0311e1
FW
3499/*
3500 * Called with IRQs disabled
3501 */
3502static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3503 enum event_type_t event_type)
3504{
3505 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
04289bb9
IM
3506}
3507
6eef8a71 3508static bool perf_less_group_idx(const void *l, const void *r)
0793a61d 3509{
6eef8a71
IR
3510 const struct perf_event *le = l, *re = r;
3511
3512 return le->group_index < re->group_index;
3513}
3514
3515static void swap_ptr(void *l, void *r)
3516{
3517 void **lp = l, **rp = r;
3518
3519 swap(*lp, *rp);
3520}
3521
3522static const struct min_heap_callbacks perf_min_heap = {
3523 .elem_size = sizeof(struct perf_event *),
3524 .less = perf_less_group_idx,
3525 .swp = swap_ptr,
3526};
3527
3528static void __heap_add(struct min_heap *heap, struct perf_event *event)
3529{
3530 struct perf_event **itrs = heap->data;
3531
3532 if (event) {
3533 itrs[heap->nr] = event;
3534 heap->nr++;
3535 }
3536}
3537
836196be
IR
3538static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx,
3539 struct perf_event_groups *groups, int cpu,
6eef8a71
IR
3540 int (*func)(struct perf_event *, void *),
3541 void *data)
3542{
95ed6c70
IR
3543#ifdef CONFIG_CGROUP_PERF
3544 struct cgroup_subsys_state *css = NULL;
3545#endif
6eef8a71
IR
3546 /* Space for per CPU and/or any CPU event iterators. */
3547 struct perf_event *itrs[2];
836196be
IR
3548 struct min_heap event_heap;
3549 struct perf_event **evt;
1cac7b1a 3550 int ret;
8e1a2031 3551
836196be
IR
3552 if (cpuctx) {
3553 event_heap = (struct min_heap){
3554 .data = cpuctx->heap,
3555 .nr = 0,
3556 .size = cpuctx->heap_size,
3557 };
c2283c93
IR
3558
3559 lockdep_assert_held(&cpuctx->ctx.lock);
95ed6c70
IR
3560
3561#ifdef CONFIG_CGROUP_PERF
3562 if (cpuctx->cgrp)
3563 css = &cpuctx->cgrp->css;
3564#endif
836196be
IR
3565 } else {
3566 event_heap = (struct min_heap){
3567 .data = itrs,
3568 .nr = 0,
3569 .size = ARRAY_SIZE(itrs),
3570 };
3571 /* Events not within a CPU context may be on any CPU. */
95ed6c70 3572 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL));
836196be
IR
3573 }
3574 evt = event_heap.data;
3575
95ed6c70
IR
3576 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL));
3577
3578#ifdef CONFIG_CGROUP_PERF
3579 for (; css; css = css->parent)
3580 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup));
3581#endif
1cac7b1a 3582
6eef8a71 3583 min_heapify_all(&event_heap, &perf_min_heap);
1cac7b1a 3584
6eef8a71 3585 while (event_heap.nr) {
1cac7b1a
PZ
3586 ret = func(*evt, data);
3587 if (ret)
3588 return ret;
3589
3590 *evt = perf_event_groups_next(*evt);
6eef8a71
IR
3591 if (*evt)
3592 min_heapify(&event_heap, 0, &perf_min_heap);
3593 else
3594 min_heap_pop(&event_heap, &perf_min_heap);
8e1a2031 3595 }
0793a61d 3596
1cac7b1a
PZ
3597 return 0;
3598}
3599
ab6f824c 3600static int merge_sched_in(struct perf_event *event, void *data)
1cac7b1a 3601{
2c2366c7
PZ
3602 struct perf_event_context *ctx = event->ctx;
3603 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3604 int *can_add_hw = data;
ab6f824c 3605
1cac7b1a
PZ
3606 if (event->state <= PERF_EVENT_STATE_OFF)
3607 return 0;
3608
3609 if (!event_filter_match(event))
3610 return 0;
3611
2c2366c7
PZ
3612 if (group_can_go_on(event, cpuctx, *can_add_hw)) {
3613 if (!group_sched_in(event, cpuctx, ctx))
ab6f824c 3614 list_add_tail(&event->active_list, get_event_list(event));
6668128a 3615 }
1cac7b1a 3616
ab6f824c
PZ
3617 if (event->state == PERF_EVENT_STATE_INACTIVE) {
3618 if (event->attr.pinned)
3619 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
1cac7b1a 3620
2c2366c7
PZ
3621 *can_add_hw = 0;
3622 ctx->rotate_necessary = 1;
3b6f9e5c 3623 }
1cac7b1a
PZ
3624
3625 return 0;
5b0311e1
FW
3626}
3627
3628static void
1cac7b1a
PZ
3629ctx_pinned_sched_in(struct perf_event_context *ctx,
3630 struct perf_cpu_context *cpuctx)
5b0311e1 3631{
2c2366c7 3632 int can_add_hw = 1;
3b6f9e5c 3633
836196be
IR
3634 if (ctx != &cpuctx->ctx)
3635 cpuctx = NULL;
3636
3637 visit_groups_merge(cpuctx, &ctx->pinned_groups,
1cac7b1a 3638 smp_processor_id(),
2c2366c7 3639 merge_sched_in, &can_add_hw);
1cac7b1a 3640}
8e1a2031 3641
1cac7b1a
PZ
3642static void
3643ctx_flexible_sched_in(struct perf_event_context *ctx,
3644 struct perf_cpu_context *cpuctx)
3645{
2c2366c7 3646 int can_add_hw = 1;
0793a61d 3647
836196be
IR
3648 if (ctx != &cpuctx->ctx)
3649 cpuctx = NULL;
3650
3651 visit_groups_merge(cpuctx, &ctx->flexible_groups,
1cac7b1a 3652 smp_processor_id(),
2c2366c7 3653 merge_sched_in, &can_add_hw);
5b0311e1
FW
3654}
3655
3656static void
3657ctx_sched_in(struct perf_event_context *ctx,
3658 struct perf_cpu_context *cpuctx,
e5d1367f
SE
3659 enum event_type_t event_type,
3660 struct task_struct *task)
5b0311e1 3661{
db24d33e 3662 int is_active = ctx->is_active;
c994d613
PZ
3663 u64 now;
3664
3665 lockdep_assert_held(&ctx->lock);
e5d1367f 3666
5b0311e1 3667 if (likely(!ctx->nr_events))
facc4307 3668 return;
5b0311e1 3669
3cbaa590 3670 ctx->is_active |= (event_type | EVENT_TIME);
63e30d3e
PZ
3671 if (ctx->task) {
3672 if (!is_active)
3673 cpuctx->task_ctx = ctx;
3674 else
3675 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3676 }
3677
3cbaa590
PZ
3678 is_active ^= ctx->is_active; /* changed bits */
3679
3680 if (is_active & EVENT_TIME) {
3681 /* start ctx time */
3682 now = perf_clock();
3683 ctx->timestamp = now;
3684 perf_cgroup_set_timestamp(task, ctx);
3685 }
3686
5b0311e1
FW
3687 /*
3688 * First go through the list and put on any pinned groups
3689 * in order to give them the best chance of going on.
3690 */
3cbaa590 3691 if (is_active & EVENT_PINNED)
6e37738a 3692 ctx_pinned_sched_in(ctx, cpuctx);
5b0311e1
FW
3693
3694 /* Then walk through the lower prio flexible groups */
3cbaa590 3695 if (is_active & EVENT_FLEXIBLE)
6e37738a 3696 ctx_flexible_sched_in(ctx, cpuctx);
235c7fc7
IM
3697}
3698
329c0e01 3699static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
e5d1367f
SE
3700 enum event_type_t event_type,
3701 struct task_struct *task)
329c0e01
FW
3702{
3703 struct perf_event_context *ctx = &cpuctx->ctx;
3704
e5d1367f 3705 ctx_sched_in(ctx, cpuctx, event_type, task);
329c0e01
FW
3706}
3707
e5d1367f
SE
3708static void perf_event_context_sched_in(struct perf_event_context *ctx,
3709 struct task_struct *task)
235c7fc7 3710{
108b02cf 3711 struct perf_cpu_context *cpuctx;
235c7fc7 3712
108b02cf 3713 cpuctx = __get_cpu_context(ctx);
329c0e01
FW
3714 if (cpuctx->task_ctx == ctx)
3715 return;
3716
facc4307 3717 perf_ctx_lock(cpuctx, ctx);
fdccc3fb 3718 /*
3719 * We must check ctx->nr_events while holding ctx->lock, such
3720 * that we serialize against perf_install_in_context().
3721 */
3722 if (!ctx->nr_events)
3723 goto unlock;
3724
1b9a644f 3725 perf_pmu_disable(ctx->pmu);
329c0e01
FW
3726 /*
3727 * We want to keep the following priority order:
3728 * cpu pinned (that don't need to move), task pinned,
3729 * cpu flexible, task flexible.
fe45bafb
AS
3730 *
3731 * However, if task's ctx is not carrying any pinned
3732 * events, no need to flip the cpuctx's events around.
329c0e01 3733 */
8e1a2031 3734 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
fe45bafb 3735 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
63e30d3e 3736 perf_event_sched_in(cpuctx, ctx, task);
facc4307 3737 perf_pmu_enable(ctx->pmu);
fdccc3fb 3738
3739unlock:
facc4307 3740 perf_ctx_unlock(cpuctx, ctx);
235c7fc7
IM
3741}
3742
8dc85d54
PZ
3743/*
3744 * Called from scheduler to add the events of the current task
3745 * with interrupts disabled.
3746 *
3747 * We restore the event value and then enable it.
3748 *
3749 * This does not protect us against NMI, but enable()
3750 * sets the enabled bit in the control field of event _before_
3751 * accessing the event control register. If a NMI hits, then it will
3752 * keep the event running.
3753 */
ab0cce56
JO
3754void __perf_event_task_sched_in(struct task_struct *prev,
3755 struct task_struct *task)
8dc85d54
PZ
3756{
3757 struct perf_event_context *ctx;
3758 int ctxn;
3759
7e41d177
PZ
3760 /*
3761 * If cgroup events exist on this CPU, then we need to check if we have
3762 * to switch in PMU state; cgroup event are system-wide mode only.
3763 *
3764 * Since cgroup events are CPU events, we must schedule these in before
3765 * we schedule in the task events.
3766 */
3767 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3768 perf_cgroup_sched_in(prev, task);
3769
8dc85d54
PZ
3770 for_each_task_context_nr(ctxn) {
3771 ctx = task->perf_event_ctxp[ctxn];
3772 if (likely(!ctx))
3773 continue;
3774
e5d1367f 3775 perf_event_context_sched_in(ctx, task);
8dc85d54 3776 }
d010b332 3777
45ac1403
AH
3778 if (atomic_read(&nr_switch_events))
3779 perf_event_switch(task, prev, true);
3780
ba532500
YZ
3781 if (__this_cpu_read(perf_sched_cb_usages))
3782 perf_pmu_sched_task(prev, task, true);
235c7fc7
IM
3783}
3784
abd50713
PZ
3785static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3786{
3787 u64 frequency = event->attr.sample_freq;
3788 u64 sec = NSEC_PER_SEC;
3789 u64 divisor, dividend;
3790
3791 int count_fls, nsec_fls, frequency_fls, sec_fls;
3792
3793 count_fls = fls64(count);
3794 nsec_fls = fls64(nsec);
3795 frequency_fls = fls64(frequency);
3796 sec_fls = 30;
3797
3798 /*
3799 * We got @count in @nsec, with a target of sample_freq HZ
3800 * the target period becomes:
3801 *
3802 * @count * 10^9
3803 * period = -------------------
3804 * @nsec * sample_freq
3805 *
3806 */
3807
3808 /*
3809 * Reduce accuracy by one bit such that @a and @b converge
3810 * to a similar magnitude.
3811 */
fe4b04fa 3812#define REDUCE_FLS(a, b) \
abd50713
PZ
3813do { \
3814 if (a##_fls > b##_fls) { \
3815 a >>= 1; \
3816 a##_fls--; \
3817 } else { \
3818 b >>= 1; \
3819 b##_fls--; \
3820 } \
3821} while (0)
3822
3823 /*
3824 * Reduce accuracy until either term fits in a u64, then proceed with
3825 * the other, so that finally we can do a u64/u64 division.
3826 */
3827 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3828 REDUCE_FLS(nsec, frequency);
3829 REDUCE_FLS(sec, count);
3830 }
3831
3832 if (count_fls + sec_fls > 64) {
3833 divisor = nsec * frequency;
3834
3835 while (count_fls + sec_fls > 64) {
3836 REDUCE_FLS(count, sec);
3837 divisor >>= 1;
3838 }
3839
3840 dividend = count * sec;
3841 } else {
3842 dividend = count * sec;
3843
3844 while (nsec_fls + frequency_fls > 64) {
3845 REDUCE_FLS(nsec, frequency);
3846 dividend >>= 1;
3847 }
3848
3849 divisor = nsec * frequency;
3850 }
3851
f6ab91ad
PZ
3852 if (!divisor)
3853 return dividend;
3854
abd50713
PZ
3855 return div64_u64(dividend, divisor);
3856}
3857
e050e3f0
SE
3858static DEFINE_PER_CPU(int, perf_throttled_count);
3859static DEFINE_PER_CPU(u64, perf_throttled_seq);
3860
f39d47ff 3861static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
bd2b5b12 3862{
cdd6c482 3863 struct hw_perf_event *hwc = &event->hw;
f6ab91ad 3864 s64 period, sample_period;
bd2b5b12
PZ
3865 s64 delta;
3866
abd50713 3867 period = perf_calculate_period(event, nsec, count);
bd2b5b12
PZ
3868
3869 delta = (s64)(period - hwc->sample_period);
3870 delta = (delta + 7) / 8; /* low pass filter */
3871
3872 sample_period = hwc->sample_period + delta;
3873
3874 if (!sample_period)
3875 sample_period = 1;
3876
bd2b5b12 3877 hwc->sample_period = sample_period;
abd50713 3878
e7850595 3879 if (local64_read(&hwc->period_left) > 8*sample_period) {
f39d47ff
SE
3880 if (disable)
3881 event->pmu->stop(event, PERF_EF_UPDATE);
3882
e7850595 3883 local64_set(&hwc->period_left, 0);
f39d47ff
SE
3884
3885 if (disable)
3886 event->pmu->start(event, PERF_EF_RELOAD);
abd50713 3887 }
bd2b5b12
PZ
3888}
3889
e050e3f0
SE
3890/*
3891 * combine freq adjustment with unthrottling to avoid two passes over the
3892 * events. At the same time, make sure, having freq events does not change
3893 * the rate of unthrottling as that would introduce bias.
3894 */
3895static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3896 int needs_unthr)
60db5e09 3897{
cdd6c482
IM
3898 struct perf_event *event;
3899 struct hw_perf_event *hwc;
e050e3f0 3900 u64 now, period = TICK_NSEC;
abd50713 3901 s64 delta;
60db5e09 3902
e050e3f0
SE
3903 /*
3904 * only need to iterate over all events iff:
3905 * - context have events in frequency mode (needs freq adjust)
3906 * - there are events to unthrottle on this cpu
3907 */
3908 if (!(ctx->nr_freq || needs_unthr))
0f5a2601
PZ
3909 return;
3910
e050e3f0 3911 raw_spin_lock(&ctx->lock);
f39d47ff 3912 perf_pmu_disable(ctx->pmu);
e050e3f0 3913
03541f8b 3914 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
cdd6c482 3915 if (event->state != PERF_EVENT_STATE_ACTIVE)
60db5e09
PZ
3916 continue;
3917
5632ab12 3918 if (!event_filter_match(event))
5d27c23d
PZ
3919 continue;
3920
44377277
AS
3921 perf_pmu_disable(event->pmu);
3922
cdd6c482 3923 hwc = &event->hw;
6a24ed6c 3924
ae23bff1 3925 if (hwc->interrupts == MAX_INTERRUPTS) {
e050e3f0 3926 hwc->interrupts = 0;
cdd6c482 3927 perf_log_throttle(event, 1);
a4eaf7f1 3928 event->pmu->start(event, 0);
a78ac325
PZ
3929 }
3930
cdd6c482 3931 if (!event->attr.freq || !event->attr.sample_freq)
44377277 3932 goto next;
60db5e09 3933
e050e3f0
SE
3934 /*
3935 * stop the event and update event->count
3936 */
3937 event->pmu->stop(event, PERF_EF_UPDATE);
3938
e7850595 3939 now = local64_read(&event->count);
abd50713
PZ
3940 delta = now - hwc->freq_count_stamp;
3941 hwc->freq_count_stamp = now;
60db5e09 3942
e050e3f0
SE
3943 /*
3944 * restart the event
3945 * reload only if value has changed
f39d47ff
SE
3946 * we have stopped the event so tell that
3947 * to perf_adjust_period() to avoid stopping it
3948 * twice.
e050e3f0 3949 */
abd50713 3950 if (delta > 0)
f39d47ff 3951 perf_adjust_period(event, period, delta, false);
e050e3f0
SE
3952
3953 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
44377277
AS
3954 next:
3955 perf_pmu_enable(event->pmu);
60db5e09 3956 }
e050e3f0 3957
f39d47ff 3958 perf_pmu_enable(ctx->pmu);
e050e3f0 3959 raw_spin_unlock(&ctx->lock);
60db5e09
PZ
3960}
3961
235c7fc7 3962/*
8703a7cf 3963 * Move @event to the tail of the @ctx's elegible events.
235c7fc7 3964 */
8703a7cf 3965static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
0793a61d 3966{
dddd3379
TG
3967 /*
3968 * Rotate the first entry last of non-pinned groups. Rotation might be
3969 * disabled by the inheritance code.
3970 */
8703a7cf
PZ
3971 if (ctx->rotate_disable)
3972 return;
8e1a2031 3973
8703a7cf
PZ
3974 perf_event_groups_delete(&ctx->flexible_groups, event);
3975 perf_event_groups_insert(&ctx->flexible_groups, event);
235c7fc7
IM
3976}
3977
7fa343b7 3978/* pick an event from the flexible_groups to rotate */
8d5bce0c 3979static inline struct perf_event *
7fa343b7 3980ctx_event_to_rotate(struct perf_event_context *ctx)
235c7fc7 3981{
7fa343b7
SL
3982 struct perf_event *event;
3983
3984 /* pick the first active flexible event */
3985 event = list_first_entry_or_null(&ctx->flexible_active,
3986 struct perf_event, active_list);
3987
3988 /* if no active flexible event, pick the first event */
3989 if (!event) {
3990 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
3991 typeof(*event), group_node);
3992 }
3993
90c91dfb
PZ
3994 /*
3995 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
3996 * finds there are unschedulable events, it will set it again.
3997 */
3998 ctx->rotate_necessary = 0;
3999
7fa343b7 4000 return event;
8d5bce0c
PZ
4001}
4002
4003static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
4004{
4005 struct perf_event *cpu_event = NULL, *task_event = NULL;
fd7d5517
IR
4006 struct perf_event_context *task_ctx = NULL;
4007 int cpu_rotate, task_rotate;
8d5bce0c
PZ
4008
4009 /*
4010 * Since we run this from IRQ context, nobody can install new
4011 * events, thus the event count values are stable.
4012 */
7fc23a53 4013
fd7d5517
IR
4014 cpu_rotate = cpuctx->ctx.rotate_necessary;
4015 task_ctx = cpuctx->task_ctx;
4016 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
9717e6cd 4017
8d5bce0c
PZ
4018 if (!(cpu_rotate || task_rotate))
4019 return false;
0f5a2601 4020
facc4307 4021 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
1b9a644f 4022 perf_pmu_disable(cpuctx->ctx.pmu);
60db5e09 4023
8d5bce0c 4024 if (task_rotate)
7fa343b7 4025 task_event = ctx_event_to_rotate(task_ctx);
8d5bce0c 4026 if (cpu_rotate)
7fa343b7 4027 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
8703a7cf 4028
8d5bce0c
PZ
4029 /*
4030 * As per the order given at ctx_resched() first 'pop' task flexible
4031 * and then, if needed CPU flexible.
4032 */
fd7d5517
IR
4033 if (task_event || (task_ctx && cpu_event))
4034 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
8d5bce0c
PZ
4035 if (cpu_event)
4036 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
0793a61d 4037
8d5bce0c 4038 if (task_event)
fd7d5517 4039 rotate_ctx(task_ctx, task_event);
8d5bce0c
PZ
4040 if (cpu_event)
4041 rotate_ctx(&cpuctx->ctx, cpu_event);
235c7fc7 4042
fd7d5517 4043 perf_event_sched_in(cpuctx, task_ctx, current);
235c7fc7 4044
0f5a2601
PZ
4045 perf_pmu_enable(cpuctx->ctx.pmu);
4046 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
9e630205 4047
8d5bce0c 4048 return true;
e9d2b064
PZ
4049}
4050
4051void perf_event_task_tick(void)
4052{
2fde4f94
MR
4053 struct list_head *head = this_cpu_ptr(&active_ctx_list);
4054 struct perf_event_context *ctx, *tmp;
e050e3f0 4055 int throttled;
b5ab4cd5 4056
16444645 4057 lockdep_assert_irqs_disabled();
e9d2b064 4058
e050e3f0
SE
4059 __this_cpu_inc(perf_throttled_seq);
4060 throttled = __this_cpu_xchg(perf_throttled_count, 0);
555e0c1e 4061 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
e050e3f0 4062
2fde4f94 4063 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
e050e3f0 4064 perf_adjust_freq_unthr_context(ctx, throttled);
0793a61d
TG
4065}
4066
889ff015
FW
4067static int event_enable_on_exec(struct perf_event *event,
4068 struct perf_event_context *ctx)
4069{
4070 if (!event->attr.enable_on_exec)
4071 return 0;
4072
4073 event->attr.enable_on_exec = 0;
4074 if (event->state >= PERF_EVENT_STATE_INACTIVE)
4075 return 0;
4076
0d3d73aa 4077 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
889ff015
FW
4078
4079 return 1;
4080}
4081
57e7986e 4082/*
cdd6c482 4083 * Enable all of a task's events that have been marked enable-on-exec.
57e7986e
PM
4084 * This expects task == current.
4085 */
c1274499 4086static void perf_event_enable_on_exec(int ctxn)
57e7986e 4087{
c1274499 4088 struct perf_event_context *ctx, *clone_ctx = NULL;
487f05e1 4089 enum event_type_t event_type = 0;
3e349507 4090 struct perf_cpu_context *cpuctx;
cdd6c482 4091 struct perf_event *event;
57e7986e
PM
4092 unsigned long flags;
4093 int enabled = 0;
4094
4095 local_irq_save(flags);
c1274499 4096 ctx = current->perf_event_ctxp[ctxn];
cdd6c482 4097 if (!ctx || !ctx->nr_events)
57e7986e
PM
4098 goto out;
4099
3e349507
PZ
4100 cpuctx = __get_cpu_context(ctx);
4101 perf_ctx_lock(cpuctx, ctx);
7fce2509 4102 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
487f05e1 4103 list_for_each_entry(event, &ctx->event_list, event_entry) {
3e349507 4104 enabled |= event_enable_on_exec(event, ctx);
487f05e1
AS
4105 event_type |= get_event_type(event);
4106 }
57e7986e
PM
4107
4108 /*
3e349507 4109 * Unclone and reschedule this context if we enabled any event.
57e7986e 4110 */
3e349507 4111 if (enabled) {
211de6eb 4112 clone_ctx = unclone_ctx(ctx);
487f05e1 4113 ctx_resched(cpuctx, ctx, event_type);
7bbba0eb
PZ
4114 } else {
4115 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
3e349507
PZ
4116 }
4117 perf_ctx_unlock(cpuctx, ctx);
57e7986e 4118
9ed6060d 4119out:
57e7986e 4120 local_irq_restore(flags);
211de6eb
PZ
4121
4122 if (clone_ctx)
4123 put_ctx(clone_ctx);
57e7986e
PM
4124}
4125
0492d4c5
PZ
4126struct perf_read_data {
4127 struct perf_event *event;
4128 bool group;
7d88962e 4129 int ret;
0492d4c5
PZ
4130};
4131
451d24d1 4132static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
d6a2f903 4133{
d6a2f903
DCC
4134 u16 local_pkg, event_pkg;
4135
4136 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
451d24d1
PZ
4137 int local_cpu = smp_processor_id();
4138
4139 event_pkg = topology_physical_package_id(event_cpu);
4140 local_pkg = topology_physical_package_id(local_cpu);
d6a2f903
DCC
4141
4142 if (event_pkg == local_pkg)
4143 return local_cpu;
4144 }
4145
4146 return event_cpu;
4147}
4148
0793a61d 4149/*
cdd6c482 4150 * Cross CPU call to read the hardware event
0793a61d 4151 */
cdd6c482 4152static void __perf_event_read(void *info)
0793a61d 4153{
0492d4c5
PZ
4154 struct perf_read_data *data = info;
4155 struct perf_event *sub, *event = data->event;
cdd6c482 4156 struct perf_event_context *ctx = event->ctx;
108b02cf 4157 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4a00c16e 4158 struct pmu *pmu = event->pmu;
621a01ea 4159
e1ac3614
PM
4160 /*
4161 * If this is a task context, we need to check whether it is
4162 * the current task context of this cpu. If not it has been
4163 * scheduled out before the smp call arrived. In that case
cdd6c482
IM
4164 * event->count would have been updated to a recent sample
4165 * when the event was scheduled out.
e1ac3614
PM
4166 */
4167 if (ctx->task && cpuctx->task_ctx != ctx)
4168 return;
4169
e625cce1 4170 raw_spin_lock(&ctx->lock);
0c1cbc18 4171 if (ctx->is_active & EVENT_TIME) {
542e72fc 4172 update_context_time(ctx);
e5d1367f
SE
4173 update_cgrp_time_from_event(event);
4174 }
0492d4c5 4175
0d3d73aa
PZ
4176 perf_event_update_time(event);
4177 if (data->group)
4178 perf_event_update_sibling_time(event);
0c1cbc18 4179
4a00c16e
SB
4180 if (event->state != PERF_EVENT_STATE_ACTIVE)
4181 goto unlock;
0492d4c5 4182
4a00c16e
SB
4183 if (!data->group) {
4184 pmu->read(event);
4185 data->ret = 0;
0492d4c5 4186 goto unlock;
4a00c16e
SB
4187 }
4188
4189 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4190
4191 pmu->read(event);
0492d4c5 4192
edb39592 4193 for_each_sibling_event(sub, event) {
4a00c16e
SB
4194 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4195 /*
4196 * Use sibling's PMU rather than @event's since
4197 * sibling could be on different (eg: software) PMU.
4198 */
0492d4c5 4199 sub->pmu->read(sub);
4a00c16e 4200 }
0492d4c5 4201 }
4a00c16e
SB
4202
4203 data->ret = pmu->commit_txn(pmu);
0492d4c5
PZ
4204
4205unlock:
e625cce1 4206 raw_spin_unlock(&ctx->lock);
0793a61d
TG
4207}
4208
b5e58793
PZ
4209static inline u64 perf_event_count(struct perf_event *event)
4210{
c39a0e2c 4211 return local64_read(&event->count) + atomic64_read(&event->child_count);
b5e58793
PZ
4212}
4213
ffe8690c
KX
4214/*
4215 * NMI-safe method to read a local event, that is an event that
4216 * is:
4217 * - either for the current task, or for this CPU
4218 * - does not have inherit set, for inherited task events
4219 * will not be local and we cannot read them atomically
4220 * - must not have a pmu::count method
4221 */
7d9285e8
YS
4222int perf_event_read_local(struct perf_event *event, u64 *value,
4223 u64 *enabled, u64 *running)
ffe8690c
KX
4224{
4225 unsigned long flags;
f91840a3 4226 int ret = 0;
ffe8690c
KX
4227
4228 /*
4229 * Disabling interrupts avoids all counter scheduling (context
4230 * switches, timer based rotation and IPIs).
4231 */
4232 local_irq_save(flags);
4233
ffe8690c
KX
4234 /*
4235 * It must not be an event with inherit set, we cannot read
4236 * all child counters from atomic context.
4237 */
f91840a3
AS
4238 if (event->attr.inherit) {
4239 ret = -EOPNOTSUPP;
4240 goto out;
4241 }
ffe8690c 4242
f91840a3
AS
4243 /* If this is a per-task event, it must be for current */
4244 if ((event->attach_state & PERF_ATTACH_TASK) &&
4245 event->hw.target != current) {
4246 ret = -EINVAL;
4247 goto out;
4248 }
4249
4250 /* If this is a per-CPU event, it must be for this CPU */
4251 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4252 event->cpu != smp_processor_id()) {
4253 ret = -EINVAL;
4254 goto out;
4255 }
ffe8690c 4256
befb1b3c
RC
4257 /* If this is a pinned event it must be running on this CPU */
4258 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4259 ret = -EBUSY;
4260 goto out;
4261 }
4262
ffe8690c
KX
4263 /*
4264 * If the event is currently on this CPU, its either a per-task event,
4265 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4266 * oncpu == -1).
4267 */
4268 if (event->oncpu == smp_processor_id())
4269 event->pmu->read(event);
4270
f91840a3 4271 *value = local64_read(&event->count);
0d3d73aa
PZ
4272 if (enabled || running) {
4273 u64 now = event->shadow_ctx_time + perf_clock();
4274 u64 __enabled, __running;
4275
4276 __perf_update_times(event, now, &__enabled, &__running);
4277 if (enabled)
4278 *enabled = __enabled;
4279 if (running)
4280 *running = __running;
4281 }
f91840a3 4282out:
ffe8690c
KX
4283 local_irq_restore(flags);
4284
f91840a3 4285 return ret;
ffe8690c
KX
4286}
4287
7d88962e 4288static int perf_event_read(struct perf_event *event, bool group)
0793a61d 4289{
0c1cbc18 4290 enum perf_event_state state = READ_ONCE(event->state);
451d24d1 4291 int event_cpu, ret = 0;
7d88962e 4292
0793a61d 4293 /*
cdd6c482
IM
4294 * If event is enabled and currently active on a CPU, update the
4295 * value in the event structure:
0793a61d 4296 */
0c1cbc18
PZ
4297again:
4298 if (state == PERF_EVENT_STATE_ACTIVE) {
4299 struct perf_read_data data;
4300
4301 /*
4302 * Orders the ->state and ->oncpu loads such that if we see
4303 * ACTIVE we must also see the right ->oncpu.
4304 *
4305 * Matches the smp_wmb() from event_sched_in().
4306 */
4307 smp_rmb();
d6a2f903 4308
451d24d1
PZ
4309 event_cpu = READ_ONCE(event->oncpu);
4310 if ((unsigned)event_cpu >= nr_cpu_ids)
4311 return 0;
4312
0c1cbc18
PZ
4313 data = (struct perf_read_data){
4314 .event = event,
4315 .group = group,
4316 .ret = 0,
4317 };
4318
451d24d1
PZ
4319 preempt_disable();
4320 event_cpu = __perf_event_read_cpu(event, event_cpu);
d6a2f903 4321
58763148
PZ
4322 /*
4323 * Purposely ignore the smp_call_function_single() return
4324 * value.
4325 *
451d24d1 4326 * If event_cpu isn't a valid CPU it means the event got
58763148
PZ
4327 * scheduled out and that will have updated the event count.
4328 *
4329 * Therefore, either way, we'll have an up-to-date event count
4330 * after this.
4331 */
451d24d1
PZ
4332 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4333 preempt_enable();
58763148 4334 ret = data.ret;
0c1cbc18
PZ
4335
4336 } else if (state == PERF_EVENT_STATE_INACTIVE) {
2b8988c9
PZ
4337 struct perf_event_context *ctx = event->ctx;
4338 unsigned long flags;
4339
e625cce1 4340 raw_spin_lock_irqsave(&ctx->lock, flags);
0c1cbc18
PZ
4341 state = event->state;
4342 if (state != PERF_EVENT_STATE_INACTIVE) {
4343 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4344 goto again;
4345 }
4346
c530ccd9 4347 /*
0c1cbc18
PZ
4348 * May read while context is not active (e.g., thread is
4349 * blocked), in that case we cannot update context time
c530ccd9 4350 */
0c1cbc18 4351 if (ctx->is_active & EVENT_TIME) {
c530ccd9 4352 update_context_time(ctx);
e5d1367f
SE
4353 update_cgrp_time_from_event(event);
4354 }
0c1cbc18 4355
0d3d73aa 4356 perf_event_update_time(event);
0492d4c5 4357 if (group)
0d3d73aa 4358 perf_event_update_sibling_time(event);
e625cce1 4359 raw_spin_unlock_irqrestore(&ctx->lock, flags);
0793a61d 4360 }
7d88962e
SB
4361
4362 return ret;
0793a61d
TG
4363}
4364
a63eaf34 4365/*
cdd6c482 4366 * Initialize the perf_event context in a task_struct:
a63eaf34 4367 */
eb184479 4368static void __perf_event_init_context(struct perf_event_context *ctx)
a63eaf34 4369{
e625cce1 4370 raw_spin_lock_init(&ctx->lock);
a63eaf34 4371 mutex_init(&ctx->mutex);
2fde4f94 4372 INIT_LIST_HEAD(&ctx->active_ctx_list);
8e1a2031
AB
4373 perf_event_groups_init(&ctx->pinned_groups);
4374 perf_event_groups_init(&ctx->flexible_groups);
a63eaf34 4375 INIT_LIST_HEAD(&ctx->event_list);
6668128a
PZ
4376 INIT_LIST_HEAD(&ctx->pinned_active);
4377 INIT_LIST_HEAD(&ctx->flexible_active);
8c94abbb 4378 refcount_set(&ctx->refcount, 1);
eb184479
PZ
4379}
4380
4381static struct perf_event_context *
4382alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4383{
4384 struct perf_event_context *ctx;
4385
4386 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4387 if (!ctx)
4388 return NULL;
4389
4390 __perf_event_init_context(ctx);
7b3c92b8
MWO
4391 if (task)
4392 ctx->task = get_task_struct(task);
eb184479
PZ
4393 ctx->pmu = pmu;
4394
4395 return ctx;
a63eaf34
PM
4396}
4397
2ebd4ffb
MH
4398static struct task_struct *
4399find_lively_task_by_vpid(pid_t vpid)
4400{
4401 struct task_struct *task;
0793a61d
TG
4402
4403 rcu_read_lock();
2ebd4ffb 4404 if (!vpid)
0793a61d
TG
4405 task = current;
4406 else
2ebd4ffb 4407 task = find_task_by_vpid(vpid);
0793a61d
TG
4408 if (task)
4409 get_task_struct(task);
4410 rcu_read_unlock();
4411
4412 if (!task)
4413 return ERR_PTR(-ESRCH);
4414
2ebd4ffb 4415 return task;
2ebd4ffb
MH
4416}
4417
fe4b04fa
PZ
4418/*
4419 * Returns a matching context with refcount and pincount.
4420 */
108b02cf 4421static struct perf_event_context *
4af57ef2
YZ
4422find_get_context(struct pmu *pmu, struct task_struct *task,
4423 struct perf_event *event)
0793a61d 4424{
211de6eb 4425 struct perf_event_context *ctx, *clone_ctx = NULL;
22a4f650 4426 struct perf_cpu_context *cpuctx;
4af57ef2 4427 void *task_ctx_data = NULL;
25346b93 4428 unsigned long flags;
8dc85d54 4429 int ctxn, err;
4af57ef2 4430 int cpu = event->cpu;
0793a61d 4431
22a4ec72 4432 if (!task) {
cdd6c482 4433 /* Must be root to operate on a CPU event: */
da97e184
JFG
4434 err = perf_allow_cpu(&event->attr);
4435 if (err)
4436 return ERR_PTR(err);
0793a61d 4437
108b02cf 4438 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
0793a61d 4439 ctx = &cpuctx->ctx;
c93f7669 4440 get_ctx(ctx);
fe4b04fa 4441 ++ctx->pin_count;
0793a61d 4442
0793a61d
TG
4443 return ctx;
4444 }
4445
8dc85d54
PZ
4446 err = -EINVAL;
4447 ctxn = pmu->task_ctx_nr;
4448 if (ctxn < 0)
4449 goto errout;
4450
4af57ef2
YZ
4451 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4452 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
4453 if (!task_ctx_data) {
4454 err = -ENOMEM;
4455 goto errout;
4456 }
4457 }
4458
9ed6060d 4459retry:
8dc85d54 4460 ctx = perf_lock_task_context(task, ctxn, &flags);
c93f7669 4461 if (ctx) {
211de6eb 4462 clone_ctx = unclone_ctx(ctx);
fe4b04fa 4463 ++ctx->pin_count;
4af57ef2
YZ
4464
4465 if (task_ctx_data && !ctx->task_ctx_data) {
4466 ctx->task_ctx_data = task_ctx_data;
4467 task_ctx_data = NULL;
4468 }
e625cce1 4469 raw_spin_unlock_irqrestore(&ctx->lock, flags);
211de6eb
PZ
4470
4471 if (clone_ctx)
4472 put_ctx(clone_ctx);
9137fb28 4473 } else {
eb184479 4474 ctx = alloc_perf_context(pmu, task);
c93f7669
PM
4475 err = -ENOMEM;
4476 if (!ctx)
4477 goto errout;
eb184479 4478
4af57ef2
YZ
4479 if (task_ctx_data) {
4480 ctx->task_ctx_data = task_ctx_data;
4481 task_ctx_data = NULL;
4482 }
4483
dbe08d82
ON
4484 err = 0;
4485 mutex_lock(&task->perf_event_mutex);
4486 /*
4487 * If it has already passed perf_event_exit_task().
4488 * we must see PF_EXITING, it takes this mutex too.
4489 */
4490 if (task->flags & PF_EXITING)
4491 err = -ESRCH;
4492 else if (task->perf_event_ctxp[ctxn])
4493 err = -EAGAIN;
fe4b04fa 4494 else {
9137fb28 4495 get_ctx(ctx);
fe4b04fa 4496 ++ctx->pin_count;
dbe08d82 4497 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
fe4b04fa 4498 }
dbe08d82
ON
4499 mutex_unlock(&task->perf_event_mutex);
4500
4501 if (unlikely(err)) {
9137fb28 4502 put_ctx(ctx);
dbe08d82
ON
4503
4504 if (err == -EAGAIN)
4505 goto retry;
4506 goto errout;
a63eaf34
PM
4507 }
4508 }
4509
4af57ef2 4510 kfree(task_ctx_data);
0793a61d 4511 return ctx;
c93f7669 4512
9ed6060d 4513errout:
4af57ef2 4514 kfree(task_ctx_data);
c93f7669 4515 return ERR_PTR(err);
0793a61d
TG
4516}
4517
6fb2915d 4518static void perf_event_free_filter(struct perf_event *event);
2541517c 4519static void perf_event_free_bpf_prog(struct perf_event *event);
6fb2915d 4520
cdd6c482 4521static void free_event_rcu(struct rcu_head *head)
592903cd 4522{
cdd6c482 4523 struct perf_event *event;
592903cd 4524
cdd6c482
IM
4525 event = container_of(head, struct perf_event, rcu_head);
4526 if (event->ns)
4527 put_pid_ns(event->ns);
6fb2915d 4528 perf_event_free_filter(event);
cdd6c482 4529 kfree(event);
592903cd
PZ
4530}
4531
b69cf536 4532static void ring_buffer_attach(struct perf_event *event,
56de4e8f 4533 struct perf_buffer *rb);
925d519a 4534
f2fb6bef
KL
4535static void detach_sb_event(struct perf_event *event)
4536{
4537 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4538
4539 raw_spin_lock(&pel->lock);
4540 list_del_rcu(&event->sb_list);
4541 raw_spin_unlock(&pel->lock);
4542}
4543
a4f144eb 4544static bool is_sb_event(struct perf_event *event)
f2fb6bef 4545{
a4f144eb
DCC
4546 struct perf_event_attr *attr = &event->attr;
4547
f2fb6bef 4548 if (event->parent)
a4f144eb 4549 return false;
f2fb6bef
KL
4550
4551 if (event->attach_state & PERF_ATTACH_TASK)
a4f144eb 4552 return false;
f2fb6bef 4553
a4f144eb
DCC
4554 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4555 attr->comm || attr->comm_exec ||
76193a94 4556 attr->task || attr->ksymbol ||
21038f2b
SL
4557 attr->context_switch ||
4558 attr->bpf_event)
a4f144eb
DCC
4559 return true;
4560 return false;
4561}
4562
4563static void unaccount_pmu_sb_event(struct perf_event *event)
4564{
4565 if (is_sb_event(event))
4566 detach_sb_event(event);
f2fb6bef
KL
4567}
4568
4beb31f3 4569static void unaccount_event_cpu(struct perf_event *event, int cpu)
f1600952 4570{
4beb31f3
FW
4571 if (event->parent)
4572 return;
4573
4beb31f3
FW
4574 if (is_cgroup_event(event))
4575 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4576}
925d519a 4577
555e0c1e
FW
4578#ifdef CONFIG_NO_HZ_FULL
4579static DEFINE_SPINLOCK(nr_freq_lock);
4580#endif
4581
4582static void unaccount_freq_event_nohz(void)
4583{
4584#ifdef CONFIG_NO_HZ_FULL
4585 spin_lock(&nr_freq_lock);
4586 if (atomic_dec_and_test(&nr_freq_events))
4587 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4588 spin_unlock(&nr_freq_lock);
4589#endif
4590}
4591
4592static void unaccount_freq_event(void)
4593{
4594 if (tick_nohz_full_enabled())
4595 unaccount_freq_event_nohz();
4596 else
4597 atomic_dec(&nr_freq_events);
4598}
4599
4beb31f3
FW
4600static void unaccount_event(struct perf_event *event)
4601{
25432ae9
PZ
4602 bool dec = false;
4603
4beb31f3
FW
4604 if (event->parent)
4605 return;
4606
4607 if (event->attach_state & PERF_ATTACH_TASK)
25432ae9 4608 dec = true;
4beb31f3
FW
4609 if (event->attr.mmap || event->attr.mmap_data)
4610 atomic_dec(&nr_mmap_events);
4611 if (event->attr.comm)
4612 atomic_dec(&nr_comm_events);
e4222673
HB
4613 if (event->attr.namespaces)
4614 atomic_dec(&nr_namespaces_events);
96aaab68
NK
4615 if (event->attr.cgroup)
4616 atomic_dec(&nr_cgroup_events);
4beb31f3
FW
4617 if (event->attr.task)
4618 atomic_dec(&nr_task_events);
948b26b6 4619 if (event->attr.freq)
555e0c1e 4620 unaccount_freq_event();
45ac1403 4621 if (event->attr.context_switch) {
25432ae9 4622 dec = true;
45ac1403
AH
4623 atomic_dec(&nr_switch_events);
4624 }
4beb31f3 4625 if (is_cgroup_event(event))
25432ae9 4626 dec = true;
4beb31f3 4627 if (has_branch_stack(event))
25432ae9 4628 dec = true;
76193a94
SL
4629 if (event->attr.ksymbol)
4630 atomic_dec(&nr_ksymbol_events);
6ee52e2a
SL
4631 if (event->attr.bpf_event)
4632 atomic_dec(&nr_bpf_events);
25432ae9 4633
9107c89e
PZ
4634 if (dec) {
4635 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4636 schedule_delayed_work(&perf_sched_work, HZ);
4637 }
4beb31f3
FW
4638
4639 unaccount_event_cpu(event, event->cpu);
f2fb6bef
KL
4640
4641 unaccount_pmu_sb_event(event);
4beb31f3 4642}
925d519a 4643
9107c89e
PZ
4644static void perf_sched_delayed(struct work_struct *work)
4645{
4646 mutex_lock(&perf_sched_mutex);
4647 if (atomic_dec_and_test(&perf_sched_count))
4648 static_branch_disable(&perf_sched_events);
4649 mutex_unlock(&perf_sched_mutex);
4650}
4651
bed5b25a
AS
4652/*
4653 * The following implement mutual exclusion of events on "exclusive" pmus
4654 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4655 * at a time, so we disallow creating events that might conflict, namely:
4656 *
4657 * 1) cpu-wide events in the presence of per-task events,
4658 * 2) per-task events in the presence of cpu-wide events,
4659 * 3) two matching events on the same context.
4660 *
4661 * The former two cases are handled in the allocation path (perf_event_alloc(),
a0733e69 4662 * _free_event()), the latter -- before the first perf_install_in_context().
bed5b25a
AS
4663 */
4664static int exclusive_event_init(struct perf_event *event)
4665{
4666 struct pmu *pmu = event->pmu;
4667
8a58ddae 4668 if (!is_exclusive_pmu(pmu))
bed5b25a
AS
4669 return 0;
4670
4671 /*
4672 * Prevent co-existence of per-task and cpu-wide events on the
4673 * same exclusive pmu.
4674 *
4675 * Negative pmu::exclusive_cnt means there are cpu-wide
4676 * events on this "exclusive" pmu, positive means there are
4677 * per-task events.
4678 *
4679 * Since this is called in perf_event_alloc() path, event::ctx
4680 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4681 * to mean "per-task event", because unlike other attach states it
4682 * never gets cleared.
4683 */
4684 if (event->attach_state & PERF_ATTACH_TASK) {
4685 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4686 return -EBUSY;
4687 } else {
4688 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4689 return -EBUSY;
4690 }
4691
4692 return 0;
4693}
4694
4695static void exclusive_event_destroy(struct perf_event *event)
4696{
4697 struct pmu *pmu = event->pmu;
4698
8a58ddae 4699 if (!is_exclusive_pmu(pmu))
bed5b25a
AS
4700 return;
4701
4702 /* see comment in exclusive_event_init() */
4703 if (event->attach_state & PERF_ATTACH_TASK)
4704 atomic_dec(&pmu->exclusive_cnt);
4705 else
4706 atomic_inc(&pmu->exclusive_cnt);
4707}
4708
4709static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4710{
3bf6215a 4711 if ((e1->pmu == e2->pmu) &&
bed5b25a
AS
4712 (e1->cpu == e2->cpu ||
4713 e1->cpu == -1 ||
4714 e2->cpu == -1))
4715 return true;
4716 return false;
4717}
4718
bed5b25a
AS
4719static bool exclusive_event_installable(struct perf_event *event,
4720 struct perf_event_context *ctx)
4721{
4722 struct perf_event *iter_event;
4723 struct pmu *pmu = event->pmu;
4724
8a58ddae
AS
4725 lockdep_assert_held(&ctx->mutex);
4726
4727 if (!is_exclusive_pmu(pmu))
bed5b25a
AS
4728 return true;
4729
4730 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4731 if (exclusive_event_match(iter_event, event))
4732 return false;
4733 }
4734
4735 return true;
4736}
4737
375637bc
AS
4738static void perf_addr_filters_splice(struct perf_event *event,
4739 struct list_head *head);
4740
683ede43 4741static void _free_event(struct perf_event *event)
f1600952 4742{
e360adbe 4743 irq_work_sync(&event->pending);
925d519a 4744
4beb31f3 4745 unaccount_event(event);
9ee318a7 4746
da97e184
JFG
4747 security_perf_event_free(event);
4748
76369139 4749 if (event->rb) {
9bb5d40c
PZ
4750 /*
4751 * Can happen when we close an event with re-directed output.
4752 *
4753 * Since we have a 0 refcount, perf_mmap_close() will skip
4754 * over us; possibly making our ring_buffer_put() the last.
4755 */
4756 mutex_lock(&event->mmap_mutex);
b69cf536 4757 ring_buffer_attach(event, NULL);
9bb5d40c 4758 mutex_unlock(&event->mmap_mutex);
a4be7c27
PZ
4759 }
4760
e5d1367f
SE
4761 if (is_cgroup_event(event))
4762 perf_detach_cgroup(event);
4763
a0733e69
PZ
4764 if (!event->parent) {
4765 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4766 put_callchain_buffers();
4767 }
4768
4769 perf_event_free_bpf_prog(event);
375637bc 4770 perf_addr_filters_splice(event, NULL);
c60f83b8 4771 kfree(event->addr_filter_ranges);
a0733e69
PZ
4772
4773 if (event->destroy)
4774 event->destroy(event);
4775
1cf8dfe8
PZ
4776 /*
4777 * Must be after ->destroy(), due to uprobe_perf_close() using
4778 * hw.target.
4779 */
621b6d2e
PB
4780 if (event->hw.target)
4781 put_task_struct(event->hw.target);
4782
1cf8dfe8
PZ
4783 /*
4784 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4785 * all task references must be cleaned up.
4786 */
4787 if (event->ctx)
4788 put_ctx(event->ctx);
4789
62a92c8f
AS
4790 exclusive_event_destroy(event);
4791 module_put(event->pmu->module);
a0733e69
PZ
4792
4793 call_rcu(&event->rcu_head, free_event_rcu);
f1600952
PZ
4794}
4795
683ede43
PZ
4796/*
4797 * Used to free events which have a known refcount of 1, such as in error paths
4798 * where the event isn't exposed yet and inherited events.
4799 */
4800static void free_event(struct perf_event *event)
0793a61d 4801{
683ede43
PZ
4802 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4803 "unexpected event refcount: %ld; ptr=%p\n",
4804 atomic_long_read(&event->refcount), event)) {
4805 /* leak to avoid use-after-free */
4806 return;
4807 }
0793a61d 4808
683ede43 4809 _free_event(event);
0793a61d
TG
4810}
4811
a66a3052 4812/*
f8697762 4813 * Remove user event from the owner task.
a66a3052 4814 */
f8697762 4815static void perf_remove_from_owner(struct perf_event *event)
fb0459d7 4816{
8882135b 4817 struct task_struct *owner;
fb0459d7 4818
8882135b 4819 rcu_read_lock();
8882135b 4820 /*
f47c02c0
PZ
4821 * Matches the smp_store_release() in perf_event_exit_task(). If we
4822 * observe !owner it means the list deletion is complete and we can
4823 * indeed free this event, otherwise we need to serialize on
8882135b
PZ
4824 * owner->perf_event_mutex.
4825 */
506458ef 4826 owner = READ_ONCE(event->owner);
8882135b
PZ
4827 if (owner) {
4828 /*
4829 * Since delayed_put_task_struct() also drops the last
4830 * task reference we can safely take a new reference
4831 * while holding the rcu_read_lock().
4832 */
4833 get_task_struct(owner);
4834 }
4835 rcu_read_unlock();
4836
4837 if (owner) {
f63a8daa
PZ
4838 /*
4839 * If we're here through perf_event_exit_task() we're already
4840 * holding ctx->mutex which would be an inversion wrt. the
4841 * normal lock order.
4842 *
4843 * However we can safely take this lock because its the child
4844 * ctx->mutex.
4845 */
4846 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4847
8882135b
PZ
4848 /*
4849 * We have to re-check the event->owner field, if it is cleared
4850 * we raced with perf_event_exit_task(), acquiring the mutex
4851 * ensured they're done, and we can proceed with freeing the
4852 * event.
4853 */
f47c02c0 4854 if (event->owner) {
8882135b 4855 list_del_init(&event->owner_entry);
f47c02c0
PZ
4856 smp_store_release(&event->owner, NULL);
4857 }
8882135b
PZ
4858 mutex_unlock(&owner->perf_event_mutex);
4859 put_task_struct(owner);
4860 }
f8697762
JO
4861}
4862
f8697762
JO
4863static void put_event(struct perf_event *event)
4864{
f8697762
JO
4865 if (!atomic_long_dec_and_test(&event->refcount))
4866 return;
4867
c6e5b732
PZ
4868 _free_event(event);
4869}
4870
4871/*
4872 * Kill an event dead; while event:refcount will preserve the event
4873 * object, it will not preserve its functionality. Once the last 'user'
4874 * gives up the object, we'll destroy the thing.
4875 */
4876int perf_event_release_kernel(struct perf_event *event)
4877{
a4f4bb6d 4878 struct perf_event_context *ctx = event->ctx;
c6e5b732 4879 struct perf_event *child, *tmp;
82d94856 4880 LIST_HEAD(free_list);
c6e5b732 4881
a4f4bb6d
PZ
4882 /*
4883 * If we got here through err_file: fput(event_file); we will not have
4884 * attached to a context yet.
4885 */
4886 if (!ctx) {
4887 WARN_ON_ONCE(event->attach_state &
4888 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4889 goto no_ctx;
4890 }
4891
f8697762
JO
4892 if (!is_kernel_event(event))
4893 perf_remove_from_owner(event);
8882135b 4894
5fa7c8ec 4895 ctx = perf_event_ctx_lock(event);
a83fe28e 4896 WARN_ON_ONCE(ctx->parent_ctx);
a69b0ca4 4897 perf_remove_from_context(event, DETACH_GROUP);
683ede43 4898
a69b0ca4 4899 raw_spin_lock_irq(&ctx->lock);
683ede43 4900 /*
d8a8cfc7 4901 * Mark this event as STATE_DEAD, there is no external reference to it
a69b0ca4 4902 * anymore.
683ede43 4903 *
a69b0ca4
PZ
4904 * Anybody acquiring event->child_mutex after the below loop _must_
4905 * also see this, most importantly inherit_event() which will avoid
4906 * placing more children on the list.
683ede43 4907 *
c6e5b732
PZ
4908 * Thus this guarantees that we will in fact observe and kill _ALL_
4909 * child events.
683ede43 4910 */
a69b0ca4
PZ
4911 event->state = PERF_EVENT_STATE_DEAD;
4912 raw_spin_unlock_irq(&ctx->lock);
4913
4914 perf_event_ctx_unlock(event, ctx);
683ede43 4915
c6e5b732
PZ
4916again:
4917 mutex_lock(&event->child_mutex);
4918 list_for_each_entry(child, &event->child_list, child_list) {
a6fa941d 4919
c6e5b732
PZ
4920 /*
4921 * Cannot change, child events are not migrated, see the
4922 * comment with perf_event_ctx_lock_nested().
4923 */
506458ef 4924 ctx = READ_ONCE(child->ctx);
c6e5b732
PZ
4925 /*
4926 * Since child_mutex nests inside ctx::mutex, we must jump
4927 * through hoops. We start by grabbing a reference on the ctx.
4928 *
4929 * Since the event cannot get freed while we hold the
4930 * child_mutex, the context must also exist and have a !0
4931 * reference count.
4932 */
4933 get_ctx(ctx);
4934
4935 /*
4936 * Now that we have a ctx ref, we can drop child_mutex, and
4937 * acquire ctx::mutex without fear of it going away. Then we
4938 * can re-acquire child_mutex.
4939 */
4940 mutex_unlock(&event->child_mutex);
4941 mutex_lock(&ctx->mutex);
4942 mutex_lock(&event->child_mutex);
4943
4944 /*
4945 * Now that we hold ctx::mutex and child_mutex, revalidate our
4946 * state, if child is still the first entry, it didn't get freed
4947 * and we can continue doing so.
4948 */
4949 tmp = list_first_entry_or_null(&event->child_list,
4950 struct perf_event, child_list);
4951 if (tmp == child) {
4952 perf_remove_from_context(child, DETACH_GROUP);
82d94856 4953 list_move(&child->child_list, &free_list);
c6e5b732
PZ
4954 /*
4955 * This matches the refcount bump in inherit_event();
4956 * this can't be the last reference.
4957 */
4958 put_event(event);
4959 }
4960
4961 mutex_unlock(&event->child_mutex);
4962 mutex_unlock(&ctx->mutex);
4963 put_ctx(ctx);
4964 goto again;
4965 }
4966 mutex_unlock(&event->child_mutex);
4967
82d94856 4968 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
1cf8dfe8
PZ
4969 void *var = &child->ctx->refcount;
4970
82d94856
PZ
4971 list_del(&child->child_list);
4972 free_event(child);
1cf8dfe8
PZ
4973
4974 /*
4975 * Wake any perf_event_free_task() waiting for this event to be
4976 * freed.
4977 */
4978 smp_mb(); /* pairs with wait_var_event() */
4979 wake_up_var(var);
82d94856
PZ
4980 }
4981
a4f4bb6d
PZ
4982no_ctx:
4983 put_event(event); /* Must be the 'last' reference */
683ede43
PZ
4984 return 0;
4985}
4986EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4987
8b10c5e2
PZ
4988/*
4989 * Called when the last reference to the file is gone.
4990 */
a6fa941d
AV
4991static int perf_release(struct inode *inode, struct file *file)
4992{
c6e5b732 4993 perf_event_release_kernel(file->private_data);
a6fa941d 4994 return 0;
fb0459d7 4995}
fb0459d7 4996
ca0dd44c 4997static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
e53c0994 4998{
cdd6c482 4999 struct perf_event *child;
e53c0994
PZ
5000 u64 total = 0;
5001
59ed446f
PZ
5002 *enabled = 0;
5003 *running = 0;
5004
6f10581a 5005 mutex_lock(&event->child_mutex);
01add3ea 5006
7d88962e 5007 (void)perf_event_read(event, false);
01add3ea
SB
5008 total += perf_event_count(event);
5009
59ed446f
PZ
5010 *enabled += event->total_time_enabled +
5011 atomic64_read(&event->child_total_time_enabled);
5012 *running += event->total_time_running +
5013 atomic64_read(&event->child_total_time_running);
5014
5015 list_for_each_entry(child, &event->child_list, child_list) {
7d88962e 5016 (void)perf_event_read(child, false);
01add3ea 5017 total += perf_event_count(child);
59ed446f
PZ
5018 *enabled += child->total_time_enabled;
5019 *running += child->total_time_running;
5020 }
6f10581a 5021 mutex_unlock(&event->child_mutex);
e53c0994
PZ
5022
5023 return total;
5024}
ca0dd44c
PZ
5025
5026u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
5027{
5028 struct perf_event_context *ctx;
5029 u64 count;
5030
5031 ctx = perf_event_ctx_lock(event);
5032 count = __perf_event_read_value(event, enabled, running);
5033 perf_event_ctx_unlock(event, ctx);
5034
5035 return count;
5036}
fb0459d7 5037EXPORT_SYMBOL_GPL(perf_event_read_value);
e53c0994 5038
7d88962e 5039static int __perf_read_group_add(struct perf_event *leader,
fa8c2693 5040 u64 read_format, u64 *values)
3dab77fb 5041{
2aeb1883 5042 struct perf_event_context *ctx = leader->ctx;
fa8c2693 5043 struct perf_event *sub;
2aeb1883 5044 unsigned long flags;
fa8c2693 5045 int n = 1; /* skip @nr */
7d88962e 5046 int ret;
f63a8daa 5047
7d88962e
SB
5048 ret = perf_event_read(leader, true);
5049 if (ret)
5050 return ret;
abf4868b 5051
a9cd8194
PZ
5052 raw_spin_lock_irqsave(&ctx->lock, flags);
5053
fa8c2693
PZ
5054 /*
5055 * Since we co-schedule groups, {enabled,running} times of siblings
5056 * will be identical to those of the leader, so we only publish one
5057 * set.
5058 */
5059 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
5060 values[n++] += leader->total_time_enabled +
5061 atomic64_read(&leader->child_total_time_enabled);
5062 }
3dab77fb 5063
fa8c2693
PZ
5064 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
5065 values[n++] += leader->total_time_running +
5066 atomic64_read(&leader->child_total_time_running);
5067 }
5068
5069 /*
5070 * Write {count,id} tuples for every sibling.
5071 */
5072 values[n++] += perf_event_count(leader);
abf4868b
PZ
5073 if (read_format & PERF_FORMAT_ID)
5074 values[n++] = primary_event_id(leader);
3dab77fb 5075
edb39592 5076 for_each_sibling_event(sub, leader) {
fa8c2693
PZ
5077 values[n++] += perf_event_count(sub);
5078 if (read_format & PERF_FORMAT_ID)
5079 values[n++] = primary_event_id(sub);
5080 }
7d88962e 5081
2aeb1883 5082 raw_spin_unlock_irqrestore(&ctx->lock, flags);
7d88962e 5083 return 0;
fa8c2693 5084}
3dab77fb 5085
fa8c2693
PZ
5086static int perf_read_group(struct perf_event *event,
5087 u64 read_format, char __user *buf)
5088{
5089 struct perf_event *leader = event->group_leader, *child;
5090 struct perf_event_context *ctx = leader->ctx;
7d88962e 5091 int ret;
fa8c2693 5092 u64 *values;
3dab77fb 5093
fa8c2693 5094 lockdep_assert_held(&ctx->mutex);
3dab77fb 5095
fa8c2693
PZ
5096 values = kzalloc(event->read_size, GFP_KERNEL);
5097 if (!values)
5098 return -ENOMEM;
3dab77fb 5099
fa8c2693
PZ
5100 values[0] = 1 + leader->nr_siblings;
5101
5102 /*
5103 * By locking the child_mutex of the leader we effectively
5104 * lock the child list of all siblings.. XXX explain how.
5105 */
5106 mutex_lock(&leader->child_mutex);
abf4868b 5107
7d88962e
SB
5108 ret = __perf_read_group_add(leader, read_format, values);
5109 if (ret)
5110 goto unlock;
5111
5112 list_for_each_entry(child, &leader->child_list, child_list) {
5113 ret = __perf_read_group_add(child, read_format, values);
5114 if (ret)
5115 goto unlock;
5116 }
abf4868b 5117
fa8c2693 5118 mutex_unlock(&leader->child_mutex);
abf4868b 5119
7d88962e 5120 ret = event->read_size;
fa8c2693
PZ
5121 if (copy_to_user(buf, values, event->read_size))
5122 ret = -EFAULT;
7d88962e 5123 goto out;
fa8c2693 5124
7d88962e
SB
5125unlock:
5126 mutex_unlock(&leader->child_mutex);
5127out:
fa8c2693 5128 kfree(values);
abf4868b 5129 return ret;
3dab77fb
PZ
5130}
5131
b15f495b 5132static int perf_read_one(struct perf_event *event,
3dab77fb
PZ
5133 u64 read_format, char __user *buf)
5134{
59ed446f 5135 u64 enabled, running;
3dab77fb
PZ
5136 u64 values[4];
5137 int n = 0;
5138
ca0dd44c 5139 values[n++] = __perf_event_read_value(event, &enabled, &running);
59ed446f
PZ
5140 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
5141 values[n++] = enabled;
5142 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5143 values[n++] = running;
3dab77fb 5144 if (read_format & PERF_FORMAT_ID)
cdd6c482 5145 values[n++] = primary_event_id(event);
3dab77fb
PZ
5146
5147 if (copy_to_user(buf, values, n * sizeof(u64)))
5148 return -EFAULT;
5149
5150 return n * sizeof(u64);
5151}
5152
dc633982
JO
5153static bool is_event_hup(struct perf_event *event)
5154{
5155 bool no_children;
5156
a69b0ca4 5157 if (event->state > PERF_EVENT_STATE_EXIT)
dc633982
JO
5158 return false;
5159
5160 mutex_lock(&event->child_mutex);
5161 no_children = list_empty(&event->child_list);
5162 mutex_unlock(&event->child_mutex);
5163 return no_children;
5164}
5165
0793a61d 5166/*
cdd6c482 5167 * Read the performance event - simple non blocking version for now
0793a61d
TG
5168 */
5169static ssize_t
b15f495b 5170__perf_read(struct perf_event *event, char __user *buf, size_t count)
0793a61d 5171{
cdd6c482 5172 u64 read_format = event->attr.read_format;
3dab77fb 5173 int ret;
0793a61d 5174
3b6f9e5c 5175 /*
788faab7 5176 * Return end-of-file for a read on an event that is in
3b6f9e5c
PM
5177 * error state (i.e. because it was pinned but it couldn't be
5178 * scheduled on to the CPU at some point).
5179 */
cdd6c482 5180 if (event->state == PERF_EVENT_STATE_ERROR)
3b6f9e5c
PM
5181 return 0;
5182
c320c7b7 5183 if (count < event->read_size)
3dab77fb
PZ
5184 return -ENOSPC;
5185
cdd6c482 5186 WARN_ON_ONCE(event->ctx->parent_ctx);
3dab77fb 5187 if (read_format & PERF_FORMAT_GROUP)
b15f495b 5188 ret = perf_read_group(event, read_format, buf);
3dab77fb 5189 else
b15f495b 5190 ret = perf_read_one(event, read_format, buf);
0793a61d 5191
3dab77fb 5192 return ret;
0793a61d
TG
5193}
5194
0793a61d
TG
5195static ssize_t
5196perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5197{
cdd6c482 5198 struct perf_event *event = file->private_data;
f63a8daa
PZ
5199 struct perf_event_context *ctx;
5200 int ret;
0793a61d 5201
da97e184
JFG
5202 ret = security_perf_event_read(event);
5203 if (ret)
5204 return ret;
5205
f63a8daa 5206 ctx = perf_event_ctx_lock(event);
b15f495b 5207 ret = __perf_read(event, buf, count);
f63a8daa
PZ
5208 perf_event_ctx_unlock(event, ctx);
5209
5210 return ret;
0793a61d
TG
5211}
5212
9dd95748 5213static __poll_t perf_poll(struct file *file, poll_table *wait)
0793a61d 5214{
cdd6c482 5215 struct perf_event *event = file->private_data;
56de4e8f 5216 struct perf_buffer *rb;
a9a08845 5217 __poll_t events = EPOLLHUP;
c7138f37 5218
e708d7ad 5219 poll_wait(file, &event->waitq, wait);
179033b3 5220
dc633982 5221 if (is_event_hup(event))
179033b3 5222 return events;
c7138f37 5223
10c6db11 5224 /*
9bb5d40c
PZ
5225 * Pin the event->rb by taking event->mmap_mutex; otherwise
5226 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
10c6db11
PZ
5227 */
5228 mutex_lock(&event->mmap_mutex);
9bb5d40c
PZ
5229 rb = event->rb;
5230 if (rb)
76369139 5231 events = atomic_xchg(&rb->poll, 0);
10c6db11 5232 mutex_unlock(&event->mmap_mutex);
0793a61d
TG
5233 return events;
5234}
5235
f63a8daa 5236static void _perf_event_reset(struct perf_event *event)
6de6a7b9 5237{
7d88962e 5238 (void)perf_event_read(event, false);
e7850595 5239 local64_set(&event->count, 0);
cdd6c482 5240 perf_event_update_userpage(event);
3df5edad
PZ
5241}
5242
52ba4b0b
LX
5243/* Assume it's not an event with inherit set. */
5244u64 perf_event_pause(struct perf_event *event, bool reset)
5245{
5246 struct perf_event_context *ctx;
5247 u64 count;
5248
5249 ctx = perf_event_ctx_lock(event);
5250 WARN_ON_ONCE(event->attr.inherit);
5251 _perf_event_disable(event);
5252 count = local64_read(&event->count);
5253 if (reset)
5254 local64_set(&event->count, 0);
5255 perf_event_ctx_unlock(event, ctx);
5256
5257 return count;
5258}
5259EXPORT_SYMBOL_GPL(perf_event_pause);
5260
c93f7669 5261/*
cdd6c482
IM
5262 * Holding the top-level event's child_mutex means that any
5263 * descendant process that has inherited this event will block
8ba289b8 5264 * in perf_event_exit_event() if it goes to exit, thus satisfying the
cdd6c482 5265 * task existence requirements of perf_event_enable/disable.
c93f7669 5266 */
cdd6c482
IM
5267static void perf_event_for_each_child(struct perf_event *event,
5268 void (*func)(struct perf_event *))
3df5edad 5269{
cdd6c482 5270 struct perf_event *child;
3df5edad 5271
cdd6c482 5272 WARN_ON_ONCE(event->ctx->parent_ctx);
f63a8daa 5273
cdd6c482
IM
5274 mutex_lock(&event->child_mutex);
5275 func(event);
5276 list_for_each_entry(child, &event->child_list, child_list)
3df5edad 5277 func(child);
cdd6c482 5278 mutex_unlock(&event->child_mutex);
3df5edad
PZ
5279}
5280
cdd6c482
IM
5281static void perf_event_for_each(struct perf_event *event,
5282 void (*func)(struct perf_event *))
3df5edad 5283{
cdd6c482
IM
5284 struct perf_event_context *ctx = event->ctx;
5285 struct perf_event *sibling;
3df5edad 5286
f63a8daa
PZ
5287 lockdep_assert_held(&ctx->mutex);
5288
cdd6c482 5289 event = event->group_leader;
75f937f2 5290
cdd6c482 5291 perf_event_for_each_child(event, func);
edb39592 5292 for_each_sibling_event(sibling, event)
724b6daa 5293 perf_event_for_each_child(sibling, func);
6de6a7b9
PZ
5294}
5295
fae3fde6
PZ
5296static void __perf_event_period(struct perf_event *event,
5297 struct perf_cpu_context *cpuctx,
5298 struct perf_event_context *ctx,
5299 void *info)
c7999c6f 5300{
fae3fde6 5301 u64 value = *((u64 *)info);
c7999c6f 5302 bool active;
08247e31 5303
cdd6c482 5304 if (event->attr.freq) {
cdd6c482 5305 event->attr.sample_freq = value;
08247e31 5306 } else {
cdd6c482
IM
5307 event->attr.sample_period = value;
5308 event->hw.sample_period = value;
08247e31 5309 }
bad7192b
PZ
5310
5311 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5312 if (active) {
5313 perf_pmu_disable(ctx->pmu);
1e02cd40
PZ
5314 /*
5315 * We could be throttled; unthrottle now to avoid the tick
5316 * trying to unthrottle while we already re-started the event.
5317 */
5318 if (event->hw.interrupts == MAX_INTERRUPTS) {
5319 event->hw.interrupts = 0;
5320 perf_log_throttle(event, 1);
5321 }
bad7192b
PZ
5322 event->pmu->stop(event, PERF_EF_UPDATE);
5323 }
5324
5325 local64_set(&event->hw.period_left, 0);
5326
5327 if (active) {
5328 event->pmu->start(event, PERF_EF_RELOAD);
5329 perf_pmu_enable(ctx->pmu);
5330 }
c7999c6f
PZ
5331}
5332
81ec3f3c
JO
5333static int perf_event_check_period(struct perf_event *event, u64 value)
5334{
5335 return event->pmu->check_period(event, value);
5336}
5337
3ca270fc 5338static int _perf_event_period(struct perf_event *event, u64 value)
c7999c6f 5339{
c7999c6f
PZ
5340 if (!is_sampling_event(event))
5341 return -EINVAL;
5342
c7999c6f
PZ
5343 if (!value)
5344 return -EINVAL;
5345
5346 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5347 return -EINVAL;
5348
81ec3f3c
JO
5349 if (perf_event_check_period(event, value))
5350 return -EINVAL;
5351
913a90bc
RB
5352 if (!event->attr.freq && (value & (1ULL << 63)))
5353 return -EINVAL;
5354
fae3fde6 5355 event_function_call(event, __perf_event_period, &value);
08247e31 5356
c7999c6f 5357 return 0;
08247e31
PZ
5358}
5359
3ca270fc
LX
5360int perf_event_period(struct perf_event *event, u64 value)
5361{
5362 struct perf_event_context *ctx;
5363 int ret;
5364
5365 ctx = perf_event_ctx_lock(event);
5366 ret = _perf_event_period(event, value);
5367 perf_event_ctx_unlock(event, ctx);
5368
5369 return ret;
5370}
5371EXPORT_SYMBOL_GPL(perf_event_period);
5372
ac9721f3
PZ
5373static const struct file_operations perf_fops;
5374
2903ff01 5375static inline int perf_fget_light(int fd, struct fd *p)
ac9721f3 5376{
2903ff01
AV
5377 struct fd f = fdget(fd);
5378 if (!f.file)
5379 return -EBADF;
ac9721f3 5380
2903ff01
AV
5381 if (f.file->f_op != &perf_fops) {
5382 fdput(f);
5383 return -EBADF;
ac9721f3 5384 }
2903ff01
AV
5385 *p = f;
5386 return 0;
ac9721f3
PZ
5387}
5388
5389static int perf_event_set_output(struct perf_event *event,
5390 struct perf_event *output_event);
6fb2915d 5391static int perf_event_set_filter(struct perf_event *event, void __user *arg);
2541517c 5392static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
32ff77e8
MC
5393static int perf_copy_attr(struct perf_event_attr __user *uattr,
5394 struct perf_event_attr *attr);
a4be7c27 5395
f63a8daa 5396static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
d859e29f 5397{
cdd6c482 5398 void (*func)(struct perf_event *);
3df5edad 5399 u32 flags = arg;
d859e29f
PM
5400
5401 switch (cmd) {
cdd6c482 5402 case PERF_EVENT_IOC_ENABLE:
f63a8daa 5403 func = _perf_event_enable;
d859e29f 5404 break;
cdd6c482 5405 case PERF_EVENT_IOC_DISABLE:
f63a8daa 5406 func = _perf_event_disable;
79f14641 5407 break;
cdd6c482 5408 case PERF_EVENT_IOC_RESET:
f63a8daa 5409 func = _perf_event_reset;
6de6a7b9 5410 break;
3df5edad 5411
cdd6c482 5412 case PERF_EVENT_IOC_REFRESH:
f63a8daa 5413 return _perf_event_refresh(event, arg);
08247e31 5414
cdd6c482 5415 case PERF_EVENT_IOC_PERIOD:
3ca270fc
LX
5416 {
5417 u64 value;
08247e31 5418
3ca270fc
LX
5419 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value)))
5420 return -EFAULT;
08247e31 5421
3ca270fc
LX
5422 return _perf_event_period(event, value);
5423 }
cf4957f1
JO
5424 case PERF_EVENT_IOC_ID:
5425 {
5426 u64 id = primary_event_id(event);
5427
5428 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5429 return -EFAULT;
5430 return 0;
5431 }
5432
cdd6c482 5433 case PERF_EVENT_IOC_SET_OUTPUT:
ac9721f3 5434 {
ac9721f3 5435 int ret;
ac9721f3 5436 if (arg != -1) {
2903ff01
AV
5437 struct perf_event *output_event;
5438 struct fd output;
5439 ret = perf_fget_light(arg, &output);
5440 if (ret)
5441 return ret;
5442 output_event = output.file->private_data;
5443 ret = perf_event_set_output(event, output_event);
5444 fdput(output);
5445 } else {
5446 ret = perf_event_set_output(event, NULL);
ac9721f3 5447 }
ac9721f3
PZ
5448 return ret;
5449 }
a4be7c27 5450
6fb2915d
LZ
5451 case PERF_EVENT_IOC_SET_FILTER:
5452 return perf_event_set_filter(event, (void __user *)arg);
5453
2541517c
AS
5454 case PERF_EVENT_IOC_SET_BPF:
5455 return perf_event_set_bpf_prog(event, arg);
5456
86e7972f 5457 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
56de4e8f 5458 struct perf_buffer *rb;
86e7972f
WN
5459
5460 rcu_read_lock();
5461 rb = rcu_dereference(event->rb);
5462 if (!rb || !rb->nr_pages) {
5463 rcu_read_unlock();
5464 return -EINVAL;
5465 }
5466 rb_toggle_paused(rb, !!arg);
5467 rcu_read_unlock();
5468 return 0;
5469 }
f371b304
YS
5470
5471 case PERF_EVENT_IOC_QUERY_BPF:
f4e2298e 5472 return perf_event_query_prog_array(event, (void __user *)arg);
32ff77e8
MC
5473
5474 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5475 struct perf_event_attr new_attr;
5476 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5477 &new_attr);
5478
5479 if (err)
5480 return err;
5481
5482 return perf_event_modify_attr(event, &new_attr);
5483 }
d859e29f 5484 default:
3df5edad 5485 return -ENOTTY;
d859e29f 5486 }
3df5edad
PZ
5487
5488 if (flags & PERF_IOC_FLAG_GROUP)
cdd6c482 5489 perf_event_for_each(event, func);
3df5edad 5490 else
cdd6c482 5491 perf_event_for_each_child(event, func);
3df5edad
PZ
5492
5493 return 0;
d859e29f
PM
5494}
5495
f63a8daa
PZ
5496static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5497{
5498 struct perf_event *event = file->private_data;
5499 struct perf_event_context *ctx;
5500 long ret;
5501
da97e184
JFG
5502 /* Treat ioctl like writes as it is likely a mutating operation. */
5503 ret = security_perf_event_write(event);
5504 if (ret)
5505 return ret;
5506
f63a8daa
PZ
5507 ctx = perf_event_ctx_lock(event);
5508 ret = _perf_ioctl(event, cmd, arg);
5509 perf_event_ctx_unlock(event, ctx);
5510
5511 return ret;
5512}
5513
b3f20785
PM
5514#ifdef CONFIG_COMPAT
5515static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5516 unsigned long arg)
5517{
5518 switch (_IOC_NR(cmd)) {
5519 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5520 case _IOC_NR(PERF_EVENT_IOC_ID):
82489c5f
ES
5521 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5522 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
b3f20785
PM
5523 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5524 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5525 cmd &= ~IOCSIZE_MASK;
5526 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5527 }
5528 break;
5529 }
5530 return perf_ioctl(file, cmd, arg);
5531}
5532#else
5533# define perf_compat_ioctl NULL
5534#endif
5535
cdd6c482 5536int perf_event_task_enable(void)
771d7cde 5537{
f63a8daa 5538 struct perf_event_context *ctx;
cdd6c482 5539 struct perf_event *event;
771d7cde 5540
cdd6c482 5541 mutex_lock(&current->perf_event_mutex);
f63a8daa
PZ
5542 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5543 ctx = perf_event_ctx_lock(event);
5544 perf_event_for_each_child(event, _perf_event_enable);
5545 perf_event_ctx_unlock(event, ctx);
5546 }
cdd6c482 5547 mutex_unlock(&current->perf_event_mutex);
771d7cde
PZ
5548
5549 return 0;
5550}
5551
cdd6c482 5552int perf_event_task_disable(void)
771d7cde 5553{
f63a8daa 5554 struct perf_event_context *ctx;
cdd6c482 5555 struct perf_event *event;
771d7cde 5556
cdd6c482 5557 mutex_lock(&current->perf_event_mutex);
f63a8daa
PZ
5558 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
5559 ctx = perf_event_ctx_lock(event);
5560 perf_event_for_each_child(event, _perf_event_disable);
5561 perf_event_ctx_unlock(event, ctx);
5562 }
cdd6c482 5563 mutex_unlock(&current->perf_event_mutex);
771d7cde
PZ
5564
5565 return 0;
5566}
5567
cdd6c482 5568static int perf_event_index(struct perf_event *event)
194002b2 5569{
a4eaf7f1
PZ
5570 if (event->hw.state & PERF_HES_STOPPED)
5571 return 0;
5572
cdd6c482 5573 if (event->state != PERF_EVENT_STATE_ACTIVE)
194002b2
PZ
5574 return 0;
5575
35edc2a5 5576 return event->pmu->event_idx(event);
194002b2
PZ
5577}
5578
c4794295 5579static void calc_timer_values(struct perf_event *event,
e3f3541c 5580 u64 *now,
7f310a5d
EM
5581 u64 *enabled,
5582 u64 *running)
c4794295 5583{
e3f3541c 5584 u64 ctx_time;
c4794295 5585
e3f3541c
PZ
5586 *now = perf_clock();
5587 ctx_time = event->shadow_ctx_time + *now;
0d3d73aa 5588 __perf_update_times(event, ctx_time, enabled, running);
c4794295
EM
5589}
5590
fa731587
PZ
5591static void perf_event_init_userpage(struct perf_event *event)
5592{
5593 struct perf_event_mmap_page *userpg;
56de4e8f 5594 struct perf_buffer *rb;
fa731587
PZ
5595
5596 rcu_read_lock();
5597 rb = rcu_dereference(event->rb);
5598 if (!rb)
5599 goto unlock;
5600
5601 userpg = rb->user_page;
5602
5603 /* Allow new userspace to detect that bit 0 is deprecated */
5604 userpg->cap_bit0_is_deprecated = 1;
5605 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
e8c6deac
AS
5606 userpg->data_offset = PAGE_SIZE;
5607 userpg->data_size = perf_data_size(rb);
fa731587
PZ
5608
5609unlock:
5610 rcu_read_unlock();
5611}
5612
c1317ec2
AL
5613void __weak arch_perf_update_userpage(
5614 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
e3f3541c
PZ
5615{
5616}
5617
38ff667b
PZ
5618/*
5619 * Callers need to ensure there can be no nesting of this function, otherwise
5620 * the seqlock logic goes bad. We can not serialize this because the arch
5621 * code calls this from NMI context.
5622 */
cdd6c482 5623void perf_event_update_userpage(struct perf_event *event)
37d81828 5624{
cdd6c482 5625 struct perf_event_mmap_page *userpg;
56de4e8f 5626 struct perf_buffer *rb;
e3f3541c 5627 u64 enabled, running, now;
38ff667b
PZ
5628
5629 rcu_read_lock();
5ec4c599
PZ
5630 rb = rcu_dereference(event->rb);
5631 if (!rb)
5632 goto unlock;
5633
0d641208
EM
5634 /*
5635 * compute total_time_enabled, total_time_running
5636 * based on snapshot values taken when the event
5637 * was last scheduled in.
5638 *
5639 * we cannot simply called update_context_time()
5640 * because of locking issue as we can be called in
5641 * NMI context
5642 */
e3f3541c 5643 calc_timer_values(event, &now, &enabled, &running);
38ff667b 5644
76369139 5645 userpg = rb->user_page;
7b732a75 5646 /*
9d2dcc8f
MF
5647 * Disable preemption to guarantee consistent time stamps are stored to
5648 * the user page.
7b732a75
PZ
5649 */
5650 preempt_disable();
37d81828 5651 ++userpg->lock;
92f22a38 5652 barrier();
cdd6c482 5653 userpg->index = perf_event_index(event);
b5e58793 5654 userpg->offset = perf_event_count(event);
365a4038 5655 if (userpg->index)
e7850595 5656 userpg->offset -= local64_read(&event->hw.prev_count);
7b732a75 5657
0d641208 5658 userpg->time_enabled = enabled +
cdd6c482 5659 atomic64_read(&event->child_total_time_enabled);
7f8b4e4e 5660
0d641208 5661 userpg->time_running = running +
cdd6c482 5662 atomic64_read(&event->child_total_time_running);
7f8b4e4e 5663
c1317ec2 5664 arch_perf_update_userpage(event, userpg, now);
e3f3541c 5665
92f22a38 5666 barrier();
37d81828 5667 ++userpg->lock;
7b732a75 5668 preempt_enable();
38ff667b 5669unlock:
7b732a75 5670 rcu_read_unlock();
37d81828 5671}
82975c46 5672EXPORT_SYMBOL_GPL(perf_event_update_userpage);
37d81828 5673
9e3ed2d7 5674static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
906010b2 5675{
11bac800 5676 struct perf_event *event = vmf->vma->vm_file->private_data;
56de4e8f 5677 struct perf_buffer *rb;
9e3ed2d7 5678 vm_fault_t ret = VM_FAULT_SIGBUS;
906010b2
PZ
5679
5680 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5681 if (vmf->pgoff == 0)
5682 ret = 0;
5683 return ret;
5684 }
5685
5686 rcu_read_lock();
76369139
FW
5687 rb = rcu_dereference(event->rb);
5688 if (!rb)
906010b2
PZ
5689 goto unlock;
5690
5691 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5692 goto unlock;
5693
76369139 5694 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
906010b2
PZ
5695 if (!vmf->page)
5696 goto unlock;
5697
5698 get_page(vmf->page);
11bac800 5699 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
906010b2
PZ
5700 vmf->page->index = vmf->pgoff;
5701
5702 ret = 0;
5703unlock:
5704 rcu_read_unlock();
5705
5706 return ret;
5707}
5708
10c6db11 5709static void ring_buffer_attach(struct perf_event *event,
56de4e8f 5710 struct perf_buffer *rb)
10c6db11 5711{
56de4e8f 5712 struct perf_buffer *old_rb = NULL;
10c6db11
PZ
5713 unsigned long flags;
5714
b69cf536
PZ
5715 if (event->rb) {
5716 /*
5717 * Should be impossible, we set this when removing
5718 * event->rb_entry and wait/clear when adding event->rb_entry.
5719 */
5720 WARN_ON_ONCE(event->rcu_pending);
10c6db11 5721
b69cf536 5722 old_rb = event->rb;
b69cf536
PZ
5723 spin_lock_irqsave(&old_rb->event_lock, flags);
5724 list_del_rcu(&event->rb_entry);
5725 spin_unlock_irqrestore(&old_rb->event_lock, flags);
10c6db11 5726
2f993cf0
ON
5727 event->rcu_batches = get_state_synchronize_rcu();
5728 event->rcu_pending = 1;
b69cf536 5729 }
10c6db11 5730
b69cf536 5731 if (rb) {
2f993cf0
ON
5732 if (event->rcu_pending) {
5733 cond_synchronize_rcu(event->rcu_batches);
5734 event->rcu_pending = 0;
5735 }
5736
b69cf536
PZ
5737 spin_lock_irqsave(&rb->event_lock, flags);
5738 list_add_rcu(&event->rb_entry, &rb->event_list);
5739 spin_unlock_irqrestore(&rb->event_lock, flags);
5740 }
5741
767ae086
AS
5742 /*
5743 * Avoid racing with perf_mmap_close(AUX): stop the event
5744 * before swizzling the event::rb pointer; if it's getting
5745 * unmapped, its aux_mmap_count will be 0 and it won't
5746 * restart. See the comment in __perf_pmu_output_stop().
5747 *
5748 * Data will inevitably be lost when set_output is done in
5749 * mid-air, but then again, whoever does it like this is
5750 * not in for the data anyway.
5751 */
5752 if (has_aux(event))
5753 perf_event_stop(event, 0);
5754
b69cf536
PZ
5755 rcu_assign_pointer(event->rb, rb);
5756
5757 if (old_rb) {
5758 ring_buffer_put(old_rb);
5759 /*
5760 * Since we detached before setting the new rb, so that we
5761 * could attach the new rb, we could have missed a wakeup.
5762 * Provide it now.
5763 */
5764 wake_up_all(&event->waitq);
5765 }
10c6db11
PZ
5766}
5767
5768static void ring_buffer_wakeup(struct perf_event *event)
5769{
56de4e8f 5770 struct perf_buffer *rb;
10c6db11
PZ
5771
5772 rcu_read_lock();
5773 rb = rcu_dereference(event->rb);
9bb5d40c
PZ
5774 if (rb) {
5775 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5776 wake_up_all(&event->waitq);
5777 }
10c6db11
PZ
5778 rcu_read_unlock();
5779}
5780
56de4e8f 5781struct perf_buffer *ring_buffer_get(struct perf_event *event)
7b732a75 5782{
56de4e8f 5783 struct perf_buffer *rb;
7b732a75 5784
ac9721f3 5785 rcu_read_lock();
76369139
FW
5786 rb = rcu_dereference(event->rb);
5787 if (rb) {
fecb8ed2 5788 if (!refcount_inc_not_zero(&rb->refcount))
76369139 5789 rb = NULL;
ac9721f3
PZ
5790 }
5791 rcu_read_unlock();
5792
76369139 5793 return rb;
ac9721f3
PZ
5794}
5795
56de4e8f 5796void ring_buffer_put(struct perf_buffer *rb)
ac9721f3 5797{
fecb8ed2 5798 if (!refcount_dec_and_test(&rb->refcount))
ac9721f3 5799 return;
7b732a75 5800
9bb5d40c 5801 WARN_ON_ONCE(!list_empty(&rb->event_list));
10c6db11 5802
76369139 5803 call_rcu(&rb->rcu_head, rb_free_rcu);
7b732a75
PZ
5804}
5805
5806static void perf_mmap_open(struct vm_area_struct *vma)
5807{
cdd6c482 5808 struct perf_event *event = vma->vm_file->private_data;
7b732a75 5809
cdd6c482 5810 atomic_inc(&event->mmap_count);
9bb5d40c 5811 atomic_inc(&event->rb->mmap_count);
1e0fb9ec 5812
45bfb2e5
PZ
5813 if (vma->vm_pgoff)
5814 atomic_inc(&event->rb->aux_mmap_count);
5815
1e0fb9ec 5816 if (event->pmu->event_mapped)
bfe33492 5817 event->pmu->event_mapped(event, vma->vm_mm);
7b732a75
PZ
5818}
5819
95ff4ca2
AS
5820static void perf_pmu_output_stop(struct perf_event *event);
5821
9bb5d40c
PZ
5822/*
5823 * A buffer can be mmap()ed multiple times; either directly through the same
5824 * event, or through other events by use of perf_event_set_output().
5825 *
5826 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5827 * the buffer here, where we still have a VM context. This means we need
5828 * to detach all events redirecting to us.
5829 */
7b732a75
PZ
5830static void perf_mmap_close(struct vm_area_struct *vma)
5831{
cdd6c482 5832 struct perf_event *event = vma->vm_file->private_data;
7b732a75 5833
56de4e8f 5834 struct perf_buffer *rb = ring_buffer_get(event);
9bb5d40c
PZ
5835 struct user_struct *mmap_user = rb->mmap_user;
5836 int mmap_locked = rb->mmap_locked;
5837 unsigned long size = perf_data_size(rb);
789f90fc 5838
1e0fb9ec 5839 if (event->pmu->event_unmapped)
bfe33492 5840 event->pmu->event_unmapped(event, vma->vm_mm);
1e0fb9ec 5841
45bfb2e5
PZ
5842 /*
5843 * rb->aux_mmap_count will always drop before rb->mmap_count and
5844 * event->mmap_count, so it is ok to use event->mmap_mutex to
5845 * serialize with perf_mmap here.
5846 */
5847 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5848 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
95ff4ca2
AS
5849 /*
5850 * Stop all AUX events that are writing to this buffer,
5851 * so that we can free its AUX pages and corresponding PMU
5852 * data. Note that after rb::aux_mmap_count dropped to zero,
5853 * they won't start any more (see perf_aux_output_begin()).
5854 */
5855 perf_pmu_output_stop(event);
5856
5857 /* now it's safe to free the pages */
36b3db03
AS
5858 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5859 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
45bfb2e5 5860
95ff4ca2 5861 /* this has to be the last one */
45bfb2e5 5862 rb_free_aux(rb);
ca3bb3d0 5863 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
95ff4ca2 5864
45bfb2e5
PZ
5865 mutex_unlock(&event->mmap_mutex);
5866 }
5867
9bb5d40c
PZ
5868 atomic_dec(&rb->mmap_count);
5869
5870 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
b69cf536 5871 goto out_put;
9bb5d40c 5872
b69cf536 5873 ring_buffer_attach(event, NULL);
9bb5d40c
PZ
5874 mutex_unlock(&event->mmap_mutex);
5875
5876 /* If there's still other mmap()s of this buffer, we're done. */
b69cf536
PZ
5877 if (atomic_read(&rb->mmap_count))
5878 goto out_put;
ac9721f3 5879
9bb5d40c
PZ
5880 /*
5881 * No other mmap()s, detach from all other events that might redirect
5882 * into the now unreachable buffer. Somewhat complicated by the
5883 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5884 */
5885again:
5886 rcu_read_lock();
5887 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5888 if (!atomic_long_inc_not_zero(&event->refcount)) {
5889 /*
5890 * This event is en-route to free_event() which will
5891 * detach it and remove it from the list.
5892 */
5893 continue;
5894 }
5895 rcu_read_unlock();
789f90fc 5896
9bb5d40c
PZ
5897 mutex_lock(&event->mmap_mutex);
5898 /*
5899 * Check we didn't race with perf_event_set_output() which can
5900 * swizzle the rb from under us while we were waiting to
5901 * acquire mmap_mutex.
5902 *
5903 * If we find a different rb; ignore this event, a next
5904 * iteration will no longer find it on the list. We have to
5905 * still restart the iteration to make sure we're not now
5906 * iterating the wrong list.
5907 */
b69cf536
PZ
5908 if (event->rb == rb)
5909 ring_buffer_attach(event, NULL);
5910
cdd6c482 5911 mutex_unlock(&event->mmap_mutex);
9bb5d40c 5912 put_event(event);
ac9721f3 5913
9bb5d40c
PZ
5914 /*
5915 * Restart the iteration; either we're on the wrong list or
5916 * destroyed its integrity by doing a deletion.
5917 */
5918 goto again;
7b732a75 5919 }
9bb5d40c
PZ
5920 rcu_read_unlock();
5921
5922 /*
5923 * It could be there's still a few 0-ref events on the list; they'll
5924 * get cleaned up by free_event() -- they'll also still have their
5925 * ref on the rb and will free it whenever they are done with it.
5926 *
5927 * Aside from that, this buffer is 'fully' detached and unmapped,
5928 * undo the VM accounting.
5929 */
5930
d44248a4
SL
5931 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
5932 &mmap_user->locked_vm);
70f8a3ca 5933 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
9bb5d40c
PZ
5934 free_uid(mmap_user);
5935
b69cf536 5936out_put:
9bb5d40c 5937 ring_buffer_put(rb); /* could be last */
37d81828
PM
5938}
5939
f0f37e2f 5940static const struct vm_operations_struct perf_mmap_vmops = {
43a21ea8 5941 .open = perf_mmap_open,
fca0c116 5942 .close = perf_mmap_close, /* non mergeable */
43a21ea8
PZ
5943 .fault = perf_mmap_fault,
5944 .page_mkwrite = perf_mmap_fault,
37d81828
PM
5945};
5946
5947static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5948{
cdd6c482 5949 struct perf_event *event = file->private_data;
22a4f650 5950 unsigned long user_locked, user_lock_limit;
789f90fc 5951 struct user_struct *user = current_user();
56de4e8f 5952 struct perf_buffer *rb = NULL;
22a4f650 5953 unsigned long locked, lock_limit;
7b732a75
PZ
5954 unsigned long vma_size;
5955 unsigned long nr_pages;
45bfb2e5 5956 long user_extra = 0, extra = 0;
d57e34fd 5957 int ret = 0, flags = 0;
37d81828 5958
c7920614
PZ
5959 /*
5960 * Don't allow mmap() of inherited per-task counters. This would
5961 * create a performance issue due to all children writing to the
76369139 5962 * same rb.
c7920614
PZ
5963 */
5964 if (event->cpu == -1 && event->attr.inherit)
5965 return -EINVAL;
5966
43a21ea8 5967 if (!(vma->vm_flags & VM_SHARED))
37d81828 5968 return -EINVAL;
7b732a75 5969
da97e184
JFG
5970 ret = security_perf_event_read(event);
5971 if (ret)
5972 return ret;
5973
7b732a75 5974 vma_size = vma->vm_end - vma->vm_start;
45bfb2e5
PZ
5975
5976 if (vma->vm_pgoff == 0) {
5977 nr_pages = (vma_size / PAGE_SIZE) - 1;
5978 } else {
5979 /*
5980 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5981 * mapped, all subsequent mappings should have the same size
5982 * and offset. Must be above the normal perf buffer.
5983 */
5984 u64 aux_offset, aux_size;
5985
5986 if (!event->rb)
5987 return -EINVAL;
5988
5989 nr_pages = vma_size / PAGE_SIZE;
5990
5991 mutex_lock(&event->mmap_mutex);
5992 ret = -EINVAL;
5993
5994 rb = event->rb;
5995 if (!rb)
5996 goto aux_unlock;
5997
6aa7de05
MR
5998 aux_offset = READ_ONCE(rb->user_page->aux_offset);
5999 aux_size = READ_ONCE(rb->user_page->aux_size);
45bfb2e5
PZ
6000
6001 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
6002 goto aux_unlock;
6003
6004 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
6005 goto aux_unlock;
6006
6007 /* already mapped with a different offset */
6008 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
6009 goto aux_unlock;
6010
6011 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
6012 goto aux_unlock;
6013
6014 /* already mapped with a different size */
6015 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
6016 goto aux_unlock;
6017
6018 if (!is_power_of_2(nr_pages))
6019 goto aux_unlock;
6020
6021 if (!atomic_inc_not_zero(&rb->mmap_count))
6022 goto aux_unlock;
6023
6024 if (rb_has_aux(rb)) {
6025 atomic_inc(&rb->aux_mmap_count);
6026 ret = 0;
6027 goto unlock;
6028 }
6029
6030 atomic_set(&rb->aux_mmap_count, 1);
6031 user_extra = nr_pages;
6032
6033 goto accounting;
6034 }
7b732a75 6035
7730d865 6036 /*
76369139 6037 * If we have rb pages ensure they're a power-of-two number, so we
7730d865
PZ
6038 * can do bitmasks instead of modulo.
6039 */
2ed11312 6040 if (nr_pages != 0 && !is_power_of_2(nr_pages))
37d81828
PM
6041 return -EINVAL;
6042
7b732a75 6043 if (vma_size != PAGE_SIZE * (1 + nr_pages))
37d81828
PM
6044 return -EINVAL;
6045
cdd6c482 6046 WARN_ON_ONCE(event->ctx->parent_ctx);
9bb5d40c 6047again:
cdd6c482 6048 mutex_lock(&event->mmap_mutex);
76369139 6049 if (event->rb) {
9bb5d40c 6050 if (event->rb->nr_pages != nr_pages) {
ebb3c4c4 6051 ret = -EINVAL;
9bb5d40c
PZ
6052 goto unlock;
6053 }
6054
6055 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
6056 /*
6057 * Raced against perf_mmap_close() through
6058 * perf_event_set_output(). Try again, hope for better
6059 * luck.
6060 */
6061 mutex_unlock(&event->mmap_mutex);
6062 goto again;
6063 }
6064
ebb3c4c4
PZ
6065 goto unlock;
6066 }
6067
789f90fc 6068 user_extra = nr_pages + 1;
45bfb2e5
PZ
6069
6070accounting:
cdd6c482 6071 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
a3862d3f
IM
6072
6073 /*
6074 * Increase the limit linearly with more CPUs:
6075 */
6076 user_lock_limit *= num_online_cpus();
6077
00346155
SL
6078 user_locked = atomic_long_read(&user->locked_vm);
6079
6080 /*
6081 * sysctl_perf_event_mlock may have changed, so that
6082 * user->locked_vm > user_lock_limit
6083 */
6084 if (user_locked > user_lock_limit)
6085 user_locked = user_lock_limit;
6086 user_locked += user_extra;
c5078f78 6087
c4b75479 6088 if (user_locked > user_lock_limit) {
d44248a4
SL
6089 /*
6090 * charge locked_vm until it hits user_lock_limit;
6091 * charge the rest from pinned_vm
6092 */
789f90fc 6093 extra = user_locked - user_lock_limit;
d44248a4
SL
6094 user_extra -= extra;
6095 }
7b732a75 6096
78d7d407 6097 lock_limit = rlimit(RLIMIT_MEMLOCK);
7b732a75 6098 lock_limit >>= PAGE_SHIFT;
70f8a3ca 6099 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
7b732a75 6100
da97e184 6101 if ((locked > lock_limit) && perf_is_paranoid() &&
459ec28a 6102 !capable(CAP_IPC_LOCK)) {
ebb3c4c4
PZ
6103 ret = -EPERM;
6104 goto unlock;
6105 }
7b732a75 6106
45bfb2e5 6107 WARN_ON(!rb && event->rb);
906010b2 6108
d57e34fd 6109 if (vma->vm_flags & VM_WRITE)
76369139 6110 flags |= RING_BUFFER_WRITABLE;
d57e34fd 6111
76369139 6112 if (!rb) {
45bfb2e5
PZ
6113 rb = rb_alloc(nr_pages,
6114 event->attr.watermark ? event->attr.wakeup_watermark : 0,
6115 event->cpu, flags);
26cb63ad 6116
45bfb2e5
PZ
6117 if (!rb) {
6118 ret = -ENOMEM;
6119 goto unlock;
6120 }
43a21ea8 6121
45bfb2e5
PZ
6122 atomic_set(&rb->mmap_count, 1);
6123 rb->mmap_user = get_current_user();
6124 rb->mmap_locked = extra;
26cb63ad 6125
45bfb2e5 6126 ring_buffer_attach(event, rb);
ac9721f3 6127
45bfb2e5
PZ
6128 perf_event_init_userpage(event);
6129 perf_event_update_userpage(event);
6130 } else {
1a594131
AS
6131 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
6132 event->attr.aux_watermark, flags);
45bfb2e5
PZ
6133 if (!ret)
6134 rb->aux_mmap_locked = extra;
6135 }
9a0f05cb 6136
ebb3c4c4 6137unlock:
45bfb2e5
PZ
6138 if (!ret) {
6139 atomic_long_add(user_extra, &user->locked_vm);
70f8a3ca 6140 atomic64_add(extra, &vma->vm_mm->pinned_vm);
45bfb2e5 6141
ac9721f3 6142 atomic_inc(&event->mmap_count);
45bfb2e5
PZ
6143 } else if (rb) {
6144 atomic_dec(&rb->mmap_count);
6145 }
6146aux_unlock:
cdd6c482 6147 mutex_unlock(&event->mmap_mutex);
37d81828 6148
9bb5d40c
PZ
6149 /*
6150 * Since pinned accounting is per vm we cannot allow fork() to copy our
6151 * vma.
6152 */
26cb63ad 6153 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
37d81828 6154 vma->vm_ops = &perf_mmap_vmops;
7b732a75 6155
1e0fb9ec 6156 if (event->pmu->event_mapped)
bfe33492 6157 event->pmu->event_mapped(event, vma->vm_mm);
1e0fb9ec 6158
7b732a75 6159 return ret;
37d81828
PM
6160}
6161
3c446b3d
PZ
6162static int perf_fasync(int fd, struct file *filp, int on)
6163{
496ad9aa 6164 struct inode *inode = file_inode(filp);
cdd6c482 6165 struct perf_event *event = filp->private_data;
3c446b3d
PZ
6166 int retval;
6167
5955102c 6168 inode_lock(inode);
cdd6c482 6169 retval = fasync_helper(fd, filp, on, &event->fasync);
5955102c 6170 inode_unlock(inode);
3c446b3d
PZ
6171
6172 if (retval < 0)
6173 return retval;
6174
6175 return 0;
6176}
6177
0793a61d 6178static const struct file_operations perf_fops = {
3326c1ce 6179 .llseek = no_llseek,
0793a61d
TG
6180 .release = perf_release,
6181 .read = perf_read,
6182 .poll = perf_poll,
d859e29f 6183 .unlocked_ioctl = perf_ioctl,
b3f20785 6184 .compat_ioctl = perf_compat_ioctl,
37d81828 6185 .mmap = perf_mmap,
3c446b3d 6186 .fasync = perf_fasync,
0793a61d
TG
6187};
6188
925d519a 6189/*
cdd6c482 6190 * Perf event wakeup
925d519a
PZ
6191 *
6192 * If there's data, ensure we set the poll() state and publish everything
6193 * to user-space before waking everybody up.
6194 */
6195
fed66e2c
PZ
6196static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6197{
6198 /* only the parent has fasync state */
6199 if (event->parent)
6200 event = event->parent;
6201 return &event->fasync;
6202}
6203
cdd6c482 6204void perf_event_wakeup(struct perf_event *event)
925d519a 6205{
10c6db11 6206 ring_buffer_wakeup(event);
4c9e2542 6207
cdd6c482 6208 if (event->pending_kill) {
fed66e2c 6209 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
cdd6c482 6210 event->pending_kill = 0;
4c9e2542 6211 }
925d519a
PZ
6212}
6213
1d54ad94
PZ
6214static void perf_pending_event_disable(struct perf_event *event)
6215{
6216 int cpu = READ_ONCE(event->pending_disable);
6217
6218 if (cpu < 0)
6219 return;
6220
6221 if (cpu == smp_processor_id()) {
6222 WRITE_ONCE(event->pending_disable, -1);
6223 perf_event_disable_local(event);
6224 return;
6225 }
6226
6227 /*
6228 * CPU-A CPU-B
6229 *
6230 * perf_event_disable_inatomic()
6231 * @pending_disable = CPU-A;
6232 * irq_work_queue();
6233 *
6234 * sched-out
6235 * @pending_disable = -1;
6236 *
6237 * sched-in
6238 * perf_event_disable_inatomic()
6239 * @pending_disable = CPU-B;
6240 * irq_work_queue(); // FAILS
6241 *
6242 * irq_work_run()
6243 * perf_pending_event()
6244 *
6245 * But the event runs on CPU-B and wants disabling there.
6246 */
6247 irq_work_queue_on(&event->pending, cpu);
6248}
6249
e360adbe 6250static void perf_pending_event(struct irq_work *entry)
79f14641 6251{
1d54ad94 6252 struct perf_event *event = container_of(entry, struct perf_event, pending);
d525211f
PZ
6253 int rctx;
6254
6255 rctx = perf_swevent_get_recursion_context();
6256 /*
6257 * If we 'fail' here, that's OK, it means recursion is already disabled
6258 * and we won't recurse 'further'.
6259 */
79f14641 6260
1d54ad94 6261 perf_pending_event_disable(event);
79f14641 6262
cdd6c482
IM
6263 if (event->pending_wakeup) {
6264 event->pending_wakeup = 0;
6265 perf_event_wakeup(event);
79f14641 6266 }
d525211f
PZ
6267
6268 if (rctx >= 0)
6269 perf_swevent_put_recursion_context(rctx);
79f14641
PZ
6270}
6271
39447b38
ZY
6272/*
6273 * We assume there is only KVM supporting the callbacks.
6274 * Later on, we might change it to a list if there is
6275 * another virtualization implementation supporting the callbacks.
6276 */
6277struct perf_guest_info_callbacks *perf_guest_cbs;
6278
6279int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6280{
6281 perf_guest_cbs = cbs;
6282 return 0;
6283}
6284EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6285
6286int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6287{
6288 perf_guest_cbs = NULL;
6289 return 0;
6290}
6291EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6292
4018994f
JO
6293static void
6294perf_output_sample_regs(struct perf_output_handle *handle,
6295 struct pt_regs *regs, u64 mask)
6296{
6297 int bit;
29dd3288 6298 DECLARE_BITMAP(_mask, 64);
4018994f 6299
29dd3288
MS
6300 bitmap_from_u64(_mask, mask);
6301 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
4018994f
JO
6302 u64 val;
6303
6304 val = perf_reg_value(regs, bit);
6305 perf_output_put(handle, val);
6306 }
6307}
6308
60e2364e 6309static void perf_sample_regs_user(struct perf_regs *regs_user,
88a7c26a
AL
6310 struct pt_regs *regs,
6311 struct pt_regs *regs_user_copy)
4018994f 6312{
88a7c26a
AL
6313 if (user_mode(regs)) {
6314 regs_user->abi = perf_reg_abi(current);
2565711f 6315 regs_user->regs = regs;
085ebfe9 6316 } else if (!(current->flags & PF_KTHREAD)) {
88a7c26a 6317 perf_get_regs_user(regs_user, regs, regs_user_copy);
2565711f
PZ
6318 } else {
6319 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6320 regs_user->regs = NULL;
4018994f
JO
6321 }
6322}
6323
60e2364e
SE
6324static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6325 struct pt_regs *regs)
6326{
6327 regs_intr->regs = regs;
6328 regs_intr->abi = perf_reg_abi(current);
6329}
6330
6331
c5ebcedb
JO
6332/*
6333 * Get remaining task size from user stack pointer.
6334 *
6335 * It'd be better to take stack vma map and limit this more
9f014e3a 6336 * precisely, but there's no way to get it safely under interrupt,
c5ebcedb
JO
6337 * so using TASK_SIZE as limit.
6338 */
6339static u64 perf_ustack_task_size(struct pt_regs *regs)
6340{
6341 unsigned long addr = perf_user_stack_pointer(regs);
6342
6343 if (!addr || addr >= TASK_SIZE)
6344 return 0;
6345
6346 return TASK_SIZE - addr;
6347}
6348
6349static u16
6350perf_sample_ustack_size(u16 stack_size, u16 header_size,
6351 struct pt_regs *regs)
6352{
6353 u64 task_size;
6354
6355 /* No regs, no stack pointer, no dump. */
6356 if (!regs)
6357 return 0;
6358
6359 /*
6360 * Check if we fit in with the requested stack size into the:
6361 * - TASK_SIZE
6362 * If we don't, we limit the size to the TASK_SIZE.
6363 *
6364 * - remaining sample size
6365 * If we don't, we customize the stack size to
6366 * fit in to the remaining sample size.
6367 */
6368
6369 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6370 stack_size = min(stack_size, (u16) task_size);
6371
6372 /* Current header size plus static size and dynamic size. */
6373 header_size += 2 * sizeof(u64);
6374
6375 /* Do we fit in with the current stack dump size? */
6376 if ((u16) (header_size + stack_size) < header_size) {
6377 /*
6378 * If we overflow the maximum size for the sample,
6379 * we customize the stack dump size to fit in.
6380 */
6381 stack_size = USHRT_MAX - header_size - sizeof(u64);
6382 stack_size = round_up(stack_size, sizeof(u64));
6383 }
6384
6385 return stack_size;
6386}
6387
6388static void
6389perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6390 struct pt_regs *regs)
6391{
6392 /* Case of a kernel thread, nothing to dump */
6393 if (!regs) {
6394 u64 size = 0;
6395 perf_output_put(handle, size);
6396 } else {
6397 unsigned long sp;
6398 unsigned int rem;
6399 u64 dyn_size;
02e18447 6400 mm_segment_t fs;
c5ebcedb
JO
6401
6402 /*
6403 * We dump:
6404 * static size
6405 * - the size requested by user or the best one we can fit
6406 * in to the sample max size
6407 * data
6408 * - user stack dump data
6409 * dynamic size
6410 * - the actual dumped size
6411 */
6412
6413 /* Static size. */
6414 perf_output_put(handle, dump_size);
6415
6416 /* Data. */
6417 sp = perf_user_stack_pointer(regs);
02e18447
YC
6418 fs = get_fs();
6419 set_fs(USER_DS);
c5ebcedb 6420 rem = __output_copy_user(handle, (void *) sp, dump_size);
02e18447 6421 set_fs(fs);
c5ebcedb
JO
6422 dyn_size = dump_size - rem;
6423
6424 perf_output_skip(handle, rem);
6425
6426 /* Dynamic size. */
6427 perf_output_put(handle, dyn_size);
6428 }
6429}
6430
a4faf00d
AS
6431static unsigned long perf_prepare_sample_aux(struct perf_event *event,
6432 struct perf_sample_data *data,
6433 size_t size)
6434{
6435 struct perf_event *sampler = event->aux_event;
56de4e8f 6436 struct perf_buffer *rb;
a4faf00d
AS
6437
6438 data->aux_size = 0;
6439
6440 if (!sampler)
6441 goto out;
6442
6443 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE))
6444 goto out;
6445
6446 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id()))
6447 goto out;
6448
6449 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6450 if (!rb)
6451 goto out;
6452
6453 /*
6454 * If this is an NMI hit inside sampling code, don't take
6455 * the sample. See also perf_aux_sample_output().
6456 */
6457 if (READ_ONCE(rb->aux_in_sampling)) {
6458 data->aux_size = 0;
6459 } else {
6460 size = min_t(size_t, size, perf_aux_size(rb));
6461 data->aux_size = ALIGN(size, sizeof(u64));
6462 }
6463 ring_buffer_put(rb);
6464
6465out:
6466 return data->aux_size;
6467}
6468
56de4e8f 6469long perf_pmu_snapshot_aux(struct perf_buffer *rb,
a4faf00d
AS
6470 struct perf_event *event,
6471 struct perf_output_handle *handle,
6472 unsigned long size)
6473{
6474 unsigned long flags;
6475 long ret;
6476
6477 /*
6478 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler
6479 * paths. If we start calling them in NMI context, they may race with
6480 * the IRQ ones, that is, for example, re-starting an event that's just
6481 * been stopped, which is why we're using a separate callback that
6482 * doesn't change the event state.
6483 *
6484 * IRQs need to be disabled to prevent IPIs from racing with us.
6485 */
6486 local_irq_save(flags);
6487 /*
6488 * Guard against NMI hits inside the critical section;
6489 * see also perf_prepare_sample_aux().
6490 */
6491 WRITE_ONCE(rb->aux_in_sampling, 1);
6492 barrier();
6493
6494 ret = event->pmu->snapshot_aux(event, handle, size);
6495
6496 barrier();
6497 WRITE_ONCE(rb->aux_in_sampling, 0);
6498 local_irq_restore(flags);
6499
6500 return ret;
6501}
6502
6503static void perf_aux_sample_output(struct perf_event *event,
6504 struct perf_output_handle *handle,
6505 struct perf_sample_data *data)
6506{
6507 struct perf_event *sampler = event->aux_event;
56de4e8f 6508 struct perf_buffer *rb;
a4faf00d 6509 unsigned long pad;
a4faf00d
AS
6510 long size;
6511
6512 if (WARN_ON_ONCE(!sampler || !data->aux_size))
6513 return;
6514
6515 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler);
6516 if (!rb)
6517 return;
6518
6519 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size);
6520
6521 /*
6522 * An error here means that perf_output_copy() failed (returned a
6523 * non-zero surplus that it didn't copy), which in its current
6524 * enlightened implementation is not possible. If that changes, we'd
6525 * like to know.
6526 */
6527 if (WARN_ON_ONCE(size < 0))
6528 goto out_put;
6529
6530 /*
6531 * The pad comes from ALIGN()ing data->aux_size up to u64 in
6532 * perf_prepare_sample_aux(), so should not be more than that.
6533 */
6534 pad = data->aux_size - size;
6535 if (WARN_ON_ONCE(pad >= sizeof(u64)))
6536 pad = 8;
6537
6538 if (pad) {
6539 u64 zero = 0;
6540 perf_output_copy(handle, &zero, pad);
6541 }
6542
6543out_put:
6544 ring_buffer_put(rb);
6545}
6546
c980d109
ACM
6547static void __perf_event_header__init_id(struct perf_event_header *header,
6548 struct perf_sample_data *data,
6549 struct perf_event *event)
6844c09d
ACM
6550{
6551 u64 sample_type = event->attr.sample_type;
6552
6553 data->type = sample_type;
6554 header->size += event->id_header_size;
6555
6556 if (sample_type & PERF_SAMPLE_TID) {
6557 /* namespace issues */
6558 data->tid_entry.pid = perf_event_pid(event, current);
6559 data->tid_entry.tid = perf_event_tid(event, current);
6560 }
6561
6562 if (sample_type & PERF_SAMPLE_TIME)
34f43927 6563 data->time = perf_event_clock(event);
6844c09d 6564
ff3d527c 6565 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6844c09d
ACM
6566 data->id = primary_event_id(event);
6567
6568 if (sample_type & PERF_SAMPLE_STREAM_ID)
6569 data->stream_id = event->id;
6570
6571 if (sample_type & PERF_SAMPLE_CPU) {
6572 data->cpu_entry.cpu = raw_smp_processor_id();
6573 data->cpu_entry.reserved = 0;
6574 }
6575}
6576
76369139
FW
6577void perf_event_header__init_id(struct perf_event_header *header,
6578 struct perf_sample_data *data,
6579 struct perf_event *event)
c980d109
ACM
6580{
6581 if (event->attr.sample_id_all)
6582 __perf_event_header__init_id(header, data, event);
6583}
6584
6585static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6586 struct perf_sample_data *data)
6587{
6588 u64 sample_type = data->type;
6589
6590 if (sample_type & PERF_SAMPLE_TID)
6591 perf_output_put(handle, data->tid_entry);
6592
6593 if (sample_type & PERF_SAMPLE_TIME)
6594 perf_output_put(handle, data->time);
6595
6596 if (sample_type & PERF_SAMPLE_ID)
6597 perf_output_put(handle, data->id);
6598
6599 if (sample_type & PERF_SAMPLE_STREAM_ID)
6600 perf_output_put(handle, data->stream_id);
6601
6602 if (sample_type & PERF_SAMPLE_CPU)
6603 perf_output_put(handle, data->cpu_entry);
ff3d527c
AH
6604
6605 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6606 perf_output_put(handle, data->id);
c980d109
ACM
6607}
6608
76369139
FW
6609void perf_event__output_id_sample(struct perf_event *event,
6610 struct perf_output_handle *handle,
6611 struct perf_sample_data *sample)
c980d109
ACM
6612{
6613 if (event->attr.sample_id_all)
6614 __perf_event__output_id_sample(handle, sample);
6615}
6616
3dab77fb 6617static void perf_output_read_one(struct perf_output_handle *handle,
eed01528
SE
6618 struct perf_event *event,
6619 u64 enabled, u64 running)
3dab77fb 6620{
cdd6c482 6621 u64 read_format = event->attr.read_format;
3dab77fb
PZ
6622 u64 values[4];
6623 int n = 0;
6624
b5e58793 6625 values[n++] = perf_event_count(event);
3dab77fb 6626 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
eed01528 6627 values[n++] = enabled +
cdd6c482 6628 atomic64_read(&event->child_total_time_enabled);
3dab77fb
PZ
6629 }
6630 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
eed01528 6631 values[n++] = running +
cdd6c482 6632 atomic64_read(&event->child_total_time_running);
3dab77fb
PZ
6633 }
6634 if (read_format & PERF_FORMAT_ID)
cdd6c482 6635 values[n++] = primary_event_id(event);
3dab77fb 6636
76369139 6637 __output_copy(handle, values, n * sizeof(u64));
3dab77fb
PZ
6638}
6639
3dab77fb 6640static void perf_output_read_group(struct perf_output_handle *handle,
eed01528
SE
6641 struct perf_event *event,
6642 u64 enabled, u64 running)
3dab77fb 6643{
cdd6c482
IM
6644 struct perf_event *leader = event->group_leader, *sub;
6645 u64 read_format = event->attr.read_format;
3dab77fb
PZ
6646 u64 values[5];
6647 int n = 0;
6648
6649 values[n++] = 1 + leader->nr_siblings;
6650
6651 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
eed01528 6652 values[n++] = enabled;
3dab77fb
PZ
6653
6654 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
eed01528 6655 values[n++] = running;
3dab77fb 6656
9e5b127d
PZ
6657 if ((leader != event) &&
6658 (leader->state == PERF_EVENT_STATE_ACTIVE))
3dab77fb
PZ
6659 leader->pmu->read(leader);
6660
b5e58793 6661 values[n++] = perf_event_count(leader);
3dab77fb 6662 if (read_format & PERF_FORMAT_ID)
cdd6c482 6663 values[n++] = primary_event_id(leader);
3dab77fb 6664
76369139 6665 __output_copy(handle, values, n * sizeof(u64));
3dab77fb 6666
edb39592 6667 for_each_sibling_event(sub, leader) {
3dab77fb
PZ
6668 n = 0;
6669
6f5ab001
JO
6670 if ((sub != event) &&
6671 (sub->state == PERF_EVENT_STATE_ACTIVE))
3dab77fb
PZ
6672 sub->pmu->read(sub);
6673
b5e58793 6674 values[n++] = perf_event_count(sub);
3dab77fb 6675 if (read_format & PERF_FORMAT_ID)
cdd6c482 6676 values[n++] = primary_event_id(sub);
3dab77fb 6677
76369139 6678 __output_copy(handle, values, n * sizeof(u64));
3dab77fb
PZ
6679 }
6680}
6681
eed01528
SE
6682#define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6683 PERF_FORMAT_TOTAL_TIME_RUNNING)
6684
ba5213ae
PZ
6685/*
6686 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6687 *
6688 * The problem is that its both hard and excessively expensive to iterate the
6689 * child list, not to mention that its impossible to IPI the children running
6690 * on another CPU, from interrupt/NMI context.
6691 */
3dab77fb 6692static void perf_output_read(struct perf_output_handle *handle,
cdd6c482 6693 struct perf_event *event)
3dab77fb 6694{
e3f3541c 6695 u64 enabled = 0, running = 0, now;
eed01528
SE
6696 u64 read_format = event->attr.read_format;
6697
6698 /*
6699 * compute total_time_enabled, total_time_running
6700 * based on snapshot values taken when the event
6701 * was last scheduled in.
6702 *
6703 * we cannot simply called update_context_time()
6704 * because of locking issue as we are called in
6705 * NMI context
6706 */
c4794295 6707 if (read_format & PERF_FORMAT_TOTAL_TIMES)
e3f3541c 6708 calc_timer_values(event, &now, &enabled, &running);
eed01528 6709
cdd6c482 6710 if (event->attr.read_format & PERF_FORMAT_GROUP)
eed01528 6711 perf_output_read_group(handle, event, enabled, running);
3dab77fb 6712 else
eed01528 6713 perf_output_read_one(handle, event, enabled, running);
3dab77fb
PZ
6714}
6715
bbfd5e4f
KL
6716static inline bool perf_sample_save_hw_index(struct perf_event *event)
6717{
6718 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX;
6719}
6720
5622f295
MM
6721void perf_output_sample(struct perf_output_handle *handle,
6722 struct perf_event_header *header,
6723 struct perf_sample_data *data,
cdd6c482 6724 struct perf_event *event)
5622f295
MM
6725{
6726 u64 sample_type = data->type;
6727
6728 perf_output_put(handle, *header);
6729
ff3d527c
AH
6730 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6731 perf_output_put(handle, data->id);
6732
5622f295
MM
6733 if (sample_type & PERF_SAMPLE_IP)
6734 perf_output_put(handle, data->ip);
6735
6736 if (sample_type & PERF_SAMPLE_TID)
6737 perf_output_put(handle, data->tid_entry);
6738
6739 if (sample_type & PERF_SAMPLE_TIME)
6740 perf_output_put(handle, data->time);
6741
6742 if (sample_type & PERF_SAMPLE_ADDR)
6743 perf_output_put(handle, data->addr);
6744
6745 if (sample_type & PERF_SAMPLE_ID)
6746 perf_output_put(handle, data->id);
6747
6748 if (sample_type & PERF_SAMPLE_STREAM_ID)
6749 perf_output_put(handle, data->stream_id);
6750
6751 if (sample_type & PERF_SAMPLE_CPU)
6752 perf_output_put(handle, data->cpu_entry);
6753
6754 if (sample_type & PERF_SAMPLE_PERIOD)
6755 perf_output_put(handle, data->period);
6756
6757 if (sample_type & PERF_SAMPLE_READ)
cdd6c482 6758 perf_output_read(handle, event);
5622f295
MM
6759
6760 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
99e818cc 6761 int size = 1;
5622f295 6762
99e818cc
JO
6763 size += data->callchain->nr;
6764 size *= sizeof(u64);
6765 __output_copy(handle, data->callchain, size);
5622f295
MM
6766 }
6767
6768 if (sample_type & PERF_SAMPLE_RAW) {
7e3f977e
DB
6769 struct perf_raw_record *raw = data->raw;
6770
6771 if (raw) {
6772 struct perf_raw_frag *frag = &raw->frag;
6773
6774 perf_output_put(handle, raw->size);
6775 do {
6776 if (frag->copy) {
6777 __output_custom(handle, frag->copy,
6778 frag->data, frag->size);
6779 } else {
6780 __output_copy(handle, frag->data,
6781 frag->size);
6782 }
6783 if (perf_raw_frag_last(frag))
6784 break;
6785 frag = frag->next;
6786 } while (1);
6787 if (frag->pad)
6788 __output_skip(handle, NULL, frag->pad);
5622f295
MM
6789 } else {
6790 struct {
6791 u32 size;
6792 u32 data;
6793 } raw = {
6794 .size = sizeof(u32),
6795 .data = 0,
6796 };
6797 perf_output_put(handle, raw);
6798 }
6799 }
a7ac67ea 6800
bce38cd5
SE
6801 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6802 if (data->br_stack) {
6803 size_t size;
6804
6805 size = data->br_stack->nr
6806 * sizeof(struct perf_branch_entry);
6807
6808 perf_output_put(handle, data->br_stack->nr);
bbfd5e4f
KL
6809 if (perf_sample_save_hw_index(event))
6810 perf_output_put(handle, data->br_stack->hw_idx);
bce38cd5
SE
6811 perf_output_copy(handle, data->br_stack->entries, size);
6812 } else {
6813 /*
6814 * we always store at least the value of nr
6815 */
6816 u64 nr = 0;
6817 perf_output_put(handle, nr);
6818 }
6819 }
4018994f
JO
6820
6821 if (sample_type & PERF_SAMPLE_REGS_USER) {
6822 u64 abi = data->regs_user.abi;
6823
6824 /*
6825 * If there are no regs to dump, notice it through
6826 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6827 */
6828 perf_output_put(handle, abi);
6829
6830 if (abi) {
6831 u64 mask = event->attr.sample_regs_user;
6832 perf_output_sample_regs(handle,
6833 data->regs_user.regs,
6834 mask);
6835 }
6836 }
c5ebcedb 6837
a5cdd40c 6838 if (sample_type & PERF_SAMPLE_STACK_USER) {
c5ebcedb
JO
6839 perf_output_sample_ustack(handle,
6840 data->stack_user_size,
6841 data->regs_user.regs);
a5cdd40c 6842 }
c3feedf2
AK
6843
6844 if (sample_type & PERF_SAMPLE_WEIGHT)
6845 perf_output_put(handle, data->weight);
d6be9ad6
SE
6846
6847 if (sample_type & PERF_SAMPLE_DATA_SRC)
6848 perf_output_put(handle, data->data_src.val);
a5cdd40c 6849
fdfbbd07
AK
6850 if (sample_type & PERF_SAMPLE_TRANSACTION)
6851 perf_output_put(handle, data->txn);
6852
60e2364e
SE
6853 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6854 u64 abi = data->regs_intr.abi;
6855 /*
6856 * If there are no regs to dump, notice it through
6857 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6858 */
6859 perf_output_put(handle, abi);
6860
6861 if (abi) {
6862 u64 mask = event->attr.sample_regs_intr;
6863
6864 perf_output_sample_regs(handle,
6865 data->regs_intr.regs,
6866 mask);
6867 }
6868 }
6869
fc7ce9c7
KL
6870 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6871 perf_output_put(handle, data->phys_addr);
6872
6546b19f
NK
6873 if (sample_type & PERF_SAMPLE_CGROUP)
6874 perf_output_put(handle, data->cgroup);
6875
a4faf00d
AS
6876 if (sample_type & PERF_SAMPLE_AUX) {
6877 perf_output_put(handle, data->aux_size);
6878
6879 if (data->aux_size)
6880 perf_aux_sample_output(event, handle, data);
6881 }
6882
a5cdd40c
PZ
6883 if (!event->attr.watermark) {
6884 int wakeup_events = event->attr.wakeup_events;
6885
6886 if (wakeup_events) {
56de4e8f 6887 struct perf_buffer *rb = handle->rb;
a5cdd40c
PZ
6888 int events = local_inc_return(&rb->events);
6889
6890 if (events >= wakeup_events) {
6891 local_sub(wakeup_events, &rb->events);
6892 local_inc(&rb->wakeup);
6893 }
6894 }
6895 }
5622f295
MM
6896}
6897
fc7ce9c7
KL
6898static u64 perf_virt_to_phys(u64 virt)
6899{
6900 u64 phys_addr = 0;
6901 struct page *p = NULL;
6902
6903 if (!virt)
6904 return 0;
6905
6906 if (virt >= TASK_SIZE) {
6907 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6908 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6909 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6910 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6911 } else {
6912 /*
6913 * Walking the pages tables for user address.
6914 * Interrupts are disabled, so it prevents any tear down
6915 * of the page tables.
6916 * Try IRQ-safe __get_user_pages_fast first.
6917 * If failed, leave phys_addr as 0.
6918 */
6919 if ((current->mm != NULL) &&
6920 (__get_user_pages_fast(virt, 1, 0, &p) == 1))
6921 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6922
6923 if (p)
6924 put_page(p);
6925 }
6926
6927 return phys_addr;
6928}
6929
99e818cc
JO
6930static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
6931
6cbc304f 6932struct perf_callchain_entry *
8cf7e0e2
JO
6933perf_callchain(struct perf_event *event, struct pt_regs *regs)
6934{
6935 bool kernel = !event->attr.exclude_callchain_kernel;
6936 bool user = !event->attr.exclude_callchain_user;
6937 /* Disallow cross-task user callchains. */
6938 bool crosstask = event->ctx->task && event->ctx->task != current;
6939 const u32 max_stack = event->attr.sample_max_stack;
99e818cc 6940 struct perf_callchain_entry *callchain;
8cf7e0e2
JO
6941
6942 if (!kernel && !user)
99e818cc 6943 return &__empty_callchain;
8cf7e0e2 6944
99e818cc
JO
6945 callchain = get_perf_callchain(regs, 0, kernel, user,
6946 max_stack, crosstask, true);
6947 return callchain ?: &__empty_callchain;
8cf7e0e2
JO
6948}
6949
5622f295
MM
6950void perf_prepare_sample(struct perf_event_header *header,
6951 struct perf_sample_data *data,
cdd6c482 6952 struct perf_event *event,
5622f295 6953 struct pt_regs *regs)
7b732a75 6954{
cdd6c482 6955 u64 sample_type = event->attr.sample_type;
7b732a75 6956
cdd6c482 6957 header->type = PERF_RECORD_SAMPLE;
c320c7b7 6958 header->size = sizeof(*header) + event->header_size;
5622f295
MM
6959
6960 header->misc = 0;
6961 header->misc |= perf_misc_flags(regs);
6fab0192 6962
c980d109 6963 __perf_event_header__init_id(header, data, event);
6844c09d 6964
c320c7b7 6965 if (sample_type & PERF_SAMPLE_IP)
5622f295
MM
6966 data->ip = perf_instruction_pointer(regs);
6967
b23f3325 6968 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5622f295 6969 int size = 1;
394ee076 6970
6cbc304f
PZ
6971 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
6972 data->callchain = perf_callchain(event, regs);
6973
99e818cc 6974 size += data->callchain->nr;
5622f295
MM
6975
6976 header->size += size * sizeof(u64);
394ee076
PZ
6977 }
6978
3a43ce68 6979 if (sample_type & PERF_SAMPLE_RAW) {
7e3f977e
DB
6980 struct perf_raw_record *raw = data->raw;
6981 int size;
6982
6983 if (raw) {
6984 struct perf_raw_frag *frag = &raw->frag;
6985 u32 sum = 0;
6986
6987 do {
6988 sum += frag->size;
6989 if (perf_raw_frag_last(frag))
6990 break;
6991 frag = frag->next;
6992 } while (1);
6993
6994 size = round_up(sum + sizeof(u32), sizeof(u64));
6995 raw->size = size - sizeof(u32);
6996 frag->pad = raw->size - sum;
6997 } else {
6998 size = sizeof(u64);
6999 }
a044560c 7000
7e3f977e 7001 header->size += size;
7f453c24 7002 }
bce38cd5
SE
7003
7004 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
7005 int size = sizeof(u64); /* nr */
7006 if (data->br_stack) {
bbfd5e4f
KL
7007 if (perf_sample_save_hw_index(event))
7008 size += sizeof(u64);
7009
bce38cd5
SE
7010 size += data->br_stack->nr
7011 * sizeof(struct perf_branch_entry);
7012 }
7013 header->size += size;
7014 }
4018994f 7015
2565711f 7016 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
88a7c26a
AL
7017 perf_sample_regs_user(&data->regs_user, regs,
7018 &data->regs_user_copy);
2565711f 7019
4018994f
JO
7020 if (sample_type & PERF_SAMPLE_REGS_USER) {
7021 /* regs dump ABI info */
7022 int size = sizeof(u64);
7023
4018994f
JO
7024 if (data->regs_user.regs) {
7025 u64 mask = event->attr.sample_regs_user;
7026 size += hweight64(mask) * sizeof(u64);
7027 }
7028
7029 header->size += size;
7030 }
c5ebcedb
JO
7031
7032 if (sample_type & PERF_SAMPLE_STACK_USER) {
7033 /*
9f014e3a 7034 * Either we need PERF_SAMPLE_STACK_USER bit to be always
c5ebcedb
JO
7035 * processed as the last one or have additional check added
7036 * in case new sample type is added, because we could eat
7037 * up the rest of the sample size.
7038 */
c5ebcedb
JO
7039 u16 stack_size = event->attr.sample_stack_user;
7040 u16 size = sizeof(u64);
7041
c5ebcedb 7042 stack_size = perf_sample_ustack_size(stack_size, header->size,
2565711f 7043 data->regs_user.regs);
c5ebcedb
JO
7044
7045 /*
7046 * If there is something to dump, add space for the dump
7047 * itself and for the field that tells the dynamic size,
7048 * which is how many have been actually dumped.
7049 */
7050 if (stack_size)
7051 size += sizeof(u64) + stack_size;
7052
7053 data->stack_user_size = stack_size;
7054 header->size += size;
7055 }
60e2364e
SE
7056
7057 if (sample_type & PERF_SAMPLE_REGS_INTR) {
7058 /* regs dump ABI info */
7059 int size = sizeof(u64);
7060
7061 perf_sample_regs_intr(&data->regs_intr, regs);
7062
7063 if (data->regs_intr.regs) {
7064 u64 mask = event->attr.sample_regs_intr;
7065
7066 size += hweight64(mask) * sizeof(u64);
7067 }
7068
7069 header->size += size;
7070 }
fc7ce9c7
KL
7071
7072 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
7073 data->phys_addr = perf_virt_to_phys(data->addr);
a4faf00d 7074
6546b19f
NK
7075#ifdef CONFIG_CGROUP_PERF
7076 if (sample_type & PERF_SAMPLE_CGROUP) {
7077 struct cgroup *cgrp;
7078
7079 /* protected by RCU */
7080 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup;
7081 data->cgroup = cgroup_id(cgrp);
7082 }
7083#endif
7084
a4faf00d
AS
7085 if (sample_type & PERF_SAMPLE_AUX) {
7086 u64 size;
7087
7088 header->size += sizeof(u64); /* size */
7089
7090 /*
7091 * Given the 16bit nature of header::size, an AUX sample can
7092 * easily overflow it, what with all the preceding sample bits.
7093 * Make sure this doesn't happen by using up to U16_MAX bytes
7094 * per sample in total (rounded down to 8 byte boundary).
7095 */
7096 size = min_t(size_t, U16_MAX - header->size,
7097 event->attr.aux_sample_size);
7098 size = rounddown(size, 8);
7099 size = perf_prepare_sample_aux(event, data, size);
7100
7101 WARN_ON_ONCE(size + header->size > U16_MAX);
7102 header->size += size;
7103 }
7104 /*
7105 * If you're adding more sample types here, you likely need to do
7106 * something about the overflowing header::size, like repurpose the
7107 * lowest 3 bits of size, which should be always zero at the moment.
7108 * This raises a more important question, do we really need 512k sized
7109 * samples and why, so good argumentation is in order for whatever you
7110 * do here next.
7111 */
7112 WARN_ON_ONCE(header->size & 7);
5622f295 7113}
7f453c24 7114
56201969 7115static __always_inline int
9ecda41a
WN
7116__perf_event_output(struct perf_event *event,
7117 struct perf_sample_data *data,
7118 struct pt_regs *regs,
7119 int (*output_begin)(struct perf_output_handle *,
7120 struct perf_event *,
7121 unsigned int))
5622f295
MM
7122{
7123 struct perf_output_handle handle;
7124 struct perf_event_header header;
56201969 7125 int err;
689802b2 7126
927c7a9e
FW
7127 /* protect the callchain buffers */
7128 rcu_read_lock();
7129
cdd6c482 7130 perf_prepare_sample(&header, data, event, regs);
5c148194 7131
56201969
ACM
7132 err = output_begin(&handle, event, header.size);
7133 if (err)
927c7a9e 7134 goto exit;
0322cd6e 7135
cdd6c482 7136 perf_output_sample(&handle, &header, data, event);
f413cdb8 7137
8a057d84 7138 perf_output_end(&handle);
927c7a9e
FW
7139
7140exit:
7141 rcu_read_unlock();
56201969 7142 return err;
0322cd6e
PZ
7143}
7144
9ecda41a
WN
7145void
7146perf_event_output_forward(struct perf_event *event,
7147 struct perf_sample_data *data,
7148 struct pt_regs *regs)
7149{
7150 __perf_event_output(event, data, regs, perf_output_begin_forward);
7151}
7152
7153void
7154perf_event_output_backward(struct perf_event *event,
7155 struct perf_sample_data *data,
7156 struct pt_regs *regs)
7157{
7158 __perf_event_output(event, data, regs, perf_output_begin_backward);
7159}
7160
56201969 7161int
9ecda41a
WN
7162perf_event_output(struct perf_event *event,
7163 struct perf_sample_data *data,
7164 struct pt_regs *regs)
7165{
56201969 7166 return __perf_event_output(event, data, regs, perf_output_begin);
9ecda41a
WN
7167}
7168
38b200d6 7169/*
cdd6c482 7170 * read event_id
38b200d6
PZ
7171 */
7172
7173struct perf_read_event {
7174 struct perf_event_header header;
7175
7176 u32 pid;
7177 u32 tid;
38b200d6
PZ
7178};
7179
7180static void
cdd6c482 7181perf_event_read_event(struct perf_event *event,
38b200d6
PZ
7182 struct task_struct *task)
7183{
7184 struct perf_output_handle handle;
c980d109 7185 struct perf_sample_data sample;
dfc65094 7186 struct perf_read_event read_event = {
38b200d6 7187 .header = {
cdd6c482 7188 .type = PERF_RECORD_READ,
38b200d6 7189 .misc = 0,
c320c7b7 7190 .size = sizeof(read_event) + event->read_size,
38b200d6 7191 },
cdd6c482
IM
7192 .pid = perf_event_pid(event, task),
7193 .tid = perf_event_tid(event, task),
38b200d6 7194 };
3dab77fb 7195 int ret;
38b200d6 7196
c980d109 7197 perf_event_header__init_id(&read_event.header, &sample, event);
a7ac67ea 7198 ret = perf_output_begin(&handle, event, read_event.header.size);
38b200d6
PZ
7199 if (ret)
7200 return;
7201
dfc65094 7202 perf_output_put(&handle, read_event);
cdd6c482 7203 perf_output_read(&handle, event);
c980d109 7204 perf_event__output_id_sample(event, &handle, &sample);
3dab77fb 7205
38b200d6
PZ
7206 perf_output_end(&handle);
7207}
7208
aab5b71e 7209typedef void (perf_iterate_f)(struct perf_event *event, void *data);
52d857a8
JO
7210
7211static void
aab5b71e
PZ
7212perf_iterate_ctx(struct perf_event_context *ctx,
7213 perf_iterate_f output,
b73e4fef 7214 void *data, bool all)
52d857a8
JO
7215{
7216 struct perf_event *event;
7217
7218 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
b73e4fef
AS
7219 if (!all) {
7220 if (event->state < PERF_EVENT_STATE_INACTIVE)
7221 continue;
7222 if (!event_filter_match(event))
7223 continue;
7224 }
7225
67516844 7226 output(event, data);
52d857a8
JO
7227 }
7228}
7229
aab5b71e 7230static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
f2fb6bef
KL
7231{
7232 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
7233 struct perf_event *event;
7234
7235 list_for_each_entry_rcu(event, &pel->list, sb_list) {
0b8f1e2e
PZ
7236 /*
7237 * Skip events that are not fully formed yet; ensure that
7238 * if we observe event->ctx, both event and ctx will be
7239 * complete enough. See perf_install_in_context().
7240 */
7241 if (!smp_load_acquire(&event->ctx))
7242 continue;
7243
f2fb6bef
KL
7244 if (event->state < PERF_EVENT_STATE_INACTIVE)
7245 continue;
7246 if (!event_filter_match(event))
7247 continue;
7248 output(event, data);
7249 }
7250}
7251
aab5b71e
PZ
7252/*
7253 * Iterate all events that need to receive side-band events.
7254 *
7255 * For new callers; ensure that account_pmu_sb_event() includes
7256 * your event, otherwise it might not get delivered.
7257 */
52d857a8 7258static void
aab5b71e 7259perf_iterate_sb(perf_iterate_f output, void *data,
52d857a8
JO
7260 struct perf_event_context *task_ctx)
7261{
52d857a8 7262 struct perf_event_context *ctx;
52d857a8
JO
7263 int ctxn;
7264
aab5b71e
PZ
7265 rcu_read_lock();
7266 preempt_disable();
7267
4e93ad60 7268 /*
aab5b71e
PZ
7269 * If we have task_ctx != NULL we only notify the task context itself.
7270 * The task_ctx is set only for EXIT events before releasing task
4e93ad60
JO
7271 * context.
7272 */
7273 if (task_ctx) {
aab5b71e
PZ
7274 perf_iterate_ctx(task_ctx, output, data, false);
7275 goto done;
4e93ad60
JO
7276 }
7277
aab5b71e 7278 perf_iterate_sb_cpu(output, data);
f2fb6bef
KL
7279
7280 for_each_task_context_nr(ctxn) {
52d857a8
JO
7281 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7282 if (ctx)
aab5b71e 7283 perf_iterate_ctx(ctx, output, data, false);
52d857a8 7284 }
aab5b71e 7285done:
f2fb6bef 7286 preempt_enable();
52d857a8 7287 rcu_read_unlock();
95ff4ca2
AS
7288}
7289
375637bc
AS
7290/*
7291 * Clear all file-based filters at exec, they'll have to be
7292 * re-instated when/if these objects are mmapped again.
7293 */
7294static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
7295{
7296 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7297 struct perf_addr_filter *filter;
7298 unsigned int restart = 0, count = 0;
7299 unsigned long flags;
7300
7301 if (!has_addr_filter(event))
7302 return;
7303
7304 raw_spin_lock_irqsave(&ifh->lock, flags);
7305 list_for_each_entry(filter, &ifh->list, entry) {
9511bce9 7306 if (filter->path.dentry) {
c60f83b8
AS
7307 event->addr_filter_ranges[count].start = 0;
7308 event->addr_filter_ranges[count].size = 0;
375637bc
AS
7309 restart++;
7310 }
7311
7312 count++;
7313 }
7314
7315 if (restart)
7316 event->addr_filters_gen++;
7317 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7318
7319 if (restart)
767ae086 7320 perf_event_stop(event, 1);
375637bc
AS
7321}
7322
7323void perf_event_exec(void)
7324{
7325 struct perf_event_context *ctx;
7326 int ctxn;
7327
7328 rcu_read_lock();
7329 for_each_task_context_nr(ctxn) {
7330 ctx = current->perf_event_ctxp[ctxn];
7331 if (!ctx)
7332 continue;
7333
7334 perf_event_enable_on_exec(ctxn);
7335
aab5b71e 7336 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
375637bc
AS
7337 true);
7338 }
7339 rcu_read_unlock();
7340}
7341
95ff4ca2 7342struct remote_output {
56de4e8f 7343 struct perf_buffer *rb;
95ff4ca2
AS
7344 int err;
7345};
7346
7347static void __perf_event_output_stop(struct perf_event *event, void *data)
7348{
7349 struct perf_event *parent = event->parent;
7350 struct remote_output *ro = data;
56de4e8f 7351 struct perf_buffer *rb = ro->rb;
375637bc
AS
7352 struct stop_event_data sd = {
7353 .event = event,
7354 };
95ff4ca2
AS
7355
7356 if (!has_aux(event))
7357 return;
7358
7359 if (!parent)
7360 parent = event;
7361
7362 /*
7363 * In case of inheritance, it will be the parent that links to the
767ae086
AS
7364 * ring-buffer, but it will be the child that's actually using it.
7365 *
7366 * We are using event::rb to determine if the event should be stopped,
7367 * however this may race with ring_buffer_attach() (through set_output),
7368 * which will make us skip the event that actually needs to be stopped.
7369 * So ring_buffer_attach() has to stop an aux event before re-assigning
7370 * its rb pointer.
95ff4ca2
AS
7371 */
7372 if (rcu_dereference(parent->rb) == rb)
375637bc 7373 ro->err = __perf_event_stop(&sd);
95ff4ca2
AS
7374}
7375
7376static int __perf_pmu_output_stop(void *info)
7377{
7378 struct perf_event *event = info;
f3a519e4 7379 struct pmu *pmu = event->ctx->pmu;
8b6a3fe8 7380 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
95ff4ca2
AS
7381 struct remote_output ro = {
7382 .rb = event->rb,
7383 };
7384
7385 rcu_read_lock();
aab5b71e 7386 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
95ff4ca2 7387 if (cpuctx->task_ctx)
aab5b71e 7388 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
b73e4fef 7389 &ro, false);
95ff4ca2
AS
7390 rcu_read_unlock();
7391
7392 return ro.err;
7393}
7394
7395static void perf_pmu_output_stop(struct perf_event *event)
7396{
7397 struct perf_event *iter;
7398 int err, cpu;
7399
7400restart:
7401 rcu_read_lock();
7402 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7403 /*
7404 * For per-CPU events, we need to make sure that neither they
7405 * nor their children are running; for cpu==-1 events it's
7406 * sufficient to stop the event itself if it's active, since
7407 * it can't have children.
7408 */
7409 cpu = iter->cpu;
7410 if (cpu == -1)
7411 cpu = READ_ONCE(iter->oncpu);
7412
7413 if (cpu == -1)
7414 continue;
7415
7416 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7417 if (err == -EAGAIN) {
7418 rcu_read_unlock();
7419 goto restart;
7420 }
7421 }
7422 rcu_read_unlock();
52d857a8
JO
7423}
7424
60313ebe 7425/*
9f498cc5
PZ
7426 * task tracking -- fork/exit
7427 *
13d7a241 7428 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
60313ebe
PZ
7429 */
7430
9f498cc5 7431struct perf_task_event {
3a80b4a3 7432 struct task_struct *task;
cdd6c482 7433 struct perf_event_context *task_ctx;
60313ebe
PZ
7434
7435 struct {
7436 struct perf_event_header header;
7437
7438 u32 pid;
7439 u32 ppid;
9f498cc5
PZ
7440 u32 tid;
7441 u32 ptid;
393b2ad8 7442 u64 time;
cdd6c482 7443 } event_id;
60313ebe
PZ
7444};
7445
67516844
JO
7446static int perf_event_task_match(struct perf_event *event)
7447{
13d7a241
SE
7448 return event->attr.comm || event->attr.mmap ||
7449 event->attr.mmap2 || event->attr.mmap_data ||
7450 event->attr.task;
67516844
JO
7451}
7452
cdd6c482 7453static void perf_event_task_output(struct perf_event *event,
52d857a8 7454 void *data)
60313ebe 7455{
52d857a8 7456 struct perf_task_event *task_event = data;
60313ebe 7457 struct perf_output_handle handle;
c980d109 7458 struct perf_sample_data sample;
9f498cc5 7459 struct task_struct *task = task_event->task;
c980d109 7460 int ret, size = task_event->event_id.header.size;
8bb39f9a 7461
67516844
JO
7462 if (!perf_event_task_match(event))
7463 return;
7464
c980d109 7465 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
60313ebe 7466
c980d109 7467 ret = perf_output_begin(&handle, event,
a7ac67ea 7468 task_event->event_id.header.size);
ef60777c 7469 if (ret)
c980d109 7470 goto out;
60313ebe 7471
cdd6c482
IM
7472 task_event->event_id.pid = perf_event_pid(event, task);
7473 task_event->event_id.ppid = perf_event_pid(event, current);
60313ebe 7474
cdd6c482
IM
7475 task_event->event_id.tid = perf_event_tid(event, task);
7476 task_event->event_id.ptid = perf_event_tid(event, current);
9f498cc5 7477
34f43927
PZ
7478 task_event->event_id.time = perf_event_clock(event);
7479
cdd6c482 7480 perf_output_put(&handle, task_event->event_id);
393b2ad8 7481
c980d109
ACM
7482 perf_event__output_id_sample(event, &handle, &sample);
7483
60313ebe 7484 perf_output_end(&handle);
c980d109
ACM
7485out:
7486 task_event->event_id.header.size = size;
60313ebe
PZ
7487}
7488
cdd6c482
IM
7489static void perf_event_task(struct task_struct *task,
7490 struct perf_event_context *task_ctx,
3a80b4a3 7491 int new)
60313ebe 7492{
9f498cc5 7493 struct perf_task_event task_event;
60313ebe 7494
cdd6c482
IM
7495 if (!atomic_read(&nr_comm_events) &&
7496 !atomic_read(&nr_mmap_events) &&
7497 !atomic_read(&nr_task_events))
60313ebe
PZ
7498 return;
7499
9f498cc5 7500 task_event = (struct perf_task_event){
3a80b4a3
PZ
7501 .task = task,
7502 .task_ctx = task_ctx,
cdd6c482 7503 .event_id = {
60313ebe 7504 .header = {
cdd6c482 7505 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
573402db 7506 .misc = 0,
cdd6c482 7507 .size = sizeof(task_event.event_id),
60313ebe 7508 },
573402db
PZ
7509 /* .pid */
7510 /* .ppid */
9f498cc5
PZ
7511 /* .tid */
7512 /* .ptid */
34f43927 7513 /* .time */
60313ebe
PZ
7514 },
7515 };
7516
aab5b71e 7517 perf_iterate_sb(perf_event_task_output,
52d857a8
JO
7518 &task_event,
7519 task_ctx);
9f498cc5
PZ
7520}
7521
cdd6c482 7522void perf_event_fork(struct task_struct *task)
9f498cc5 7523{
cdd6c482 7524 perf_event_task(task, NULL, 1);
e4222673 7525 perf_event_namespaces(task);
60313ebe
PZ
7526}
7527
8d1b2d93
PZ
7528/*
7529 * comm tracking
7530 */
7531
7532struct perf_comm_event {
22a4f650
IM
7533 struct task_struct *task;
7534 char *comm;
8d1b2d93
PZ
7535 int comm_size;
7536
7537 struct {
7538 struct perf_event_header header;
7539
7540 u32 pid;
7541 u32 tid;
cdd6c482 7542 } event_id;
8d1b2d93
PZ
7543};
7544
67516844
JO
7545static int perf_event_comm_match(struct perf_event *event)
7546{
7547 return event->attr.comm;
7548}
7549
cdd6c482 7550static void perf_event_comm_output(struct perf_event *event,
52d857a8 7551 void *data)
8d1b2d93 7552{
52d857a8 7553 struct perf_comm_event *comm_event = data;
8d1b2d93 7554 struct perf_output_handle handle;
c980d109 7555 struct perf_sample_data sample;
cdd6c482 7556 int size = comm_event->event_id.header.size;
c980d109
ACM
7557 int ret;
7558
67516844
JO
7559 if (!perf_event_comm_match(event))
7560 return;
7561
c980d109
ACM
7562 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7563 ret = perf_output_begin(&handle, event,
a7ac67ea 7564 comm_event->event_id.header.size);
8d1b2d93
PZ
7565
7566 if (ret)
c980d109 7567 goto out;
8d1b2d93 7568
cdd6c482
IM
7569 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7570 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
709e50cf 7571
cdd6c482 7572 perf_output_put(&handle, comm_event->event_id);
76369139 7573 __output_copy(&handle, comm_event->comm,
8d1b2d93 7574 comm_event->comm_size);
c980d109
ACM
7575
7576 perf_event__output_id_sample(event, &handle, &sample);
7577
8d1b2d93 7578 perf_output_end(&handle);
c980d109
ACM
7579out:
7580 comm_event->event_id.header.size = size;
8d1b2d93
PZ
7581}
7582
cdd6c482 7583static void perf_event_comm_event(struct perf_comm_event *comm_event)
8d1b2d93 7584{
413ee3b4 7585 char comm[TASK_COMM_LEN];
8d1b2d93 7586 unsigned int size;
8d1b2d93 7587
413ee3b4 7588 memset(comm, 0, sizeof(comm));
96b02d78 7589 strlcpy(comm, comm_event->task->comm, sizeof(comm));
888fcee0 7590 size = ALIGN(strlen(comm)+1, sizeof(u64));
8d1b2d93
PZ
7591
7592 comm_event->comm = comm;
7593 comm_event->comm_size = size;
7594
cdd6c482 7595 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8dc85d54 7596
aab5b71e 7597 perf_iterate_sb(perf_event_comm_output,
52d857a8
JO
7598 comm_event,
7599 NULL);
8d1b2d93
PZ
7600}
7601
82b89778 7602void perf_event_comm(struct task_struct *task, bool exec)
8d1b2d93 7603{
9ee318a7
PZ
7604 struct perf_comm_event comm_event;
7605
cdd6c482 7606 if (!atomic_read(&nr_comm_events))
9ee318a7 7607 return;
a63eaf34 7608
9ee318a7 7609 comm_event = (struct perf_comm_event){
8d1b2d93 7610 .task = task,
573402db
PZ
7611 /* .comm */
7612 /* .comm_size */
cdd6c482 7613 .event_id = {
573402db 7614 .header = {
cdd6c482 7615 .type = PERF_RECORD_COMM,
82b89778 7616 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
573402db
PZ
7617 /* .size */
7618 },
7619 /* .pid */
7620 /* .tid */
8d1b2d93
PZ
7621 },
7622 };
7623
cdd6c482 7624 perf_event_comm_event(&comm_event);
8d1b2d93
PZ
7625}
7626
e4222673
HB
7627/*
7628 * namespaces tracking
7629 */
7630
7631struct perf_namespaces_event {
7632 struct task_struct *task;
7633
7634 struct {
7635 struct perf_event_header header;
7636
7637 u32 pid;
7638 u32 tid;
7639 u64 nr_namespaces;
7640 struct perf_ns_link_info link_info[NR_NAMESPACES];
7641 } event_id;
7642};
7643
7644static int perf_event_namespaces_match(struct perf_event *event)
7645{
7646 return event->attr.namespaces;
7647}
7648
7649static void perf_event_namespaces_output(struct perf_event *event,
7650 void *data)
7651{
7652 struct perf_namespaces_event *namespaces_event = data;
7653 struct perf_output_handle handle;
7654 struct perf_sample_data sample;
34900ec5 7655 u16 header_size = namespaces_event->event_id.header.size;
e4222673
HB
7656 int ret;
7657
7658 if (!perf_event_namespaces_match(event))
7659 return;
7660
7661 perf_event_header__init_id(&namespaces_event->event_id.header,
7662 &sample, event);
7663 ret = perf_output_begin(&handle, event,
7664 namespaces_event->event_id.header.size);
7665 if (ret)
34900ec5 7666 goto out;
e4222673
HB
7667
7668 namespaces_event->event_id.pid = perf_event_pid(event,
7669 namespaces_event->task);
7670 namespaces_event->event_id.tid = perf_event_tid(event,
7671 namespaces_event->task);
7672
7673 perf_output_put(&handle, namespaces_event->event_id);
7674
7675 perf_event__output_id_sample(event, &handle, &sample);
7676
7677 perf_output_end(&handle);
34900ec5
JO
7678out:
7679 namespaces_event->event_id.header.size = header_size;
e4222673
HB
7680}
7681
7682static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7683 struct task_struct *task,
7684 const struct proc_ns_operations *ns_ops)
7685{
7686 struct path ns_path;
7687 struct inode *ns_inode;
ce623f89 7688 int error;
e4222673
HB
7689
7690 error = ns_get_path(&ns_path, task, ns_ops);
7691 if (!error) {
7692 ns_inode = ns_path.dentry->d_inode;
7693 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7694 ns_link_info->ino = ns_inode->i_ino;
0e18dd12 7695 path_put(&ns_path);
e4222673
HB
7696 }
7697}
7698
7699void perf_event_namespaces(struct task_struct *task)
7700{
7701 struct perf_namespaces_event namespaces_event;
7702 struct perf_ns_link_info *ns_link_info;
7703
7704 if (!atomic_read(&nr_namespaces_events))
7705 return;
7706
7707 namespaces_event = (struct perf_namespaces_event){
7708 .task = task,
7709 .event_id = {
7710 .header = {
7711 .type = PERF_RECORD_NAMESPACES,
7712 .misc = 0,
7713 .size = sizeof(namespaces_event.event_id),
7714 },
7715 /* .pid */
7716 /* .tid */
7717 .nr_namespaces = NR_NAMESPACES,
7718 /* .link_info[NR_NAMESPACES] */
7719 },
7720 };
7721
7722 ns_link_info = namespaces_event.event_id.link_info;
7723
7724 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7725 task, &mntns_operations);
7726
7727#ifdef CONFIG_USER_NS
7728 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7729 task, &userns_operations);
7730#endif
7731#ifdef CONFIG_NET_NS
7732 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7733 task, &netns_operations);
7734#endif
7735#ifdef CONFIG_UTS_NS
7736 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7737 task, &utsns_operations);
7738#endif
7739#ifdef CONFIG_IPC_NS
7740 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7741 task, &ipcns_operations);
7742#endif
7743#ifdef CONFIG_PID_NS
7744 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7745 task, &pidns_operations);
7746#endif
7747#ifdef CONFIG_CGROUPS
7748 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7749 task, &cgroupns_operations);
7750#endif
7751
7752 perf_iterate_sb(perf_event_namespaces_output,
7753 &namespaces_event,
7754 NULL);
7755}
7756
96aaab68
NK
7757/*
7758 * cgroup tracking
7759 */
7760#ifdef CONFIG_CGROUP_PERF
7761
7762struct perf_cgroup_event {
7763 char *path;
7764 int path_size;
7765 struct {
7766 struct perf_event_header header;
7767 u64 id;
7768 char path[];
7769 } event_id;
7770};
7771
7772static int perf_event_cgroup_match(struct perf_event *event)
7773{
7774 return event->attr.cgroup;
7775}
7776
7777static void perf_event_cgroup_output(struct perf_event *event, void *data)
7778{
7779 struct perf_cgroup_event *cgroup_event = data;
7780 struct perf_output_handle handle;
7781 struct perf_sample_data sample;
7782 u16 header_size = cgroup_event->event_id.header.size;
7783 int ret;
7784
7785 if (!perf_event_cgroup_match(event))
7786 return;
7787
7788 perf_event_header__init_id(&cgroup_event->event_id.header,
7789 &sample, event);
7790 ret = perf_output_begin(&handle, event,
7791 cgroup_event->event_id.header.size);
7792 if (ret)
7793 goto out;
7794
7795 perf_output_put(&handle, cgroup_event->event_id);
7796 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size);
7797
7798 perf_event__output_id_sample(event, &handle, &sample);
7799
7800 perf_output_end(&handle);
7801out:
7802 cgroup_event->event_id.header.size = header_size;
7803}
7804
7805static void perf_event_cgroup(struct cgroup *cgrp)
7806{
7807 struct perf_cgroup_event cgroup_event;
7808 char path_enomem[16] = "//enomem";
7809 char *pathname;
7810 size_t size;
7811
7812 if (!atomic_read(&nr_cgroup_events))
7813 return;
7814
7815 cgroup_event = (struct perf_cgroup_event){
7816 .event_id = {
7817 .header = {
7818 .type = PERF_RECORD_CGROUP,
7819 .misc = 0,
7820 .size = sizeof(cgroup_event.event_id),
7821 },
7822 .id = cgroup_id(cgrp),
7823 },
7824 };
7825
7826 pathname = kmalloc(PATH_MAX, GFP_KERNEL);
7827 if (pathname == NULL) {
7828 cgroup_event.path = path_enomem;
7829 } else {
7830 /* just to be sure to have enough space for alignment */
7831 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64));
7832 cgroup_event.path = pathname;
7833 }
7834
7835 /*
7836 * Since our buffer works in 8 byte units we need to align our string
7837 * size to a multiple of 8. However, we must guarantee the tail end is
7838 * zero'd out to avoid leaking random bits to userspace.
7839 */
7840 size = strlen(cgroup_event.path) + 1;
7841 while (!IS_ALIGNED(size, sizeof(u64)))
7842 cgroup_event.path[size++] = '\0';
7843
7844 cgroup_event.event_id.header.size += size;
7845 cgroup_event.path_size = size;
7846
7847 perf_iterate_sb(perf_event_cgroup_output,
7848 &cgroup_event,
7849 NULL);
7850
7851 kfree(pathname);
7852}
7853
7854#endif
7855
0a4a9391
PZ
7856/*
7857 * mmap tracking
7858 */
7859
7860struct perf_mmap_event {
089dd79d
PZ
7861 struct vm_area_struct *vma;
7862
7863 const char *file_name;
7864 int file_size;
13d7a241
SE
7865 int maj, min;
7866 u64 ino;
7867 u64 ino_generation;
f972eb63 7868 u32 prot, flags;
0a4a9391
PZ
7869
7870 struct {
7871 struct perf_event_header header;
7872
7873 u32 pid;
7874 u32 tid;
7875 u64 start;
7876 u64 len;
7877 u64 pgoff;
cdd6c482 7878 } event_id;
0a4a9391
PZ
7879};
7880
67516844
JO
7881static int perf_event_mmap_match(struct perf_event *event,
7882 void *data)
7883{
7884 struct perf_mmap_event *mmap_event = data;
7885 struct vm_area_struct *vma = mmap_event->vma;
7886 int executable = vma->vm_flags & VM_EXEC;
7887
7888 return (!executable && event->attr.mmap_data) ||
13d7a241 7889 (executable && (event->attr.mmap || event->attr.mmap2));
67516844
JO
7890}
7891
cdd6c482 7892static void perf_event_mmap_output(struct perf_event *event,
52d857a8 7893 void *data)
0a4a9391 7894{
52d857a8 7895 struct perf_mmap_event *mmap_event = data;
0a4a9391 7896 struct perf_output_handle handle;
c980d109 7897 struct perf_sample_data sample;
cdd6c482 7898 int size = mmap_event->event_id.header.size;
d9c1bb2f 7899 u32 type = mmap_event->event_id.header.type;
c980d109 7900 int ret;
0a4a9391 7901
67516844
JO
7902 if (!perf_event_mmap_match(event, data))
7903 return;
7904
13d7a241
SE
7905 if (event->attr.mmap2) {
7906 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
7907 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
7908 mmap_event->event_id.header.size += sizeof(mmap_event->min);
7909 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
d008d525 7910 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
f972eb63
PZ
7911 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
7912 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
13d7a241
SE
7913 }
7914
c980d109
ACM
7915 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
7916 ret = perf_output_begin(&handle, event,
a7ac67ea 7917 mmap_event->event_id.header.size);
0a4a9391 7918 if (ret)
c980d109 7919 goto out;
0a4a9391 7920
cdd6c482
IM
7921 mmap_event->event_id.pid = perf_event_pid(event, current);
7922 mmap_event->event_id.tid = perf_event_tid(event, current);
709e50cf 7923
cdd6c482 7924 perf_output_put(&handle, mmap_event->event_id);
13d7a241
SE
7925
7926 if (event->attr.mmap2) {
7927 perf_output_put(&handle, mmap_event->maj);
7928 perf_output_put(&handle, mmap_event->min);
7929 perf_output_put(&handle, mmap_event->ino);
7930 perf_output_put(&handle, mmap_event->ino_generation);
f972eb63
PZ
7931 perf_output_put(&handle, mmap_event->prot);
7932 perf_output_put(&handle, mmap_event->flags);
13d7a241
SE
7933 }
7934
76369139 7935 __output_copy(&handle, mmap_event->file_name,
0a4a9391 7936 mmap_event->file_size);
c980d109
ACM
7937
7938 perf_event__output_id_sample(event, &handle, &sample);
7939
78d613eb 7940 perf_output_end(&handle);
c980d109
ACM
7941out:
7942 mmap_event->event_id.header.size = size;
d9c1bb2f 7943 mmap_event->event_id.header.type = type;
0a4a9391
PZ
7944}
7945
cdd6c482 7946static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
0a4a9391 7947{
089dd79d
PZ
7948 struct vm_area_struct *vma = mmap_event->vma;
7949 struct file *file = vma->vm_file;
13d7a241
SE
7950 int maj = 0, min = 0;
7951 u64 ino = 0, gen = 0;
f972eb63 7952 u32 prot = 0, flags = 0;
0a4a9391
PZ
7953 unsigned int size;
7954 char tmp[16];
7955 char *buf = NULL;
2c42cfbf 7956 char *name;
413ee3b4 7957
0b3589be
PZ
7958 if (vma->vm_flags & VM_READ)
7959 prot |= PROT_READ;
7960 if (vma->vm_flags & VM_WRITE)
7961 prot |= PROT_WRITE;
7962 if (vma->vm_flags & VM_EXEC)
7963 prot |= PROT_EXEC;
7964
7965 if (vma->vm_flags & VM_MAYSHARE)
7966 flags = MAP_SHARED;
7967 else
7968 flags = MAP_PRIVATE;
7969
7970 if (vma->vm_flags & VM_DENYWRITE)
7971 flags |= MAP_DENYWRITE;
7972 if (vma->vm_flags & VM_MAYEXEC)
7973 flags |= MAP_EXECUTABLE;
7974 if (vma->vm_flags & VM_LOCKED)
7975 flags |= MAP_LOCKED;
7976 if (vma->vm_flags & VM_HUGETLB)
7977 flags |= MAP_HUGETLB;
7978
0a4a9391 7979 if (file) {
13d7a241
SE
7980 struct inode *inode;
7981 dev_t dev;
3ea2f2b9 7982
2c42cfbf 7983 buf = kmalloc(PATH_MAX, GFP_KERNEL);
0a4a9391 7984 if (!buf) {
c7e548b4
ON
7985 name = "//enomem";
7986 goto cpy_name;
0a4a9391 7987 }
413ee3b4 7988 /*
3ea2f2b9 7989 * d_path() works from the end of the rb backwards, so we
413ee3b4
AB
7990 * need to add enough zero bytes after the string to handle
7991 * the 64bit alignment we do later.
7992 */
9bf39ab2 7993 name = file_path(file, buf, PATH_MAX - sizeof(u64));
0a4a9391 7994 if (IS_ERR(name)) {
c7e548b4
ON
7995 name = "//toolong";
7996 goto cpy_name;
0a4a9391 7997 }
13d7a241
SE
7998 inode = file_inode(vma->vm_file);
7999 dev = inode->i_sb->s_dev;
8000 ino = inode->i_ino;
8001 gen = inode->i_generation;
8002 maj = MAJOR(dev);
8003 min = MINOR(dev);
f972eb63 8004
c7e548b4 8005 goto got_name;
0a4a9391 8006 } else {
fbe26abe
JO
8007 if (vma->vm_ops && vma->vm_ops->name) {
8008 name = (char *) vma->vm_ops->name(vma);
8009 if (name)
8010 goto cpy_name;
8011 }
8012
2c42cfbf 8013 name = (char *)arch_vma_name(vma);
c7e548b4
ON
8014 if (name)
8015 goto cpy_name;
089dd79d 8016
32c5fb7e 8017 if (vma->vm_start <= vma->vm_mm->start_brk &&
3af9e859 8018 vma->vm_end >= vma->vm_mm->brk) {
c7e548b4
ON
8019 name = "[heap]";
8020 goto cpy_name;
32c5fb7e
ON
8021 }
8022 if (vma->vm_start <= vma->vm_mm->start_stack &&
3af9e859 8023 vma->vm_end >= vma->vm_mm->start_stack) {
c7e548b4
ON
8024 name = "[stack]";
8025 goto cpy_name;
089dd79d
PZ
8026 }
8027
c7e548b4
ON
8028 name = "//anon";
8029 goto cpy_name;
0a4a9391
PZ
8030 }
8031
c7e548b4
ON
8032cpy_name:
8033 strlcpy(tmp, name, sizeof(tmp));
8034 name = tmp;
0a4a9391 8035got_name:
2c42cfbf
PZ
8036 /*
8037 * Since our buffer works in 8 byte units we need to align our string
8038 * size to a multiple of 8. However, we must guarantee the tail end is
8039 * zero'd out to avoid leaking random bits to userspace.
8040 */
8041 size = strlen(name)+1;
8042 while (!IS_ALIGNED(size, sizeof(u64)))
8043 name[size++] = '\0';
0a4a9391
PZ
8044
8045 mmap_event->file_name = name;
8046 mmap_event->file_size = size;
13d7a241
SE
8047 mmap_event->maj = maj;
8048 mmap_event->min = min;
8049 mmap_event->ino = ino;
8050 mmap_event->ino_generation = gen;
f972eb63
PZ
8051 mmap_event->prot = prot;
8052 mmap_event->flags = flags;
0a4a9391 8053
2fe85427
SE
8054 if (!(vma->vm_flags & VM_EXEC))
8055 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
8056
cdd6c482 8057 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
0a4a9391 8058
aab5b71e 8059 perf_iterate_sb(perf_event_mmap_output,
52d857a8
JO
8060 mmap_event,
8061 NULL);
665c2142 8062
0a4a9391
PZ
8063 kfree(buf);
8064}
8065
375637bc
AS
8066/*
8067 * Check whether inode and address range match filter criteria.
8068 */
8069static bool perf_addr_filter_match(struct perf_addr_filter *filter,
8070 struct file *file, unsigned long offset,
8071 unsigned long size)
8072{
7f635ff1
MP
8073 /* d_inode(NULL) won't be equal to any mapped user-space file */
8074 if (!filter->path.dentry)
8075 return false;
8076
9511bce9 8077 if (d_inode(filter->path.dentry) != file_inode(file))
375637bc
AS
8078 return false;
8079
8080 if (filter->offset > offset + size)
8081 return false;
8082
8083 if (filter->offset + filter->size < offset)
8084 return false;
8085
8086 return true;
8087}
8088
c60f83b8
AS
8089static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
8090 struct vm_area_struct *vma,
8091 struct perf_addr_filter_range *fr)
8092{
8093 unsigned long vma_size = vma->vm_end - vma->vm_start;
8094 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
8095 struct file *file = vma->vm_file;
8096
8097 if (!perf_addr_filter_match(filter, file, off, vma_size))
8098 return false;
8099
8100 if (filter->offset < off) {
8101 fr->start = vma->vm_start;
8102 fr->size = min(vma_size, filter->size - (off - filter->offset));
8103 } else {
8104 fr->start = vma->vm_start + filter->offset - off;
8105 fr->size = min(vma->vm_end - fr->start, filter->size);
8106 }
8107
8108 return true;
8109}
8110
375637bc
AS
8111static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
8112{
8113 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
8114 struct vm_area_struct *vma = data;
375637bc
AS
8115 struct perf_addr_filter *filter;
8116 unsigned int restart = 0, count = 0;
c60f83b8 8117 unsigned long flags;
375637bc
AS
8118
8119 if (!has_addr_filter(event))
8120 return;
8121
c60f83b8 8122 if (!vma->vm_file)
375637bc
AS
8123 return;
8124
8125 raw_spin_lock_irqsave(&ifh->lock, flags);
8126 list_for_each_entry(filter, &ifh->list, entry) {
c60f83b8
AS
8127 if (perf_addr_filter_vma_adjust(filter, vma,
8128 &event->addr_filter_ranges[count]))
375637bc 8129 restart++;
375637bc
AS
8130
8131 count++;
8132 }
8133
8134 if (restart)
8135 event->addr_filters_gen++;
8136 raw_spin_unlock_irqrestore(&ifh->lock, flags);
8137
8138 if (restart)
767ae086 8139 perf_event_stop(event, 1);
375637bc
AS
8140}
8141
8142/*
8143 * Adjust all task's events' filters to the new vma
8144 */
8145static void perf_addr_filters_adjust(struct vm_area_struct *vma)
8146{
8147 struct perf_event_context *ctx;
8148 int ctxn;
8149
12b40a23
MP
8150 /*
8151 * Data tracing isn't supported yet and as such there is no need
8152 * to keep track of anything that isn't related to executable code:
8153 */
8154 if (!(vma->vm_flags & VM_EXEC))
8155 return;
8156
375637bc
AS
8157 rcu_read_lock();
8158 for_each_task_context_nr(ctxn) {
8159 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
8160 if (!ctx)
8161 continue;
8162
aab5b71e 8163 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
375637bc
AS
8164 }
8165 rcu_read_unlock();
8166}
8167
3af9e859 8168void perf_event_mmap(struct vm_area_struct *vma)
0a4a9391 8169{
9ee318a7
PZ
8170 struct perf_mmap_event mmap_event;
8171
cdd6c482 8172 if (!atomic_read(&nr_mmap_events))
9ee318a7
PZ
8173 return;
8174
8175 mmap_event = (struct perf_mmap_event){
089dd79d 8176 .vma = vma,
573402db
PZ
8177 /* .file_name */
8178 /* .file_size */
cdd6c482 8179 .event_id = {
573402db 8180 .header = {
cdd6c482 8181 .type = PERF_RECORD_MMAP,
39447b38 8182 .misc = PERF_RECORD_MISC_USER,
573402db
PZ
8183 /* .size */
8184 },
8185 /* .pid */
8186 /* .tid */
089dd79d
PZ
8187 .start = vma->vm_start,
8188 .len = vma->vm_end - vma->vm_start,
3a0304e9 8189 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
0a4a9391 8190 },
13d7a241
SE
8191 /* .maj (attr_mmap2 only) */
8192 /* .min (attr_mmap2 only) */
8193 /* .ino (attr_mmap2 only) */
8194 /* .ino_generation (attr_mmap2 only) */
f972eb63
PZ
8195 /* .prot (attr_mmap2 only) */
8196 /* .flags (attr_mmap2 only) */
0a4a9391
PZ
8197 };
8198
375637bc 8199 perf_addr_filters_adjust(vma);
cdd6c482 8200 perf_event_mmap_event(&mmap_event);
0a4a9391
PZ
8201}
8202
68db7e98
AS
8203void perf_event_aux_event(struct perf_event *event, unsigned long head,
8204 unsigned long size, u64 flags)
8205{
8206 struct perf_output_handle handle;
8207 struct perf_sample_data sample;
8208 struct perf_aux_event {
8209 struct perf_event_header header;
8210 u64 offset;
8211 u64 size;
8212 u64 flags;
8213 } rec = {
8214 .header = {
8215 .type = PERF_RECORD_AUX,
8216 .misc = 0,
8217 .size = sizeof(rec),
8218 },
8219 .offset = head,
8220 .size = size,
8221 .flags = flags,
8222 };
8223 int ret;
8224
8225 perf_event_header__init_id(&rec.header, &sample, event);
8226 ret = perf_output_begin(&handle, event, rec.header.size);
8227
8228 if (ret)
8229 return;
8230
8231 perf_output_put(&handle, rec);
8232 perf_event__output_id_sample(event, &handle, &sample);
8233
8234 perf_output_end(&handle);
8235}
8236
f38b0dbb
KL
8237/*
8238 * Lost/dropped samples logging
8239 */
8240void perf_log_lost_samples(struct perf_event *event, u64 lost)
8241{
8242 struct perf_output_handle handle;
8243 struct perf_sample_data sample;
8244 int ret;
8245
8246 struct {
8247 struct perf_event_header header;
8248 u64 lost;
8249 } lost_samples_event = {
8250 .header = {
8251 .type = PERF_RECORD_LOST_SAMPLES,
8252 .misc = 0,
8253 .size = sizeof(lost_samples_event),
8254 },
8255 .lost = lost,
8256 };
8257
8258 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
8259
8260 ret = perf_output_begin(&handle, event,
8261 lost_samples_event.header.size);
8262 if (ret)
8263 return;
8264
8265 perf_output_put(&handle, lost_samples_event);
8266 perf_event__output_id_sample(event, &handle, &sample);
8267 perf_output_end(&handle);
8268}
8269
45ac1403
AH
8270/*
8271 * context_switch tracking
8272 */
8273
8274struct perf_switch_event {
8275 struct task_struct *task;
8276 struct task_struct *next_prev;
8277
8278 struct {
8279 struct perf_event_header header;
8280 u32 next_prev_pid;
8281 u32 next_prev_tid;
8282 } event_id;
8283};
8284
8285static int perf_event_switch_match(struct perf_event *event)
8286{
8287 return event->attr.context_switch;
8288}
8289
8290static void perf_event_switch_output(struct perf_event *event, void *data)
8291{
8292 struct perf_switch_event *se = data;
8293 struct perf_output_handle handle;
8294 struct perf_sample_data sample;
8295 int ret;
8296
8297 if (!perf_event_switch_match(event))
8298 return;
8299
8300 /* Only CPU-wide events are allowed to see next/prev pid/tid */
8301 if (event->ctx->task) {
8302 se->event_id.header.type = PERF_RECORD_SWITCH;
8303 se->event_id.header.size = sizeof(se->event_id.header);
8304 } else {
8305 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
8306 se->event_id.header.size = sizeof(se->event_id);
8307 se->event_id.next_prev_pid =
8308 perf_event_pid(event, se->next_prev);
8309 se->event_id.next_prev_tid =
8310 perf_event_tid(event, se->next_prev);
8311 }
8312
8313 perf_event_header__init_id(&se->event_id.header, &sample, event);
8314
8315 ret = perf_output_begin(&handle, event, se->event_id.header.size);
8316 if (ret)
8317 return;
8318
8319 if (event->ctx->task)
8320 perf_output_put(&handle, se->event_id.header);
8321 else
8322 perf_output_put(&handle, se->event_id);
8323
8324 perf_event__output_id_sample(event, &handle, &sample);
8325
8326 perf_output_end(&handle);
8327}
8328
8329static void perf_event_switch(struct task_struct *task,
8330 struct task_struct *next_prev, bool sched_in)
8331{
8332 struct perf_switch_event switch_event;
8333
8334 /* N.B. caller checks nr_switch_events != 0 */
8335
8336 switch_event = (struct perf_switch_event){
8337 .task = task,
8338 .next_prev = next_prev,
8339 .event_id = {
8340 .header = {
8341 /* .type */
8342 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
8343 /* .size */
8344 },
8345 /* .next_prev_pid */
8346 /* .next_prev_tid */
8347 },
8348 };
8349
101592b4
AB
8350 if (!sched_in && task->state == TASK_RUNNING)
8351 switch_event.event_id.header.misc |=
8352 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
8353
aab5b71e 8354 perf_iterate_sb(perf_event_switch_output,
45ac1403
AH
8355 &switch_event,
8356 NULL);
8357}
8358
a78ac325
PZ
8359/*
8360 * IRQ throttle logging
8361 */
8362
cdd6c482 8363static void perf_log_throttle(struct perf_event *event, int enable)
a78ac325
PZ
8364{
8365 struct perf_output_handle handle;
c980d109 8366 struct perf_sample_data sample;
a78ac325
PZ
8367 int ret;
8368
8369 struct {
8370 struct perf_event_header header;
8371 u64 time;
cca3f454 8372 u64 id;
7f453c24 8373 u64 stream_id;
a78ac325
PZ
8374 } throttle_event = {
8375 .header = {
cdd6c482 8376 .type = PERF_RECORD_THROTTLE,
a78ac325
PZ
8377 .misc = 0,
8378 .size = sizeof(throttle_event),
8379 },
34f43927 8380 .time = perf_event_clock(event),
cdd6c482
IM
8381 .id = primary_event_id(event),
8382 .stream_id = event->id,
a78ac325
PZ
8383 };
8384
966ee4d6 8385 if (enable)
cdd6c482 8386 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
966ee4d6 8387
c980d109
ACM
8388 perf_event_header__init_id(&throttle_event.header, &sample, event);
8389
8390 ret = perf_output_begin(&handle, event,
a7ac67ea 8391 throttle_event.header.size);
a78ac325
PZ
8392 if (ret)
8393 return;
8394
8395 perf_output_put(&handle, throttle_event);
c980d109 8396 perf_event__output_id_sample(event, &handle, &sample);
a78ac325
PZ
8397 perf_output_end(&handle);
8398}
8399
76193a94
SL
8400/*
8401 * ksymbol register/unregister tracking
8402 */
8403
8404struct perf_ksymbol_event {
8405 const char *name;
8406 int name_len;
8407 struct {
8408 struct perf_event_header header;
8409 u64 addr;
8410 u32 len;
8411 u16 ksym_type;
8412 u16 flags;
8413 } event_id;
8414};
8415
8416static int perf_event_ksymbol_match(struct perf_event *event)
8417{
8418 return event->attr.ksymbol;
8419}
8420
8421static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8422{
8423 struct perf_ksymbol_event *ksymbol_event = data;
8424 struct perf_output_handle handle;
8425 struct perf_sample_data sample;
8426 int ret;
8427
8428 if (!perf_event_ksymbol_match(event))
8429 return;
8430
8431 perf_event_header__init_id(&ksymbol_event->event_id.header,
8432 &sample, event);
8433 ret = perf_output_begin(&handle, event,
8434 ksymbol_event->event_id.header.size);
8435 if (ret)
8436 return;
8437
8438 perf_output_put(&handle, ksymbol_event->event_id);
8439 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8440 perf_event__output_id_sample(event, &handle, &sample);
8441
8442 perf_output_end(&handle);
8443}
8444
8445void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8446 const char *sym)
8447{
8448 struct perf_ksymbol_event ksymbol_event;
8449 char name[KSYM_NAME_LEN];
8450 u16 flags = 0;
8451 int name_len;
8452
8453 if (!atomic_read(&nr_ksymbol_events))
8454 return;
8455
8456 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8457 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8458 goto err;
8459
8460 strlcpy(name, sym, KSYM_NAME_LEN);
8461 name_len = strlen(name) + 1;
8462 while (!IS_ALIGNED(name_len, sizeof(u64)))
8463 name[name_len++] = '\0';
8464 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8465
8466 if (unregister)
8467 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8468
8469 ksymbol_event = (struct perf_ksymbol_event){
8470 .name = name,
8471 .name_len = name_len,
8472 .event_id = {
8473 .header = {
8474 .type = PERF_RECORD_KSYMBOL,
8475 .size = sizeof(ksymbol_event.event_id) +
8476 name_len,
8477 },
8478 .addr = addr,
8479 .len = len,
8480 .ksym_type = ksym_type,
8481 .flags = flags,
8482 },
8483 };
8484
8485 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8486 return;
8487err:
8488 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8489}
8490
6ee52e2a
SL
8491/*
8492 * bpf program load/unload tracking
8493 */
8494
8495struct perf_bpf_event {
8496 struct bpf_prog *prog;
8497 struct {
8498 struct perf_event_header header;
8499 u16 type;
8500 u16 flags;
8501 u32 id;
8502 u8 tag[BPF_TAG_SIZE];
8503 } event_id;
8504};
8505
8506static int perf_event_bpf_match(struct perf_event *event)
8507{
8508 return event->attr.bpf_event;
8509}
8510
8511static void perf_event_bpf_output(struct perf_event *event, void *data)
8512{
8513 struct perf_bpf_event *bpf_event = data;
8514 struct perf_output_handle handle;
8515 struct perf_sample_data sample;
8516 int ret;
8517
8518 if (!perf_event_bpf_match(event))
8519 return;
8520
8521 perf_event_header__init_id(&bpf_event->event_id.header,
8522 &sample, event);
8523 ret = perf_output_begin(&handle, event,
8524 bpf_event->event_id.header.size);
8525 if (ret)
8526 return;
8527
8528 perf_output_put(&handle, bpf_event->event_id);
8529 perf_event__output_id_sample(event, &handle, &sample);
8530
8531 perf_output_end(&handle);
8532}
8533
8534static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8535 enum perf_bpf_event_type type)
8536{
8537 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
6ee52e2a
SL
8538 int i;
8539
8540 if (prog->aux->func_cnt == 0) {
6ee52e2a
SL
8541 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8542 (u64)(unsigned long)prog->bpf_func,
bfea9a85
JO
8543 prog->jited_len, unregister,
8544 prog->aux->ksym.name);
6ee52e2a
SL
8545 } else {
8546 for (i = 0; i < prog->aux->func_cnt; i++) {
8547 struct bpf_prog *subprog = prog->aux->func[i];
8548
6ee52e2a
SL
8549 perf_event_ksymbol(
8550 PERF_RECORD_KSYMBOL_TYPE_BPF,
8551 (u64)(unsigned long)subprog->bpf_func,
bfea9a85
JO
8552 subprog->jited_len, unregister,
8553 prog->aux->ksym.name);
6ee52e2a
SL
8554 }
8555 }
8556}
8557
8558void perf_event_bpf_event(struct bpf_prog *prog,
8559 enum perf_bpf_event_type type,
8560 u16 flags)
8561{
8562 struct perf_bpf_event bpf_event;
8563
8564 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8565 type >= PERF_BPF_EVENT_MAX)
8566 return;
8567
8568 switch (type) {
8569 case PERF_BPF_EVENT_PROG_LOAD:
8570 case PERF_BPF_EVENT_PROG_UNLOAD:
8571 if (atomic_read(&nr_ksymbol_events))
8572 perf_event_bpf_emit_ksymbols(prog, type);
8573 break;
8574 default:
8575 break;
8576 }
8577
8578 if (!atomic_read(&nr_bpf_events))
8579 return;
8580
8581 bpf_event = (struct perf_bpf_event){
8582 .prog = prog,
8583 .event_id = {
8584 .header = {
8585 .type = PERF_RECORD_BPF_EVENT,
8586 .size = sizeof(bpf_event.event_id),
8587 },
8588 .type = type,
8589 .flags = flags,
8590 .id = prog->aux->id,
8591 },
8592 };
8593
8594 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8595
8596 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8597 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8598}
8599
8d4e6c4c
AS
8600void perf_event_itrace_started(struct perf_event *event)
8601{
8602 event->attach_state |= PERF_ATTACH_ITRACE;
8603}
8604
ec0d7729
AS
8605static void perf_log_itrace_start(struct perf_event *event)
8606{
8607 struct perf_output_handle handle;
8608 struct perf_sample_data sample;
8609 struct perf_aux_event {
8610 struct perf_event_header header;
8611 u32 pid;
8612 u32 tid;
8613 } rec;
8614 int ret;
8615
8616 if (event->parent)
8617 event = event->parent;
8618
8619 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8d4e6c4c 8620 event->attach_state & PERF_ATTACH_ITRACE)
ec0d7729
AS
8621 return;
8622
ec0d7729
AS
8623 rec.header.type = PERF_RECORD_ITRACE_START;
8624 rec.header.misc = 0;
8625 rec.header.size = sizeof(rec);
8626 rec.pid = perf_event_pid(event, current);
8627 rec.tid = perf_event_tid(event, current);
8628
8629 perf_event_header__init_id(&rec.header, &sample, event);
8630 ret = perf_output_begin(&handle, event, rec.header.size);
8631
8632 if (ret)
8633 return;
8634
8635 perf_output_put(&handle, rec);
8636 perf_event__output_id_sample(event, &handle, &sample);
8637
8638 perf_output_end(&handle);
8639}
8640
475113d9
JO
8641static int
8642__perf_event_account_interrupt(struct perf_event *event, int throttle)
f6c7d5fe 8643{
cdd6c482 8644 struct hw_perf_event *hwc = &event->hw;
79f14641 8645 int ret = 0;
475113d9 8646 u64 seq;
96398826 8647
e050e3f0
SE
8648 seq = __this_cpu_read(perf_throttled_seq);
8649 if (seq != hwc->interrupts_seq) {
8650 hwc->interrupts_seq = seq;
8651 hwc->interrupts = 1;
8652 } else {
8653 hwc->interrupts++;
8654 if (unlikely(throttle
8655 && hwc->interrupts >= max_samples_per_tick)) {
8656 __this_cpu_inc(perf_throttled_count);
555e0c1e 8657 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
163ec435
PZ
8658 hwc->interrupts = MAX_INTERRUPTS;
8659 perf_log_throttle(event, 0);
a78ac325
PZ
8660 ret = 1;
8661 }
e050e3f0 8662 }
60db5e09 8663
cdd6c482 8664 if (event->attr.freq) {
def0a9b2 8665 u64 now = perf_clock();
abd50713 8666 s64 delta = now - hwc->freq_time_stamp;
bd2b5b12 8667
abd50713 8668 hwc->freq_time_stamp = now;
bd2b5b12 8669
abd50713 8670 if (delta > 0 && delta < 2*TICK_NSEC)
f39d47ff 8671 perf_adjust_period(event, delta, hwc->last_period, true);
bd2b5b12
PZ
8672 }
8673
475113d9
JO
8674 return ret;
8675}
8676
8677int perf_event_account_interrupt(struct perf_event *event)
8678{
8679 return __perf_event_account_interrupt(event, 1);
8680}
8681
8682/*
8683 * Generic event overflow handling, sampling.
8684 */
8685
8686static int __perf_event_overflow(struct perf_event *event,
8687 int throttle, struct perf_sample_data *data,
8688 struct pt_regs *regs)
8689{
8690 int events = atomic_read(&event->event_limit);
8691 int ret = 0;
8692
8693 /*
8694 * Non-sampling counters might still use the PMI to fold short
8695 * hardware counters, ignore those.
8696 */
8697 if (unlikely(!is_sampling_event(event)))
8698 return 0;
8699
8700 ret = __perf_event_account_interrupt(event, throttle);
cc1582c2 8701
2023b359
PZ
8702 /*
8703 * XXX event_limit might not quite work as expected on inherited
cdd6c482 8704 * events
2023b359
PZ
8705 */
8706
cdd6c482
IM
8707 event->pending_kill = POLL_IN;
8708 if (events && atomic_dec_and_test(&event->event_limit)) {
79f14641 8709 ret = 1;
cdd6c482 8710 event->pending_kill = POLL_HUP;
5aab90ce
JO
8711
8712 perf_event_disable_inatomic(event);
79f14641
PZ
8713 }
8714
aa6a5f3c 8715 READ_ONCE(event->overflow_handler)(event, data, regs);
453f19ee 8716
fed66e2c 8717 if (*perf_event_fasync(event) && event->pending_kill) {
a8b0ca17
PZ
8718 event->pending_wakeup = 1;
8719 irq_work_queue(&event->pending);
f506b3dc
PZ
8720 }
8721
79f14641 8722 return ret;
f6c7d5fe
PZ
8723}
8724
a8b0ca17 8725int perf_event_overflow(struct perf_event *event,
5622f295
MM
8726 struct perf_sample_data *data,
8727 struct pt_regs *regs)
850bc73f 8728{
a8b0ca17 8729 return __perf_event_overflow(event, 1, data, regs);
850bc73f
PZ
8730}
8731
15dbf27c 8732/*
cdd6c482 8733 * Generic software event infrastructure
15dbf27c
PZ
8734 */
8735
b28ab83c
PZ
8736struct swevent_htable {
8737 struct swevent_hlist *swevent_hlist;
8738 struct mutex hlist_mutex;
8739 int hlist_refcount;
8740
8741 /* Recursion avoidance in each contexts */
8742 int recursion[PERF_NR_CONTEXTS];
8743};
8744
8745static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
8746
7b4b6658 8747/*
cdd6c482
IM
8748 * We directly increment event->count and keep a second value in
8749 * event->hw.period_left to count intervals. This period event
7b4b6658
PZ
8750 * is kept in the range [-sample_period, 0] so that we can use the
8751 * sign as trigger.
8752 */
8753
ab573844 8754u64 perf_swevent_set_period(struct perf_event *event)
15dbf27c 8755{
cdd6c482 8756 struct hw_perf_event *hwc = &event->hw;
7b4b6658
PZ
8757 u64 period = hwc->last_period;
8758 u64 nr, offset;
8759 s64 old, val;
8760
8761 hwc->last_period = hwc->sample_period;
15dbf27c
PZ
8762
8763again:
e7850595 8764 old = val = local64_read(&hwc->period_left);
7b4b6658
PZ
8765 if (val < 0)
8766 return 0;
15dbf27c 8767
7b4b6658
PZ
8768 nr = div64_u64(period + val, period);
8769 offset = nr * period;
8770 val -= offset;
e7850595 8771 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
7b4b6658 8772 goto again;
15dbf27c 8773
7b4b6658 8774 return nr;
15dbf27c
PZ
8775}
8776
0cff784a 8777static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
a8b0ca17 8778 struct perf_sample_data *data,
5622f295 8779 struct pt_regs *regs)
15dbf27c 8780{
cdd6c482 8781 struct hw_perf_event *hwc = &event->hw;
850bc73f 8782 int throttle = 0;
15dbf27c 8783
0cff784a
PZ
8784 if (!overflow)
8785 overflow = perf_swevent_set_period(event);
15dbf27c 8786
7b4b6658
PZ
8787 if (hwc->interrupts == MAX_INTERRUPTS)
8788 return;
15dbf27c 8789
7b4b6658 8790 for (; overflow; overflow--) {
a8b0ca17 8791 if (__perf_event_overflow(event, throttle,
5622f295 8792 data, regs)) {
7b4b6658
PZ
8793 /*
8794 * We inhibit the overflow from happening when
8795 * hwc->interrupts == MAX_INTERRUPTS.
8796 */
8797 break;
8798 }
cf450a73 8799 throttle = 1;
7b4b6658 8800 }
15dbf27c
PZ
8801}
8802
a4eaf7f1 8803static void perf_swevent_event(struct perf_event *event, u64 nr,
a8b0ca17 8804 struct perf_sample_data *data,
5622f295 8805 struct pt_regs *regs)
7b4b6658 8806{
cdd6c482 8807 struct hw_perf_event *hwc = &event->hw;
d6d020e9 8808
e7850595 8809 local64_add(nr, &event->count);
d6d020e9 8810
0cff784a
PZ
8811 if (!regs)
8812 return;
8813
6c7e550f 8814 if (!is_sampling_event(event))
7b4b6658 8815 return;
d6d020e9 8816
5d81e5cf
AV
8817 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
8818 data->period = nr;
8819 return perf_swevent_overflow(event, 1, data, regs);
8820 } else
8821 data->period = event->hw.last_period;
8822
0cff784a 8823 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
a8b0ca17 8824 return perf_swevent_overflow(event, 1, data, regs);
0cff784a 8825
e7850595 8826 if (local64_add_negative(nr, &hwc->period_left))
7b4b6658 8827 return;
df1a132b 8828
a8b0ca17 8829 perf_swevent_overflow(event, 0, data, regs);
d6d020e9
PZ
8830}
8831
f5ffe02e
FW
8832static int perf_exclude_event(struct perf_event *event,
8833 struct pt_regs *regs)
8834{
a4eaf7f1 8835 if (event->hw.state & PERF_HES_STOPPED)
91b2f482 8836 return 1;
a4eaf7f1 8837
f5ffe02e
FW
8838 if (regs) {
8839 if (event->attr.exclude_user && user_mode(regs))
8840 return 1;
8841
8842 if (event->attr.exclude_kernel && !user_mode(regs))
8843 return 1;
8844 }
8845
8846 return 0;
8847}
8848
cdd6c482 8849static int perf_swevent_match(struct perf_event *event,
1c432d89 8850 enum perf_type_id type,
6fb2915d
LZ
8851 u32 event_id,
8852 struct perf_sample_data *data,
8853 struct pt_regs *regs)
15dbf27c 8854{
cdd6c482 8855 if (event->attr.type != type)
a21ca2ca 8856 return 0;
f5ffe02e 8857
cdd6c482 8858 if (event->attr.config != event_id)
15dbf27c
PZ
8859 return 0;
8860
f5ffe02e
FW
8861 if (perf_exclude_event(event, regs))
8862 return 0;
15dbf27c
PZ
8863
8864 return 1;
8865}
8866
76e1d904
FW
8867static inline u64 swevent_hash(u64 type, u32 event_id)
8868{
8869 u64 val = event_id | (type << 32);
8870
8871 return hash_64(val, SWEVENT_HLIST_BITS);
8872}
8873
49f135ed
FW
8874static inline struct hlist_head *
8875__find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
76e1d904 8876{
49f135ed
FW
8877 u64 hash = swevent_hash(type, event_id);
8878
8879 return &hlist->heads[hash];
8880}
76e1d904 8881
49f135ed
FW
8882/* For the read side: events when they trigger */
8883static inline struct hlist_head *
b28ab83c 8884find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
49f135ed
FW
8885{
8886 struct swevent_hlist *hlist;
76e1d904 8887
b28ab83c 8888 hlist = rcu_dereference(swhash->swevent_hlist);
76e1d904
FW
8889 if (!hlist)
8890 return NULL;
8891
49f135ed
FW
8892 return __find_swevent_head(hlist, type, event_id);
8893}
8894
8895/* For the event head insertion and removal in the hlist */
8896static inline struct hlist_head *
b28ab83c 8897find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
49f135ed
FW
8898{
8899 struct swevent_hlist *hlist;
8900 u32 event_id = event->attr.config;
8901 u64 type = event->attr.type;
8902
8903 /*
8904 * Event scheduling is always serialized against hlist allocation
8905 * and release. Which makes the protected version suitable here.
8906 * The context lock guarantees that.
8907 */
b28ab83c 8908 hlist = rcu_dereference_protected(swhash->swevent_hlist,
49f135ed
FW
8909 lockdep_is_held(&event->ctx->lock));
8910 if (!hlist)
8911 return NULL;
8912
8913 return __find_swevent_head(hlist, type, event_id);
76e1d904
FW
8914}
8915
8916static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
a8b0ca17 8917 u64 nr,
76e1d904
FW
8918 struct perf_sample_data *data,
8919 struct pt_regs *regs)
15dbf27c 8920{
4a32fea9 8921 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
cdd6c482 8922 struct perf_event *event;
76e1d904 8923 struct hlist_head *head;
15dbf27c 8924
76e1d904 8925 rcu_read_lock();
b28ab83c 8926 head = find_swevent_head_rcu(swhash, type, event_id);
76e1d904
FW
8927 if (!head)
8928 goto end;
8929
b67bfe0d 8930 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6fb2915d 8931 if (perf_swevent_match(event, type, event_id, data, regs))
a8b0ca17 8932 perf_swevent_event(event, nr, data, regs);
15dbf27c 8933 }
76e1d904
FW
8934end:
8935 rcu_read_unlock();
15dbf27c
PZ
8936}
8937
86038c5e
PZI
8938DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
8939
4ed7c92d 8940int perf_swevent_get_recursion_context(void)
96f6d444 8941{
4a32fea9 8942 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
96f6d444 8943
b28ab83c 8944 return get_recursion_context(swhash->recursion);
96f6d444 8945}
645e8cc0 8946EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
96f6d444 8947
98b5c2c6 8948void perf_swevent_put_recursion_context(int rctx)
15dbf27c 8949{
4a32fea9 8950 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
927c7a9e 8951
b28ab83c 8952 put_recursion_context(swhash->recursion, rctx);
ce71b9df 8953}
15dbf27c 8954
86038c5e 8955void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
b8e83514 8956{
a4234bfc 8957 struct perf_sample_data data;
4ed7c92d 8958
86038c5e 8959 if (WARN_ON_ONCE(!regs))
4ed7c92d 8960 return;
a4234bfc 8961
fd0d000b 8962 perf_sample_data_init(&data, addr, 0);
a8b0ca17 8963 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
86038c5e
PZI
8964}
8965
8966void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
8967{
8968 int rctx;
8969
8970 preempt_disable_notrace();
8971 rctx = perf_swevent_get_recursion_context();
8972 if (unlikely(rctx < 0))
8973 goto fail;
8974
8975 ___perf_sw_event(event_id, nr, regs, addr);
4ed7c92d
PZ
8976
8977 perf_swevent_put_recursion_context(rctx);
86038c5e 8978fail:
1c024eca 8979 preempt_enable_notrace();
b8e83514
PZ
8980}
8981
cdd6c482 8982static void perf_swevent_read(struct perf_event *event)
15dbf27c 8983{
15dbf27c
PZ
8984}
8985
a4eaf7f1 8986static int perf_swevent_add(struct perf_event *event, int flags)
15dbf27c 8987{
4a32fea9 8988 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
cdd6c482 8989 struct hw_perf_event *hwc = &event->hw;
76e1d904
FW
8990 struct hlist_head *head;
8991
6c7e550f 8992 if (is_sampling_event(event)) {
7b4b6658 8993 hwc->last_period = hwc->sample_period;
cdd6c482 8994 perf_swevent_set_period(event);
7b4b6658 8995 }
76e1d904 8996
a4eaf7f1
PZ
8997 hwc->state = !(flags & PERF_EF_START);
8998
b28ab83c 8999 head = find_swevent_head(swhash, event);
12ca6ad2 9000 if (WARN_ON_ONCE(!head))
76e1d904
FW
9001 return -EINVAL;
9002
9003 hlist_add_head_rcu(&event->hlist_entry, head);
6a694a60 9004 perf_event_update_userpage(event);
76e1d904 9005
15dbf27c
PZ
9006 return 0;
9007}
9008
a4eaf7f1 9009static void perf_swevent_del(struct perf_event *event, int flags)
15dbf27c 9010{
76e1d904 9011 hlist_del_rcu(&event->hlist_entry);
15dbf27c
PZ
9012}
9013
a4eaf7f1 9014static void perf_swevent_start(struct perf_event *event, int flags)
5c92d124 9015{
a4eaf7f1 9016 event->hw.state = 0;
d6d020e9 9017}
aa9c4c0f 9018
a4eaf7f1 9019static void perf_swevent_stop(struct perf_event *event, int flags)
d6d020e9 9020{
a4eaf7f1 9021 event->hw.state = PERF_HES_STOPPED;
bae43c99
IM
9022}
9023
49f135ed
FW
9024/* Deref the hlist from the update side */
9025static inline struct swevent_hlist *
b28ab83c 9026swevent_hlist_deref(struct swevent_htable *swhash)
49f135ed 9027{
b28ab83c
PZ
9028 return rcu_dereference_protected(swhash->swevent_hlist,
9029 lockdep_is_held(&swhash->hlist_mutex));
49f135ed
FW
9030}
9031
b28ab83c 9032static void swevent_hlist_release(struct swevent_htable *swhash)
76e1d904 9033{
b28ab83c 9034 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
76e1d904 9035
49f135ed 9036 if (!hlist)
76e1d904
FW
9037 return;
9038
70691d4a 9039 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
fa4bbc4c 9040 kfree_rcu(hlist, rcu_head);
76e1d904
FW
9041}
9042
3b364d7b 9043static void swevent_hlist_put_cpu(int cpu)
76e1d904 9044{
b28ab83c 9045 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
76e1d904 9046
b28ab83c 9047 mutex_lock(&swhash->hlist_mutex);
76e1d904 9048
b28ab83c
PZ
9049 if (!--swhash->hlist_refcount)
9050 swevent_hlist_release(swhash);
76e1d904 9051
b28ab83c 9052 mutex_unlock(&swhash->hlist_mutex);
76e1d904
FW
9053}
9054
3b364d7b 9055static void swevent_hlist_put(void)
76e1d904
FW
9056{
9057 int cpu;
9058
76e1d904 9059 for_each_possible_cpu(cpu)
3b364d7b 9060 swevent_hlist_put_cpu(cpu);
76e1d904
FW
9061}
9062
3b364d7b 9063static int swevent_hlist_get_cpu(int cpu)
76e1d904 9064{
b28ab83c 9065 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
76e1d904
FW
9066 int err = 0;
9067
b28ab83c 9068 mutex_lock(&swhash->hlist_mutex);
a63fbed7
TG
9069 if (!swevent_hlist_deref(swhash) &&
9070 cpumask_test_cpu(cpu, perf_online_mask)) {
76e1d904
FW
9071 struct swevent_hlist *hlist;
9072
9073 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
9074 if (!hlist) {
9075 err = -ENOMEM;
9076 goto exit;
9077 }
b28ab83c 9078 rcu_assign_pointer(swhash->swevent_hlist, hlist);
76e1d904 9079 }
b28ab83c 9080 swhash->hlist_refcount++;
9ed6060d 9081exit:
b28ab83c 9082 mutex_unlock(&swhash->hlist_mutex);
76e1d904
FW
9083
9084 return err;
9085}
9086
3b364d7b 9087static int swevent_hlist_get(void)
76e1d904 9088{
3b364d7b 9089 int err, cpu, failed_cpu;
76e1d904 9090
a63fbed7 9091 mutex_lock(&pmus_lock);
76e1d904 9092 for_each_possible_cpu(cpu) {
3b364d7b 9093 err = swevent_hlist_get_cpu(cpu);
76e1d904
FW
9094 if (err) {
9095 failed_cpu = cpu;
9096 goto fail;
9097 }
9098 }
a63fbed7 9099 mutex_unlock(&pmus_lock);
76e1d904 9100 return 0;
9ed6060d 9101fail:
76e1d904
FW
9102 for_each_possible_cpu(cpu) {
9103 if (cpu == failed_cpu)
9104 break;
3b364d7b 9105 swevent_hlist_put_cpu(cpu);
76e1d904 9106 }
a63fbed7 9107 mutex_unlock(&pmus_lock);
76e1d904
FW
9108 return err;
9109}
9110
c5905afb 9111struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
95476b64 9112
b0a873eb
PZ
9113static void sw_perf_event_destroy(struct perf_event *event)
9114{
9115 u64 event_id = event->attr.config;
95476b64 9116
b0a873eb
PZ
9117 WARN_ON(event->parent);
9118
c5905afb 9119 static_key_slow_dec(&perf_swevent_enabled[event_id]);
3b364d7b 9120 swevent_hlist_put();
b0a873eb
PZ
9121}
9122
9123static int perf_swevent_init(struct perf_event *event)
9124{
8176cced 9125 u64 event_id = event->attr.config;
b0a873eb
PZ
9126
9127 if (event->attr.type != PERF_TYPE_SOFTWARE)
9128 return -ENOENT;
9129
2481c5fa
SE
9130 /*
9131 * no branch sampling for software events
9132 */
9133 if (has_branch_stack(event))
9134 return -EOPNOTSUPP;
9135
b0a873eb
PZ
9136 switch (event_id) {
9137 case PERF_COUNT_SW_CPU_CLOCK:
9138 case PERF_COUNT_SW_TASK_CLOCK:
9139 return -ENOENT;
9140
9141 default:
9142 break;
9143 }
9144
ce677831 9145 if (event_id >= PERF_COUNT_SW_MAX)
b0a873eb
PZ
9146 return -ENOENT;
9147
9148 if (!event->parent) {
9149 int err;
9150
3b364d7b 9151 err = swevent_hlist_get();
b0a873eb
PZ
9152 if (err)
9153 return err;
9154
c5905afb 9155 static_key_slow_inc(&perf_swevent_enabled[event_id]);
b0a873eb
PZ
9156 event->destroy = sw_perf_event_destroy;
9157 }
9158
9159 return 0;
9160}
9161
9162static struct pmu perf_swevent = {
89a1e187 9163 .task_ctx_nr = perf_sw_context,
95476b64 9164
34f43927
PZ
9165 .capabilities = PERF_PMU_CAP_NO_NMI,
9166
b0a873eb 9167 .event_init = perf_swevent_init,
a4eaf7f1
PZ
9168 .add = perf_swevent_add,
9169 .del = perf_swevent_del,
9170 .start = perf_swevent_start,
9171 .stop = perf_swevent_stop,
1c024eca 9172 .read = perf_swevent_read,
1c024eca
PZ
9173};
9174
b0a873eb
PZ
9175#ifdef CONFIG_EVENT_TRACING
9176
1c024eca
PZ
9177static int perf_tp_filter_match(struct perf_event *event,
9178 struct perf_sample_data *data)
9179{
7e3f977e 9180 void *record = data->raw->frag.data;
1c024eca 9181
b71b437e
PZ
9182 /* only top level events have filters set */
9183 if (event->parent)
9184 event = event->parent;
9185
1c024eca
PZ
9186 if (likely(!event->filter) || filter_match_preds(event->filter, record))
9187 return 1;
9188 return 0;
9189}
9190
9191static int perf_tp_event_match(struct perf_event *event,
9192 struct perf_sample_data *data,
9193 struct pt_regs *regs)
9194{
a0f7d0f7
FW
9195 if (event->hw.state & PERF_HES_STOPPED)
9196 return 0;
580d607c 9197 /*
9fd2e48b 9198 * If exclude_kernel, only trace user-space tracepoints (uprobes)
580d607c 9199 */
9fd2e48b 9200 if (event->attr.exclude_kernel && !user_mode(regs))
1c024eca
PZ
9201 return 0;
9202
9203 if (!perf_tp_filter_match(event, data))
9204 return 0;
9205
9206 return 1;
9207}
9208
85b67bcb
AS
9209void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
9210 struct trace_event_call *call, u64 count,
9211 struct pt_regs *regs, struct hlist_head *head,
9212 struct task_struct *task)
9213{
e87c6bc3 9214 if (bpf_prog_array_valid(call)) {
85b67bcb 9215 *(struct pt_regs **)raw_data = regs;
e87c6bc3 9216 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
85b67bcb
AS
9217 perf_swevent_put_recursion_context(rctx);
9218 return;
9219 }
9220 }
9221 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
8fd0fbbe 9222 rctx, task);
85b67bcb
AS
9223}
9224EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
9225
1e1dcd93 9226void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
e6dab5ff 9227 struct pt_regs *regs, struct hlist_head *head, int rctx,
8fd0fbbe 9228 struct task_struct *task)
95476b64
FW
9229{
9230 struct perf_sample_data data;
8fd0fbbe 9231 struct perf_event *event;
1c024eca 9232
95476b64 9233 struct perf_raw_record raw = {
7e3f977e
DB
9234 .frag = {
9235 .size = entry_size,
9236 .data = record,
9237 },
95476b64
FW
9238 };
9239
1e1dcd93 9240 perf_sample_data_init(&data, 0, 0);
95476b64
FW
9241 data.raw = &raw;
9242
1e1dcd93
AS
9243 perf_trace_buf_update(record, event_type);
9244
8fd0fbbe 9245 hlist_for_each_entry_rcu(event, head, hlist_entry) {
1c024eca 9246 if (perf_tp_event_match(event, &data, regs))
a8b0ca17 9247 perf_swevent_event(event, count, &data, regs);
4f41c013 9248 }
ecc55f84 9249
e6dab5ff
AV
9250 /*
9251 * If we got specified a target task, also iterate its context and
9252 * deliver this event there too.
9253 */
9254 if (task && task != current) {
9255 struct perf_event_context *ctx;
9256 struct trace_entry *entry = record;
9257
9258 rcu_read_lock();
9259 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
9260 if (!ctx)
9261 goto unlock;
9262
9263 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
cd6fb677
JO
9264 if (event->cpu != smp_processor_id())
9265 continue;
e6dab5ff
AV
9266 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9267 continue;
9268 if (event->attr.config != entry->type)
9269 continue;
9270 if (perf_tp_event_match(event, &data, regs))
9271 perf_swevent_event(event, count, &data, regs);
9272 }
9273unlock:
9274 rcu_read_unlock();
9275 }
9276
ecc55f84 9277 perf_swevent_put_recursion_context(rctx);
95476b64
FW
9278}
9279EXPORT_SYMBOL_GPL(perf_tp_event);
9280
cdd6c482 9281static void tp_perf_event_destroy(struct perf_event *event)
e077df4f 9282{
1c024eca 9283 perf_trace_destroy(event);
e077df4f
PZ
9284}
9285
b0a873eb 9286static int perf_tp_event_init(struct perf_event *event)
e077df4f 9287{
76e1d904
FW
9288 int err;
9289
b0a873eb
PZ
9290 if (event->attr.type != PERF_TYPE_TRACEPOINT)
9291 return -ENOENT;
9292
2481c5fa
SE
9293 /*
9294 * no branch sampling for tracepoint events
9295 */
9296 if (has_branch_stack(event))
9297 return -EOPNOTSUPP;
9298
1c024eca
PZ
9299 err = perf_trace_init(event);
9300 if (err)
b0a873eb 9301 return err;
e077df4f 9302
cdd6c482 9303 event->destroy = tp_perf_event_destroy;
e077df4f 9304
b0a873eb
PZ
9305 return 0;
9306}
9307
9308static struct pmu perf_tracepoint = {
89a1e187
PZ
9309 .task_ctx_nr = perf_sw_context,
9310
b0a873eb 9311 .event_init = perf_tp_event_init,
a4eaf7f1
PZ
9312 .add = perf_trace_add,
9313 .del = perf_trace_del,
9314 .start = perf_swevent_start,
9315 .stop = perf_swevent_stop,
b0a873eb 9316 .read = perf_swevent_read,
b0a873eb
PZ
9317};
9318
33ea4b24 9319#if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
e12f03d7
SL
9320/*
9321 * Flags in config, used by dynamic PMU kprobe and uprobe
9322 * The flags should match following PMU_FORMAT_ATTR().
9323 *
9324 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
9325 * if not set, create kprobe/uprobe
a6ca88b2
SL
9326 *
9327 * The following values specify a reference counter (or semaphore in the
9328 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
9329 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
9330 *
9331 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
9332 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
e12f03d7
SL
9333 */
9334enum perf_probe_config {
9335 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
a6ca88b2
SL
9336 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
9337 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
e12f03d7
SL
9338};
9339
9340PMU_FORMAT_ATTR(retprobe, "config:0");
a6ca88b2 9341#endif
e12f03d7 9342
a6ca88b2
SL
9343#ifdef CONFIG_KPROBE_EVENTS
9344static struct attribute *kprobe_attrs[] = {
e12f03d7
SL
9345 &format_attr_retprobe.attr,
9346 NULL,
9347};
9348
a6ca88b2 9349static struct attribute_group kprobe_format_group = {
e12f03d7 9350 .name = "format",
a6ca88b2 9351 .attrs = kprobe_attrs,
e12f03d7
SL
9352};
9353
a6ca88b2
SL
9354static const struct attribute_group *kprobe_attr_groups[] = {
9355 &kprobe_format_group,
e12f03d7
SL
9356 NULL,
9357};
9358
9359static int perf_kprobe_event_init(struct perf_event *event);
9360static struct pmu perf_kprobe = {
9361 .task_ctx_nr = perf_sw_context,
9362 .event_init = perf_kprobe_event_init,
9363 .add = perf_trace_add,
9364 .del = perf_trace_del,
9365 .start = perf_swevent_start,
9366 .stop = perf_swevent_stop,
9367 .read = perf_swevent_read,
a6ca88b2 9368 .attr_groups = kprobe_attr_groups,
e12f03d7
SL
9369};
9370
9371static int perf_kprobe_event_init(struct perf_event *event)
9372{
9373 int err;
9374 bool is_retprobe;
9375
9376 if (event->attr.type != perf_kprobe.type)
9377 return -ENOENT;
32e6e967
SL
9378
9379 if (!capable(CAP_SYS_ADMIN))
9380 return -EACCES;
9381
e12f03d7
SL
9382 /*
9383 * no branch sampling for probe events
9384 */
9385 if (has_branch_stack(event))
9386 return -EOPNOTSUPP;
9387
9388 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9389 err = perf_kprobe_init(event, is_retprobe);
9390 if (err)
9391 return err;
9392
9393 event->destroy = perf_kprobe_destroy;
9394
9395 return 0;
9396}
9397#endif /* CONFIG_KPROBE_EVENTS */
9398
33ea4b24 9399#ifdef CONFIG_UPROBE_EVENTS
a6ca88b2
SL
9400PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
9401
9402static struct attribute *uprobe_attrs[] = {
9403 &format_attr_retprobe.attr,
9404 &format_attr_ref_ctr_offset.attr,
9405 NULL,
9406};
9407
9408static struct attribute_group uprobe_format_group = {
9409 .name = "format",
9410 .attrs = uprobe_attrs,
9411};
9412
9413static const struct attribute_group *uprobe_attr_groups[] = {
9414 &uprobe_format_group,
9415 NULL,
9416};
9417
33ea4b24
SL
9418static int perf_uprobe_event_init(struct perf_event *event);
9419static struct pmu perf_uprobe = {
9420 .task_ctx_nr = perf_sw_context,
9421 .event_init = perf_uprobe_event_init,
9422 .add = perf_trace_add,
9423 .del = perf_trace_del,
9424 .start = perf_swevent_start,
9425 .stop = perf_swevent_stop,
9426 .read = perf_swevent_read,
a6ca88b2 9427 .attr_groups = uprobe_attr_groups,
33ea4b24
SL
9428};
9429
9430static int perf_uprobe_event_init(struct perf_event *event)
9431{
9432 int err;
a6ca88b2 9433 unsigned long ref_ctr_offset;
33ea4b24
SL
9434 bool is_retprobe;
9435
9436 if (event->attr.type != perf_uprobe.type)
9437 return -ENOENT;
32e6e967
SL
9438
9439 if (!capable(CAP_SYS_ADMIN))
9440 return -EACCES;
9441
33ea4b24
SL
9442 /*
9443 * no branch sampling for probe events
9444 */
9445 if (has_branch_stack(event))
9446 return -EOPNOTSUPP;
9447
9448 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
a6ca88b2
SL
9449 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9450 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
33ea4b24
SL
9451 if (err)
9452 return err;
9453
9454 event->destroy = perf_uprobe_destroy;
9455
9456 return 0;
9457}
9458#endif /* CONFIG_UPROBE_EVENTS */
9459
b0a873eb
PZ
9460static inline void perf_tp_register(void)
9461{
2e80a82a 9462 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
e12f03d7
SL
9463#ifdef CONFIG_KPROBE_EVENTS
9464 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9465#endif
33ea4b24
SL
9466#ifdef CONFIG_UPROBE_EVENTS
9467 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9468#endif
e077df4f 9469}
6fb2915d 9470
6fb2915d
LZ
9471static void perf_event_free_filter(struct perf_event *event)
9472{
9473 ftrace_profile_free_filter(event);
9474}
9475
aa6a5f3c
AS
9476#ifdef CONFIG_BPF_SYSCALL
9477static void bpf_overflow_handler(struct perf_event *event,
9478 struct perf_sample_data *data,
9479 struct pt_regs *regs)
9480{
9481 struct bpf_perf_event_data_kern ctx = {
9482 .data = data,
7d9285e8 9483 .event = event,
aa6a5f3c
AS
9484 };
9485 int ret = 0;
9486
c895f6f7 9487 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
aa6a5f3c
AS
9488 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9489 goto out;
9490 rcu_read_lock();
88575199 9491 ret = BPF_PROG_RUN(event->prog, &ctx);
aa6a5f3c
AS
9492 rcu_read_unlock();
9493out:
9494 __this_cpu_dec(bpf_prog_active);
aa6a5f3c
AS
9495 if (!ret)
9496 return;
9497
9498 event->orig_overflow_handler(event, data, regs);
9499}
9500
9501static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9502{
9503 struct bpf_prog *prog;
9504
9505 if (event->overflow_handler_context)
9506 /* hw breakpoint or kernel counter */
9507 return -EINVAL;
9508
9509 if (event->prog)
9510 return -EEXIST;
9511
9512 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9513 if (IS_ERR(prog))
9514 return PTR_ERR(prog);
9515
9516 event->prog = prog;
9517 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9518 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9519 return 0;
9520}
9521
9522static void perf_event_free_bpf_handler(struct perf_event *event)
9523{
9524 struct bpf_prog *prog = event->prog;
9525
9526 if (!prog)
9527 return;
9528
9529 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9530 event->prog = NULL;
9531 bpf_prog_put(prog);
9532}
9533#else
9534static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9535{
9536 return -EOPNOTSUPP;
9537}
9538static void perf_event_free_bpf_handler(struct perf_event *event)
9539{
9540}
9541#endif
9542
e12f03d7
SL
9543/*
9544 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9545 * with perf_event_open()
9546 */
9547static inline bool perf_event_is_tracing(struct perf_event *event)
9548{
9549 if (event->pmu == &perf_tracepoint)
9550 return true;
9551#ifdef CONFIG_KPROBE_EVENTS
9552 if (event->pmu == &perf_kprobe)
9553 return true;
33ea4b24
SL
9554#endif
9555#ifdef CONFIG_UPROBE_EVENTS
9556 if (event->pmu == &perf_uprobe)
9557 return true;
e12f03d7
SL
9558#endif
9559 return false;
9560}
9561
2541517c
AS
9562static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9563{
cf5f5cea 9564 bool is_kprobe, is_tracepoint, is_syscall_tp;
2541517c 9565 struct bpf_prog *prog;
e87c6bc3 9566 int ret;
2541517c 9567
e12f03d7 9568 if (!perf_event_is_tracing(event))
f91840a3 9569 return perf_event_set_bpf_handler(event, prog_fd);
2541517c 9570
98b5c2c6
AS
9571 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9572 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
cf5f5cea
YS
9573 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9574 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
98b5c2c6 9575 /* bpf programs can only be attached to u/kprobe or tracepoint */
2541517c
AS
9576 return -EINVAL;
9577
9578 prog = bpf_prog_get(prog_fd);
9579 if (IS_ERR(prog))
9580 return PTR_ERR(prog);
9581
98b5c2c6 9582 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
cf5f5cea
YS
9583 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9584 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
2541517c
AS
9585 /* valid fd, but invalid bpf program type */
9586 bpf_prog_put(prog);
9587 return -EINVAL;
9588 }
9589
9802d865
JB
9590 /* Kprobe override only works for kprobes, not uprobes. */
9591 if (prog->kprobe_override &&
9592 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9593 bpf_prog_put(prog);
9594 return -EINVAL;
9595 }
9596
cf5f5cea 9597 if (is_tracepoint || is_syscall_tp) {
32bbe007
AS
9598 int off = trace_event_get_offsets(event->tp_event);
9599
9600 if (prog->aux->max_ctx_offset > off) {
9601 bpf_prog_put(prog);
9602 return -EACCES;
9603 }
9604 }
2541517c 9605
e87c6bc3
YS
9606 ret = perf_event_attach_bpf_prog(event, prog);
9607 if (ret)
9608 bpf_prog_put(prog);
9609 return ret;
2541517c
AS
9610}
9611
9612static void perf_event_free_bpf_prog(struct perf_event *event)
9613{
e12f03d7 9614 if (!perf_event_is_tracing(event)) {
0b4c6841 9615 perf_event_free_bpf_handler(event);
2541517c 9616 return;
2541517c 9617 }
e87c6bc3 9618 perf_event_detach_bpf_prog(event);
2541517c
AS
9619}
9620
e077df4f 9621#else
6fb2915d 9622
b0a873eb 9623static inline void perf_tp_register(void)
e077df4f 9624{
e077df4f 9625}
6fb2915d 9626
6fb2915d
LZ
9627static void perf_event_free_filter(struct perf_event *event)
9628{
9629}
9630
2541517c
AS
9631static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9632{
9633 return -ENOENT;
9634}
9635
9636static void perf_event_free_bpf_prog(struct perf_event *event)
9637{
9638}
07b139c8 9639#endif /* CONFIG_EVENT_TRACING */
e077df4f 9640
24f1e32c 9641#ifdef CONFIG_HAVE_HW_BREAKPOINT
f5ffe02e 9642void perf_bp_event(struct perf_event *bp, void *data)
24f1e32c 9643{
f5ffe02e
FW
9644 struct perf_sample_data sample;
9645 struct pt_regs *regs = data;
9646
fd0d000b 9647 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
f5ffe02e 9648
a4eaf7f1 9649 if (!bp->hw.state && !perf_exclude_event(bp, regs))
a8b0ca17 9650 perf_swevent_event(bp, 1, &sample, regs);
24f1e32c
FW
9651}
9652#endif
9653
375637bc
AS
9654/*
9655 * Allocate a new address filter
9656 */
9657static struct perf_addr_filter *
9658perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9659{
9660 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9661 struct perf_addr_filter *filter;
9662
9663 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9664 if (!filter)
9665 return NULL;
9666
9667 INIT_LIST_HEAD(&filter->entry);
9668 list_add_tail(&filter->entry, filters);
9669
9670 return filter;
9671}
9672
9673static void free_filters_list(struct list_head *filters)
9674{
9675 struct perf_addr_filter *filter, *iter;
9676
9677 list_for_each_entry_safe(filter, iter, filters, entry) {
9511bce9 9678 path_put(&filter->path);
375637bc
AS
9679 list_del(&filter->entry);
9680 kfree(filter);
9681 }
9682}
9683
9684/*
9685 * Free existing address filters and optionally install new ones
9686 */
9687static void perf_addr_filters_splice(struct perf_event *event,
9688 struct list_head *head)
9689{
9690 unsigned long flags;
9691 LIST_HEAD(list);
9692
9693 if (!has_addr_filter(event))
9694 return;
9695
9696 /* don't bother with children, they don't have their own filters */
9697 if (event->parent)
9698 return;
9699
9700 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9701
9702 list_splice_init(&event->addr_filters.list, &list);
9703 if (head)
9704 list_splice(head, &event->addr_filters.list);
9705
9706 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9707
9708 free_filters_list(&list);
9709}
9710
9711/*
9712 * Scan through mm's vmas and see if one of them matches the
9713 * @filter; if so, adjust filter's address range.
9714 * Called with mm::mmap_sem down for reading.
9715 */
c60f83b8
AS
9716static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9717 struct mm_struct *mm,
9718 struct perf_addr_filter_range *fr)
375637bc
AS
9719{
9720 struct vm_area_struct *vma;
9721
9722 for (vma = mm->mmap; vma; vma = vma->vm_next) {
c60f83b8 9723 if (!vma->vm_file)
375637bc
AS
9724 continue;
9725
c60f83b8
AS
9726 if (perf_addr_filter_vma_adjust(filter, vma, fr))
9727 return;
375637bc 9728 }
375637bc
AS
9729}
9730
9731/*
9732 * Update event's address range filters based on the
9733 * task's existing mappings, if any.
9734 */
9735static void perf_event_addr_filters_apply(struct perf_event *event)
9736{
9737 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9738 struct task_struct *task = READ_ONCE(event->ctx->task);
9739 struct perf_addr_filter *filter;
9740 struct mm_struct *mm = NULL;
9741 unsigned int count = 0;
9742 unsigned long flags;
9743
9744 /*
9745 * We may observe TASK_TOMBSTONE, which means that the event tear-down
9746 * will stop on the parent's child_mutex that our caller is also holding
9747 */
9748 if (task == TASK_TOMBSTONE)
9749 return;
9750
52a44f83
AS
9751 if (ifh->nr_file_filters) {
9752 mm = get_task_mm(event->ctx->task);
9753 if (!mm)
9754 goto restart;
375637bc 9755
52a44f83
AS
9756 down_read(&mm->mmap_sem);
9757 }
375637bc
AS
9758
9759 raw_spin_lock_irqsave(&ifh->lock, flags);
9760 list_for_each_entry(filter, &ifh->list, entry) {
52a44f83
AS
9761 if (filter->path.dentry) {
9762 /*
9763 * Adjust base offset if the filter is associated to a
9764 * binary that needs to be mapped:
9765 */
9766 event->addr_filter_ranges[count].start = 0;
9767 event->addr_filter_ranges[count].size = 0;
375637bc 9768
c60f83b8 9769 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
52a44f83
AS
9770 } else {
9771 event->addr_filter_ranges[count].start = filter->offset;
9772 event->addr_filter_ranges[count].size = filter->size;
9773 }
375637bc
AS
9774
9775 count++;
9776 }
9777
9778 event->addr_filters_gen++;
9779 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9780
52a44f83
AS
9781 if (ifh->nr_file_filters) {
9782 up_read(&mm->mmap_sem);
375637bc 9783
52a44f83
AS
9784 mmput(mm);
9785 }
375637bc
AS
9786
9787restart:
767ae086 9788 perf_event_stop(event, 1);
375637bc
AS
9789}
9790
9791/*
9792 * Address range filtering: limiting the data to certain
9793 * instruction address ranges. Filters are ioctl()ed to us from
9794 * userspace as ascii strings.
9795 *
9796 * Filter string format:
9797 *
9798 * ACTION RANGE_SPEC
9799 * where ACTION is one of the
9800 * * "filter": limit the trace to this region
9801 * * "start": start tracing from this address
9802 * * "stop": stop tracing at this address/region;
9803 * RANGE_SPEC is
9804 * * for kernel addresses: <start address>[/<size>]
9805 * * for object files: <start address>[/<size>]@</path/to/object/file>
9806 *
6ed70cf3
AS
9807 * if <size> is not specified or is zero, the range is treated as a single
9808 * address; not valid for ACTION=="filter".
375637bc
AS
9809 */
9810enum {
e96271f3 9811 IF_ACT_NONE = -1,
375637bc
AS
9812 IF_ACT_FILTER,
9813 IF_ACT_START,
9814 IF_ACT_STOP,
9815 IF_SRC_FILE,
9816 IF_SRC_KERNEL,
9817 IF_SRC_FILEADDR,
9818 IF_SRC_KERNELADDR,
9819};
9820
9821enum {
9822 IF_STATE_ACTION = 0,
9823 IF_STATE_SOURCE,
9824 IF_STATE_END,
9825};
9826
9827static const match_table_t if_tokens = {
9828 { IF_ACT_FILTER, "filter" },
9829 { IF_ACT_START, "start" },
9830 { IF_ACT_STOP, "stop" },
9831 { IF_SRC_FILE, "%u/%u@%s" },
9832 { IF_SRC_KERNEL, "%u/%u" },
9833 { IF_SRC_FILEADDR, "%u@%s" },
9834 { IF_SRC_KERNELADDR, "%u" },
e96271f3 9835 { IF_ACT_NONE, NULL },
375637bc
AS
9836};
9837
9838/*
9839 * Address filter string parser
9840 */
9841static int
9842perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
9843 struct list_head *filters)
9844{
9845 struct perf_addr_filter *filter = NULL;
9846 char *start, *orig, *filename = NULL;
375637bc
AS
9847 substring_t args[MAX_OPT_ARGS];
9848 int state = IF_STATE_ACTION, token;
9849 unsigned int kernel = 0;
9850 int ret = -EINVAL;
9851
9852 orig = fstr = kstrdup(fstr, GFP_KERNEL);
9853 if (!fstr)
9854 return -ENOMEM;
9855
9856 while ((start = strsep(&fstr, " ,\n")) != NULL) {
6ed70cf3
AS
9857 static const enum perf_addr_filter_action_t actions[] = {
9858 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
9859 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
9860 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
9861 };
375637bc
AS
9862 ret = -EINVAL;
9863
9864 if (!*start)
9865 continue;
9866
9867 /* filter definition begins */
9868 if (state == IF_STATE_ACTION) {
9869 filter = perf_addr_filter_new(event, filters);
9870 if (!filter)
9871 goto fail;
9872 }
9873
9874 token = match_token(start, if_tokens, args);
9875 switch (token) {
9876 case IF_ACT_FILTER:
9877 case IF_ACT_START:
375637bc
AS
9878 case IF_ACT_STOP:
9879 if (state != IF_STATE_ACTION)
9880 goto fail;
9881
6ed70cf3 9882 filter->action = actions[token];
375637bc
AS
9883 state = IF_STATE_SOURCE;
9884 break;
9885
9886 case IF_SRC_KERNELADDR:
9887 case IF_SRC_KERNEL:
9888 kernel = 1;
10c3405f 9889 /* fall through */
375637bc
AS
9890
9891 case IF_SRC_FILEADDR:
9892 case IF_SRC_FILE:
9893 if (state != IF_STATE_SOURCE)
9894 goto fail;
9895
375637bc
AS
9896 *args[0].to = 0;
9897 ret = kstrtoul(args[0].from, 0, &filter->offset);
9898 if (ret)
9899 goto fail;
9900
6ed70cf3 9901 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
375637bc
AS
9902 *args[1].to = 0;
9903 ret = kstrtoul(args[1].from, 0, &filter->size);
9904 if (ret)
9905 goto fail;
9906 }
9907
4059ffd0 9908 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
6ed70cf3 9909 int fpos = token == IF_SRC_FILE ? 2 : 1;
4059ffd0
MP
9910
9911 filename = match_strdup(&args[fpos]);
375637bc
AS
9912 if (!filename) {
9913 ret = -ENOMEM;
9914 goto fail;
9915 }
9916 }
9917
9918 state = IF_STATE_END;
9919 break;
9920
9921 default:
9922 goto fail;
9923 }
9924
9925 /*
9926 * Filter definition is fully parsed, validate and install it.
9927 * Make sure that it doesn't contradict itself or the event's
9928 * attribute.
9929 */
9930 if (state == IF_STATE_END) {
9ccbfbb1 9931 ret = -EINVAL;
375637bc
AS
9932 if (kernel && event->attr.exclude_kernel)
9933 goto fail;
9934
6ed70cf3
AS
9935 /*
9936 * ACTION "filter" must have a non-zero length region
9937 * specified.
9938 */
9939 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
9940 !filter->size)
9941 goto fail;
9942
375637bc
AS
9943 if (!kernel) {
9944 if (!filename)
9945 goto fail;
9946
6ce77bfd
AS
9947 /*
9948 * For now, we only support file-based filters
9949 * in per-task events; doing so for CPU-wide
9950 * events requires additional context switching
9951 * trickery, since same object code will be
9952 * mapped at different virtual addresses in
9953 * different processes.
9954 */
9955 ret = -EOPNOTSUPP;
9956 if (!event->ctx->task)
9957 goto fail_free_name;
9958
375637bc 9959 /* look up the path and grab its inode */
9511bce9
SL
9960 ret = kern_path(filename, LOOKUP_FOLLOW,
9961 &filter->path);
375637bc
AS
9962 if (ret)
9963 goto fail_free_name;
9964
375637bc
AS
9965 kfree(filename);
9966 filename = NULL;
9967
9968 ret = -EINVAL;
9511bce9
SL
9969 if (!filter->path.dentry ||
9970 !S_ISREG(d_inode(filter->path.dentry)
9971 ->i_mode))
375637bc 9972 goto fail;
6ce77bfd
AS
9973
9974 event->addr_filters.nr_file_filters++;
375637bc
AS
9975 }
9976
9977 /* ready to consume more filters */
9978 state = IF_STATE_ACTION;
9979 filter = NULL;
9980 }
9981 }
9982
9983 if (state != IF_STATE_ACTION)
9984 goto fail;
9985
9986 kfree(orig);
9987
9988 return 0;
9989
9990fail_free_name:
9991 kfree(filename);
9992fail:
9993 free_filters_list(filters);
9994 kfree(orig);
9995
9996 return ret;
9997}
9998
9999static int
10000perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
10001{
10002 LIST_HEAD(filters);
10003 int ret;
10004
10005 /*
10006 * Since this is called in perf_ioctl() path, we're already holding
10007 * ctx::mutex.
10008 */
10009 lockdep_assert_held(&event->ctx->mutex);
10010
10011 if (WARN_ON_ONCE(event->parent))
10012 return -EINVAL;
10013
375637bc
AS
10014 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
10015 if (ret)
6ce77bfd 10016 goto fail_clear_files;
375637bc
AS
10017
10018 ret = event->pmu->addr_filters_validate(&filters);
6ce77bfd
AS
10019 if (ret)
10020 goto fail_free_filters;
375637bc
AS
10021
10022 /* remove existing filters, if any */
10023 perf_addr_filters_splice(event, &filters);
10024
10025 /* install new filters */
10026 perf_event_for_each_child(event, perf_event_addr_filters_apply);
10027
6ce77bfd
AS
10028 return ret;
10029
10030fail_free_filters:
10031 free_filters_list(&filters);
10032
10033fail_clear_files:
10034 event->addr_filters.nr_file_filters = 0;
10035
375637bc
AS
10036 return ret;
10037}
10038
c796bbbe
AS
10039static int perf_event_set_filter(struct perf_event *event, void __user *arg)
10040{
c796bbbe 10041 int ret = -EINVAL;
e12f03d7 10042 char *filter_str;
c796bbbe
AS
10043
10044 filter_str = strndup_user(arg, PAGE_SIZE);
10045 if (IS_ERR(filter_str))
10046 return PTR_ERR(filter_str);
10047
e12f03d7
SL
10048#ifdef CONFIG_EVENT_TRACING
10049 if (perf_event_is_tracing(event)) {
10050 struct perf_event_context *ctx = event->ctx;
10051
10052 /*
10053 * Beware, here be dragons!!
10054 *
10055 * the tracepoint muck will deadlock against ctx->mutex, but
10056 * the tracepoint stuff does not actually need it. So
10057 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
10058 * already have a reference on ctx.
10059 *
10060 * This can result in event getting moved to a different ctx,
10061 * but that does not affect the tracepoint state.
10062 */
10063 mutex_unlock(&ctx->mutex);
10064 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
10065 mutex_lock(&ctx->mutex);
10066 } else
10067#endif
10068 if (has_addr_filter(event))
375637bc 10069 ret = perf_event_set_addr_filter(event, filter_str);
c796bbbe
AS
10070
10071 kfree(filter_str);
10072 return ret;
10073}
10074
b0a873eb
PZ
10075/*
10076 * hrtimer based swevent callback
10077 */
f29ac756 10078
b0a873eb 10079static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
f29ac756 10080{
b0a873eb
PZ
10081 enum hrtimer_restart ret = HRTIMER_RESTART;
10082 struct perf_sample_data data;
10083 struct pt_regs *regs;
10084 struct perf_event *event;
10085 u64 period;
f29ac756 10086
b0a873eb 10087 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
ba3dd36c
PZ
10088
10089 if (event->state != PERF_EVENT_STATE_ACTIVE)
10090 return HRTIMER_NORESTART;
10091
b0a873eb 10092 event->pmu->read(event);
f344011c 10093
fd0d000b 10094 perf_sample_data_init(&data, 0, event->hw.last_period);
b0a873eb
PZ
10095 regs = get_irq_regs();
10096
10097 if (regs && !perf_exclude_event(event, regs)) {
77aeeebd 10098 if (!(event->attr.exclude_idle && is_idle_task(current)))
33b07b8b 10099 if (__perf_event_overflow(event, 1, &data, regs))
b0a873eb
PZ
10100 ret = HRTIMER_NORESTART;
10101 }
24f1e32c 10102
b0a873eb
PZ
10103 period = max_t(u64, 10000, event->hw.sample_period);
10104 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
24f1e32c 10105
b0a873eb 10106 return ret;
f29ac756
PZ
10107}
10108
b0a873eb 10109static void perf_swevent_start_hrtimer(struct perf_event *event)
5c92d124 10110{
b0a873eb 10111 struct hw_perf_event *hwc = &event->hw;
5d508e82
FBH
10112 s64 period;
10113
10114 if (!is_sampling_event(event))
10115 return;
f5ffe02e 10116
5d508e82
FBH
10117 period = local64_read(&hwc->period_left);
10118 if (period) {
10119 if (period < 0)
10120 period = 10000;
fa407f35 10121
5d508e82
FBH
10122 local64_set(&hwc->period_left, 0);
10123 } else {
10124 period = max_t(u64, 10000, hwc->sample_period);
10125 }
3497d206 10126 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
30f9028b 10127 HRTIMER_MODE_REL_PINNED_HARD);
24f1e32c 10128}
b0a873eb
PZ
10129
10130static void perf_swevent_cancel_hrtimer(struct perf_event *event)
24f1e32c 10131{
b0a873eb
PZ
10132 struct hw_perf_event *hwc = &event->hw;
10133
6c7e550f 10134 if (is_sampling_event(event)) {
b0a873eb 10135 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
fa407f35 10136 local64_set(&hwc->period_left, ktime_to_ns(remaining));
b0a873eb
PZ
10137
10138 hrtimer_cancel(&hwc->hrtimer);
10139 }
24f1e32c
FW
10140}
10141
ba3dd36c
PZ
10142static void perf_swevent_init_hrtimer(struct perf_event *event)
10143{
10144 struct hw_perf_event *hwc = &event->hw;
10145
10146 if (!is_sampling_event(event))
10147 return;
10148
30f9028b 10149 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
ba3dd36c
PZ
10150 hwc->hrtimer.function = perf_swevent_hrtimer;
10151
10152 /*
10153 * Since hrtimers have a fixed rate, we can do a static freq->period
10154 * mapping and avoid the whole period adjust feedback stuff.
10155 */
10156 if (event->attr.freq) {
10157 long freq = event->attr.sample_freq;
10158
10159 event->attr.sample_period = NSEC_PER_SEC / freq;
10160 hwc->sample_period = event->attr.sample_period;
10161 local64_set(&hwc->period_left, hwc->sample_period);
778141e3 10162 hwc->last_period = hwc->sample_period;
ba3dd36c
PZ
10163 event->attr.freq = 0;
10164 }
10165}
10166
b0a873eb
PZ
10167/*
10168 * Software event: cpu wall time clock
10169 */
10170
10171static void cpu_clock_event_update(struct perf_event *event)
24f1e32c 10172{
b0a873eb
PZ
10173 s64 prev;
10174 u64 now;
10175
a4eaf7f1 10176 now = local_clock();
b0a873eb
PZ
10177 prev = local64_xchg(&event->hw.prev_count, now);
10178 local64_add(now - prev, &event->count);
24f1e32c 10179}
24f1e32c 10180
a4eaf7f1 10181static void cpu_clock_event_start(struct perf_event *event, int flags)
b0a873eb 10182{
a4eaf7f1 10183 local64_set(&event->hw.prev_count, local_clock());
b0a873eb 10184 perf_swevent_start_hrtimer(event);
b0a873eb
PZ
10185}
10186
a4eaf7f1 10187static void cpu_clock_event_stop(struct perf_event *event, int flags)
f29ac756 10188{
b0a873eb
PZ
10189 perf_swevent_cancel_hrtimer(event);
10190 cpu_clock_event_update(event);
10191}
f29ac756 10192
a4eaf7f1
PZ
10193static int cpu_clock_event_add(struct perf_event *event, int flags)
10194{
10195 if (flags & PERF_EF_START)
10196 cpu_clock_event_start(event, flags);
6a694a60 10197 perf_event_update_userpage(event);
a4eaf7f1
PZ
10198
10199 return 0;
10200}
10201
10202static void cpu_clock_event_del(struct perf_event *event, int flags)
10203{
10204 cpu_clock_event_stop(event, flags);
10205}
10206
b0a873eb
PZ
10207static void cpu_clock_event_read(struct perf_event *event)
10208{
10209 cpu_clock_event_update(event);
10210}
f344011c 10211
b0a873eb
PZ
10212static int cpu_clock_event_init(struct perf_event *event)
10213{
10214 if (event->attr.type != PERF_TYPE_SOFTWARE)
10215 return -ENOENT;
10216
10217 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
10218 return -ENOENT;
10219
2481c5fa
SE
10220 /*
10221 * no branch sampling for software events
10222 */
10223 if (has_branch_stack(event))
10224 return -EOPNOTSUPP;
10225
ba3dd36c
PZ
10226 perf_swevent_init_hrtimer(event);
10227
b0a873eb 10228 return 0;
f29ac756
PZ
10229}
10230
b0a873eb 10231static struct pmu perf_cpu_clock = {
89a1e187
PZ
10232 .task_ctx_nr = perf_sw_context,
10233
34f43927
PZ
10234 .capabilities = PERF_PMU_CAP_NO_NMI,
10235
b0a873eb 10236 .event_init = cpu_clock_event_init,
a4eaf7f1
PZ
10237 .add = cpu_clock_event_add,
10238 .del = cpu_clock_event_del,
10239 .start = cpu_clock_event_start,
10240 .stop = cpu_clock_event_stop,
b0a873eb
PZ
10241 .read = cpu_clock_event_read,
10242};
10243
10244/*
10245 * Software event: task time clock
10246 */
10247
10248static void task_clock_event_update(struct perf_event *event, u64 now)
5c92d124 10249{
b0a873eb
PZ
10250 u64 prev;
10251 s64 delta;
5c92d124 10252
b0a873eb
PZ
10253 prev = local64_xchg(&event->hw.prev_count, now);
10254 delta = now - prev;
10255 local64_add(delta, &event->count);
10256}
5c92d124 10257
a4eaf7f1 10258static void task_clock_event_start(struct perf_event *event, int flags)
b0a873eb 10259{
a4eaf7f1 10260 local64_set(&event->hw.prev_count, event->ctx->time);
b0a873eb 10261 perf_swevent_start_hrtimer(event);
b0a873eb
PZ
10262}
10263
a4eaf7f1 10264static void task_clock_event_stop(struct perf_event *event, int flags)
b0a873eb
PZ
10265{
10266 perf_swevent_cancel_hrtimer(event);
10267 task_clock_event_update(event, event->ctx->time);
a4eaf7f1
PZ
10268}
10269
10270static int task_clock_event_add(struct perf_event *event, int flags)
10271{
10272 if (flags & PERF_EF_START)
10273 task_clock_event_start(event, flags);
6a694a60 10274 perf_event_update_userpage(event);
b0a873eb 10275
a4eaf7f1
PZ
10276 return 0;
10277}
10278
10279static void task_clock_event_del(struct perf_event *event, int flags)
10280{
10281 task_clock_event_stop(event, PERF_EF_UPDATE);
b0a873eb
PZ
10282}
10283
10284static void task_clock_event_read(struct perf_event *event)
10285{
768a06e2
PZ
10286 u64 now = perf_clock();
10287 u64 delta = now - event->ctx->timestamp;
10288 u64 time = event->ctx->time + delta;
b0a873eb
PZ
10289
10290 task_clock_event_update(event, time);
10291}
10292
10293static int task_clock_event_init(struct perf_event *event)
6fb2915d 10294{
b0a873eb
PZ
10295 if (event->attr.type != PERF_TYPE_SOFTWARE)
10296 return -ENOENT;
10297
10298 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
10299 return -ENOENT;
10300
2481c5fa
SE
10301 /*
10302 * no branch sampling for software events
10303 */
10304 if (has_branch_stack(event))
10305 return -EOPNOTSUPP;
10306
ba3dd36c
PZ
10307 perf_swevent_init_hrtimer(event);
10308
b0a873eb 10309 return 0;
6fb2915d
LZ
10310}
10311
b0a873eb 10312static struct pmu perf_task_clock = {
89a1e187
PZ
10313 .task_ctx_nr = perf_sw_context,
10314
34f43927
PZ
10315 .capabilities = PERF_PMU_CAP_NO_NMI,
10316
b0a873eb 10317 .event_init = task_clock_event_init,
a4eaf7f1
PZ
10318 .add = task_clock_event_add,
10319 .del = task_clock_event_del,
10320 .start = task_clock_event_start,
10321 .stop = task_clock_event_stop,
b0a873eb
PZ
10322 .read = task_clock_event_read,
10323};
6fb2915d 10324
ad5133b7 10325static void perf_pmu_nop_void(struct pmu *pmu)
e077df4f 10326{
e077df4f 10327}
6fb2915d 10328
fbbe0701
SB
10329static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
10330{
10331}
10332
ad5133b7 10333static int perf_pmu_nop_int(struct pmu *pmu)
6fb2915d 10334{
ad5133b7 10335 return 0;
6fb2915d
LZ
10336}
10337
81ec3f3c
JO
10338static int perf_event_nop_int(struct perf_event *event, u64 value)
10339{
10340 return 0;
10341}
10342
18ab2cd3 10343static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
fbbe0701
SB
10344
10345static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
6fb2915d 10346{
fbbe0701
SB
10347 __this_cpu_write(nop_txn_flags, flags);
10348
10349 if (flags & ~PERF_PMU_TXN_ADD)
10350 return;
10351
ad5133b7 10352 perf_pmu_disable(pmu);
6fb2915d
LZ
10353}
10354
ad5133b7
PZ
10355static int perf_pmu_commit_txn(struct pmu *pmu)
10356{
fbbe0701
SB
10357 unsigned int flags = __this_cpu_read(nop_txn_flags);
10358
10359 __this_cpu_write(nop_txn_flags, 0);
10360
10361 if (flags & ~PERF_PMU_TXN_ADD)
10362 return 0;
10363
ad5133b7
PZ
10364 perf_pmu_enable(pmu);
10365 return 0;
10366}
e077df4f 10367
ad5133b7 10368static void perf_pmu_cancel_txn(struct pmu *pmu)
24f1e32c 10369{
fbbe0701
SB
10370 unsigned int flags = __this_cpu_read(nop_txn_flags);
10371
10372 __this_cpu_write(nop_txn_flags, 0);
10373
10374 if (flags & ~PERF_PMU_TXN_ADD)
10375 return;
10376
ad5133b7 10377 perf_pmu_enable(pmu);
24f1e32c
FW
10378}
10379
35edc2a5
PZ
10380static int perf_event_idx_default(struct perf_event *event)
10381{
c719f560 10382 return 0;
35edc2a5
PZ
10383}
10384
8dc85d54
PZ
10385/*
10386 * Ensures all contexts with the same task_ctx_nr have the same
10387 * pmu_cpu_context too.
10388 */
9e317041 10389static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
24f1e32c 10390{
8dc85d54 10391 struct pmu *pmu;
b326e956 10392
8dc85d54
PZ
10393 if (ctxn < 0)
10394 return NULL;
24f1e32c 10395
8dc85d54
PZ
10396 list_for_each_entry(pmu, &pmus, entry) {
10397 if (pmu->task_ctx_nr == ctxn)
10398 return pmu->pmu_cpu_context;
10399 }
24f1e32c 10400
8dc85d54 10401 return NULL;
24f1e32c
FW
10402}
10403
51676957
PZ
10404static void free_pmu_context(struct pmu *pmu)
10405{
df0062b2
WD
10406 /*
10407 * Static contexts such as perf_sw_context have a global lifetime
10408 * and may be shared between different PMUs. Avoid freeing them
10409 * when a single PMU is going away.
10410 */
10411 if (pmu->task_ctx_nr > perf_invalid_context)
10412 return;
10413
51676957 10414 free_percpu(pmu->pmu_cpu_context);
24f1e32c 10415}
6e855cd4
AS
10416
10417/*
10418 * Let userspace know that this PMU supports address range filtering:
10419 */
10420static ssize_t nr_addr_filters_show(struct device *dev,
10421 struct device_attribute *attr,
10422 char *page)
10423{
10424 struct pmu *pmu = dev_get_drvdata(dev);
10425
10426 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10427}
10428DEVICE_ATTR_RO(nr_addr_filters);
10429
2e80a82a 10430static struct idr pmu_idr;
d6d020e9 10431
abe43400
PZ
10432static ssize_t
10433type_show(struct device *dev, struct device_attribute *attr, char *page)
10434{
10435 struct pmu *pmu = dev_get_drvdata(dev);
10436
10437 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10438}
90826ca7 10439static DEVICE_ATTR_RO(type);
abe43400 10440
62b85639
SE
10441static ssize_t
10442perf_event_mux_interval_ms_show(struct device *dev,
10443 struct device_attribute *attr,
10444 char *page)
10445{
10446 struct pmu *pmu = dev_get_drvdata(dev);
10447
10448 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10449}
10450
272325c4
PZ
10451static DEFINE_MUTEX(mux_interval_mutex);
10452
62b85639
SE
10453static ssize_t
10454perf_event_mux_interval_ms_store(struct device *dev,
10455 struct device_attribute *attr,
10456 const char *buf, size_t count)
10457{
10458 struct pmu *pmu = dev_get_drvdata(dev);
10459 int timer, cpu, ret;
10460
10461 ret = kstrtoint(buf, 0, &timer);
10462 if (ret)
10463 return ret;
10464
10465 if (timer < 1)
10466 return -EINVAL;
10467
10468 /* same value, noting to do */
10469 if (timer == pmu->hrtimer_interval_ms)
10470 return count;
10471
272325c4 10472 mutex_lock(&mux_interval_mutex);
62b85639
SE
10473 pmu->hrtimer_interval_ms = timer;
10474
10475 /* update all cpuctx for this PMU */
a63fbed7 10476 cpus_read_lock();
272325c4 10477 for_each_online_cpu(cpu) {
62b85639
SE
10478 struct perf_cpu_context *cpuctx;
10479 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10480 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10481
272325c4
PZ
10482 cpu_function_call(cpu,
10483 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
62b85639 10484 }
a63fbed7 10485 cpus_read_unlock();
272325c4 10486 mutex_unlock(&mux_interval_mutex);
62b85639
SE
10487
10488 return count;
10489}
90826ca7 10490static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
62b85639 10491
90826ca7
GKH
10492static struct attribute *pmu_dev_attrs[] = {
10493 &dev_attr_type.attr,
10494 &dev_attr_perf_event_mux_interval_ms.attr,
10495 NULL,
abe43400 10496};
90826ca7 10497ATTRIBUTE_GROUPS(pmu_dev);
abe43400
PZ
10498
10499static int pmu_bus_running;
10500static struct bus_type pmu_bus = {
10501 .name = "event_source",
90826ca7 10502 .dev_groups = pmu_dev_groups,
abe43400
PZ
10503};
10504
10505static void pmu_dev_release(struct device *dev)
10506{
10507 kfree(dev);
10508}
10509
10510static int pmu_dev_alloc(struct pmu *pmu)
10511{
10512 int ret = -ENOMEM;
10513
10514 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10515 if (!pmu->dev)
10516 goto out;
10517
0c9d42ed 10518 pmu->dev->groups = pmu->attr_groups;
abe43400
PZ
10519 device_initialize(pmu->dev);
10520 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10521 if (ret)
10522 goto free_dev;
10523
10524 dev_set_drvdata(pmu->dev, pmu);
10525 pmu->dev->bus = &pmu_bus;
10526 pmu->dev->release = pmu_dev_release;
10527 ret = device_add(pmu->dev);
10528 if (ret)
10529 goto free_dev;
10530
6e855cd4
AS
10531 /* For PMUs with address filters, throw in an extra attribute: */
10532 if (pmu->nr_addr_filters)
10533 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters);
10534
10535 if (ret)
10536 goto del_dev;
10537
f3a3a825
JO
10538 if (pmu->attr_update)
10539 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10540
10541 if (ret)
10542 goto del_dev;
10543
abe43400
PZ
10544out:
10545 return ret;
10546
6e855cd4
AS
10547del_dev:
10548 device_del(pmu->dev);
10549
abe43400
PZ
10550free_dev:
10551 put_device(pmu->dev);
10552 goto out;
10553}
10554
547e9fd7 10555static struct lock_class_key cpuctx_mutex;
facc4307 10556static struct lock_class_key cpuctx_lock;
547e9fd7 10557
03d8e80b 10558int perf_pmu_register(struct pmu *pmu, const char *name, int type)
24f1e32c 10559{
66d258c5 10560 int cpu, ret, max = PERF_TYPE_MAX;
24f1e32c 10561
b0a873eb 10562 mutex_lock(&pmus_lock);
33696fc0
PZ
10563 ret = -ENOMEM;
10564 pmu->pmu_disable_count = alloc_percpu(int);
10565 if (!pmu->pmu_disable_count)
10566 goto unlock;
f29ac756 10567
2e80a82a
PZ
10568 pmu->type = -1;
10569 if (!name)
10570 goto skip_type;
10571 pmu->name = name;
10572
66d258c5
PZ
10573 if (type != PERF_TYPE_SOFTWARE) {
10574 if (type >= 0)
10575 max = type;
10576
10577 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL);
10578 if (ret < 0)
2e80a82a 10579 goto free_pdc;
66d258c5
PZ
10580
10581 WARN_ON(type >= 0 && ret != type);
10582
10583 type = ret;
2e80a82a
PZ
10584 }
10585 pmu->type = type;
10586
abe43400
PZ
10587 if (pmu_bus_running) {
10588 ret = pmu_dev_alloc(pmu);
10589 if (ret)
10590 goto free_idr;
10591 }
10592
2e80a82a 10593skip_type:
26657848
PZ
10594 if (pmu->task_ctx_nr == perf_hw_context) {
10595 static int hw_context_taken = 0;
10596
5101ef20
MR
10597 /*
10598 * Other than systems with heterogeneous CPUs, it never makes
10599 * sense for two PMUs to share perf_hw_context. PMUs which are
10600 * uncore must use perf_invalid_context.
10601 */
10602 if (WARN_ON_ONCE(hw_context_taken &&
10603 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
26657848
PZ
10604 pmu->task_ctx_nr = perf_invalid_context;
10605
10606 hw_context_taken = 1;
10607 }
10608
8dc85d54
PZ
10609 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10610 if (pmu->pmu_cpu_context)
10611 goto got_cpu_context;
f29ac756 10612
c4814202 10613 ret = -ENOMEM;
108b02cf
PZ
10614 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10615 if (!pmu->pmu_cpu_context)
abe43400 10616 goto free_dev;
f344011c 10617
108b02cf
PZ
10618 for_each_possible_cpu(cpu) {
10619 struct perf_cpu_context *cpuctx;
10620
10621 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
eb184479 10622 __perf_event_init_context(&cpuctx->ctx);
547e9fd7 10623 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
facc4307 10624 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
108b02cf 10625 cpuctx->ctx.pmu = pmu;
a63fbed7 10626 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
9e630205 10627
272325c4 10628 __perf_mux_hrtimer_init(cpuctx, cpu);
836196be
IR
10629
10630 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default);
10631 cpuctx->heap = cpuctx->heap_default;
108b02cf 10632 }
76e1d904 10633
8dc85d54 10634got_cpu_context:
ad5133b7
PZ
10635 if (!pmu->start_txn) {
10636 if (pmu->pmu_enable) {
10637 /*
10638 * If we have pmu_enable/pmu_disable calls, install
10639 * transaction stubs that use that to try and batch
10640 * hardware accesses.
10641 */
10642 pmu->start_txn = perf_pmu_start_txn;
10643 pmu->commit_txn = perf_pmu_commit_txn;
10644 pmu->cancel_txn = perf_pmu_cancel_txn;
10645 } else {
fbbe0701 10646 pmu->start_txn = perf_pmu_nop_txn;
ad5133b7
PZ
10647 pmu->commit_txn = perf_pmu_nop_int;
10648 pmu->cancel_txn = perf_pmu_nop_void;
f344011c 10649 }
5c92d124 10650 }
15dbf27c 10651
ad5133b7
PZ
10652 if (!pmu->pmu_enable) {
10653 pmu->pmu_enable = perf_pmu_nop_void;
10654 pmu->pmu_disable = perf_pmu_nop_void;
10655 }
10656
81ec3f3c
JO
10657 if (!pmu->check_period)
10658 pmu->check_period = perf_event_nop_int;
10659
35edc2a5
PZ
10660 if (!pmu->event_idx)
10661 pmu->event_idx = perf_event_idx_default;
10662
d44f821b
LK
10663 /*
10664 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list,
10665 * since these cannot be in the IDR. This way the linear search
10666 * is fast, provided a valid software event is provided.
10667 */
10668 if (type == PERF_TYPE_SOFTWARE || !name)
10669 list_add_rcu(&pmu->entry, &pmus);
10670 else
10671 list_add_tail_rcu(&pmu->entry, &pmus);
10672
bed5b25a 10673 atomic_set(&pmu->exclusive_cnt, 0);
33696fc0
PZ
10674 ret = 0;
10675unlock:
b0a873eb
PZ
10676 mutex_unlock(&pmus_lock);
10677
33696fc0 10678 return ret;
108b02cf 10679
abe43400
PZ
10680free_dev:
10681 device_del(pmu->dev);
10682 put_device(pmu->dev);
10683
2e80a82a 10684free_idr:
66d258c5 10685 if (pmu->type != PERF_TYPE_SOFTWARE)
2e80a82a
PZ
10686 idr_remove(&pmu_idr, pmu->type);
10687
108b02cf
PZ
10688free_pdc:
10689 free_percpu(pmu->pmu_disable_count);
10690 goto unlock;
f29ac756 10691}
c464c76e 10692EXPORT_SYMBOL_GPL(perf_pmu_register);
f29ac756 10693
b0a873eb 10694void perf_pmu_unregister(struct pmu *pmu)
5c92d124 10695{
b0a873eb
PZ
10696 mutex_lock(&pmus_lock);
10697 list_del_rcu(&pmu->entry);
5c92d124 10698
0475f9ea 10699 /*
cde8e884
PZ
10700 * We dereference the pmu list under both SRCU and regular RCU, so
10701 * synchronize against both of those.
0475f9ea 10702 */
b0a873eb 10703 synchronize_srcu(&pmus_srcu);
cde8e884 10704 synchronize_rcu();
d6d020e9 10705
33696fc0 10706 free_percpu(pmu->pmu_disable_count);
66d258c5 10707 if (pmu->type != PERF_TYPE_SOFTWARE)
2e80a82a 10708 idr_remove(&pmu_idr, pmu->type);
a9f97721 10709 if (pmu_bus_running) {
0933840a
JO
10710 if (pmu->nr_addr_filters)
10711 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10712 device_del(pmu->dev);
10713 put_device(pmu->dev);
10714 }
51676957 10715 free_pmu_context(pmu);
a9f97721 10716 mutex_unlock(&pmus_lock);
b0a873eb 10717}
c464c76e 10718EXPORT_SYMBOL_GPL(perf_pmu_unregister);
d6d020e9 10719
e321d02d
KL
10720static inline bool has_extended_regs(struct perf_event *event)
10721{
10722 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
10723 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
10724}
10725
cc34b98b
MR
10726static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
10727{
ccd41c86 10728 struct perf_event_context *ctx = NULL;
cc34b98b
MR
10729 int ret;
10730
10731 if (!try_module_get(pmu->module))
10732 return -ENODEV;
ccd41c86 10733
0c7296ca
PZ
10734 /*
10735 * A number of pmu->event_init() methods iterate the sibling_list to,
10736 * for example, validate if the group fits on the PMU. Therefore,
10737 * if this is a sibling event, acquire the ctx->mutex to protect
10738 * the sibling_list.
10739 */
10740 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
8b10c5e2
PZ
10741 /*
10742 * This ctx->mutex can nest when we're called through
10743 * inheritance. See the perf_event_ctx_lock_nested() comment.
10744 */
10745 ctx = perf_event_ctx_lock_nested(event->group_leader,
10746 SINGLE_DEPTH_NESTING);
ccd41c86
PZ
10747 BUG_ON(!ctx);
10748 }
10749
cc34b98b
MR
10750 event->pmu = pmu;
10751 ret = pmu->event_init(event);
ccd41c86
PZ
10752
10753 if (ctx)
10754 perf_event_ctx_unlock(event->group_leader, ctx);
10755
cc6795ae 10756 if (!ret) {
e321d02d
KL
10757 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
10758 has_extended_regs(event))
10759 ret = -EOPNOTSUPP;
10760
cc6795ae 10761 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
e321d02d 10762 event_has_any_exclude_flag(event))
cc6795ae 10763 ret = -EINVAL;
e321d02d
KL
10764
10765 if (ret && event->destroy)
10766 event->destroy(event);
cc6795ae
AM
10767 }
10768
cc34b98b
MR
10769 if (ret)
10770 module_put(pmu->module);
10771
10772 return ret;
10773}
10774
18ab2cd3 10775static struct pmu *perf_init_event(struct perf_event *event)
b0a873eb 10776{
66d258c5 10777 int idx, type, ret;
85c617ab 10778 struct pmu *pmu;
b0a873eb
PZ
10779
10780 idx = srcu_read_lock(&pmus_srcu);
2e80a82a 10781
40999312
KL
10782 /* Try parent's PMU first: */
10783 if (event->parent && event->parent->pmu) {
10784 pmu = event->parent->pmu;
10785 ret = perf_try_init_event(pmu, event);
10786 if (!ret)
10787 goto unlock;
10788 }
10789
66d258c5
PZ
10790 /*
10791 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE
10792 * are often aliases for PERF_TYPE_RAW.
10793 */
10794 type = event->attr.type;
10795 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE)
10796 type = PERF_TYPE_RAW;
10797
10798again:
2e80a82a 10799 rcu_read_lock();
66d258c5 10800 pmu = idr_find(&pmu_idr, type);
2e80a82a 10801 rcu_read_unlock();
940c5b29 10802 if (pmu) {
cc34b98b 10803 ret = perf_try_init_event(pmu, event);
66d258c5
PZ
10804 if (ret == -ENOENT && event->attr.type != type) {
10805 type = event->attr.type;
10806 goto again;
10807 }
10808
940c5b29
LM
10809 if (ret)
10810 pmu = ERR_PTR(ret);
66d258c5 10811
2e80a82a 10812 goto unlock;
940c5b29 10813 }
2e80a82a 10814
9f0bff11 10815 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) {
cc34b98b 10816 ret = perf_try_init_event(pmu, event);
b0a873eb 10817 if (!ret)
e5f4d339 10818 goto unlock;
76e1d904 10819
b0a873eb
PZ
10820 if (ret != -ENOENT) {
10821 pmu = ERR_PTR(ret);
e5f4d339 10822 goto unlock;
f344011c 10823 }
5c92d124 10824 }
e5f4d339
PZ
10825 pmu = ERR_PTR(-ENOENT);
10826unlock:
b0a873eb 10827 srcu_read_unlock(&pmus_srcu, idx);
15dbf27c 10828
4aeb0b42 10829 return pmu;
5c92d124
IM
10830}
10831
f2fb6bef
KL
10832static void attach_sb_event(struct perf_event *event)
10833{
10834 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
10835
10836 raw_spin_lock(&pel->lock);
10837 list_add_rcu(&event->sb_list, &pel->list);
10838 raw_spin_unlock(&pel->lock);
10839}
10840
aab5b71e
PZ
10841/*
10842 * We keep a list of all !task (and therefore per-cpu) events
10843 * that need to receive side-band records.
10844 *
10845 * This avoids having to scan all the various PMU per-cpu contexts
10846 * looking for them.
10847 */
f2fb6bef
KL
10848static void account_pmu_sb_event(struct perf_event *event)
10849{
a4f144eb 10850 if (is_sb_event(event))
f2fb6bef
KL
10851 attach_sb_event(event);
10852}
10853
4beb31f3
FW
10854static void account_event_cpu(struct perf_event *event, int cpu)
10855{
10856 if (event->parent)
10857 return;
10858
4beb31f3
FW
10859 if (is_cgroup_event(event))
10860 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
10861}
10862
555e0c1e
FW
10863/* Freq events need the tick to stay alive (see perf_event_task_tick). */
10864static void account_freq_event_nohz(void)
10865{
10866#ifdef CONFIG_NO_HZ_FULL
10867 /* Lock so we don't race with concurrent unaccount */
10868 spin_lock(&nr_freq_lock);
10869 if (atomic_inc_return(&nr_freq_events) == 1)
10870 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
10871 spin_unlock(&nr_freq_lock);
10872#endif
10873}
10874
10875static void account_freq_event(void)
10876{
10877 if (tick_nohz_full_enabled())
10878 account_freq_event_nohz();
10879 else
10880 atomic_inc(&nr_freq_events);
10881}
10882
10883
766d6c07
FW
10884static void account_event(struct perf_event *event)
10885{
25432ae9
PZ
10886 bool inc = false;
10887
4beb31f3
FW
10888 if (event->parent)
10889 return;
10890
766d6c07 10891 if (event->attach_state & PERF_ATTACH_TASK)
25432ae9 10892 inc = true;
766d6c07
FW
10893 if (event->attr.mmap || event->attr.mmap_data)
10894 atomic_inc(&nr_mmap_events);
10895 if (event->attr.comm)
10896 atomic_inc(&nr_comm_events);
e4222673
HB
10897 if (event->attr.namespaces)
10898 atomic_inc(&nr_namespaces_events);
96aaab68
NK
10899 if (event->attr.cgroup)
10900 atomic_inc(&nr_cgroup_events);
766d6c07
FW
10901 if (event->attr.task)
10902 atomic_inc(&nr_task_events);
555e0c1e
FW
10903 if (event->attr.freq)
10904 account_freq_event();
45ac1403
AH
10905 if (event->attr.context_switch) {
10906 atomic_inc(&nr_switch_events);
25432ae9 10907 inc = true;
45ac1403 10908 }
4beb31f3 10909 if (has_branch_stack(event))
25432ae9 10910 inc = true;
4beb31f3 10911 if (is_cgroup_event(event))
25432ae9 10912 inc = true;
76193a94
SL
10913 if (event->attr.ksymbol)
10914 atomic_inc(&nr_ksymbol_events);
6ee52e2a
SL
10915 if (event->attr.bpf_event)
10916 atomic_inc(&nr_bpf_events);
25432ae9 10917
9107c89e 10918 if (inc) {
5bce9db1
AS
10919 /*
10920 * We need the mutex here because static_branch_enable()
10921 * must complete *before* the perf_sched_count increment
10922 * becomes visible.
10923 */
9107c89e
PZ
10924 if (atomic_inc_not_zero(&perf_sched_count))
10925 goto enabled;
10926
10927 mutex_lock(&perf_sched_mutex);
10928 if (!atomic_read(&perf_sched_count)) {
10929 static_branch_enable(&perf_sched_events);
10930 /*
10931 * Guarantee that all CPUs observe they key change and
10932 * call the perf scheduling hooks before proceeding to
10933 * install events that need them.
10934 */
0809d954 10935 synchronize_rcu();
9107c89e
PZ
10936 }
10937 /*
10938 * Now that we have waited for the sync_sched(), allow further
10939 * increments to by-pass the mutex.
10940 */
10941 atomic_inc(&perf_sched_count);
10942 mutex_unlock(&perf_sched_mutex);
10943 }
10944enabled:
4beb31f3
FW
10945
10946 account_event_cpu(event, event->cpu);
f2fb6bef
KL
10947
10948 account_pmu_sb_event(event);
766d6c07
FW
10949}
10950
0793a61d 10951/*
788faab7 10952 * Allocate and initialize an event structure
0793a61d 10953 */
cdd6c482 10954static struct perf_event *
c3f00c70 10955perf_event_alloc(struct perf_event_attr *attr, int cpu,
d580ff86
PZ
10956 struct task_struct *task,
10957 struct perf_event *group_leader,
10958 struct perf_event *parent_event,
4dc0da86 10959 perf_overflow_handler_t overflow_handler,
79dff51e 10960 void *context, int cgroup_fd)
0793a61d 10961{
51b0fe39 10962 struct pmu *pmu;
cdd6c482
IM
10963 struct perf_event *event;
10964 struct hw_perf_event *hwc;
90983b16 10965 long err = -EINVAL;
0793a61d 10966
66832eb4
ON
10967 if ((unsigned)cpu >= nr_cpu_ids) {
10968 if (!task || cpu != -1)
10969 return ERR_PTR(-EINVAL);
10970 }
10971
c3f00c70 10972 event = kzalloc(sizeof(*event), GFP_KERNEL);
cdd6c482 10973 if (!event)
d5d2bc0d 10974 return ERR_PTR(-ENOMEM);
0793a61d 10975
04289bb9 10976 /*
cdd6c482 10977 * Single events are their own group leaders, with an
04289bb9
IM
10978 * empty sibling list:
10979 */
10980 if (!group_leader)
cdd6c482 10981 group_leader = event;
04289bb9 10982
cdd6c482
IM
10983 mutex_init(&event->child_mutex);
10984 INIT_LIST_HEAD(&event->child_list);
fccc714b 10985
cdd6c482
IM
10986 INIT_LIST_HEAD(&event->event_entry);
10987 INIT_LIST_HEAD(&event->sibling_list);
6668128a 10988 INIT_LIST_HEAD(&event->active_list);
8e1a2031 10989 init_event_group(event);
10c6db11 10990 INIT_LIST_HEAD(&event->rb_entry);
71ad88ef 10991 INIT_LIST_HEAD(&event->active_entry);
375637bc 10992 INIT_LIST_HEAD(&event->addr_filters.list);
f3ae75de
SE
10993 INIT_HLIST_NODE(&event->hlist_entry);
10994
10c6db11 10995
cdd6c482 10996 init_waitqueue_head(&event->waitq);
1d54ad94 10997 event->pending_disable = -1;
e360adbe 10998 init_irq_work(&event->pending, perf_pending_event);
0793a61d 10999
cdd6c482 11000 mutex_init(&event->mmap_mutex);
375637bc 11001 raw_spin_lock_init(&event->addr_filters.lock);
7b732a75 11002
a6fa941d 11003 atomic_long_set(&event->refcount, 1);
cdd6c482
IM
11004 event->cpu = cpu;
11005 event->attr = *attr;
11006 event->group_leader = group_leader;
11007 event->pmu = NULL;
cdd6c482 11008 event->oncpu = -1;
a96bbc16 11009
cdd6c482 11010 event->parent = parent_event;
b84fbc9f 11011
17cf22c3 11012 event->ns = get_pid_ns(task_active_pid_ns(current));
cdd6c482 11013 event->id = atomic64_inc_return(&perf_event_id);
a96bbc16 11014
cdd6c482 11015 event->state = PERF_EVENT_STATE_INACTIVE;
329d876d 11016
d580ff86
PZ
11017 if (task) {
11018 event->attach_state = PERF_ATTACH_TASK;
d580ff86 11019 /*
50f16a8b
PZ
11020 * XXX pmu::event_init needs to know what task to account to
11021 * and we cannot use the ctx information because we need the
11022 * pmu before we get a ctx.
d580ff86 11023 */
7b3c92b8 11024 event->hw.target = get_task_struct(task);
d580ff86
PZ
11025 }
11026
34f43927
PZ
11027 event->clock = &local_clock;
11028 if (parent_event)
11029 event->clock = parent_event->clock;
11030
4dc0da86 11031 if (!overflow_handler && parent_event) {
b326e956 11032 overflow_handler = parent_event->overflow_handler;
4dc0da86 11033 context = parent_event->overflow_handler_context;
f1e4ba5b 11034#if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
aa6a5f3c 11035 if (overflow_handler == bpf_overflow_handler) {
85192dbf 11036 struct bpf_prog *prog = parent_event->prog;
aa6a5f3c 11037
85192dbf 11038 bpf_prog_inc(prog);
aa6a5f3c
AS
11039 event->prog = prog;
11040 event->orig_overflow_handler =
11041 parent_event->orig_overflow_handler;
11042 }
11043#endif
4dc0da86 11044 }
66832eb4 11045
1879445d
WN
11046 if (overflow_handler) {
11047 event->overflow_handler = overflow_handler;
11048 event->overflow_handler_context = context;
9ecda41a
WN
11049 } else if (is_write_backward(event)){
11050 event->overflow_handler = perf_event_output_backward;
11051 event->overflow_handler_context = NULL;
1879445d 11052 } else {
9ecda41a 11053 event->overflow_handler = perf_event_output_forward;
1879445d
WN
11054 event->overflow_handler_context = NULL;
11055 }
97eaf530 11056
0231bb53 11057 perf_event__state_init(event);
a86ed508 11058
4aeb0b42 11059 pmu = NULL;
b8e83514 11060
cdd6c482 11061 hwc = &event->hw;
bd2b5b12 11062 hwc->sample_period = attr->sample_period;
0d48696f 11063 if (attr->freq && attr->sample_freq)
bd2b5b12 11064 hwc->sample_period = 1;
eced1dfc 11065 hwc->last_period = hwc->sample_period;
bd2b5b12 11066
e7850595 11067 local64_set(&hwc->period_left, hwc->sample_period);
60db5e09 11068
2023b359 11069 /*
ba5213ae
PZ
11070 * We currently do not support PERF_SAMPLE_READ on inherited events.
11071 * See perf_output_read().
2023b359 11072 */
ba5213ae 11073 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
90983b16 11074 goto err_ns;
a46a2300
YZ
11075
11076 if (!has_branch_stack(event))
11077 event->attr.branch_sample_type = 0;
2023b359 11078
b0a873eb 11079 pmu = perf_init_event(event);
85c617ab 11080 if (IS_ERR(pmu)) {
4aeb0b42 11081 err = PTR_ERR(pmu);
90983b16 11082 goto err_ns;
621a01ea 11083 }
d5d2bc0d 11084
09f4e8f0
PZ
11085 /*
11086 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
11087 * be different on other CPUs in the uncore mask.
11088 */
11089 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
11090 err = -EINVAL;
11091 goto err_pmu;
11092 }
11093
ab43762e
AS
11094 if (event->attr.aux_output &&
11095 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
11096 err = -EOPNOTSUPP;
11097 goto err_pmu;
11098 }
11099
98add2af
PZ
11100 if (cgroup_fd != -1) {
11101 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
11102 if (err)
11103 goto err_pmu;
11104 }
11105
bed5b25a
AS
11106 err = exclusive_event_init(event);
11107 if (err)
11108 goto err_pmu;
11109
375637bc 11110 if (has_addr_filter(event)) {
c60f83b8
AS
11111 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
11112 sizeof(struct perf_addr_filter_range),
11113 GFP_KERNEL);
11114 if (!event->addr_filter_ranges) {
36cc2b92 11115 err = -ENOMEM;
375637bc 11116 goto err_per_task;
36cc2b92 11117 }
375637bc 11118
18736eef
AS
11119 /*
11120 * Clone the parent's vma offsets: they are valid until exec()
11121 * even if the mm is not shared with the parent.
11122 */
11123 if (event->parent) {
11124 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
11125
11126 raw_spin_lock_irq(&ifh->lock);
c60f83b8
AS
11127 memcpy(event->addr_filter_ranges,
11128 event->parent->addr_filter_ranges,
11129 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
18736eef
AS
11130 raw_spin_unlock_irq(&ifh->lock);
11131 }
11132
375637bc
AS
11133 /* force hw sync on the address filters */
11134 event->addr_filters_gen = 1;
11135 }
11136
cdd6c482 11137 if (!event->parent) {
927c7a9e 11138 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
97c79a38 11139 err = get_callchain_buffers(attr->sample_max_stack);
90983b16 11140 if (err)
375637bc 11141 goto err_addr_filters;
d010b332 11142 }
f344011c 11143 }
9ee318a7 11144
da97e184
JFG
11145 err = security_perf_event_alloc(event);
11146 if (err)
11147 goto err_callchain_buffer;
11148
927a5570
AS
11149 /* symmetric to unaccount_event() in _free_event() */
11150 account_event(event);
11151
cdd6c482 11152 return event;
90983b16 11153
da97e184
JFG
11154err_callchain_buffer:
11155 if (!event->parent) {
11156 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
11157 put_callchain_buffers();
11158 }
375637bc 11159err_addr_filters:
c60f83b8 11160 kfree(event->addr_filter_ranges);
375637bc 11161
bed5b25a
AS
11162err_per_task:
11163 exclusive_event_destroy(event);
11164
90983b16 11165err_pmu:
98add2af
PZ
11166 if (is_cgroup_event(event))
11167 perf_detach_cgroup(event);
90983b16
FW
11168 if (event->destroy)
11169 event->destroy(event);
c464c76e 11170 module_put(pmu->module);
90983b16
FW
11171err_ns:
11172 if (event->ns)
11173 put_pid_ns(event->ns);
621b6d2e
PB
11174 if (event->hw.target)
11175 put_task_struct(event->hw.target);
90983b16
FW
11176 kfree(event);
11177
11178 return ERR_PTR(err);
0793a61d
TG
11179}
11180
cdd6c482
IM
11181static int perf_copy_attr(struct perf_event_attr __user *uattr,
11182 struct perf_event_attr *attr)
974802ea 11183{
974802ea 11184 u32 size;
cdf8073d 11185 int ret;
974802ea 11186
c2ba8f41 11187 /* Zero the full structure, so that a short copy will be nice. */
974802ea
PZ
11188 memset(attr, 0, sizeof(*attr));
11189
11190 ret = get_user(size, &uattr->size);
11191 if (ret)
11192 return ret;
11193
c2ba8f41
AS
11194 /* ABI compatibility quirk: */
11195 if (!size)
974802ea 11196 size = PERF_ATTR_SIZE_VER0;
c2ba8f41 11197 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
974802ea
PZ
11198 goto err_size;
11199
c2ba8f41
AS
11200 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
11201 if (ret) {
11202 if (ret == -E2BIG)
11203 goto err_size;
11204 return ret;
974802ea
PZ
11205 }
11206
f12f42ac
MX
11207 attr->size = size;
11208
a4faf00d 11209 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
974802ea
PZ
11210 return -EINVAL;
11211
11212 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
11213 return -EINVAL;
11214
11215 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
11216 return -EINVAL;
11217
bce38cd5
SE
11218 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
11219 u64 mask = attr->branch_sample_type;
11220
11221 /* only using defined bits */
11222 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
11223 return -EINVAL;
11224
11225 /* at least one branch bit must be set */
11226 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
11227 return -EINVAL;
11228
bce38cd5
SE
11229 /* propagate priv level, when not set for branch */
11230 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
11231
11232 /* exclude_kernel checked on syscall entry */
11233 if (!attr->exclude_kernel)
11234 mask |= PERF_SAMPLE_BRANCH_KERNEL;
11235
11236 if (!attr->exclude_user)
11237 mask |= PERF_SAMPLE_BRANCH_USER;
11238
11239 if (!attr->exclude_hv)
11240 mask |= PERF_SAMPLE_BRANCH_HV;
11241 /*
11242 * adjust user setting (for HW filter setup)
11243 */
11244 attr->branch_sample_type = mask;
11245 }
e712209a 11246 /* privileged levels capture (kernel, hv): check permissions */
da97e184
JFG
11247 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
11248 ret = perf_allow_kernel(attr);
11249 if (ret)
11250 return ret;
11251 }
bce38cd5 11252 }
4018994f 11253
c5ebcedb 11254 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
4018994f 11255 ret = perf_reg_validate(attr->sample_regs_user);
c5ebcedb
JO
11256 if (ret)
11257 return ret;
11258 }
11259
11260 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
11261 if (!arch_perf_have_user_stack_dump())
11262 return -ENOSYS;
11263
11264 /*
11265 * We have __u32 type for the size, but so far
11266 * we can only use __u16 as maximum due to the
11267 * __u16 sample size limit.
11268 */
11269 if (attr->sample_stack_user >= USHRT_MAX)
78b562fb 11270 return -EINVAL;
c5ebcedb 11271 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
78b562fb 11272 return -EINVAL;
c5ebcedb 11273 }
4018994f 11274
5f970521
JO
11275 if (!attr->sample_max_stack)
11276 attr->sample_max_stack = sysctl_perf_event_max_stack;
11277
60e2364e
SE
11278 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
11279 ret = perf_reg_validate(attr->sample_regs_intr);
6546b19f
NK
11280
11281#ifndef CONFIG_CGROUP_PERF
11282 if (attr->sample_type & PERF_SAMPLE_CGROUP)
11283 return -EINVAL;
11284#endif
11285
974802ea
PZ
11286out:
11287 return ret;
11288
11289err_size:
11290 put_user(sizeof(*attr), &uattr->size);
11291 ret = -E2BIG;
11292 goto out;
11293}
11294
ac9721f3
PZ
11295static int
11296perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
a4be7c27 11297{
56de4e8f 11298 struct perf_buffer *rb = NULL;
a4be7c27
PZ
11299 int ret = -EINVAL;
11300
ac9721f3 11301 if (!output_event)
a4be7c27
PZ
11302 goto set;
11303
ac9721f3
PZ
11304 /* don't allow circular references */
11305 if (event == output_event)
a4be7c27
PZ
11306 goto out;
11307
0f139300
PZ
11308 /*
11309 * Don't allow cross-cpu buffers
11310 */
11311 if (output_event->cpu != event->cpu)
11312 goto out;
11313
11314 /*
76369139 11315 * If its not a per-cpu rb, it must be the same task.
0f139300
PZ
11316 */
11317 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
11318 goto out;
11319
34f43927
PZ
11320 /*
11321 * Mixing clocks in the same buffer is trouble you don't need.
11322 */
11323 if (output_event->clock != event->clock)
11324 goto out;
11325
9ecda41a
WN
11326 /*
11327 * Either writing ring buffer from beginning or from end.
11328 * Mixing is not allowed.
11329 */
11330 if (is_write_backward(output_event) != is_write_backward(event))
11331 goto out;
11332
45bfb2e5
PZ
11333 /*
11334 * If both events generate aux data, they must be on the same PMU
11335 */
11336 if (has_aux(event) && has_aux(output_event) &&
11337 event->pmu != output_event->pmu)
11338 goto out;
11339
a4be7c27 11340set:
cdd6c482 11341 mutex_lock(&event->mmap_mutex);
ac9721f3
PZ
11342 /* Can't redirect output if we've got an active mmap() */
11343 if (atomic_read(&event->mmap_count))
11344 goto unlock;
a4be7c27 11345
ac9721f3 11346 if (output_event) {
76369139
FW
11347 /* get the rb we want to redirect to */
11348 rb = ring_buffer_get(output_event);
11349 if (!rb)
ac9721f3 11350 goto unlock;
a4be7c27
PZ
11351 }
11352
b69cf536 11353 ring_buffer_attach(event, rb);
9bb5d40c 11354
a4be7c27 11355 ret = 0;
ac9721f3
PZ
11356unlock:
11357 mutex_unlock(&event->mmap_mutex);
11358
a4be7c27 11359out:
a4be7c27
PZ
11360 return ret;
11361}
11362
f63a8daa
PZ
11363static void mutex_lock_double(struct mutex *a, struct mutex *b)
11364{
11365 if (b < a)
11366 swap(a, b);
11367
11368 mutex_lock(a);
11369 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
11370}
11371
34f43927
PZ
11372static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
11373{
11374 bool nmi_safe = false;
11375
11376 switch (clk_id) {
11377 case CLOCK_MONOTONIC:
11378 event->clock = &ktime_get_mono_fast_ns;
11379 nmi_safe = true;
11380 break;
11381
11382 case CLOCK_MONOTONIC_RAW:
11383 event->clock = &ktime_get_raw_fast_ns;
11384 nmi_safe = true;
11385 break;
11386
11387 case CLOCK_REALTIME:
11388 event->clock = &ktime_get_real_ns;
11389 break;
11390
11391 case CLOCK_BOOTTIME:
9285ec4c 11392 event->clock = &ktime_get_boottime_ns;
34f43927
PZ
11393 break;
11394
11395 case CLOCK_TAI:
9285ec4c 11396 event->clock = &ktime_get_clocktai_ns;
34f43927
PZ
11397 break;
11398
11399 default:
11400 return -EINVAL;
11401 }
11402
11403 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
11404 return -EINVAL;
11405
11406 return 0;
11407}
11408
321027c1
PZ
11409/*
11410 * Variation on perf_event_ctx_lock_nested(), except we take two context
11411 * mutexes.
11412 */
11413static struct perf_event_context *
11414__perf_event_ctx_lock_double(struct perf_event *group_leader,
11415 struct perf_event_context *ctx)
11416{
11417 struct perf_event_context *gctx;
11418
11419again:
11420 rcu_read_lock();
11421 gctx = READ_ONCE(group_leader->ctx);
8c94abbb 11422 if (!refcount_inc_not_zero(&gctx->refcount)) {
321027c1
PZ
11423 rcu_read_unlock();
11424 goto again;
11425 }
11426 rcu_read_unlock();
11427
11428 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11429
11430 if (group_leader->ctx != gctx) {
11431 mutex_unlock(&ctx->mutex);
11432 mutex_unlock(&gctx->mutex);
11433 put_ctx(gctx);
11434 goto again;
11435 }
11436
11437 return gctx;
11438}
11439
0793a61d 11440/**
cdd6c482 11441 * sys_perf_event_open - open a performance event, associate it to a task/cpu
9f66a381 11442 *
cdd6c482 11443 * @attr_uptr: event_id type attributes for monitoring/sampling
0793a61d 11444 * @pid: target pid
9f66a381 11445 * @cpu: target cpu
cdd6c482 11446 * @group_fd: group leader event fd
0793a61d 11447 */
cdd6c482
IM
11448SYSCALL_DEFINE5(perf_event_open,
11449 struct perf_event_attr __user *, attr_uptr,
2743a5b0 11450 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
0793a61d 11451{
b04243ef
PZ
11452 struct perf_event *group_leader = NULL, *output_event = NULL;
11453 struct perf_event *event, *sibling;
cdd6c482 11454 struct perf_event_attr attr;
f63a8daa 11455 struct perf_event_context *ctx, *uninitialized_var(gctx);
cdd6c482 11456 struct file *event_file = NULL;
2903ff01 11457 struct fd group = {NULL, 0};
38a81da2 11458 struct task_struct *task = NULL;
89a1e187 11459 struct pmu *pmu;
ea635c64 11460 int event_fd;
b04243ef 11461 int move_group = 0;
dc86cabe 11462 int err;
a21b0b35 11463 int f_flags = O_RDWR;
79dff51e 11464 int cgroup_fd = -1;
0793a61d 11465
2743a5b0 11466 /* for future expandability... */
e5d1367f 11467 if (flags & ~PERF_FLAG_ALL)
2743a5b0
PM
11468 return -EINVAL;
11469
da97e184
JFG
11470 /* Do we allow access to perf_event_open(2) ? */
11471 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11472 if (err)
11473 return err;
11474
dc86cabe
IM
11475 err = perf_copy_attr(attr_uptr, &attr);
11476 if (err)
11477 return err;
eab656ae 11478
0764771d 11479 if (!attr.exclude_kernel) {
da97e184
JFG
11480 err = perf_allow_kernel(&attr);
11481 if (err)
11482 return err;
0764771d
PZ
11483 }
11484
e4222673
HB
11485 if (attr.namespaces) {
11486 if (!capable(CAP_SYS_ADMIN))
11487 return -EACCES;
11488 }
11489
df58ab24 11490 if (attr.freq) {
cdd6c482 11491 if (attr.sample_freq > sysctl_perf_event_sample_rate)
df58ab24 11492 return -EINVAL;
0819b2e3
PZ
11493 } else {
11494 if (attr.sample_period & (1ULL << 63))
11495 return -EINVAL;
df58ab24
PZ
11496 }
11497
fc7ce9c7 11498 /* Only privileged users can get physical addresses */
da97e184
JFG
11499 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11500 err = perf_allow_kernel(&attr);
11501 if (err)
11502 return err;
11503 }
fc7ce9c7 11504
b0c8fdc7
DH
11505 err = security_locked_down(LOCKDOWN_PERF);
11506 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR))
11507 /* REGS_INTR can leak data, lockdown must prevent this */
11508 return err;
11509
11510 err = 0;
11511
e5d1367f
SE
11512 /*
11513 * In cgroup mode, the pid argument is used to pass the fd
11514 * opened to the cgroup directory in cgroupfs. The cpu argument
11515 * designates the cpu on which to monitor threads from that
11516 * cgroup.
11517 */
11518 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11519 return -EINVAL;
11520
a21b0b35
YD
11521 if (flags & PERF_FLAG_FD_CLOEXEC)
11522 f_flags |= O_CLOEXEC;
11523
11524 event_fd = get_unused_fd_flags(f_flags);
ea635c64
AV
11525 if (event_fd < 0)
11526 return event_fd;
11527
ac9721f3 11528 if (group_fd != -1) {
2903ff01
AV
11529 err = perf_fget_light(group_fd, &group);
11530 if (err)
d14b12d7 11531 goto err_fd;
2903ff01 11532 group_leader = group.file->private_data;
ac9721f3
PZ
11533 if (flags & PERF_FLAG_FD_OUTPUT)
11534 output_event = group_leader;
11535 if (flags & PERF_FLAG_FD_NO_GROUP)
11536 group_leader = NULL;
11537 }
11538
e5d1367f 11539 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
c6be5a5c
PZ
11540 task = find_lively_task_by_vpid(pid);
11541 if (IS_ERR(task)) {
11542 err = PTR_ERR(task);
11543 goto err_group_fd;
11544 }
11545 }
11546
1f4ee503
PZ
11547 if (task && group_leader &&
11548 group_leader->attr.inherit != attr.inherit) {
11549 err = -EINVAL;
11550 goto err_task;
11551 }
11552
79c9ce57 11553 if (task) {
69143038 11554 err = mutex_lock_interruptible(&task->signal->exec_update_mutex);
79c9ce57 11555 if (err)
e5aeee51 11556 goto err_task;
79c9ce57
PZ
11557
11558 /*
11559 * Reuse ptrace permission checks for now.
11560 *
69143038 11561 * We must hold exec_update_mutex across this and any potential
79c9ce57
PZ
11562 * perf_install_in_context() call for this new event to
11563 * serialize against exec() altering our credentials (and the
11564 * perf_event_exit_task() that could imply).
11565 */
11566 err = -EACCES;
11567 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11568 goto err_cred;
11569 }
11570
79dff51e
MF
11571 if (flags & PERF_FLAG_PID_CGROUP)
11572 cgroup_fd = pid;
11573
4dc0da86 11574 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
79dff51e 11575 NULL, NULL, cgroup_fd);
d14b12d7
SE
11576 if (IS_ERR(event)) {
11577 err = PTR_ERR(event);
79c9ce57 11578 goto err_cred;
d14b12d7
SE
11579 }
11580
53b25335
VW
11581 if (is_sampling_event(event)) {
11582 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
a1396555 11583 err = -EOPNOTSUPP;
53b25335
VW
11584 goto err_alloc;
11585 }
11586 }
11587
89a1e187
PZ
11588 /*
11589 * Special case software events and allow them to be part of
11590 * any hardware group.
11591 */
11592 pmu = event->pmu;
b04243ef 11593
34f43927
PZ
11594 if (attr.use_clockid) {
11595 err = perf_event_set_clock(event, attr.clockid);
11596 if (err)
11597 goto err_alloc;
11598 }
11599
4ff6a8de
DCC
11600 if (pmu->task_ctx_nr == perf_sw_context)
11601 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11602
a1150c20
SL
11603 if (group_leader) {
11604 if (is_software_event(event) &&
11605 !in_software_context(group_leader)) {
b04243ef 11606 /*
a1150c20
SL
11607 * If the event is a sw event, but the group_leader
11608 * is on hw context.
b04243ef 11609 *
a1150c20
SL
11610 * Allow the addition of software events to hw
11611 * groups, this is safe because software events
11612 * never fail to schedule.
b04243ef 11613 */
a1150c20
SL
11614 pmu = group_leader->ctx->pmu;
11615 } else if (!is_software_event(event) &&
11616 is_software_event(group_leader) &&
4ff6a8de 11617 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
b04243ef
PZ
11618 /*
11619 * In case the group is a pure software group, and we
11620 * try to add a hardware event, move the whole group to
11621 * the hardware context.
11622 */
11623 move_group = 1;
11624 }
11625 }
89a1e187
PZ
11626
11627 /*
11628 * Get the target context (task or percpu):
11629 */
4af57ef2 11630 ctx = find_get_context(pmu, task, event);
89a1e187
PZ
11631 if (IS_ERR(ctx)) {
11632 err = PTR_ERR(ctx);
c6be5a5c 11633 goto err_alloc;
89a1e187
PZ
11634 }
11635
ccff286d 11636 /*
cdd6c482 11637 * Look up the group leader (we will attach this event to it):
04289bb9 11638 */
ac9721f3 11639 if (group_leader) {
dc86cabe 11640 err = -EINVAL;
04289bb9 11641
04289bb9 11642 /*
ccff286d
IM
11643 * Do not allow a recursive hierarchy (this new sibling
11644 * becoming part of another group-sibling):
11645 */
11646 if (group_leader->group_leader != group_leader)
c3f00c70 11647 goto err_context;
34f43927
PZ
11648
11649 /* All events in a group should have the same clock */
11650 if (group_leader->clock != event->clock)
11651 goto err_context;
11652
ccff286d 11653 /*
64aee2a9
MR
11654 * Make sure we're both events for the same CPU;
11655 * grouping events for different CPUs is broken; since
11656 * you can never concurrently schedule them anyhow.
04289bb9 11657 */
64aee2a9
MR
11658 if (group_leader->cpu != event->cpu)
11659 goto err_context;
c3c87e77 11660
64aee2a9
MR
11661 /*
11662 * Make sure we're both on the same task, or both
11663 * per-CPU events.
11664 */
11665 if (group_leader->ctx->task != ctx->task)
11666 goto err_context;
11667
11668 /*
11669 * Do not allow to attach to a group in a different task
11670 * or CPU context. If we're moving SW events, we'll fix
11671 * this up later, so allow that.
11672 */
11673 if (!move_group && group_leader->ctx != ctx)
11674 goto err_context;
b04243ef 11675
3b6f9e5c
PM
11676 /*
11677 * Only a group leader can be exclusive or pinned
11678 */
0d48696f 11679 if (attr.exclusive || attr.pinned)
c3f00c70 11680 goto err_context;
ac9721f3
PZ
11681 }
11682
11683 if (output_event) {
11684 err = perf_event_set_output(event, output_event);
11685 if (err)
c3f00c70 11686 goto err_context;
ac9721f3 11687 }
0793a61d 11688
a21b0b35
YD
11689 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11690 f_flags);
ea635c64
AV
11691 if (IS_ERR(event_file)) {
11692 err = PTR_ERR(event_file);
201c2f85 11693 event_file = NULL;
c3f00c70 11694 goto err_context;
ea635c64 11695 }
9b51f66d 11696
b04243ef 11697 if (move_group) {
321027c1
PZ
11698 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11699
84c4e620
PZ
11700 if (gctx->task == TASK_TOMBSTONE) {
11701 err = -ESRCH;
11702 goto err_locked;
11703 }
321027c1
PZ
11704
11705 /*
11706 * Check if we raced against another sys_perf_event_open() call
11707 * moving the software group underneath us.
11708 */
11709 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11710 /*
11711 * If someone moved the group out from under us, check
11712 * if this new event wound up on the same ctx, if so
11713 * its the regular !move_group case, otherwise fail.
11714 */
11715 if (gctx != ctx) {
11716 err = -EINVAL;
11717 goto err_locked;
11718 } else {
11719 perf_event_ctx_unlock(group_leader, gctx);
11720 move_group = 0;
11721 }
11722 }
8a58ddae
AS
11723
11724 /*
11725 * Failure to create exclusive events returns -EBUSY.
11726 */
11727 err = -EBUSY;
11728 if (!exclusive_event_installable(group_leader, ctx))
11729 goto err_locked;
11730
11731 for_each_sibling_event(sibling, group_leader) {
11732 if (!exclusive_event_installable(sibling, ctx))
11733 goto err_locked;
11734 }
f55fc2a5
PZ
11735 } else {
11736 mutex_lock(&ctx->mutex);
11737 }
11738
84c4e620
PZ
11739 if (ctx->task == TASK_TOMBSTONE) {
11740 err = -ESRCH;
11741 goto err_locked;
11742 }
11743
a723968c
PZ
11744 if (!perf_event_validate_size(event)) {
11745 err = -E2BIG;
11746 goto err_locked;
11747 }
11748
a63fbed7
TG
11749 if (!task) {
11750 /*
11751 * Check if the @cpu we're creating an event for is online.
11752 *
11753 * We use the perf_cpu_context::ctx::mutex to serialize against
11754 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11755 */
11756 struct perf_cpu_context *cpuctx =
11757 container_of(ctx, struct perf_cpu_context, ctx);
11758
11759 if (!cpuctx->online) {
11760 err = -ENODEV;
11761 goto err_locked;
11762 }
11763 }
11764
da9ec3d3
MR
11765 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) {
11766 err = -EINVAL;
ab43762e 11767 goto err_locked;
da9ec3d3 11768 }
a63fbed7 11769
f55fc2a5
PZ
11770 /*
11771 * Must be under the same ctx::mutex as perf_install_in_context(),
11772 * because we need to serialize with concurrent event creation.
11773 */
11774 if (!exclusive_event_installable(event, ctx)) {
f55fc2a5
PZ
11775 err = -EBUSY;
11776 goto err_locked;
11777 }
f63a8daa 11778
f55fc2a5
PZ
11779 WARN_ON_ONCE(ctx->parent_ctx);
11780
79c9ce57
PZ
11781 /*
11782 * This is the point on no return; we cannot fail hereafter. This is
11783 * where we start modifying current state.
11784 */
11785
f55fc2a5 11786 if (move_group) {
f63a8daa
PZ
11787 /*
11788 * See perf_event_ctx_lock() for comments on the details
11789 * of swizzling perf_event::ctx.
11790 */
45a0e07a 11791 perf_remove_from_context(group_leader, 0);
279b5165 11792 put_ctx(gctx);
0231bb53 11793
edb39592 11794 for_each_sibling_event(sibling, group_leader) {
45a0e07a 11795 perf_remove_from_context(sibling, 0);
b04243ef
PZ
11796 put_ctx(gctx);
11797 }
b04243ef 11798
f63a8daa
PZ
11799 /*
11800 * Wait for everybody to stop referencing the events through
11801 * the old lists, before installing it on new lists.
11802 */
0cda4c02 11803 synchronize_rcu();
f63a8daa 11804
8f95b435
PZI
11805 /*
11806 * Install the group siblings before the group leader.
11807 *
11808 * Because a group leader will try and install the entire group
11809 * (through the sibling list, which is still in-tact), we can
11810 * end up with siblings installed in the wrong context.
11811 *
11812 * By installing siblings first we NO-OP because they're not
11813 * reachable through the group lists.
11814 */
edb39592 11815 for_each_sibling_event(sibling, group_leader) {
8f95b435 11816 perf_event__state_init(sibling);
9fc81d87 11817 perf_install_in_context(ctx, sibling, sibling->cpu);
b04243ef
PZ
11818 get_ctx(ctx);
11819 }
8f95b435
PZI
11820
11821 /*
11822 * Removing from the context ends up with disabled
11823 * event. What we want here is event in the initial
11824 * startup state, ready to be add into new context.
11825 */
11826 perf_event__state_init(group_leader);
11827 perf_install_in_context(ctx, group_leader, group_leader->cpu);
11828 get_ctx(ctx);
bed5b25a
AS
11829 }
11830
f73e22ab
PZ
11831 /*
11832 * Precalculate sample_data sizes; do while holding ctx::mutex such
11833 * that we're serialized against further additions and before
11834 * perf_install_in_context() which is the point the event is active and
11835 * can use these values.
11836 */
11837 perf_event__header_size(event);
11838 perf_event__id_header_size(event);
11839
78cd2c74
PZ
11840 event->owner = current;
11841
e2d37cd2 11842 perf_install_in_context(ctx, event, event->cpu);
fe4b04fa 11843 perf_unpin_context(ctx);
f63a8daa 11844
f55fc2a5 11845 if (move_group)
321027c1 11846 perf_event_ctx_unlock(group_leader, gctx);
d859e29f 11847 mutex_unlock(&ctx->mutex);
9b51f66d 11848
79c9ce57 11849 if (task) {
69143038 11850 mutex_unlock(&task->signal->exec_update_mutex);
79c9ce57
PZ
11851 put_task_struct(task);
11852 }
11853
cdd6c482
IM
11854 mutex_lock(&current->perf_event_mutex);
11855 list_add_tail(&event->owner_entry, &current->perf_event_list);
11856 mutex_unlock(&current->perf_event_mutex);
082ff5a2 11857
8a49542c
PZ
11858 /*
11859 * Drop the reference on the group_event after placing the
11860 * new event on the sibling_list. This ensures destruction
11861 * of the group leader will find the pointer to itself in
11862 * perf_group_detach().
11863 */
2903ff01 11864 fdput(group);
ea635c64
AV
11865 fd_install(event_fd, event_file);
11866 return event_fd;
0793a61d 11867
f55fc2a5
PZ
11868err_locked:
11869 if (move_group)
321027c1 11870 perf_event_ctx_unlock(group_leader, gctx);
f55fc2a5
PZ
11871 mutex_unlock(&ctx->mutex);
11872/* err_file: */
11873 fput(event_file);
c3f00c70 11874err_context:
fe4b04fa 11875 perf_unpin_context(ctx);
ea635c64 11876 put_ctx(ctx);
c6be5a5c 11877err_alloc:
13005627
PZ
11878 /*
11879 * If event_file is set, the fput() above will have called ->release()
11880 * and that will take care of freeing the event.
11881 */
11882 if (!event_file)
11883 free_event(event);
79c9ce57
PZ
11884err_cred:
11885 if (task)
69143038 11886 mutex_unlock(&task->signal->exec_update_mutex);
1f4ee503 11887err_task:
e7d0bc04
PZ
11888 if (task)
11889 put_task_struct(task);
89a1e187 11890err_group_fd:
2903ff01 11891 fdput(group);
ea635c64
AV
11892err_fd:
11893 put_unused_fd(event_fd);
dc86cabe 11894 return err;
0793a61d
TG
11895}
11896
fb0459d7
AV
11897/**
11898 * perf_event_create_kernel_counter
11899 *
11900 * @attr: attributes of the counter to create
11901 * @cpu: cpu in which the counter is bound
38a81da2 11902 * @task: task to profile (NULL for percpu)
fb0459d7
AV
11903 */
11904struct perf_event *
11905perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
38a81da2 11906 struct task_struct *task,
4dc0da86
AK
11907 perf_overflow_handler_t overflow_handler,
11908 void *context)
fb0459d7 11909{
fb0459d7 11910 struct perf_event_context *ctx;
c3f00c70 11911 struct perf_event *event;
fb0459d7 11912 int err;
d859e29f 11913
dce5affb
AS
11914 /*
11915 * Grouping is not supported for kernel events, neither is 'AUX',
11916 * make sure the caller's intentions are adjusted.
11917 */
11918 if (attr->aux_output)
11919 return ERR_PTR(-EINVAL);
11920
4dc0da86 11921 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
79dff51e 11922 overflow_handler, context, -1);
c3f00c70
PZ
11923 if (IS_ERR(event)) {
11924 err = PTR_ERR(event);
11925 goto err;
11926 }
d859e29f 11927
f8697762 11928 /* Mark owner so we could distinguish it from user events. */
63b6da39 11929 event->owner = TASK_TOMBSTONE;
f8697762 11930
f25d8ba9
AS
11931 /*
11932 * Get the target context (task or percpu):
11933 */
4af57ef2 11934 ctx = find_get_context(event->pmu, task, event);
c6567f64
FW
11935 if (IS_ERR(ctx)) {
11936 err = PTR_ERR(ctx);
c3f00c70 11937 goto err_free;
d859e29f 11938 }
fb0459d7 11939
fb0459d7
AV
11940 WARN_ON_ONCE(ctx->parent_ctx);
11941 mutex_lock(&ctx->mutex);
84c4e620
PZ
11942 if (ctx->task == TASK_TOMBSTONE) {
11943 err = -ESRCH;
11944 goto err_unlock;
11945 }
11946
a63fbed7
TG
11947 if (!task) {
11948 /*
11949 * Check if the @cpu we're creating an event for is online.
11950 *
11951 * We use the perf_cpu_context::ctx::mutex to serialize against
11952 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11953 */
11954 struct perf_cpu_context *cpuctx =
11955 container_of(ctx, struct perf_cpu_context, ctx);
11956 if (!cpuctx->online) {
11957 err = -ENODEV;
11958 goto err_unlock;
11959 }
11960 }
11961
bed5b25a 11962 if (!exclusive_event_installable(event, ctx)) {
bed5b25a 11963 err = -EBUSY;
84c4e620 11964 goto err_unlock;
bed5b25a
AS
11965 }
11966
4ce54af8 11967 perf_install_in_context(ctx, event, event->cpu);
fe4b04fa 11968 perf_unpin_context(ctx);
fb0459d7
AV
11969 mutex_unlock(&ctx->mutex);
11970
fb0459d7
AV
11971 return event;
11972
84c4e620
PZ
11973err_unlock:
11974 mutex_unlock(&ctx->mutex);
11975 perf_unpin_context(ctx);
11976 put_ctx(ctx);
c3f00c70
PZ
11977err_free:
11978 free_event(event);
11979err:
c6567f64 11980 return ERR_PTR(err);
9b51f66d 11981}
fb0459d7 11982EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
9b51f66d 11983
0cda4c02
YZ
11984void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
11985{
11986 struct perf_event_context *src_ctx;
11987 struct perf_event_context *dst_ctx;
11988 struct perf_event *event, *tmp;
11989 LIST_HEAD(events);
11990
11991 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
11992 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
11993
f63a8daa
PZ
11994 /*
11995 * See perf_event_ctx_lock() for comments on the details
11996 * of swizzling perf_event::ctx.
11997 */
11998 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
0cda4c02
YZ
11999 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
12000 event_entry) {
45a0e07a 12001 perf_remove_from_context(event, 0);
9a545de0 12002 unaccount_event_cpu(event, src_cpu);
0cda4c02 12003 put_ctx(src_ctx);
9886167d 12004 list_add(&event->migrate_entry, &events);
0cda4c02 12005 }
0cda4c02 12006
8f95b435
PZI
12007 /*
12008 * Wait for the events to quiesce before re-instating them.
12009 */
0cda4c02
YZ
12010 synchronize_rcu();
12011
8f95b435
PZI
12012 /*
12013 * Re-instate events in 2 passes.
12014 *
12015 * Skip over group leaders and only install siblings on this first
12016 * pass, siblings will not get enabled without a leader, however a
12017 * leader will enable its siblings, even if those are still on the old
12018 * context.
12019 */
12020 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12021 if (event->group_leader == event)
12022 continue;
12023
12024 list_del(&event->migrate_entry);
12025 if (event->state >= PERF_EVENT_STATE_OFF)
12026 event->state = PERF_EVENT_STATE_INACTIVE;
12027 account_event_cpu(event, dst_cpu);
12028 perf_install_in_context(dst_ctx, event, dst_cpu);
12029 get_ctx(dst_ctx);
12030 }
12031
12032 /*
12033 * Once all the siblings are setup properly, install the group leaders
12034 * to make it go.
12035 */
9886167d
PZ
12036 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
12037 list_del(&event->migrate_entry);
0cda4c02
YZ
12038 if (event->state >= PERF_EVENT_STATE_OFF)
12039 event->state = PERF_EVENT_STATE_INACTIVE;
9a545de0 12040 account_event_cpu(event, dst_cpu);
0cda4c02
YZ
12041 perf_install_in_context(dst_ctx, event, dst_cpu);
12042 get_ctx(dst_ctx);
12043 }
12044 mutex_unlock(&dst_ctx->mutex);
f63a8daa 12045 mutex_unlock(&src_ctx->mutex);
0cda4c02
YZ
12046}
12047EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
12048
cdd6c482 12049static void sync_child_event(struct perf_event *child_event,
38b200d6 12050 struct task_struct *child)
d859e29f 12051{
cdd6c482 12052 struct perf_event *parent_event = child_event->parent;
8bc20959 12053 u64 child_val;
d859e29f 12054
cdd6c482
IM
12055 if (child_event->attr.inherit_stat)
12056 perf_event_read_event(child_event, child);
38b200d6 12057
b5e58793 12058 child_val = perf_event_count(child_event);
d859e29f
PM
12059
12060 /*
12061 * Add back the child's count to the parent's count:
12062 */
a6e6dea6 12063 atomic64_add(child_val, &parent_event->child_count);
cdd6c482
IM
12064 atomic64_add(child_event->total_time_enabled,
12065 &parent_event->child_total_time_enabled);
12066 atomic64_add(child_event->total_time_running,
12067 &parent_event->child_total_time_running);
d859e29f
PM
12068}
12069
9b51f66d 12070static void
8ba289b8
PZ
12071perf_event_exit_event(struct perf_event *child_event,
12072 struct perf_event_context *child_ctx,
12073 struct task_struct *child)
9b51f66d 12074{
8ba289b8
PZ
12075 struct perf_event *parent_event = child_event->parent;
12076
1903d50c
PZ
12077 /*
12078 * Do not destroy the 'original' grouping; because of the context
12079 * switch optimization the original events could've ended up in a
12080 * random child task.
12081 *
12082 * If we were to destroy the original group, all group related
12083 * operations would cease to function properly after this random
12084 * child dies.
12085 *
12086 * Do destroy all inherited groups, we don't care about those
12087 * and being thorough is better.
12088 */
32132a3d
PZ
12089 raw_spin_lock_irq(&child_ctx->lock);
12090 WARN_ON_ONCE(child_ctx->is_active);
12091
8ba289b8 12092 if (parent_event)
32132a3d
PZ
12093 perf_group_detach(child_event);
12094 list_del_event(child_event, child_ctx);
0d3d73aa 12095 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
32132a3d 12096 raw_spin_unlock_irq(&child_ctx->lock);
0cc0c027 12097
9b51f66d 12098 /*
8ba289b8 12099 * Parent events are governed by their filedesc, retain them.
9b51f66d 12100 */
8ba289b8 12101 if (!parent_event) {
179033b3 12102 perf_event_wakeup(child_event);
8ba289b8 12103 return;
4bcf349a 12104 }
8ba289b8
PZ
12105 /*
12106 * Child events can be cleaned up.
12107 */
12108
12109 sync_child_event(child_event, child);
12110
12111 /*
12112 * Remove this event from the parent's list
12113 */
12114 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
12115 mutex_lock(&parent_event->child_mutex);
12116 list_del_init(&child_event->child_list);
12117 mutex_unlock(&parent_event->child_mutex);
12118
12119 /*
12120 * Kick perf_poll() for is_event_hup().
12121 */
12122 perf_event_wakeup(parent_event);
12123 free_event(child_event);
12124 put_event(parent_event);
9b51f66d
IM
12125}
12126
8dc85d54 12127static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
9b51f66d 12128{
211de6eb 12129 struct perf_event_context *child_ctx, *clone_ctx = NULL;
63b6da39 12130 struct perf_event *child_event, *next;
63b6da39
PZ
12131
12132 WARN_ON_ONCE(child != current);
9b51f66d 12133
6a3351b6 12134 child_ctx = perf_pin_task_context(child, ctxn);
63b6da39 12135 if (!child_ctx)
9b51f66d
IM
12136 return;
12137
ad3a37de 12138 /*
6a3351b6
PZ
12139 * In order to reduce the amount of tricky in ctx tear-down, we hold
12140 * ctx::mutex over the entire thing. This serializes against almost
12141 * everything that wants to access the ctx.
12142 *
12143 * The exception is sys_perf_event_open() /
12144 * perf_event_create_kernel_count() which does find_get_context()
12145 * without ctx::mutex (it cannot because of the move_group double mutex
12146 * lock thing). See the comments in perf_install_in_context().
ad3a37de 12147 */
6a3351b6 12148 mutex_lock(&child_ctx->mutex);
c93f7669
PM
12149
12150 /*
6a3351b6
PZ
12151 * In a single ctx::lock section, de-schedule the events and detach the
12152 * context from the task such that we cannot ever get it scheduled back
12153 * in.
c93f7669 12154 */
6a3351b6 12155 raw_spin_lock_irq(&child_ctx->lock);
487f05e1 12156 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
4a1c0f26 12157
71a851b4 12158 /*
63b6da39
PZ
12159 * Now that the context is inactive, destroy the task <-> ctx relation
12160 * and mark the context dead.
71a851b4 12161 */
63b6da39
PZ
12162 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
12163 put_ctx(child_ctx); /* cannot be last */
12164 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
12165 put_task_struct(current); /* cannot be last */
4a1c0f26 12166
211de6eb 12167 clone_ctx = unclone_ctx(child_ctx);
6a3351b6 12168 raw_spin_unlock_irq(&child_ctx->lock);
9f498cc5 12169
211de6eb
PZ
12170 if (clone_ctx)
12171 put_ctx(clone_ctx);
4a1c0f26 12172
9f498cc5 12173 /*
cdd6c482
IM
12174 * Report the task dead after unscheduling the events so that we
12175 * won't get any samples after PERF_RECORD_EXIT. We can however still
12176 * get a few PERF_RECORD_READ events.
9f498cc5 12177 */
cdd6c482 12178 perf_event_task(child, child_ctx, 0);
a63eaf34 12179
ebf905fc 12180 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8ba289b8 12181 perf_event_exit_event(child_event, child_ctx, child);
8bc20959 12182
a63eaf34
PM
12183 mutex_unlock(&child_ctx->mutex);
12184
12185 put_ctx(child_ctx);
9b51f66d
IM
12186}
12187
8dc85d54
PZ
12188/*
12189 * When a child task exits, feed back event values to parent events.
79c9ce57 12190 *
69143038 12191 * Can be called with exec_update_mutex held when called from
79c9ce57 12192 * install_exec_creds().
8dc85d54
PZ
12193 */
12194void perf_event_exit_task(struct task_struct *child)
12195{
8882135b 12196 struct perf_event *event, *tmp;
8dc85d54
PZ
12197 int ctxn;
12198
8882135b
PZ
12199 mutex_lock(&child->perf_event_mutex);
12200 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
12201 owner_entry) {
12202 list_del_init(&event->owner_entry);
12203
12204 /*
12205 * Ensure the list deletion is visible before we clear
12206 * the owner, closes a race against perf_release() where
12207 * we need to serialize on the owner->perf_event_mutex.
12208 */
f47c02c0 12209 smp_store_release(&event->owner, NULL);
8882135b
PZ
12210 }
12211 mutex_unlock(&child->perf_event_mutex);
12212
8dc85d54
PZ
12213 for_each_task_context_nr(ctxn)
12214 perf_event_exit_task_context(child, ctxn);
4e93ad60
JO
12215
12216 /*
12217 * The perf_event_exit_task_context calls perf_event_task
12218 * with child's task_ctx, which generates EXIT events for
12219 * child contexts and sets child->perf_event_ctxp[] to NULL.
12220 * At this point we need to send EXIT events to cpu contexts.
12221 */
12222 perf_event_task(child, NULL, 0);
8dc85d54
PZ
12223}
12224
889ff015
FW
12225static void perf_free_event(struct perf_event *event,
12226 struct perf_event_context *ctx)
12227{
12228 struct perf_event *parent = event->parent;
12229
12230 if (WARN_ON_ONCE(!parent))
12231 return;
12232
12233 mutex_lock(&parent->child_mutex);
12234 list_del_init(&event->child_list);
12235 mutex_unlock(&parent->child_mutex);
12236
a6fa941d 12237 put_event(parent);
889ff015 12238
652884fe 12239 raw_spin_lock_irq(&ctx->lock);
8a49542c 12240 perf_group_detach(event);
889ff015 12241 list_del_event(event, ctx);
652884fe 12242 raw_spin_unlock_irq(&ctx->lock);
889ff015
FW
12243 free_event(event);
12244}
12245
bbbee908 12246/*
1cf8dfe8
PZ
12247 * Free a context as created by inheritance by perf_event_init_task() below,
12248 * used by fork() in case of fail.
652884fe 12249 *
1cf8dfe8
PZ
12250 * Even though the task has never lived, the context and events have been
12251 * exposed through the child_list, so we must take care tearing it all down.
bbbee908 12252 */
cdd6c482 12253void perf_event_free_task(struct task_struct *task)
bbbee908 12254{
8dc85d54 12255 struct perf_event_context *ctx;
cdd6c482 12256 struct perf_event *event, *tmp;
8dc85d54 12257 int ctxn;
bbbee908 12258
8dc85d54
PZ
12259 for_each_task_context_nr(ctxn) {
12260 ctx = task->perf_event_ctxp[ctxn];
12261 if (!ctx)
12262 continue;
bbbee908 12263
8dc85d54 12264 mutex_lock(&ctx->mutex);
e552a838
PZ
12265 raw_spin_lock_irq(&ctx->lock);
12266 /*
12267 * Destroy the task <-> ctx relation and mark the context dead.
12268 *
12269 * This is important because even though the task hasn't been
12270 * exposed yet the context has been (through child_list).
12271 */
12272 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
12273 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
12274 put_task_struct(task); /* cannot be last */
12275 raw_spin_unlock_irq(&ctx->lock);
bbbee908 12276
15121c78 12277 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
8dc85d54 12278 perf_free_event(event, ctx);
bbbee908 12279
8dc85d54 12280 mutex_unlock(&ctx->mutex);
1cf8dfe8
PZ
12281
12282 /*
12283 * perf_event_release_kernel() could've stolen some of our
12284 * child events and still have them on its free_list. In that
12285 * case we must wait for these events to have been freed (in
12286 * particular all their references to this task must've been
12287 * dropped).
12288 *
12289 * Without this copy_process() will unconditionally free this
12290 * task (irrespective of its reference count) and
12291 * _free_event()'s put_task_struct(event->hw.target) will be a
12292 * use-after-free.
12293 *
12294 * Wait for all events to drop their context reference.
12295 */
12296 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
12297 put_ctx(ctx); /* must be last */
8dc85d54 12298 }
889ff015
FW
12299}
12300
4e231c79
PZ
12301void perf_event_delayed_put(struct task_struct *task)
12302{
12303 int ctxn;
12304
12305 for_each_task_context_nr(ctxn)
12306 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
12307}
12308
e03e7ee3 12309struct file *perf_event_get(unsigned int fd)
ffe8690c 12310{
02e5ad97 12311 struct file *file = fget(fd);
e03e7ee3
AS
12312 if (!file)
12313 return ERR_PTR(-EBADF);
ffe8690c 12314
e03e7ee3
AS
12315 if (file->f_op != &perf_fops) {
12316 fput(file);
12317 return ERR_PTR(-EBADF);
12318 }
ffe8690c 12319
e03e7ee3 12320 return file;
ffe8690c
KX
12321}
12322
f8d959a5
YS
12323const struct perf_event *perf_get_event(struct file *file)
12324{
12325 if (file->f_op != &perf_fops)
12326 return ERR_PTR(-EINVAL);
12327
12328 return file->private_data;
12329}
12330
ffe8690c
KX
12331const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
12332{
12333 if (!event)
12334 return ERR_PTR(-EINVAL);
12335
12336 return &event->attr;
12337}
12338
97dee4f3 12339/*
788faab7 12340 * Inherit an event from parent task to child task.
d8a8cfc7
PZ
12341 *
12342 * Returns:
12343 * - valid pointer on success
12344 * - NULL for orphaned events
12345 * - IS_ERR() on error
97dee4f3
PZ
12346 */
12347static struct perf_event *
12348inherit_event(struct perf_event *parent_event,
12349 struct task_struct *parent,
12350 struct perf_event_context *parent_ctx,
12351 struct task_struct *child,
12352 struct perf_event *group_leader,
12353 struct perf_event_context *child_ctx)
12354{
8ca2bd41 12355 enum perf_event_state parent_state = parent_event->state;
97dee4f3 12356 struct perf_event *child_event;
cee010ec 12357 unsigned long flags;
97dee4f3
PZ
12358
12359 /*
12360 * Instead of creating recursive hierarchies of events,
12361 * we link inherited events back to the original parent,
12362 * which has a filp for sure, which we use as the reference
12363 * count:
12364 */
12365 if (parent_event->parent)
12366 parent_event = parent_event->parent;
12367
12368 child_event = perf_event_alloc(&parent_event->attr,
12369 parent_event->cpu,
d580ff86 12370 child,
97dee4f3 12371 group_leader, parent_event,
79dff51e 12372 NULL, NULL, -1);
97dee4f3
PZ
12373 if (IS_ERR(child_event))
12374 return child_event;
a6fa941d 12375
313ccb96
JO
12376
12377 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
12378 !child_ctx->task_ctx_data) {
12379 struct pmu *pmu = child_event->pmu;
12380
12381 child_ctx->task_ctx_data = kzalloc(pmu->task_ctx_size,
12382 GFP_KERNEL);
12383 if (!child_ctx->task_ctx_data) {
12384 free_event(child_event);
697d8778 12385 return ERR_PTR(-ENOMEM);
313ccb96
JO
12386 }
12387 }
12388
c6e5b732
PZ
12389 /*
12390 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
12391 * must be under the same lock in order to serialize against
12392 * perf_event_release_kernel(), such that either we must observe
12393 * is_orphaned_event() or they will observe us on the child_list.
12394 */
12395 mutex_lock(&parent_event->child_mutex);
fadfe7be
JO
12396 if (is_orphaned_event(parent_event) ||
12397 !atomic_long_inc_not_zero(&parent_event->refcount)) {
c6e5b732 12398 mutex_unlock(&parent_event->child_mutex);
313ccb96 12399 /* task_ctx_data is freed with child_ctx */
a6fa941d
AV
12400 free_event(child_event);
12401 return NULL;
12402 }
12403
97dee4f3
PZ
12404 get_ctx(child_ctx);
12405
12406 /*
12407 * Make the child state follow the state of the parent event,
12408 * not its attr.disabled bit. We hold the parent's mutex,
12409 * so we won't race with perf_event_{en, dis}able_family.
12410 */
1929def9 12411 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
97dee4f3
PZ
12412 child_event->state = PERF_EVENT_STATE_INACTIVE;
12413 else
12414 child_event->state = PERF_EVENT_STATE_OFF;
12415
12416 if (parent_event->attr.freq) {
12417 u64 sample_period = parent_event->hw.sample_period;
12418 struct hw_perf_event *hwc = &child_event->hw;
12419
12420 hwc->sample_period = sample_period;
12421 hwc->last_period = sample_period;
12422
12423 local64_set(&hwc->period_left, sample_period);
12424 }
12425
12426 child_event->ctx = child_ctx;
12427 child_event->overflow_handler = parent_event->overflow_handler;
4dc0da86
AK
12428 child_event->overflow_handler_context
12429 = parent_event->overflow_handler_context;
97dee4f3 12430
614b6780
TG
12431 /*
12432 * Precalculate sample_data sizes
12433 */
12434 perf_event__header_size(child_event);
6844c09d 12435 perf_event__id_header_size(child_event);
614b6780 12436
97dee4f3
PZ
12437 /*
12438 * Link it up in the child's context:
12439 */
cee010ec 12440 raw_spin_lock_irqsave(&child_ctx->lock, flags);
97dee4f3 12441 add_event_to_ctx(child_event, child_ctx);
cee010ec 12442 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
97dee4f3 12443
97dee4f3
PZ
12444 /*
12445 * Link this into the parent event's child list
12446 */
97dee4f3
PZ
12447 list_add_tail(&child_event->child_list, &parent_event->child_list);
12448 mutex_unlock(&parent_event->child_mutex);
12449
12450 return child_event;
12451}
12452
d8a8cfc7
PZ
12453/*
12454 * Inherits an event group.
12455 *
12456 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12457 * This matches with perf_event_release_kernel() removing all child events.
12458 *
12459 * Returns:
12460 * - 0 on success
12461 * - <0 on error
12462 */
97dee4f3
PZ
12463static int inherit_group(struct perf_event *parent_event,
12464 struct task_struct *parent,
12465 struct perf_event_context *parent_ctx,
12466 struct task_struct *child,
12467 struct perf_event_context *child_ctx)
12468{
12469 struct perf_event *leader;
12470 struct perf_event *sub;
12471 struct perf_event *child_ctr;
12472
12473 leader = inherit_event(parent_event, parent, parent_ctx,
12474 child, NULL, child_ctx);
12475 if (IS_ERR(leader))
12476 return PTR_ERR(leader);
d8a8cfc7
PZ
12477 /*
12478 * @leader can be NULL here because of is_orphaned_event(). In this
12479 * case inherit_event() will create individual events, similar to what
12480 * perf_group_detach() would do anyway.
12481 */
edb39592 12482 for_each_sibling_event(sub, parent_event) {
97dee4f3
PZ
12483 child_ctr = inherit_event(sub, parent, parent_ctx,
12484 child, leader, child_ctx);
12485 if (IS_ERR(child_ctr))
12486 return PTR_ERR(child_ctr);
f733c6b5 12487
00496fe5 12488 if (sub->aux_event == parent_event && child_ctr &&
f733c6b5
AS
12489 !perf_get_aux_event(child_ctr, leader))
12490 return -EINVAL;
97dee4f3
PZ
12491 }
12492 return 0;
889ff015
FW
12493}
12494
d8a8cfc7
PZ
12495/*
12496 * Creates the child task context and tries to inherit the event-group.
12497 *
12498 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12499 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12500 * consistent with perf_event_release_kernel() removing all child events.
12501 *
12502 * Returns:
12503 * - 0 on success
12504 * - <0 on error
12505 */
889ff015
FW
12506static int
12507inherit_task_group(struct perf_event *event, struct task_struct *parent,
12508 struct perf_event_context *parent_ctx,
8dc85d54 12509 struct task_struct *child, int ctxn,
889ff015
FW
12510 int *inherited_all)
12511{
12512 int ret;
8dc85d54 12513 struct perf_event_context *child_ctx;
889ff015
FW
12514
12515 if (!event->attr.inherit) {
12516 *inherited_all = 0;
12517 return 0;
bbbee908
PZ
12518 }
12519
fe4b04fa 12520 child_ctx = child->perf_event_ctxp[ctxn];
889ff015
FW
12521 if (!child_ctx) {
12522 /*
12523 * This is executed from the parent task context, so
12524 * inherit events that have been marked for cloning.
12525 * First allocate and initialize a context for the
12526 * child.
12527 */
734df5ab 12528 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
889ff015
FW
12529 if (!child_ctx)
12530 return -ENOMEM;
bbbee908 12531
8dc85d54 12532 child->perf_event_ctxp[ctxn] = child_ctx;
889ff015
FW
12533 }
12534
12535 ret = inherit_group(event, parent, parent_ctx,
12536 child, child_ctx);
12537
12538 if (ret)
12539 *inherited_all = 0;
12540
12541 return ret;
bbbee908
PZ
12542}
12543
9b51f66d 12544/*
cdd6c482 12545 * Initialize the perf_event context in task_struct
9b51f66d 12546 */
985c8dcb 12547static int perf_event_init_context(struct task_struct *child, int ctxn)
9b51f66d 12548{
889ff015 12549 struct perf_event_context *child_ctx, *parent_ctx;
cdd6c482
IM
12550 struct perf_event_context *cloned_ctx;
12551 struct perf_event *event;
9b51f66d 12552 struct task_struct *parent = current;
564c2b21 12553 int inherited_all = 1;
dddd3379 12554 unsigned long flags;
6ab423e0 12555 int ret = 0;
9b51f66d 12556
8dc85d54 12557 if (likely(!parent->perf_event_ctxp[ctxn]))
6ab423e0
PZ
12558 return 0;
12559
ad3a37de 12560 /*
25346b93
PM
12561 * If the parent's context is a clone, pin it so it won't get
12562 * swapped under us.
ad3a37de 12563 */
8dc85d54 12564 parent_ctx = perf_pin_task_context(parent, ctxn);
ffb4ef21
PZ
12565 if (!parent_ctx)
12566 return 0;
25346b93 12567
ad3a37de
PM
12568 /*
12569 * No need to check if parent_ctx != NULL here; since we saw
12570 * it non-NULL earlier, the only reason for it to become NULL
12571 * is if we exit, and since we're currently in the middle of
12572 * a fork we can't be exiting at the same time.
12573 */
ad3a37de 12574
9b51f66d
IM
12575 /*
12576 * Lock the parent list. No need to lock the child - not PID
12577 * hashed yet and not running, so nobody can access it.
12578 */
d859e29f 12579 mutex_lock(&parent_ctx->mutex);
9b51f66d
IM
12580
12581 /*
12582 * We dont have to disable NMIs - we are only looking at
12583 * the list, not manipulating it:
12584 */
6e6804d2 12585 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
8dc85d54
PZ
12586 ret = inherit_task_group(event, parent, parent_ctx,
12587 child, ctxn, &inherited_all);
889ff015 12588 if (ret)
e7cc4865 12589 goto out_unlock;
889ff015 12590 }
b93f7978 12591
dddd3379
TG
12592 /*
12593 * We can't hold ctx->lock when iterating the ->flexible_group list due
12594 * to allocations, but we need to prevent rotation because
12595 * rotate_ctx() will change the list from interrupt context.
12596 */
12597 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12598 parent_ctx->rotate_disable = 1;
12599 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12600
6e6804d2 12601 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
8dc85d54
PZ
12602 ret = inherit_task_group(event, parent, parent_ctx,
12603 child, ctxn, &inherited_all);
889ff015 12604 if (ret)
e7cc4865 12605 goto out_unlock;
564c2b21
PM
12606 }
12607
dddd3379
TG
12608 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12609 parent_ctx->rotate_disable = 0;
dddd3379 12610
8dc85d54 12611 child_ctx = child->perf_event_ctxp[ctxn];
889ff015 12612
05cbaa28 12613 if (child_ctx && inherited_all) {
564c2b21
PM
12614 /*
12615 * Mark the child context as a clone of the parent
12616 * context, or of whatever the parent is a clone of.
c5ed5145
PZ
12617 *
12618 * Note that if the parent is a clone, the holding of
12619 * parent_ctx->lock avoids it from being uncloned.
564c2b21 12620 */
c5ed5145 12621 cloned_ctx = parent_ctx->parent_ctx;
ad3a37de
PM
12622 if (cloned_ctx) {
12623 child_ctx->parent_ctx = cloned_ctx;
25346b93 12624 child_ctx->parent_gen = parent_ctx->parent_gen;
564c2b21
PM
12625 } else {
12626 child_ctx->parent_ctx = parent_ctx;
12627 child_ctx->parent_gen = parent_ctx->generation;
12628 }
12629 get_ctx(child_ctx->parent_ctx);
9b51f66d
IM
12630 }
12631
c5ed5145 12632 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
e7cc4865 12633out_unlock:
d859e29f 12634 mutex_unlock(&parent_ctx->mutex);
6ab423e0 12635
25346b93 12636 perf_unpin_context(parent_ctx);
fe4b04fa 12637 put_ctx(parent_ctx);
ad3a37de 12638
6ab423e0 12639 return ret;
9b51f66d
IM
12640}
12641
8dc85d54
PZ
12642/*
12643 * Initialize the perf_event context in task_struct
12644 */
12645int perf_event_init_task(struct task_struct *child)
12646{
12647 int ctxn, ret;
12648
8550d7cb
ON
12649 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12650 mutex_init(&child->perf_event_mutex);
12651 INIT_LIST_HEAD(&child->perf_event_list);
12652
8dc85d54
PZ
12653 for_each_task_context_nr(ctxn) {
12654 ret = perf_event_init_context(child, ctxn);
6c72e350
PZ
12655 if (ret) {
12656 perf_event_free_task(child);
8dc85d54 12657 return ret;
6c72e350 12658 }
8dc85d54
PZ
12659 }
12660
12661 return 0;
12662}
12663
220b140b
PM
12664static void __init perf_event_init_all_cpus(void)
12665{
b28ab83c 12666 struct swevent_htable *swhash;
220b140b 12667 int cpu;
220b140b 12668
a63fbed7
TG
12669 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12670
220b140b 12671 for_each_possible_cpu(cpu) {
b28ab83c
PZ
12672 swhash = &per_cpu(swevent_htable, cpu);
12673 mutex_init(&swhash->hlist_mutex);
2fde4f94 12674 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
f2fb6bef
KL
12675
12676 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12677 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
e48c1788 12678
058fe1c0
DCC
12679#ifdef CONFIG_CGROUP_PERF
12680 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12681#endif
e48c1788 12682 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
220b140b
PM
12683 }
12684}
12685
d18bf422 12686static void perf_swevent_init_cpu(unsigned int cpu)
0793a61d 12687{
108b02cf 12688 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
0793a61d 12689
b28ab83c 12690 mutex_lock(&swhash->hlist_mutex);
059fcd8c 12691 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
76e1d904
FW
12692 struct swevent_hlist *hlist;
12693
b28ab83c
PZ
12694 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12695 WARN_ON(!hlist);
12696 rcu_assign_pointer(swhash->swevent_hlist, hlist);
76e1d904 12697 }
b28ab83c 12698 mutex_unlock(&swhash->hlist_mutex);
0793a61d
TG
12699}
12700
2965faa5 12701#if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
108b02cf 12702static void __perf_event_exit_context(void *__info)
0793a61d 12703{
108b02cf 12704 struct perf_event_context *ctx = __info;
fae3fde6
PZ
12705 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12706 struct perf_event *event;
0793a61d 12707
fae3fde6 12708 raw_spin_lock(&ctx->lock);
0ee098c9 12709 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
fae3fde6 12710 list_for_each_entry(event, &ctx->event_list, event_entry)
45a0e07a 12711 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
fae3fde6 12712 raw_spin_unlock(&ctx->lock);
0793a61d 12713}
108b02cf
PZ
12714
12715static void perf_event_exit_cpu_context(int cpu)
12716{
a63fbed7 12717 struct perf_cpu_context *cpuctx;
108b02cf
PZ
12718 struct perf_event_context *ctx;
12719 struct pmu *pmu;
108b02cf 12720
a63fbed7
TG
12721 mutex_lock(&pmus_lock);
12722 list_for_each_entry(pmu, &pmus, entry) {
12723 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12724 ctx = &cpuctx->ctx;
108b02cf
PZ
12725
12726 mutex_lock(&ctx->mutex);
12727 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
a63fbed7 12728 cpuctx->online = 0;
108b02cf
PZ
12729 mutex_unlock(&ctx->mutex);
12730 }
a63fbed7
TG
12731 cpumask_clear_cpu(cpu, perf_online_mask);
12732 mutex_unlock(&pmus_lock);
108b02cf 12733}
00e16c3d
TG
12734#else
12735
12736static void perf_event_exit_cpu_context(int cpu) { }
12737
12738#endif
108b02cf 12739
a63fbed7
TG
12740int perf_event_init_cpu(unsigned int cpu)
12741{
12742 struct perf_cpu_context *cpuctx;
12743 struct perf_event_context *ctx;
12744 struct pmu *pmu;
12745
12746 perf_swevent_init_cpu(cpu);
12747
12748 mutex_lock(&pmus_lock);
12749 cpumask_set_cpu(cpu, perf_online_mask);
12750 list_for_each_entry(pmu, &pmus, entry) {
12751 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12752 ctx = &cpuctx->ctx;
12753
12754 mutex_lock(&ctx->mutex);
12755 cpuctx->online = 1;
12756 mutex_unlock(&ctx->mutex);
12757 }
12758 mutex_unlock(&pmus_lock);
12759
12760 return 0;
12761}
12762
00e16c3d 12763int perf_event_exit_cpu(unsigned int cpu)
0793a61d 12764{
e3703f8c 12765 perf_event_exit_cpu_context(cpu);
00e16c3d 12766 return 0;
0793a61d 12767}
0793a61d 12768
c277443c
PZ
12769static int
12770perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
12771{
12772 int cpu;
12773
12774 for_each_online_cpu(cpu)
12775 perf_event_exit_cpu(cpu);
12776
12777 return NOTIFY_OK;
12778}
12779
12780/*
12781 * Run the perf reboot notifier at the very last possible moment so that
12782 * the generic watchdog code runs as long as possible.
12783 */
12784static struct notifier_block perf_reboot_notifier = {
12785 .notifier_call = perf_reboot,
12786 .priority = INT_MIN,
12787};
12788
cdd6c482 12789void __init perf_event_init(void)
0793a61d 12790{
3c502e7a
JW
12791 int ret;
12792
2e80a82a
PZ
12793 idr_init(&pmu_idr);
12794
220b140b 12795 perf_event_init_all_cpus();
b0a873eb 12796 init_srcu_struct(&pmus_srcu);
2e80a82a
PZ
12797 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
12798 perf_pmu_register(&perf_cpu_clock, NULL, -1);
12799 perf_pmu_register(&perf_task_clock, NULL, -1);
b0a873eb 12800 perf_tp_register();
00e16c3d 12801 perf_event_init_cpu(smp_processor_id());
c277443c 12802 register_reboot_notifier(&perf_reboot_notifier);
3c502e7a
JW
12803
12804 ret = init_hw_breakpoint();
12805 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
b2029520 12806
b01c3a00
JO
12807 /*
12808 * Build time assertion that we keep the data_head at the intended
12809 * location. IOW, validation we got the __reserved[] size right.
12810 */
12811 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
12812 != 1024);
0793a61d 12813}
abe43400 12814
fd979c01
CS
12815ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
12816 char *page)
12817{
12818 struct perf_pmu_events_attr *pmu_attr =
12819 container_of(attr, struct perf_pmu_events_attr, attr);
12820
12821 if (pmu_attr->event_str)
12822 return sprintf(page, "%s\n", pmu_attr->event_str);
12823
12824 return 0;
12825}
675965b0 12826EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
fd979c01 12827
abe43400
PZ
12828static int __init perf_event_sysfs_init(void)
12829{
12830 struct pmu *pmu;
12831 int ret;
12832
12833 mutex_lock(&pmus_lock);
12834
12835 ret = bus_register(&pmu_bus);
12836 if (ret)
12837 goto unlock;
12838
12839 list_for_each_entry(pmu, &pmus, entry) {
12840 if (!pmu->name || pmu->type < 0)
12841 continue;
12842
12843 ret = pmu_dev_alloc(pmu);
12844 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
12845 }
12846 pmu_bus_running = 1;
12847 ret = 0;
12848
12849unlock:
12850 mutex_unlock(&pmus_lock);
12851
12852 return ret;
12853}
12854device_initcall(perf_event_sysfs_init);
e5d1367f
SE
12855
12856#ifdef CONFIG_CGROUP_PERF
eb95419b
TH
12857static struct cgroup_subsys_state *
12858perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
e5d1367f
SE
12859{
12860 struct perf_cgroup *jc;
e5d1367f 12861
1b15d055 12862 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
e5d1367f
SE
12863 if (!jc)
12864 return ERR_PTR(-ENOMEM);
12865
e5d1367f
SE
12866 jc->info = alloc_percpu(struct perf_cgroup_info);
12867 if (!jc->info) {
12868 kfree(jc);
12869 return ERR_PTR(-ENOMEM);
12870 }
12871
e5d1367f
SE
12872 return &jc->css;
12873}
12874
eb95419b 12875static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
e5d1367f 12876{
eb95419b
TH
12877 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
12878
e5d1367f
SE
12879 free_percpu(jc->info);
12880 kfree(jc);
12881}
12882
96aaab68
NK
12883static int perf_cgroup_css_online(struct cgroup_subsys_state *css)
12884{
12885 perf_event_cgroup(css->cgroup);
12886 return 0;
12887}
12888
e5d1367f
SE
12889static int __perf_cgroup_move(void *info)
12890{
12891 struct task_struct *task = info;
ddaaf4e2 12892 rcu_read_lock();
e5d1367f 12893 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
ddaaf4e2 12894 rcu_read_unlock();
e5d1367f
SE
12895 return 0;
12896}
12897
1f7dd3e5 12898static void perf_cgroup_attach(struct cgroup_taskset *tset)
e5d1367f 12899{
bb9d97b6 12900 struct task_struct *task;
1f7dd3e5 12901 struct cgroup_subsys_state *css;
bb9d97b6 12902
1f7dd3e5 12903 cgroup_taskset_for_each(task, css, tset)
bb9d97b6 12904 task_function_call(task, __perf_cgroup_move, task);
e5d1367f
SE
12905}
12906
073219e9 12907struct cgroup_subsys perf_event_cgrp_subsys = {
92fb9748
TH
12908 .css_alloc = perf_cgroup_css_alloc,
12909 .css_free = perf_cgroup_css_free,
96aaab68 12910 .css_online = perf_cgroup_css_online,
bb9d97b6 12911 .attach = perf_cgroup_attach,
968ebff1
TH
12912 /*
12913 * Implicitly enable on dfl hierarchy so that perf events can
12914 * always be filtered by cgroup2 path as long as perf_event
12915 * controller is not mounted on a legacy hierarchy.
12916 */
12917 .implicit_on_dfl = true,
8cfd8147 12918 .threaded = true,
e5d1367f
SE
12919};
12920#endif /* CONFIG_CGROUP_PERF */