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