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