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