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