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