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