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