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