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