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