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