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