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