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