perf: Fix ctx time tracking by introducing EVENT_TIME
[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);
3146 list_for_each_entry(event, &ctx->event_list, event_entry)
3147 enabled |= event_enable_on_exec(event, ctx);
57e7986e
PM
3148
3149 /*
3e349507 3150 * Unclone and reschedule this context if we enabled any event.
57e7986e 3151 */
3e349507 3152 if (enabled) {
211de6eb 3153 clone_ctx = unclone_ctx(ctx);
3e349507
PZ
3154 ctx_resched(cpuctx, ctx);
3155 }
3156 perf_ctx_unlock(cpuctx, ctx);
57e7986e 3157
9ed6060d 3158out:
57e7986e 3159 local_irq_restore(flags);
211de6eb
PZ
3160
3161 if (clone_ctx)
3162 put_ctx(clone_ctx);
57e7986e
PM
3163}
3164
e041e328
PZ
3165void perf_event_exec(void)
3166{
e041e328
PZ
3167 int ctxn;
3168
3169 rcu_read_lock();
c1274499
PZ
3170 for_each_task_context_nr(ctxn)
3171 perf_event_enable_on_exec(ctxn);
e041e328
PZ
3172 rcu_read_unlock();
3173}
3174
0492d4c5
PZ
3175struct perf_read_data {
3176 struct perf_event *event;
3177 bool group;
7d88962e 3178 int ret;
0492d4c5
PZ
3179};
3180
0793a61d 3181/*
cdd6c482 3182 * Cross CPU call to read the hardware event
0793a61d 3183 */
cdd6c482 3184static void __perf_event_read(void *info)
0793a61d 3185{
0492d4c5
PZ
3186 struct perf_read_data *data = info;
3187 struct perf_event *sub, *event = data->event;
cdd6c482 3188 struct perf_event_context *ctx = event->ctx;
108b02cf 3189 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
4a00c16e 3190 struct pmu *pmu = event->pmu;
621a01ea 3191
e1ac3614
PM
3192 /*
3193 * If this is a task context, we need to check whether it is
3194 * the current task context of this cpu. If not it has been
3195 * scheduled out before the smp call arrived. In that case
cdd6c482
IM
3196 * event->count would have been updated to a recent sample
3197 * when the event was scheduled out.
e1ac3614
PM
3198 */
3199 if (ctx->task && cpuctx->task_ctx != ctx)
3200 return;
3201
e625cce1 3202 raw_spin_lock(&ctx->lock);
e5d1367f 3203 if (ctx->is_active) {
542e72fc 3204 update_context_time(ctx);
e5d1367f
SE
3205 update_cgrp_time_from_event(event);
3206 }
0492d4c5 3207
cdd6c482 3208 update_event_times(event);
4a00c16e
SB
3209 if (event->state != PERF_EVENT_STATE_ACTIVE)
3210 goto unlock;
0492d4c5 3211
4a00c16e
SB
3212 if (!data->group) {
3213 pmu->read(event);
3214 data->ret = 0;
0492d4c5 3215 goto unlock;
4a00c16e
SB
3216 }
3217
3218 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
3219
3220 pmu->read(event);
0492d4c5
PZ
3221
3222 list_for_each_entry(sub, &event->sibling_list, group_entry) {
3223 update_event_times(sub);
4a00c16e
SB
3224 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
3225 /*
3226 * Use sibling's PMU rather than @event's since
3227 * sibling could be on different (eg: software) PMU.
3228 */
0492d4c5 3229 sub->pmu->read(sub);
4a00c16e 3230 }
0492d4c5 3231 }
4a00c16e
SB
3232
3233 data->ret = pmu->commit_txn(pmu);
0492d4c5
PZ
3234
3235unlock:
e625cce1 3236 raw_spin_unlock(&ctx->lock);
0793a61d
TG
3237}
3238
b5e58793
PZ
3239static inline u64 perf_event_count(struct perf_event *event)
3240{
eacd3ecc
MF
3241 if (event->pmu->count)
3242 return event->pmu->count(event);
3243
3244 return __perf_event_count(event);
b5e58793
PZ
3245}
3246
ffe8690c
KX
3247/*
3248 * NMI-safe method to read a local event, that is an event that
3249 * is:
3250 * - either for the current task, or for this CPU
3251 * - does not have inherit set, for inherited task events
3252 * will not be local and we cannot read them atomically
3253 * - must not have a pmu::count method
3254 */
3255u64 perf_event_read_local(struct perf_event *event)
3256{
3257 unsigned long flags;
3258 u64 val;
3259
3260 /*
3261 * Disabling interrupts avoids all counter scheduling (context
3262 * switches, timer based rotation and IPIs).
3263 */
3264 local_irq_save(flags);
3265
3266 /* If this is a per-task event, it must be for current */
3267 WARN_ON_ONCE((event->attach_state & PERF_ATTACH_TASK) &&
3268 event->hw.target != current);
3269
3270 /* If this is a per-CPU event, it must be for this CPU */
3271 WARN_ON_ONCE(!(event->attach_state & PERF_ATTACH_TASK) &&
3272 event->cpu != smp_processor_id());
3273
3274 /*
3275 * It must not be an event with inherit set, we cannot read
3276 * all child counters from atomic context.
3277 */
3278 WARN_ON_ONCE(event->attr.inherit);
3279
3280 /*
3281 * It must not have a pmu::count method, those are not
3282 * NMI safe.
3283 */
3284 WARN_ON_ONCE(event->pmu->count);
3285
3286 /*
3287 * If the event is currently on this CPU, its either a per-task event,
3288 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
3289 * oncpu == -1).
3290 */
3291 if (event->oncpu == smp_processor_id())
3292 event->pmu->read(event);
3293
3294 val = local64_read(&event->count);
3295 local_irq_restore(flags);
3296
3297 return val;
3298}
3299
7d88962e 3300static int perf_event_read(struct perf_event *event, bool group)
0793a61d 3301{
7d88962e
SB
3302 int ret = 0;
3303
0793a61d 3304 /*
cdd6c482
IM
3305 * If event is enabled and currently active on a CPU, update the
3306 * value in the event structure:
0793a61d 3307 */
cdd6c482 3308 if (event->state == PERF_EVENT_STATE_ACTIVE) {
0492d4c5
PZ
3309 struct perf_read_data data = {
3310 .event = event,
3311 .group = group,
7d88962e 3312 .ret = 0,
0492d4c5 3313 };
cdd6c482 3314 smp_call_function_single(event->oncpu,
0492d4c5 3315 __perf_event_read, &data, 1);
7d88962e 3316 ret = data.ret;
cdd6c482 3317 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
2b8988c9
PZ
3318 struct perf_event_context *ctx = event->ctx;
3319 unsigned long flags;
3320
e625cce1 3321 raw_spin_lock_irqsave(&ctx->lock, flags);
c530ccd9
SE
3322 /*
3323 * may read while context is not active
3324 * (e.g., thread is blocked), in that case
3325 * we cannot update context time
3326 */
e5d1367f 3327 if (ctx->is_active) {
c530ccd9 3328 update_context_time(ctx);
e5d1367f
SE
3329 update_cgrp_time_from_event(event);
3330 }
0492d4c5
PZ
3331 if (group)
3332 update_group_times(event);
3333 else
3334 update_event_times(event);
e625cce1 3335 raw_spin_unlock_irqrestore(&ctx->lock, flags);
0793a61d 3336 }
7d88962e
SB
3337
3338 return ret;
0793a61d
TG
3339}
3340
a63eaf34 3341/*
cdd6c482 3342 * Initialize the perf_event context in a task_struct:
a63eaf34 3343 */
eb184479 3344static void __perf_event_init_context(struct perf_event_context *ctx)
a63eaf34 3345{
e625cce1 3346 raw_spin_lock_init(&ctx->lock);
a63eaf34 3347 mutex_init(&ctx->mutex);
2fde4f94 3348 INIT_LIST_HEAD(&ctx->active_ctx_list);
889ff015
FW
3349 INIT_LIST_HEAD(&ctx->pinned_groups);
3350 INIT_LIST_HEAD(&ctx->flexible_groups);
a63eaf34
PM
3351 INIT_LIST_HEAD(&ctx->event_list);
3352 atomic_set(&ctx->refcount, 1);
eb184479
PZ
3353}
3354
3355static struct perf_event_context *
3356alloc_perf_context(struct pmu *pmu, struct task_struct *task)
3357{
3358 struct perf_event_context *ctx;
3359
3360 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
3361 if (!ctx)
3362 return NULL;
3363
3364 __perf_event_init_context(ctx);
3365 if (task) {
3366 ctx->task = task;
3367 get_task_struct(task);
0793a61d 3368 }
eb184479
PZ
3369 ctx->pmu = pmu;
3370
3371 return ctx;
a63eaf34
PM
3372}
3373
2ebd4ffb
MH
3374static struct task_struct *
3375find_lively_task_by_vpid(pid_t vpid)
3376{
3377 struct task_struct *task;
3378 int err;
0793a61d
TG
3379
3380 rcu_read_lock();
2ebd4ffb 3381 if (!vpid)
0793a61d
TG
3382 task = current;
3383 else
2ebd4ffb 3384 task = find_task_by_vpid(vpid);
0793a61d
TG
3385 if (task)
3386 get_task_struct(task);
3387 rcu_read_unlock();
3388
3389 if (!task)
3390 return ERR_PTR(-ESRCH);
3391
0793a61d 3392 /* Reuse ptrace permission checks for now. */
c93f7669 3393 err = -EACCES;
caaee623 3394 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
c93f7669
PM
3395 goto errout;
3396
2ebd4ffb
MH
3397 return task;
3398errout:
3399 put_task_struct(task);
3400 return ERR_PTR(err);
3401
3402}
3403
fe4b04fa
PZ
3404/*
3405 * Returns a matching context with refcount and pincount.
3406 */
108b02cf 3407static struct perf_event_context *
4af57ef2
YZ
3408find_get_context(struct pmu *pmu, struct task_struct *task,
3409 struct perf_event *event)
0793a61d 3410{
211de6eb 3411 struct perf_event_context *ctx, *clone_ctx = NULL;
22a4f650 3412 struct perf_cpu_context *cpuctx;
4af57ef2 3413 void *task_ctx_data = NULL;
25346b93 3414 unsigned long flags;
8dc85d54 3415 int ctxn, err;
4af57ef2 3416 int cpu = event->cpu;
0793a61d 3417
22a4ec72 3418 if (!task) {
cdd6c482 3419 /* Must be root to operate on a CPU event: */
0764771d 3420 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
0793a61d
TG
3421 return ERR_PTR(-EACCES);
3422
0793a61d 3423 /*
cdd6c482 3424 * We could be clever and allow to attach a event to an
0793a61d
TG
3425 * offline CPU and activate it when the CPU comes up, but
3426 * that's for later.
3427 */
f6325e30 3428 if (!cpu_online(cpu))
0793a61d
TG
3429 return ERR_PTR(-ENODEV);
3430
108b02cf 3431 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
0793a61d 3432 ctx = &cpuctx->ctx;
c93f7669 3433 get_ctx(ctx);
fe4b04fa 3434 ++ctx->pin_count;
0793a61d 3435
0793a61d
TG
3436 return ctx;
3437 }
3438
8dc85d54
PZ
3439 err = -EINVAL;
3440 ctxn = pmu->task_ctx_nr;
3441 if (ctxn < 0)
3442 goto errout;
3443
4af57ef2
YZ
3444 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
3445 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
3446 if (!task_ctx_data) {
3447 err = -ENOMEM;
3448 goto errout;
3449 }
3450 }
3451
9ed6060d 3452retry:
8dc85d54 3453 ctx = perf_lock_task_context(task, ctxn, &flags);
c93f7669 3454 if (ctx) {
211de6eb 3455 clone_ctx = unclone_ctx(ctx);
fe4b04fa 3456 ++ctx->pin_count;
4af57ef2
YZ
3457
3458 if (task_ctx_data && !ctx->task_ctx_data) {
3459 ctx->task_ctx_data = task_ctx_data;
3460 task_ctx_data = NULL;
3461 }
e625cce1 3462 raw_spin_unlock_irqrestore(&ctx->lock, flags);
211de6eb
PZ
3463
3464 if (clone_ctx)
3465 put_ctx(clone_ctx);
9137fb28 3466 } else {
eb184479 3467 ctx = alloc_perf_context(pmu, task);
c93f7669
PM
3468 err = -ENOMEM;
3469 if (!ctx)
3470 goto errout;
eb184479 3471
4af57ef2
YZ
3472 if (task_ctx_data) {
3473 ctx->task_ctx_data = task_ctx_data;
3474 task_ctx_data = NULL;
3475 }
3476
dbe08d82
ON
3477 err = 0;
3478 mutex_lock(&task->perf_event_mutex);
3479 /*
3480 * If it has already passed perf_event_exit_task().
3481 * we must see PF_EXITING, it takes this mutex too.
3482 */
3483 if (task->flags & PF_EXITING)
3484 err = -ESRCH;
3485 else if (task->perf_event_ctxp[ctxn])
3486 err = -EAGAIN;
fe4b04fa 3487 else {
9137fb28 3488 get_ctx(ctx);
fe4b04fa 3489 ++ctx->pin_count;
dbe08d82 3490 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
fe4b04fa 3491 }
dbe08d82
ON
3492 mutex_unlock(&task->perf_event_mutex);
3493
3494 if (unlikely(err)) {
9137fb28 3495 put_ctx(ctx);
dbe08d82
ON
3496
3497 if (err == -EAGAIN)
3498 goto retry;
3499 goto errout;
a63eaf34
PM
3500 }
3501 }
3502
4af57ef2 3503 kfree(task_ctx_data);
0793a61d 3504 return ctx;
c93f7669 3505
9ed6060d 3506errout:
4af57ef2 3507 kfree(task_ctx_data);
c93f7669 3508 return ERR_PTR(err);
0793a61d
TG
3509}
3510
6fb2915d 3511static void perf_event_free_filter(struct perf_event *event);
2541517c 3512static void perf_event_free_bpf_prog(struct perf_event *event);
6fb2915d 3513
cdd6c482 3514static void free_event_rcu(struct rcu_head *head)
592903cd 3515{
cdd6c482 3516 struct perf_event *event;
592903cd 3517
cdd6c482
IM
3518 event = container_of(head, struct perf_event, rcu_head);
3519 if (event->ns)
3520 put_pid_ns(event->ns);
6fb2915d 3521 perf_event_free_filter(event);
cdd6c482 3522 kfree(event);
592903cd
PZ
3523}
3524
b69cf536
PZ
3525static void ring_buffer_attach(struct perf_event *event,
3526 struct ring_buffer *rb);
925d519a 3527
4beb31f3 3528static void unaccount_event_cpu(struct perf_event *event, int cpu)
f1600952 3529{
4beb31f3
FW
3530 if (event->parent)
3531 return;
3532
4beb31f3
FW
3533 if (is_cgroup_event(event))
3534 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
3535}
925d519a 3536
4beb31f3
FW
3537static void unaccount_event(struct perf_event *event)
3538{
25432ae9
PZ
3539 bool dec = false;
3540
4beb31f3
FW
3541 if (event->parent)
3542 return;
3543
3544 if (event->attach_state & PERF_ATTACH_TASK)
25432ae9 3545 dec = true;
4beb31f3
FW
3546 if (event->attr.mmap || event->attr.mmap_data)
3547 atomic_dec(&nr_mmap_events);
3548 if (event->attr.comm)
3549 atomic_dec(&nr_comm_events);
3550 if (event->attr.task)
3551 atomic_dec(&nr_task_events);
948b26b6
FW
3552 if (event->attr.freq)
3553 atomic_dec(&nr_freq_events);
45ac1403 3554 if (event->attr.context_switch) {
25432ae9 3555 dec = true;
45ac1403
AH
3556 atomic_dec(&nr_switch_events);
3557 }
4beb31f3 3558 if (is_cgroup_event(event))
25432ae9 3559 dec = true;
4beb31f3 3560 if (has_branch_stack(event))
25432ae9
PZ
3561 dec = true;
3562
9107c89e
PZ
3563 if (dec) {
3564 if (!atomic_add_unless(&perf_sched_count, -1, 1))
3565 schedule_delayed_work(&perf_sched_work, HZ);
3566 }
4beb31f3
FW
3567
3568 unaccount_event_cpu(event, event->cpu);
3569}
925d519a 3570
9107c89e
PZ
3571static void perf_sched_delayed(struct work_struct *work)
3572{
3573 mutex_lock(&perf_sched_mutex);
3574 if (atomic_dec_and_test(&perf_sched_count))
3575 static_branch_disable(&perf_sched_events);
3576 mutex_unlock(&perf_sched_mutex);
3577}
3578
bed5b25a
AS
3579/*
3580 * The following implement mutual exclusion of events on "exclusive" pmus
3581 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
3582 * at a time, so we disallow creating events that might conflict, namely:
3583 *
3584 * 1) cpu-wide events in the presence of per-task events,
3585 * 2) per-task events in the presence of cpu-wide events,
3586 * 3) two matching events on the same context.
3587 *
3588 * The former two cases are handled in the allocation path (perf_event_alloc(),
a0733e69 3589 * _free_event()), the latter -- before the first perf_install_in_context().
bed5b25a
AS
3590 */
3591static int exclusive_event_init(struct perf_event *event)
3592{
3593 struct pmu *pmu = event->pmu;
3594
3595 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3596 return 0;
3597
3598 /*
3599 * Prevent co-existence of per-task and cpu-wide events on the
3600 * same exclusive pmu.
3601 *
3602 * Negative pmu::exclusive_cnt means there are cpu-wide
3603 * events on this "exclusive" pmu, positive means there are
3604 * per-task events.
3605 *
3606 * Since this is called in perf_event_alloc() path, event::ctx
3607 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
3608 * to mean "per-task event", because unlike other attach states it
3609 * never gets cleared.
3610 */
3611 if (event->attach_state & PERF_ATTACH_TASK) {
3612 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
3613 return -EBUSY;
3614 } else {
3615 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
3616 return -EBUSY;
3617 }
3618
3619 return 0;
3620}
3621
3622static void exclusive_event_destroy(struct perf_event *event)
3623{
3624 struct pmu *pmu = event->pmu;
3625
3626 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3627 return;
3628
3629 /* see comment in exclusive_event_init() */
3630 if (event->attach_state & PERF_ATTACH_TASK)
3631 atomic_dec(&pmu->exclusive_cnt);
3632 else
3633 atomic_inc(&pmu->exclusive_cnt);
3634}
3635
3636static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
3637{
3638 if ((e1->pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) &&
3639 (e1->cpu == e2->cpu ||
3640 e1->cpu == -1 ||
3641 e2->cpu == -1))
3642 return true;
3643 return false;
3644}
3645
3646/* Called under the same ctx::mutex as perf_install_in_context() */
3647static bool exclusive_event_installable(struct perf_event *event,
3648 struct perf_event_context *ctx)
3649{
3650 struct perf_event *iter_event;
3651 struct pmu *pmu = event->pmu;
3652
3653 if (!(pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE))
3654 return true;
3655
3656 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
3657 if (exclusive_event_match(iter_event, event))
3658 return false;
3659 }
3660
3661 return true;
3662}
3663
683ede43 3664static void _free_event(struct perf_event *event)
f1600952 3665{
e360adbe 3666 irq_work_sync(&event->pending);
925d519a 3667
4beb31f3 3668 unaccount_event(event);
9ee318a7 3669
76369139 3670 if (event->rb) {
9bb5d40c
PZ
3671 /*
3672 * Can happen when we close an event with re-directed output.
3673 *
3674 * Since we have a 0 refcount, perf_mmap_close() will skip
3675 * over us; possibly making our ring_buffer_put() the last.
3676 */
3677 mutex_lock(&event->mmap_mutex);
b69cf536 3678 ring_buffer_attach(event, NULL);
9bb5d40c 3679 mutex_unlock(&event->mmap_mutex);
a4be7c27
PZ
3680 }
3681
e5d1367f
SE
3682 if (is_cgroup_event(event))
3683 perf_detach_cgroup(event);
3684
a0733e69
PZ
3685 if (!event->parent) {
3686 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
3687 put_callchain_buffers();
3688 }
3689
3690 perf_event_free_bpf_prog(event);
3691
3692 if (event->destroy)
3693 event->destroy(event);
3694
3695 if (event->ctx)
3696 put_ctx(event->ctx);
3697
3698 if (event->pmu) {
3699 exclusive_event_destroy(event);
3700 module_put(event->pmu->module);
3701 }
3702
3703 call_rcu(&event->rcu_head, free_event_rcu);
f1600952
PZ
3704}
3705
683ede43
PZ
3706/*
3707 * Used to free events which have a known refcount of 1, such as in error paths
3708 * where the event isn't exposed yet and inherited events.
3709 */
3710static void free_event(struct perf_event *event)
0793a61d 3711{
683ede43
PZ
3712 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
3713 "unexpected event refcount: %ld; ptr=%p\n",
3714 atomic_long_read(&event->refcount), event)) {
3715 /* leak to avoid use-after-free */
3716 return;
3717 }
0793a61d 3718
683ede43 3719 _free_event(event);
0793a61d
TG
3720}
3721
a66a3052 3722/*
f8697762 3723 * Remove user event from the owner task.
a66a3052 3724 */
f8697762 3725static void perf_remove_from_owner(struct perf_event *event)
fb0459d7 3726{
8882135b 3727 struct task_struct *owner;
fb0459d7 3728
8882135b 3729 rcu_read_lock();
8882135b 3730 /*
f47c02c0
PZ
3731 * Matches the smp_store_release() in perf_event_exit_task(). If we
3732 * observe !owner it means the list deletion is complete and we can
3733 * indeed free this event, otherwise we need to serialize on
8882135b
PZ
3734 * owner->perf_event_mutex.
3735 */
f47c02c0 3736 owner = lockless_dereference(event->owner);
8882135b
PZ
3737 if (owner) {
3738 /*
3739 * Since delayed_put_task_struct() also drops the last
3740 * task reference we can safely take a new reference
3741 * while holding the rcu_read_lock().
3742 */
3743 get_task_struct(owner);
3744 }
3745 rcu_read_unlock();
3746
3747 if (owner) {
f63a8daa
PZ
3748 /*
3749 * If we're here through perf_event_exit_task() we're already
3750 * holding ctx->mutex which would be an inversion wrt. the
3751 * normal lock order.
3752 *
3753 * However we can safely take this lock because its the child
3754 * ctx->mutex.
3755 */
3756 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
3757
8882135b
PZ
3758 /*
3759 * We have to re-check the event->owner field, if it is cleared
3760 * we raced with perf_event_exit_task(), acquiring the mutex
3761 * ensured they're done, and we can proceed with freeing the
3762 * event.
3763 */
f47c02c0 3764 if (event->owner) {
8882135b 3765 list_del_init(&event->owner_entry);
f47c02c0
PZ
3766 smp_store_release(&event->owner, NULL);
3767 }
8882135b
PZ
3768 mutex_unlock(&owner->perf_event_mutex);
3769 put_task_struct(owner);
3770 }
f8697762
JO
3771}
3772
f8697762
JO
3773static void put_event(struct perf_event *event)
3774{
f8697762
JO
3775 if (!atomic_long_dec_and_test(&event->refcount))
3776 return;
3777
c6e5b732
PZ
3778 _free_event(event);
3779}
3780
3781/*
3782 * Kill an event dead; while event:refcount will preserve the event
3783 * object, it will not preserve its functionality. Once the last 'user'
3784 * gives up the object, we'll destroy the thing.
3785 */
3786int perf_event_release_kernel(struct perf_event *event)
3787{
a4f4bb6d 3788 struct perf_event_context *ctx = event->ctx;
c6e5b732
PZ
3789 struct perf_event *child, *tmp;
3790
a4f4bb6d
PZ
3791 /*
3792 * If we got here through err_file: fput(event_file); we will not have
3793 * attached to a context yet.
3794 */
3795 if (!ctx) {
3796 WARN_ON_ONCE(event->attach_state &
3797 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
3798 goto no_ctx;
3799 }
3800
f8697762
JO
3801 if (!is_kernel_event(event))
3802 perf_remove_from_owner(event);
8882135b 3803
5fa7c8ec 3804 ctx = perf_event_ctx_lock(event);
a83fe28e 3805 WARN_ON_ONCE(ctx->parent_ctx);
a69b0ca4 3806 perf_remove_from_context(event, DETACH_GROUP);
683ede43 3807
a69b0ca4 3808 raw_spin_lock_irq(&ctx->lock);
683ede43 3809 /*
a69b0ca4
PZ
3810 * Mark this even as STATE_DEAD, there is no external reference to it
3811 * anymore.
683ede43 3812 *
a69b0ca4
PZ
3813 * Anybody acquiring event->child_mutex after the below loop _must_
3814 * also see this, most importantly inherit_event() which will avoid
3815 * placing more children on the list.
683ede43 3816 *
c6e5b732
PZ
3817 * Thus this guarantees that we will in fact observe and kill _ALL_
3818 * child events.
683ede43 3819 */
a69b0ca4
PZ
3820 event->state = PERF_EVENT_STATE_DEAD;
3821 raw_spin_unlock_irq(&ctx->lock);
3822
3823 perf_event_ctx_unlock(event, ctx);
683ede43 3824
c6e5b732
PZ
3825again:
3826 mutex_lock(&event->child_mutex);
3827 list_for_each_entry(child, &event->child_list, child_list) {
a6fa941d 3828
c6e5b732
PZ
3829 /*
3830 * Cannot change, child events are not migrated, see the
3831 * comment with perf_event_ctx_lock_nested().
3832 */
3833 ctx = lockless_dereference(child->ctx);
3834 /*
3835 * Since child_mutex nests inside ctx::mutex, we must jump
3836 * through hoops. We start by grabbing a reference on the ctx.
3837 *
3838 * Since the event cannot get freed while we hold the
3839 * child_mutex, the context must also exist and have a !0
3840 * reference count.
3841 */
3842 get_ctx(ctx);
3843
3844 /*
3845 * Now that we have a ctx ref, we can drop child_mutex, and
3846 * acquire ctx::mutex without fear of it going away. Then we
3847 * can re-acquire child_mutex.
3848 */
3849 mutex_unlock(&event->child_mutex);
3850 mutex_lock(&ctx->mutex);
3851 mutex_lock(&event->child_mutex);
3852
3853 /*
3854 * Now that we hold ctx::mutex and child_mutex, revalidate our
3855 * state, if child is still the first entry, it didn't get freed
3856 * and we can continue doing so.
3857 */
3858 tmp = list_first_entry_or_null(&event->child_list,
3859 struct perf_event, child_list);
3860 if (tmp == child) {
3861 perf_remove_from_context(child, DETACH_GROUP);
3862 list_del(&child->child_list);
3863 free_event(child);
3864 /*
3865 * This matches the refcount bump in inherit_event();
3866 * this can't be the last reference.
3867 */
3868 put_event(event);
3869 }
3870
3871 mutex_unlock(&event->child_mutex);
3872 mutex_unlock(&ctx->mutex);
3873 put_ctx(ctx);
3874 goto again;
3875 }
3876 mutex_unlock(&event->child_mutex);
3877
a4f4bb6d
PZ
3878no_ctx:
3879 put_event(event); /* Must be the 'last' reference */
683ede43
PZ
3880 return 0;
3881}
3882EXPORT_SYMBOL_GPL(perf_event_release_kernel);
3883
8b10c5e2
PZ
3884/*
3885 * Called when the last reference to the file is gone.
3886 */
a6fa941d
AV
3887static int perf_release(struct inode *inode, struct file *file)
3888{
c6e5b732 3889 perf_event_release_kernel(file->private_data);
a6fa941d 3890 return 0;
fb0459d7 3891}
fb0459d7 3892
59ed446f 3893u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
e53c0994 3894{
cdd6c482 3895 struct perf_event *child;
e53c0994
PZ
3896 u64 total = 0;
3897
59ed446f
PZ
3898 *enabled = 0;
3899 *running = 0;
3900
6f10581a 3901 mutex_lock(&event->child_mutex);
01add3ea 3902
7d88962e 3903 (void)perf_event_read(event, false);
01add3ea
SB
3904 total += perf_event_count(event);
3905
59ed446f
PZ
3906 *enabled += event->total_time_enabled +
3907 atomic64_read(&event->child_total_time_enabled);
3908 *running += event->total_time_running +
3909 atomic64_read(&event->child_total_time_running);
3910
3911 list_for_each_entry(child, &event->child_list, child_list) {
7d88962e 3912 (void)perf_event_read(child, false);
01add3ea 3913 total += perf_event_count(child);
59ed446f
PZ
3914 *enabled += child->total_time_enabled;
3915 *running += child->total_time_running;
3916 }
6f10581a 3917 mutex_unlock(&event->child_mutex);
e53c0994
PZ
3918
3919 return total;
3920}
fb0459d7 3921EXPORT_SYMBOL_GPL(perf_event_read_value);
e53c0994 3922
7d88962e 3923static int __perf_read_group_add(struct perf_event *leader,
fa8c2693 3924 u64 read_format, u64 *values)
3dab77fb 3925{
fa8c2693
PZ
3926 struct perf_event *sub;
3927 int n = 1; /* skip @nr */
7d88962e 3928 int ret;
f63a8daa 3929
7d88962e
SB
3930 ret = perf_event_read(leader, true);
3931 if (ret)
3932 return ret;
abf4868b 3933
fa8c2693
PZ
3934 /*
3935 * Since we co-schedule groups, {enabled,running} times of siblings
3936 * will be identical to those of the leader, so we only publish one
3937 * set.
3938 */
3939 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3940 values[n++] += leader->total_time_enabled +
3941 atomic64_read(&leader->child_total_time_enabled);
3942 }
3dab77fb 3943
fa8c2693
PZ
3944 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3945 values[n++] += leader->total_time_running +
3946 atomic64_read(&leader->child_total_time_running);
3947 }
3948
3949 /*
3950 * Write {count,id} tuples for every sibling.
3951 */
3952 values[n++] += perf_event_count(leader);
abf4868b
PZ
3953 if (read_format & PERF_FORMAT_ID)
3954 values[n++] = primary_event_id(leader);
3dab77fb 3955
fa8c2693
PZ
3956 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3957 values[n++] += perf_event_count(sub);
3958 if (read_format & PERF_FORMAT_ID)
3959 values[n++] = primary_event_id(sub);
3960 }
7d88962e
SB
3961
3962 return 0;
fa8c2693 3963}
3dab77fb 3964
fa8c2693
PZ
3965static int perf_read_group(struct perf_event *event,
3966 u64 read_format, char __user *buf)
3967{
3968 struct perf_event *leader = event->group_leader, *child;
3969 struct perf_event_context *ctx = leader->ctx;
7d88962e 3970 int ret;
fa8c2693 3971 u64 *values;
3dab77fb 3972
fa8c2693 3973 lockdep_assert_held(&ctx->mutex);
3dab77fb 3974
fa8c2693
PZ
3975 values = kzalloc(event->read_size, GFP_KERNEL);
3976 if (!values)
3977 return -ENOMEM;
3dab77fb 3978
fa8c2693
PZ
3979 values[0] = 1 + leader->nr_siblings;
3980
3981 /*
3982 * By locking the child_mutex of the leader we effectively
3983 * lock the child list of all siblings.. XXX explain how.
3984 */
3985 mutex_lock(&leader->child_mutex);
abf4868b 3986
7d88962e
SB
3987 ret = __perf_read_group_add(leader, read_format, values);
3988 if (ret)
3989 goto unlock;
3990
3991 list_for_each_entry(child, &leader->child_list, child_list) {
3992 ret = __perf_read_group_add(child, read_format, values);
3993 if (ret)
3994 goto unlock;
3995 }
abf4868b 3996
fa8c2693 3997 mutex_unlock(&leader->child_mutex);
abf4868b 3998
7d88962e 3999 ret = event->read_size;
fa8c2693
PZ
4000 if (copy_to_user(buf, values, event->read_size))
4001 ret = -EFAULT;
7d88962e 4002 goto out;
fa8c2693 4003
7d88962e
SB
4004unlock:
4005 mutex_unlock(&leader->child_mutex);
4006out:
fa8c2693 4007 kfree(values);
abf4868b 4008 return ret;
3dab77fb
PZ
4009}
4010
b15f495b 4011static int perf_read_one(struct perf_event *event,
3dab77fb
PZ
4012 u64 read_format, char __user *buf)
4013{
59ed446f 4014 u64 enabled, running;
3dab77fb
PZ
4015 u64 values[4];
4016 int n = 0;
4017
59ed446f
PZ
4018 values[n++] = perf_event_read_value(event, &enabled, &running);
4019 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4020 values[n++] = enabled;
4021 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
4022 values[n++] = running;
3dab77fb 4023 if (read_format & PERF_FORMAT_ID)
cdd6c482 4024 values[n++] = primary_event_id(event);
3dab77fb
PZ
4025
4026 if (copy_to_user(buf, values, n * sizeof(u64)))
4027 return -EFAULT;
4028
4029 return n * sizeof(u64);
4030}
4031
dc633982
JO
4032static bool is_event_hup(struct perf_event *event)
4033{
4034 bool no_children;
4035
a69b0ca4 4036 if (event->state > PERF_EVENT_STATE_EXIT)
dc633982
JO
4037 return false;
4038
4039 mutex_lock(&event->child_mutex);
4040 no_children = list_empty(&event->child_list);
4041 mutex_unlock(&event->child_mutex);
4042 return no_children;
4043}
4044
0793a61d 4045/*
cdd6c482 4046 * Read the performance event - simple non blocking version for now
0793a61d
TG
4047 */
4048static ssize_t
b15f495b 4049__perf_read(struct perf_event *event, char __user *buf, size_t count)
0793a61d 4050{
cdd6c482 4051 u64 read_format = event->attr.read_format;
3dab77fb 4052 int ret;
0793a61d 4053
3b6f9e5c 4054 /*
cdd6c482 4055 * Return end-of-file for a read on a event that is in
3b6f9e5c
PM
4056 * error state (i.e. because it was pinned but it couldn't be
4057 * scheduled on to the CPU at some point).
4058 */
cdd6c482 4059 if (event->state == PERF_EVENT_STATE_ERROR)
3b6f9e5c
PM
4060 return 0;
4061
c320c7b7 4062 if (count < event->read_size)
3dab77fb
PZ
4063 return -ENOSPC;
4064
cdd6c482 4065 WARN_ON_ONCE(event->ctx->parent_ctx);
3dab77fb 4066 if (read_format & PERF_FORMAT_GROUP)
b15f495b 4067 ret = perf_read_group(event, read_format, buf);
3dab77fb 4068 else
b15f495b 4069 ret = perf_read_one(event, read_format, buf);
0793a61d 4070
3dab77fb 4071 return ret;
0793a61d
TG
4072}
4073
0793a61d
TG
4074static ssize_t
4075perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
4076{
cdd6c482 4077 struct perf_event *event = file->private_data;
f63a8daa
PZ
4078 struct perf_event_context *ctx;
4079 int ret;
0793a61d 4080
f63a8daa 4081 ctx = perf_event_ctx_lock(event);
b15f495b 4082 ret = __perf_read(event, buf, count);
f63a8daa
PZ
4083 perf_event_ctx_unlock(event, ctx);
4084
4085 return ret;
0793a61d
TG
4086}
4087
4088static unsigned int perf_poll(struct file *file, poll_table *wait)
4089{
cdd6c482 4090 struct perf_event *event = file->private_data;
76369139 4091 struct ring_buffer *rb;
61b67684 4092 unsigned int events = POLLHUP;
c7138f37 4093
e708d7ad 4094 poll_wait(file, &event->waitq, wait);
179033b3 4095
dc633982 4096 if (is_event_hup(event))
179033b3 4097 return events;
c7138f37 4098
10c6db11 4099 /*
9bb5d40c
PZ
4100 * Pin the event->rb by taking event->mmap_mutex; otherwise
4101 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
10c6db11
PZ
4102 */
4103 mutex_lock(&event->mmap_mutex);
9bb5d40c
PZ
4104 rb = event->rb;
4105 if (rb)
76369139 4106 events = atomic_xchg(&rb->poll, 0);
10c6db11 4107 mutex_unlock(&event->mmap_mutex);
0793a61d
TG
4108 return events;
4109}
4110
f63a8daa 4111static void _perf_event_reset(struct perf_event *event)
6de6a7b9 4112{
7d88962e 4113 (void)perf_event_read(event, false);
e7850595 4114 local64_set(&event->count, 0);
cdd6c482 4115 perf_event_update_userpage(event);
3df5edad
PZ
4116}
4117
c93f7669 4118/*
cdd6c482
IM
4119 * Holding the top-level event's child_mutex means that any
4120 * descendant process that has inherited this event will block
8ba289b8 4121 * in perf_event_exit_event() if it goes to exit, thus satisfying the
cdd6c482 4122 * task existence requirements of perf_event_enable/disable.
c93f7669 4123 */
cdd6c482
IM
4124static void perf_event_for_each_child(struct perf_event *event,
4125 void (*func)(struct perf_event *))
3df5edad 4126{
cdd6c482 4127 struct perf_event *child;
3df5edad 4128
cdd6c482 4129 WARN_ON_ONCE(event->ctx->parent_ctx);
f63a8daa 4130
cdd6c482
IM
4131 mutex_lock(&event->child_mutex);
4132 func(event);
4133 list_for_each_entry(child, &event->child_list, child_list)
3df5edad 4134 func(child);
cdd6c482 4135 mutex_unlock(&event->child_mutex);
3df5edad
PZ
4136}
4137
cdd6c482
IM
4138static void perf_event_for_each(struct perf_event *event,
4139 void (*func)(struct perf_event *))
3df5edad 4140{
cdd6c482
IM
4141 struct perf_event_context *ctx = event->ctx;
4142 struct perf_event *sibling;
3df5edad 4143
f63a8daa
PZ
4144 lockdep_assert_held(&ctx->mutex);
4145
cdd6c482 4146 event = event->group_leader;
75f937f2 4147
cdd6c482 4148 perf_event_for_each_child(event, func);
cdd6c482 4149 list_for_each_entry(sibling, &event->sibling_list, group_entry)
724b6daa 4150 perf_event_for_each_child(sibling, func);
6de6a7b9
PZ
4151}
4152
fae3fde6
PZ
4153static void __perf_event_period(struct perf_event *event,
4154 struct perf_cpu_context *cpuctx,
4155 struct perf_event_context *ctx,
4156 void *info)
c7999c6f 4157{
fae3fde6 4158 u64 value = *((u64 *)info);
c7999c6f 4159 bool active;
08247e31 4160
cdd6c482 4161 if (event->attr.freq) {
cdd6c482 4162 event->attr.sample_freq = value;
08247e31 4163 } else {
cdd6c482
IM
4164 event->attr.sample_period = value;
4165 event->hw.sample_period = value;
08247e31 4166 }
bad7192b
PZ
4167
4168 active = (event->state == PERF_EVENT_STATE_ACTIVE);
4169 if (active) {
4170 perf_pmu_disable(ctx->pmu);
4171 event->pmu->stop(event, PERF_EF_UPDATE);
4172 }
4173
4174 local64_set(&event->hw.period_left, 0);
4175
4176 if (active) {
4177 event->pmu->start(event, PERF_EF_RELOAD);
4178 perf_pmu_enable(ctx->pmu);
4179 }
c7999c6f
PZ
4180}
4181
4182static int perf_event_period(struct perf_event *event, u64 __user *arg)
4183{
c7999c6f
PZ
4184 u64 value;
4185
4186 if (!is_sampling_event(event))
4187 return -EINVAL;
4188
4189 if (copy_from_user(&value, arg, sizeof(value)))
4190 return -EFAULT;
4191
4192 if (!value)
4193 return -EINVAL;
4194
4195 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
4196 return -EINVAL;
4197
fae3fde6 4198 event_function_call(event, __perf_event_period, &value);
08247e31 4199
c7999c6f 4200 return 0;
08247e31
PZ
4201}
4202
ac9721f3
PZ
4203static const struct file_operations perf_fops;
4204
2903ff01 4205static inline int perf_fget_light(int fd, struct fd *p)
ac9721f3 4206{
2903ff01
AV
4207 struct fd f = fdget(fd);
4208 if (!f.file)
4209 return -EBADF;
ac9721f3 4210
2903ff01
AV
4211 if (f.file->f_op != &perf_fops) {
4212 fdput(f);
4213 return -EBADF;
ac9721f3 4214 }
2903ff01
AV
4215 *p = f;
4216 return 0;
ac9721f3
PZ
4217}
4218
4219static int perf_event_set_output(struct perf_event *event,
4220 struct perf_event *output_event);
6fb2915d 4221static int perf_event_set_filter(struct perf_event *event, void __user *arg);
2541517c 4222static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
a4be7c27 4223
f63a8daa 4224static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
d859e29f 4225{
cdd6c482 4226 void (*func)(struct perf_event *);
3df5edad 4227 u32 flags = arg;
d859e29f
PM
4228
4229 switch (cmd) {
cdd6c482 4230 case PERF_EVENT_IOC_ENABLE:
f63a8daa 4231 func = _perf_event_enable;
d859e29f 4232 break;
cdd6c482 4233 case PERF_EVENT_IOC_DISABLE:
f63a8daa 4234 func = _perf_event_disable;
79f14641 4235 break;
cdd6c482 4236 case PERF_EVENT_IOC_RESET:
f63a8daa 4237 func = _perf_event_reset;
6de6a7b9 4238 break;
3df5edad 4239
cdd6c482 4240 case PERF_EVENT_IOC_REFRESH:
f63a8daa 4241 return _perf_event_refresh(event, arg);
08247e31 4242
cdd6c482
IM
4243 case PERF_EVENT_IOC_PERIOD:
4244 return perf_event_period(event, (u64 __user *)arg);
08247e31 4245
cf4957f1
JO
4246 case PERF_EVENT_IOC_ID:
4247 {
4248 u64 id = primary_event_id(event);
4249
4250 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
4251 return -EFAULT;
4252 return 0;
4253 }
4254
cdd6c482 4255 case PERF_EVENT_IOC_SET_OUTPUT:
ac9721f3 4256 {
ac9721f3 4257 int ret;
ac9721f3 4258 if (arg != -1) {
2903ff01
AV
4259 struct perf_event *output_event;
4260 struct fd output;
4261 ret = perf_fget_light(arg, &output);
4262 if (ret)
4263 return ret;
4264 output_event = output.file->private_data;
4265 ret = perf_event_set_output(event, output_event);
4266 fdput(output);
4267 } else {
4268 ret = perf_event_set_output(event, NULL);
ac9721f3 4269 }
ac9721f3
PZ
4270 return ret;
4271 }
a4be7c27 4272
6fb2915d
LZ
4273 case PERF_EVENT_IOC_SET_FILTER:
4274 return perf_event_set_filter(event, (void __user *)arg);
4275
2541517c
AS
4276 case PERF_EVENT_IOC_SET_BPF:
4277 return perf_event_set_bpf_prog(event, arg);
4278
d859e29f 4279 default:
3df5edad 4280 return -ENOTTY;
d859e29f 4281 }
3df5edad
PZ
4282
4283 if (flags & PERF_IOC_FLAG_GROUP)
cdd6c482 4284 perf_event_for_each(event, func);
3df5edad 4285 else
cdd6c482 4286 perf_event_for_each_child(event, func);
3df5edad
PZ
4287
4288 return 0;
d859e29f
PM
4289}
4290
f63a8daa
PZ
4291static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
4292{
4293 struct perf_event *event = file->private_data;
4294 struct perf_event_context *ctx;
4295 long ret;
4296
4297 ctx = perf_event_ctx_lock(event);
4298 ret = _perf_ioctl(event, cmd, arg);
4299 perf_event_ctx_unlock(event, ctx);
4300
4301 return ret;
4302}
4303
b3f20785
PM
4304#ifdef CONFIG_COMPAT
4305static long perf_compat_ioctl(struct file *file, unsigned int cmd,
4306 unsigned long arg)
4307{
4308 switch (_IOC_NR(cmd)) {
4309 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
4310 case _IOC_NR(PERF_EVENT_IOC_ID):
4311 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
4312 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
4313 cmd &= ~IOCSIZE_MASK;
4314 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
4315 }
4316 break;
4317 }
4318 return perf_ioctl(file, cmd, arg);
4319}
4320#else
4321# define perf_compat_ioctl NULL
4322#endif
4323
cdd6c482 4324int perf_event_task_enable(void)
771d7cde 4325{
f63a8daa 4326 struct perf_event_context *ctx;
cdd6c482 4327 struct perf_event *event;
771d7cde 4328
cdd6c482 4329 mutex_lock(&current->perf_event_mutex);
f63a8daa
PZ
4330 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4331 ctx = perf_event_ctx_lock(event);
4332 perf_event_for_each_child(event, _perf_event_enable);
4333 perf_event_ctx_unlock(event, ctx);
4334 }
cdd6c482 4335 mutex_unlock(&current->perf_event_mutex);
771d7cde
PZ
4336
4337 return 0;
4338}
4339
cdd6c482 4340int perf_event_task_disable(void)
771d7cde 4341{
f63a8daa 4342 struct perf_event_context *ctx;
cdd6c482 4343 struct perf_event *event;
771d7cde 4344
cdd6c482 4345 mutex_lock(&current->perf_event_mutex);
f63a8daa
PZ
4346 list_for_each_entry(event, &current->perf_event_list, owner_entry) {
4347 ctx = perf_event_ctx_lock(event);
4348 perf_event_for_each_child(event, _perf_event_disable);
4349 perf_event_ctx_unlock(event, ctx);
4350 }
cdd6c482 4351 mutex_unlock(&current->perf_event_mutex);
771d7cde
PZ
4352
4353 return 0;
4354}
4355
cdd6c482 4356static int perf_event_index(struct perf_event *event)
194002b2 4357{
a4eaf7f1
PZ
4358 if (event->hw.state & PERF_HES_STOPPED)
4359 return 0;
4360
cdd6c482 4361 if (event->state != PERF_EVENT_STATE_ACTIVE)
194002b2
PZ
4362 return 0;
4363
35edc2a5 4364 return event->pmu->event_idx(event);
194002b2
PZ
4365}
4366
c4794295 4367static void calc_timer_values(struct perf_event *event,
e3f3541c 4368 u64 *now,
7f310a5d
EM
4369 u64 *enabled,
4370 u64 *running)
c4794295 4371{
e3f3541c 4372 u64 ctx_time;
c4794295 4373
e3f3541c
PZ
4374 *now = perf_clock();
4375 ctx_time = event->shadow_ctx_time + *now;
c4794295
EM
4376 *enabled = ctx_time - event->tstamp_enabled;
4377 *running = ctx_time - event->tstamp_running;
4378}
4379
fa731587
PZ
4380static void perf_event_init_userpage(struct perf_event *event)
4381{
4382 struct perf_event_mmap_page *userpg;
4383 struct ring_buffer *rb;
4384
4385 rcu_read_lock();
4386 rb = rcu_dereference(event->rb);
4387 if (!rb)
4388 goto unlock;
4389
4390 userpg = rb->user_page;
4391
4392 /* Allow new userspace to detect that bit 0 is deprecated */
4393 userpg->cap_bit0_is_deprecated = 1;
4394 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
e8c6deac
AS
4395 userpg->data_offset = PAGE_SIZE;
4396 userpg->data_size = perf_data_size(rb);
fa731587
PZ
4397
4398unlock:
4399 rcu_read_unlock();
4400}
4401
c1317ec2
AL
4402void __weak arch_perf_update_userpage(
4403 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
e3f3541c
PZ
4404{
4405}
4406
38ff667b
PZ
4407/*
4408 * Callers need to ensure there can be no nesting of this function, otherwise
4409 * the seqlock logic goes bad. We can not serialize this because the arch
4410 * code calls this from NMI context.
4411 */
cdd6c482 4412void perf_event_update_userpage(struct perf_event *event)
37d81828 4413{
cdd6c482 4414 struct perf_event_mmap_page *userpg;
76369139 4415 struct ring_buffer *rb;
e3f3541c 4416 u64 enabled, running, now;
38ff667b
PZ
4417
4418 rcu_read_lock();
5ec4c599
PZ
4419 rb = rcu_dereference(event->rb);
4420 if (!rb)
4421 goto unlock;
4422
0d641208
EM
4423 /*
4424 * compute total_time_enabled, total_time_running
4425 * based on snapshot values taken when the event
4426 * was last scheduled in.
4427 *
4428 * we cannot simply called update_context_time()
4429 * because of locking issue as we can be called in
4430 * NMI context
4431 */
e3f3541c 4432 calc_timer_values(event, &now, &enabled, &running);
38ff667b 4433
76369139 4434 userpg = rb->user_page;
7b732a75
PZ
4435 /*
4436 * Disable preemption so as to not let the corresponding user-space
4437 * spin too long if we get preempted.
4438 */
4439 preempt_disable();
37d81828 4440 ++userpg->lock;
92f22a38 4441 barrier();
cdd6c482 4442 userpg->index = perf_event_index(event);
b5e58793 4443 userpg->offset = perf_event_count(event);
365a4038 4444 if (userpg->index)
e7850595 4445 userpg->offset -= local64_read(&event->hw.prev_count);
7b732a75 4446
0d641208 4447 userpg->time_enabled = enabled +
cdd6c482 4448 atomic64_read(&event->child_total_time_enabled);
7f8b4e4e 4449
0d641208 4450 userpg->time_running = running +
cdd6c482 4451 atomic64_read(&event->child_total_time_running);
7f8b4e4e 4452
c1317ec2 4453 arch_perf_update_userpage(event, userpg, now);
e3f3541c 4454
92f22a38 4455 barrier();
37d81828 4456 ++userpg->lock;
7b732a75 4457 preempt_enable();
38ff667b 4458unlock:
7b732a75 4459 rcu_read_unlock();
37d81828
PM
4460}
4461
906010b2
PZ
4462static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
4463{
4464 struct perf_event *event = vma->vm_file->private_data;
76369139 4465 struct ring_buffer *rb;
906010b2
PZ
4466 int ret = VM_FAULT_SIGBUS;
4467
4468 if (vmf->flags & FAULT_FLAG_MKWRITE) {
4469 if (vmf->pgoff == 0)
4470 ret = 0;
4471 return ret;
4472 }
4473
4474 rcu_read_lock();
76369139
FW
4475 rb = rcu_dereference(event->rb);
4476 if (!rb)
906010b2
PZ
4477 goto unlock;
4478
4479 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
4480 goto unlock;
4481
76369139 4482 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
906010b2
PZ
4483 if (!vmf->page)
4484 goto unlock;
4485
4486 get_page(vmf->page);
4487 vmf->page->mapping = vma->vm_file->f_mapping;
4488 vmf->page->index = vmf->pgoff;
4489
4490 ret = 0;
4491unlock:
4492 rcu_read_unlock();
4493
4494 return ret;
4495}
4496
10c6db11
PZ
4497static void ring_buffer_attach(struct perf_event *event,
4498 struct ring_buffer *rb)
4499{
b69cf536 4500 struct ring_buffer *old_rb = NULL;
10c6db11
PZ
4501 unsigned long flags;
4502
b69cf536
PZ
4503 if (event->rb) {
4504 /*
4505 * Should be impossible, we set this when removing
4506 * event->rb_entry and wait/clear when adding event->rb_entry.
4507 */
4508 WARN_ON_ONCE(event->rcu_pending);
10c6db11 4509
b69cf536 4510 old_rb = event->rb;
b69cf536
PZ
4511 spin_lock_irqsave(&old_rb->event_lock, flags);
4512 list_del_rcu(&event->rb_entry);
4513 spin_unlock_irqrestore(&old_rb->event_lock, flags);
10c6db11 4514
2f993cf0
ON
4515 event->rcu_batches = get_state_synchronize_rcu();
4516 event->rcu_pending = 1;
b69cf536 4517 }
10c6db11 4518
b69cf536 4519 if (rb) {
2f993cf0
ON
4520 if (event->rcu_pending) {
4521 cond_synchronize_rcu(event->rcu_batches);
4522 event->rcu_pending = 0;
4523 }
4524
b69cf536
PZ
4525 spin_lock_irqsave(&rb->event_lock, flags);
4526 list_add_rcu(&event->rb_entry, &rb->event_list);
4527 spin_unlock_irqrestore(&rb->event_lock, flags);
4528 }
4529
4530 rcu_assign_pointer(event->rb, rb);
4531
4532 if (old_rb) {
4533 ring_buffer_put(old_rb);
4534 /*
4535 * Since we detached before setting the new rb, so that we
4536 * could attach the new rb, we could have missed a wakeup.
4537 * Provide it now.
4538 */
4539 wake_up_all(&event->waitq);
4540 }
10c6db11
PZ
4541}
4542
4543static void ring_buffer_wakeup(struct perf_event *event)
4544{
4545 struct ring_buffer *rb;
4546
4547 rcu_read_lock();
4548 rb = rcu_dereference(event->rb);
9bb5d40c
PZ
4549 if (rb) {
4550 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
4551 wake_up_all(&event->waitq);
4552 }
10c6db11
PZ
4553 rcu_read_unlock();
4554}
4555
fdc26706 4556struct ring_buffer *ring_buffer_get(struct perf_event *event)
7b732a75 4557{
76369139 4558 struct ring_buffer *rb;
7b732a75 4559
ac9721f3 4560 rcu_read_lock();
76369139
FW
4561 rb = rcu_dereference(event->rb);
4562 if (rb) {
4563 if (!atomic_inc_not_zero(&rb->refcount))
4564 rb = NULL;
ac9721f3
PZ
4565 }
4566 rcu_read_unlock();
4567
76369139 4568 return rb;
ac9721f3
PZ
4569}
4570
fdc26706 4571void ring_buffer_put(struct ring_buffer *rb)
ac9721f3 4572{
76369139 4573 if (!atomic_dec_and_test(&rb->refcount))
ac9721f3 4574 return;
7b732a75 4575
9bb5d40c 4576 WARN_ON_ONCE(!list_empty(&rb->event_list));
10c6db11 4577
76369139 4578 call_rcu(&rb->rcu_head, rb_free_rcu);
7b732a75
PZ
4579}
4580
4581static void perf_mmap_open(struct vm_area_struct *vma)
4582{
cdd6c482 4583 struct perf_event *event = vma->vm_file->private_data;
7b732a75 4584
cdd6c482 4585 atomic_inc(&event->mmap_count);
9bb5d40c 4586 atomic_inc(&event->rb->mmap_count);
1e0fb9ec 4587
45bfb2e5
PZ
4588 if (vma->vm_pgoff)
4589 atomic_inc(&event->rb->aux_mmap_count);
4590
1e0fb9ec
AL
4591 if (event->pmu->event_mapped)
4592 event->pmu->event_mapped(event);
7b732a75
PZ
4593}
4594
9bb5d40c
PZ
4595/*
4596 * A buffer can be mmap()ed multiple times; either directly through the same
4597 * event, or through other events by use of perf_event_set_output().
4598 *
4599 * In order to undo the VM accounting done by perf_mmap() we need to destroy
4600 * the buffer here, where we still have a VM context. This means we need
4601 * to detach all events redirecting to us.
4602 */
7b732a75
PZ
4603static void perf_mmap_close(struct vm_area_struct *vma)
4604{
cdd6c482 4605 struct perf_event *event = vma->vm_file->private_data;
7b732a75 4606
b69cf536 4607 struct ring_buffer *rb = ring_buffer_get(event);
9bb5d40c
PZ
4608 struct user_struct *mmap_user = rb->mmap_user;
4609 int mmap_locked = rb->mmap_locked;
4610 unsigned long size = perf_data_size(rb);
789f90fc 4611
1e0fb9ec
AL
4612 if (event->pmu->event_unmapped)
4613 event->pmu->event_unmapped(event);
4614
45bfb2e5
PZ
4615 /*
4616 * rb->aux_mmap_count will always drop before rb->mmap_count and
4617 * event->mmap_count, so it is ok to use event->mmap_mutex to
4618 * serialize with perf_mmap here.
4619 */
4620 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
4621 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
4622 atomic_long_sub(rb->aux_nr_pages, &mmap_user->locked_vm);
4623 vma->vm_mm->pinned_vm -= rb->aux_mmap_locked;
4624
4625 rb_free_aux(rb);
4626 mutex_unlock(&event->mmap_mutex);
4627 }
4628
9bb5d40c
PZ
4629 atomic_dec(&rb->mmap_count);
4630
4631 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
b69cf536 4632 goto out_put;
9bb5d40c 4633
b69cf536 4634 ring_buffer_attach(event, NULL);
9bb5d40c
PZ
4635 mutex_unlock(&event->mmap_mutex);
4636
4637 /* If there's still other mmap()s of this buffer, we're done. */
b69cf536
PZ
4638 if (atomic_read(&rb->mmap_count))
4639 goto out_put;
ac9721f3 4640
9bb5d40c
PZ
4641 /*
4642 * No other mmap()s, detach from all other events that might redirect
4643 * into the now unreachable buffer. Somewhat complicated by the
4644 * fact that rb::event_lock otherwise nests inside mmap_mutex.
4645 */
4646again:
4647 rcu_read_lock();
4648 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
4649 if (!atomic_long_inc_not_zero(&event->refcount)) {
4650 /*
4651 * This event is en-route to free_event() which will
4652 * detach it and remove it from the list.
4653 */
4654 continue;
4655 }
4656 rcu_read_unlock();
789f90fc 4657
9bb5d40c
PZ
4658 mutex_lock(&event->mmap_mutex);
4659 /*
4660 * Check we didn't race with perf_event_set_output() which can
4661 * swizzle the rb from under us while we were waiting to
4662 * acquire mmap_mutex.
4663 *
4664 * If we find a different rb; ignore this event, a next
4665 * iteration will no longer find it on the list. We have to
4666 * still restart the iteration to make sure we're not now
4667 * iterating the wrong list.
4668 */
b69cf536
PZ
4669 if (event->rb == rb)
4670 ring_buffer_attach(event, NULL);
4671
cdd6c482 4672 mutex_unlock(&event->mmap_mutex);
9bb5d40c 4673 put_event(event);
ac9721f3 4674
9bb5d40c
PZ
4675 /*
4676 * Restart the iteration; either we're on the wrong list or
4677 * destroyed its integrity by doing a deletion.
4678 */
4679 goto again;
7b732a75 4680 }
9bb5d40c
PZ
4681 rcu_read_unlock();
4682
4683 /*
4684 * It could be there's still a few 0-ref events on the list; they'll
4685 * get cleaned up by free_event() -- they'll also still have their
4686 * ref on the rb and will free it whenever they are done with it.
4687 *
4688 * Aside from that, this buffer is 'fully' detached and unmapped,
4689 * undo the VM accounting.
4690 */
4691
4692 atomic_long_sub((size >> PAGE_SHIFT) + 1, &mmap_user->locked_vm);
4693 vma->vm_mm->pinned_vm -= mmap_locked;
4694 free_uid(mmap_user);
4695
b69cf536 4696out_put:
9bb5d40c 4697 ring_buffer_put(rb); /* could be last */
37d81828
PM
4698}
4699
f0f37e2f 4700static const struct vm_operations_struct perf_mmap_vmops = {
43a21ea8 4701 .open = perf_mmap_open,
45bfb2e5 4702 .close = perf_mmap_close, /* non mergable */
43a21ea8
PZ
4703 .fault = perf_mmap_fault,
4704 .page_mkwrite = perf_mmap_fault,
37d81828
PM
4705};
4706
4707static int perf_mmap(struct file *file, struct vm_area_struct *vma)
4708{
cdd6c482 4709 struct perf_event *event = file->private_data;
22a4f650 4710 unsigned long user_locked, user_lock_limit;
789f90fc 4711 struct user_struct *user = current_user();
22a4f650 4712 unsigned long locked, lock_limit;
45bfb2e5 4713 struct ring_buffer *rb = NULL;
7b732a75
PZ
4714 unsigned long vma_size;
4715 unsigned long nr_pages;
45bfb2e5 4716 long user_extra = 0, extra = 0;
d57e34fd 4717 int ret = 0, flags = 0;
37d81828 4718
c7920614
PZ
4719 /*
4720 * Don't allow mmap() of inherited per-task counters. This would
4721 * create a performance issue due to all children writing to the
76369139 4722 * same rb.
c7920614
PZ
4723 */
4724 if (event->cpu == -1 && event->attr.inherit)
4725 return -EINVAL;
4726
43a21ea8 4727 if (!(vma->vm_flags & VM_SHARED))
37d81828 4728 return -EINVAL;
7b732a75
PZ
4729
4730 vma_size = vma->vm_end - vma->vm_start;
45bfb2e5
PZ
4731
4732 if (vma->vm_pgoff == 0) {
4733 nr_pages = (vma_size / PAGE_SIZE) - 1;
4734 } else {
4735 /*
4736 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
4737 * mapped, all subsequent mappings should have the same size
4738 * and offset. Must be above the normal perf buffer.
4739 */
4740 u64 aux_offset, aux_size;
4741
4742 if (!event->rb)
4743 return -EINVAL;
4744
4745 nr_pages = vma_size / PAGE_SIZE;
4746
4747 mutex_lock(&event->mmap_mutex);
4748 ret = -EINVAL;
4749
4750 rb = event->rb;
4751 if (!rb)
4752 goto aux_unlock;
4753
4754 aux_offset = ACCESS_ONCE(rb->user_page->aux_offset);
4755 aux_size = ACCESS_ONCE(rb->user_page->aux_size);
4756
4757 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
4758 goto aux_unlock;
4759
4760 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
4761 goto aux_unlock;
4762
4763 /* already mapped with a different offset */
4764 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
4765 goto aux_unlock;
4766
4767 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
4768 goto aux_unlock;
4769
4770 /* already mapped with a different size */
4771 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
4772 goto aux_unlock;
4773
4774 if (!is_power_of_2(nr_pages))
4775 goto aux_unlock;
4776
4777 if (!atomic_inc_not_zero(&rb->mmap_count))
4778 goto aux_unlock;
4779
4780 if (rb_has_aux(rb)) {
4781 atomic_inc(&rb->aux_mmap_count);
4782 ret = 0;
4783 goto unlock;
4784 }
4785
4786 atomic_set(&rb->aux_mmap_count, 1);
4787 user_extra = nr_pages;
4788
4789 goto accounting;
4790 }
7b732a75 4791
7730d865 4792 /*
76369139 4793 * If we have rb pages ensure they're a power-of-two number, so we
7730d865
PZ
4794 * can do bitmasks instead of modulo.
4795 */
2ed11312 4796 if (nr_pages != 0 && !is_power_of_2(nr_pages))
37d81828
PM
4797 return -EINVAL;
4798
7b732a75 4799 if (vma_size != PAGE_SIZE * (1 + nr_pages))
37d81828
PM
4800 return -EINVAL;
4801
cdd6c482 4802 WARN_ON_ONCE(event->ctx->parent_ctx);
9bb5d40c 4803again:
cdd6c482 4804 mutex_lock(&event->mmap_mutex);
76369139 4805 if (event->rb) {
9bb5d40c 4806 if (event->rb->nr_pages != nr_pages) {
ebb3c4c4 4807 ret = -EINVAL;
9bb5d40c
PZ
4808 goto unlock;
4809 }
4810
4811 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
4812 /*
4813 * Raced against perf_mmap_close() through
4814 * perf_event_set_output(). Try again, hope for better
4815 * luck.
4816 */
4817 mutex_unlock(&event->mmap_mutex);
4818 goto again;
4819 }
4820
ebb3c4c4
PZ
4821 goto unlock;
4822 }
4823
789f90fc 4824 user_extra = nr_pages + 1;
45bfb2e5
PZ
4825
4826accounting:
cdd6c482 4827 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
a3862d3f
IM
4828
4829 /*
4830 * Increase the limit linearly with more CPUs:
4831 */
4832 user_lock_limit *= num_online_cpus();
4833
789f90fc 4834 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
c5078f78 4835
789f90fc
PZ
4836 if (user_locked > user_lock_limit)
4837 extra = user_locked - user_lock_limit;
7b732a75 4838
78d7d407 4839 lock_limit = rlimit(RLIMIT_MEMLOCK);
7b732a75 4840 lock_limit >>= PAGE_SHIFT;
bc3e53f6 4841 locked = vma->vm_mm->pinned_vm + extra;
7b732a75 4842
459ec28a
IM
4843 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
4844 !capable(CAP_IPC_LOCK)) {
ebb3c4c4
PZ
4845 ret = -EPERM;
4846 goto unlock;
4847 }
7b732a75 4848
45bfb2e5 4849 WARN_ON(!rb && event->rb);
906010b2 4850
d57e34fd 4851 if (vma->vm_flags & VM_WRITE)
76369139 4852 flags |= RING_BUFFER_WRITABLE;
d57e34fd 4853
76369139 4854 if (!rb) {
45bfb2e5
PZ
4855 rb = rb_alloc(nr_pages,
4856 event->attr.watermark ? event->attr.wakeup_watermark : 0,
4857 event->cpu, flags);
26cb63ad 4858
45bfb2e5
PZ
4859 if (!rb) {
4860 ret = -ENOMEM;
4861 goto unlock;
4862 }
43a21ea8 4863
45bfb2e5
PZ
4864 atomic_set(&rb->mmap_count, 1);
4865 rb->mmap_user = get_current_user();
4866 rb->mmap_locked = extra;
26cb63ad 4867
45bfb2e5 4868 ring_buffer_attach(event, rb);
ac9721f3 4869
45bfb2e5
PZ
4870 perf_event_init_userpage(event);
4871 perf_event_update_userpage(event);
4872 } else {
1a594131
AS
4873 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
4874 event->attr.aux_watermark, flags);
45bfb2e5
PZ
4875 if (!ret)
4876 rb->aux_mmap_locked = extra;
4877 }
9a0f05cb 4878
ebb3c4c4 4879unlock:
45bfb2e5
PZ
4880 if (!ret) {
4881 atomic_long_add(user_extra, &user->locked_vm);
4882 vma->vm_mm->pinned_vm += extra;
4883
ac9721f3 4884 atomic_inc(&event->mmap_count);
45bfb2e5
PZ
4885 } else if (rb) {
4886 atomic_dec(&rb->mmap_count);
4887 }
4888aux_unlock:
cdd6c482 4889 mutex_unlock(&event->mmap_mutex);
37d81828 4890
9bb5d40c
PZ
4891 /*
4892 * Since pinned accounting is per vm we cannot allow fork() to copy our
4893 * vma.
4894 */
26cb63ad 4895 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
37d81828 4896 vma->vm_ops = &perf_mmap_vmops;
7b732a75 4897
1e0fb9ec
AL
4898 if (event->pmu->event_mapped)
4899 event->pmu->event_mapped(event);
4900
7b732a75 4901 return ret;
37d81828
PM
4902}
4903
3c446b3d
PZ
4904static int perf_fasync(int fd, struct file *filp, int on)
4905{
496ad9aa 4906 struct inode *inode = file_inode(filp);
cdd6c482 4907 struct perf_event *event = filp->private_data;
3c446b3d
PZ
4908 int retval;
4909
5955102c 4910 inode_lock(inode);
cdd6c482 4911 retval = fasync_helper(fd, filp, on, &event->fasync);
5955102c 4912 inode_unlock(inode);
3c446b3d
PZ
4913
4914 if (retval < 0)
4915 return retval;
4916
4917 return 0;
4918}
4919
0793a61d 4920static const struct file_operations perf_fops = {
3326c1ce 4921 .llseek = no_llseek,
0793a61d
TG
4922 .release = perf_release,
4923 .read = perf_read,
4924 .poll = perf_poll,
d859e29f 4925 .unlocked_ioctl = perf_ioctl,
b3f20785 4926 .compat_ioctl = perf_compat_ioctl,
37d81828 4927 .mmap = perf_mmap,
3c446b3d 4928 .fasync = perf_fasync,
0793a61d
TG
4929};
4930
925d519a 4931/*
cdd6c482 4932 * Perf event wakeup
925d519a
PZ
4933 *
4934 * If there's data, ensure we set the poll() state and publish everything
4935 * to user-space before waking everybody up.
4936 */
4937
fed66e2c
PZ
4938static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
4939{
4940 /* only the parent has fasync state */
4941 if (event->parent)
4942 event = event->parent;
4943 return &event->fasync;
4944}
4945
cdd6c482 4946void perf_event_wakeup(struct perf_event *event)
925d519a 4947{
10c6db11 4948 ring_buffer_wakeup(event);
4c9e2542 4949
cdd6c482 4950 if (event->pending_kill) {
fed66e2c 4951 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
cdd6c482 4952 event->pending_kill = 0;
4c9e2542 4953 }
925d519a
PZ
4954}
4955
e360adbe 4956static void perf_pending_event(struct irq_work *entry)
79f14641 4957{
cdd6c482
IM
4958 struct perf_event *event = container_of(entry,
4959 struct perf_event, pending);
d525211f
PZ
4960 int rctx;
4961
4962 rctx = perf_swevent_get_recursion_context();
4963 /*
4964 * If we 'fail' here, that's OK, it means recursion is already disabled
4965 * and we won't recurse 'further'.
4966 */
79f14641 4967
cdd6c482
IM
4968 if (event->pending_disable) {
4969 event->pending_disable = 0;
fae3fde6 4970 perf_event_disable_local(event);
79f14641
PZ
4971 }
4972
cdd6c482
IM
4973 if (event->pending_wakeup) {
4974 event->pending_wakeup = 0;
4975 perf_event_wakeup(event);
79f14641 4976 }
d525211f
PZ
4977
4978 if (rctx >= 0)
4979 perf_swevent_put_recursion_context(rctx);
79f14641
PZ
4980}
4981
39447b38
ZY
4982/*
4983 * We assume there is only KVM supporting the callbacks.
4984 * Later on, we might change it to a list if there is
4985 * another virtualization implementation supporting the callbacks.
4986 */
4987struct perf_guest_info_callbacks *perf_guest_cbs;
4988
4989int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4990{
4991 perf_guest_cbs = cbs;
4992 return 0;
4993}
4994EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
4995
4996int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
4997{
4998 perf_guest_cbs = NULL;
4999 return 0;
5000}
5001EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
5002
4018994f
JO
5003static void
5004perf_output_sample_regs(struct perf_output_handle *handle,
5005 struct pt_regs *regs, u64 mask)
5006{
5007 int bit;
5008
5009 for_each_set_bit(bit, (const unsigned long *) &mask,
5010 sizeof(mask) * BITS_PER_BYTE) {
5011 u64 val;
5012
5013 val = perf_reg_value(regs, bit);
5014 perf_output_put(handle, val);
5015 }
5016}
5017
60e2364e 5018static void perf_sample_regs_user(struct perf_regs *regs_user,
88a7c26a
AL
5019 struct pt_regs *regs,
5020 struct pt_regs *regs_user_copy)
4018994f 5021{
88a7c26a
AL
5022 if (user_mode(regs)) {
5023 regs_user->abi = perf_reg_abi(current);
2565711f 5024 regs_user->regs = regs;
88a7c26a
AL
5025 } else if (current->mm) {
5026 perf_get_regs_user(regs_user, regs, regs_user_copy);
2565711f
PZ
5027 } else {
5028 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
5029 regs_user->regs = NULL;
4018994f
JO
5030 }
5031}
5032
60e2364e
SE
5033static void perf_sample_regs_intr(struct perf_regs *regs_intr,
5034 struct pt_regs *regs)
5035{
5036 regs_intr->regs = regs;
5037 regs_intr->abi = perf_reg_abi(current);
5038}
5039
5040
c5ebcedb
JO
5041/*
5042 * Get remaining task size from user stack pointer.
5043 *
5044 * It'd be better to take stack vma map and limit this more
5045 * precisly, but there's no way to get it safely under interrupt,
5046 * so using TASK_SIZE as limit.
5047 */
5048static u64 perf_ustack_task_size(struct pt_regs *regs)
5049{
5050 unsigned long addr = perf_user_stack_pointer(regs);
5051
5052 if (!addr || addr >= TASK_SIZE)
5053 return 0;
5054
5055 return TASK_SIZE - addr;
5056}
5057
5058static u16
5059perf_sample_ustack_size(u16 stack_size, u16 header_size,
5060 struct pt_regs *regs)
5061{
5062 u64 task_size;
5063
5064 /* No regs, no stack pointer, no dump. */
5065 if (!regs)
5066 return 0;
5067
5068 /*
5069 * Check if we fit in with the requested stack size into the:
5070 * - TASK_SIZE
5071 * If we don't, we limit the size to the TASK_SIZE.
5072 *
5073 * - remaining sample size
5074 * If we don't, we customize the stack size to
5075 * fit in to the remaining sample size.
5076 */
5077
5078 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
5079 stack_size = min(stack_size, (u16) task_size);
5080
5081 /* Current header size plus static size and dynamic size. */
5082 header_size += 2 * sizeof(u64);
5083
5084 /* Do we fit in with the current stack dump size? */
5085 if ((u16) (header_size + stack_size) < header_size) {
5086 /*
5087 * If we overflow the maximum size for the sample,
5088 * we customize the stack dump size to fit in.
5089 */
5090 stack_size = USHRT_MAX - header_size - sizeof(u64);
5091 stack_size = round_up(stack_size, sizeof(u64));
5092 }
5093
5094 return stack_size;
5095}
5096
5097static void
5098perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
5099 struct pt_regs *regs)
5100{
5101 /* Case of a kernel thread, nothing to dump */
5102 if (!regs) {
5103 u64 size = 0;
5104 perf_output_put(handle, size);
5105 } else {
5106 unsigned long sp;
5107 unsigned int rem;
5108 u64 dyn_size;
5109
5110 /*
5111 * We dump:
5112 * static size
5113 * - the size requested by user or the best one we can fit
5114 * in to the sample max size
5115 * data
5116 * - user stack dump data
5117 * dynamic size
5118 * - the actual dumped size
5119 */
5120
5121 /* Static size. */
5122 perf_output_put(handle, dump_size);
5123
5124 /* Data. */
5125 sp = perf_user_stack_pointer(regs);
5126 rem = __output_copy_user(handle, (void *) sp, dump_size);
5127 dyn_size = dump_size - rem;
5128
5129 perf_output_skip(handle, rem);
5130
5131 /* Dynamic size. */
5132 perf_output_put(handle, dyn_size);
5133 }
5134}
5135
c980d109
ACM
5136static void __perf_event_header__init_id(struct perf_event_header *header,
5137 struct perf_sample_data *data,
5138 struct perf_event *event)
6844c09d
ACM
5139{
5140 u64 sample_type = event->attr.sample_type;
5141
5142 data->type = sample_type;
5143 header->size += event->id_header_size;
5144
5145 if (sample_type & PERF_SAMPLE_TID) {
5146 /* namespace issues */
5147 data->tid_entry.pid = perf_event_pid(event, current);
5148 data->tid_entry.tid = perf_event_tid(event, current);
5149 }
5150
5151 if (sample_type & PERF_SAMPLE_TIME)
34f43927 5152 data->time = perf_event_clock(event);
6844c09d 5153
ff3d527c 5154 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6844c09d
ACM
5155 data->id = primary_event_id(event);
5156
5157 if (sample_type & PERF_SAMPLE_STREAM_ID)
5158 data->stream_id = event->id;
5159
5160 if (sample_type & PERF_SAMPLE_CPU) {
5161 data->cpu_entry.cpu = raw_smp_processor_id();
5162 data->cpu_entry.reserved = 0;
5163 }
5164}
5165
76369139
FW
5166void perf_event_header__init_id(struct perf_event_header *header,
5167 struct perf_sample_data *data,
5168 struct perf_event *event)
c980d109
ACM
5169{
5170 if (event->attr.sample_id_all)
5171 __perf_event_header__init_id(header, data, event);
5172}
5173
5174static void __perf_event__output_id_sample(struct perf_output_handle *handle,
5175 struct perf_sample_data *data)
5176{
5177 u64 sample_type = data->type;
5178
5179 if (sample_type & PERF_SAMPLE_TID)
5180 perf_output_put(handle, data->tid_entry);
5181
5182 if (sample_type & PERF_SAMPLE_TIME)
5183 perf_output_put(handle, data->time);
5184
5185 if (sample_type & PERF_SAMPLE_ID)
5186 perf_output_put(handle, data->id);
5187
5188 if (sample_type & PERF_SAMPLE_STREAM_ID)
5189 perf_output_put(handle, data->stream_id);
5190
5191 if (sample_type & PERF_SAMPLE_CPU)
5192 perf_output_put(handle, data->cpu_entry);
ff3d527c
AH
5193
5194 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5195 perf_output_put(handle, data->id);
c980d109
ACM
5196}
5197
76369139
FW
5198void perf_event__output_id_sample(struct perf_event *event,
5199 struct perf_output_handle *handle,
5200 struct perf_sample_data *sample)
c980d109
ACM
5201{
5202 if (event->attr.sample_id_all)
5203 __perf_event__output_id_sample(handle, sample);
5204}
5205
3dab77fb 5206static void perf_output_read_one(struct perf_output_handle *handle,
eed01528
SE
5207 struct perf_event *event,
5208 u64 enabled, u64 running)
3dab77fb 5209{
cdd6c482 5210 u64 read_format = event->attr.read_format;
3dab77fb
PZ
5211 u64 values[4];
5212 int n = 0;
5213
b5e58793 5214 values[n++] = perf_event_count(event);
3dab77fb 5215 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
eed01528 5216 values[n++] = enabled +
cdd6c482 5217 atomic64_read(&event->child_total_time_enabled);
3dab77fb
PZ
5218 }
5219 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
eed01528 5220 values[n++] = running +
cdd6c482 5221 atomic64_read(&event->child_total_time_running);
3dab77fb
PZ
5222 }
5223 if (read_format & PERF_FORMAT_ID)
cdd6c482 5224 values[n++] = primary_event_id(event);
3dab77fb 5225
76369139 5226 __output_copy(handle, values, n * sizeof(u64));
3dab77fb
PZ
5227}
5228
5229/*
cdd6c482 5230 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
3dab77fb
PZ
5231 */
5232static void perf_output_read_group(struct perf_output_handle *handle,
eed01528
SE
5233 struct perf_event *event,
5234 u64 enabled, u64 running)
3dab77fb 5235{
cdd6c482
IM
5236 struct perf_event *leader = event->group_leader, *sub;
5237 u64 read_format = event->attr.read_format;
3dab77fb
PZ
5238 u64 values[5];
5239 int n = 0;
5240
5241 values[n++] = 1 + leader->nr_siblings;
5242
5243 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
eed01528 5244 values[n++] = enabled;
3dab77fb
PZ
5245
5246 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
eed01528 5247 values[n++] = running;
3dab77fb 5248
cdd6c482 5249 if (leader != event)
3dab77fb
PZ
5250 leader->pmu->read(leader);
5251
b5e58793 5252 values[n++] = perf_event_count(leader);
3dab77fb 5253 if (read_format & PERF_FORMAT_ID)
cdd6c482 5254 values[n++] = primary_event_id(leader);
3dab77fb 5255
76369139 5256 __output_copy(handle, values, n * sizeof(u64));
3dab77fb 5257
65abc865 5258 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3dab77fb
PZ
5259 n = 0;
5260
6f5ab001
JO
5261 if ((sub != event) &&
5262 (sub->state == PERF_EVENT_STATE_ACTIVE))
3dab77fb
PZ
5263 sub->pmu->read(sub);
5264
b5e58793 5265 values[n++] = perf_event_count(sub);
3dab77fb 5266 if (read_format & PERF_FORMAT_ID)
cdd6c482 5267 values[n++] = primary_event_id(sub);
3dab77fb 5268
76369139 5269 __output_copy(handle, values, n * sizeof(u64));
3dab77fb
PZ
5270 }
5271}
5272
eed01528
SE
5273#define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
5274 PERF_FORMAT_TOTAL_TIME_RUNNING)
5275
3dab77fb 5276static void perf_output_read(struct perf_output_handle *handle,
cdd6c482 5277 struct perf_event *event)
3dab77fb 5278{
e3f3541c 5279 u64 enabled = 0, running = 0, now;
eed01528
SE
5280 u64 read_format = event->attr.read_format;
5281
5282 /*
5283 * compute total_time_enabled, total_time_running
5284 * based on snapshot values taken when the event
5285 * was last scheduled in.
5286 *
5287 * we cannot simply called update_context_time()
5288 * because of locking issue as we are called in
5289 * NMI context
5290 */
c4794295 5291 if (read_format & PERF_FORMAT_TOTAL_TIMES)
e3f3541c 5292 calc_timer_values(event, &now, &enabled, &running);
eed01528 5293
cdd6c482 5294 if (event->attr.read_format & PERF_FORMAT_GROUP)
eed01528 5295 perf_output_read_group(handle, event, enabled, running);
3dab77fb 5296 else
eed01528 5297 perf_output_read_one(handle, event, enabled, running);
3dab77fb
PZ
5298}
5299
5622f295
MM
5300void perf_output_sample(struct perf_output_handle *handle,
5301 struct perf_event_header *header,
5302 struct perf_sample_data *data,
cdd6c482 5303 struct perf_event *event)
5622f295
MM
5304{
5305 u64 sample_type = data->type;
5306
5307 perf_output_put(handle, *header);
5308
ff3d527c
AH
5309 if (sample_type & PERF_SAMPLE_IDENTIFIER)
5310 perf_output_put(handle, data->id);
5311
5622f295
MM
5312 if (sample_type & PERF_SAMPLE_IP)
5313 perf_output_put(handle, data->ip);
5314
5315 if (sample_type & PERF_SAMPLE_TID)
5316 perf_output_put(handle, data->tid_entry);
5317
5318 if (sample_type & PERF_SAMPLE_TIME)
5319 perf_output_put(handle, data->time);
5320
5321 if (sample_type & PERF_SAMPLE_ADDR)
5322 perf_output_put(handle, data->addr);
5323
5324 if (sample_type & PERF_SAMPLE_ID)
5325 perf_output_put(handle, data->id);
5326
5327 if (sample_type & PERF_SAMPLE_STREAM_ID)
5328 perf_output_put(handle, data->stream_id);
5329
5330 if (sample_type & PERF_SAMPLE_CPU)
5331 perf_output_put(handle, data->cpu_entry);
5332
5333 if (sample_type & PERF_SAMPLE_PERIOD)
5334 perf_output_put(handle, data->period);
5335
5336 if (sample_type & PERF_SAMPLE_READ)
cdd6c482 5337 perf_output_read(handle, event);
5622f295
MM
5338
5339 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5340 if (data->callchain) {
5341 int size = 1;
5342
5343 if (data->callchain)
5344 size += data->callchain->nr;
5345
5346 size *= sizeof(u64);
5347
76369139 5348 __output_copy(handle, data->callchain, size);
5622f295
MM
5349 } else {
5350 u64 nr = 0;
5351 perf_output_put(handle, nr);
5352 }
5353 }
5354
5355 if (sample_type & PERF_SAMPLE_RAW) {
5356 if (data->raw) {
fa128e6a
AS
5357 u32 raw_size = data->raw->size;
5358 u32 real_size = round_up(raw_size + sizeof(u32),
5359 sizeof(u64)) - sizeof(u32);
5360 u64 zero = 0;
5361
5362 perf_output_put(handle, real_size);
5363 __output_copy(handle, data->raw->data, raw_size);
5364 if (real_size - raw_size)
5365 __output_copy(handle, &zero, real_size - raw_size);
5622f295
MM
5366 } else {
5367 struct {
5368 u32 size;
5369 u32 data;
5370 } raw = {
5371 .size = sizeof(u32),
5372 .data = 0,
5373 };
5374 perf_output_put(handle, raw);
5375 }
5376 }
a7ac67ea 5377
bce38cd5
SE
5378 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5379 if (data->br_stack) {
5380 size_t size;
5381
5382 size = data->br_stack->nr
5383 * sizeof(struct perf_branch_entry);
5384
5385 perf_output_put(handle, data->br_stack->nr);
5386 perf_output_copy(handle, data->br_stack->entries, size);
5387 } else {
5388 /*
5389 * we always store at least the value of nr
5390 */
5391 u64 nr = 0;
5392 perf_output_put(handle, nr);
5393 }
5394 }
4018994f
JO
5395
5396 if (sample_type & PERF_SAMPLE_REGS_USER) {
5397 u64 abi = data->regs_user.abi;
5398
5399 /*
5400 * If there are no regs to dump, notice it through
5401 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5402 */
5403 perf_output_put(handle, abi);
5404
5405 if (abi) {
5406 u64 mask = event->attr.sample_regs_user;
5407 perf_output_sample_regs(handle,
5408 data->regs_user.regs,
5409 mask);
5410 }
5411 }
c5ebcedb 5412
a5cdd40c 5413 if (sample_type & PERF_SAMPLE_STACK_USER) {
c5ebcedb
JO
5414 perf_output_sample_ustack(handle,
5415 data->stack_user_size,
5416 data->regs_user.regs);
a5cdd40c 5417 }
c3feedf2
AK
5418
5419 if (sample_type & PERF_SAMPLE_WEIGHT)
5420 perf_output_put(handle, data->weight);
d6be9ad6
SE
5421
5422 if (sample_type & PERF_SAMPLE_DATA_SRC)
5423 perf_output_put(handle, data->data_src.val);
a5cdd40c 5424
fdfbbd07
AK
5425 if (sample_type & PERF_SAMPLE_TRANSACTION)
5426 perf_output_put(handle, data->txn);
5427
60e2364e
SE
5428 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5429 u64 abi = data->regs_intr.abi;
5430 /*
5431 * If there are no regs to dump, notice it through
5432 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
5433 */
5434 perf_output_put(handle, abi);
5435
5436 if (abi) {
5437 u64 mask = event->attr.sample_regs_intr;
5438
5439 perf_output_sample_regs(handle,
5440 data->regs_intr.regs,
5441 mask);
5442 }
5443 }
5444
a5cdd40c
PZ
5445 if (!event->attr.watermark) {
5446 int wakeup_events = event->attr.wakeup_events;
5447
5448 if (wakeup_events) {
5449 struct ring_buffer *rb = handle->rb;
5450 int events = local_inc_return(&rb->events);
5451
5452 if (events >= wakeup_events) {
5453 local_sub(wakeup_events, &rb->events);
5454 local_inc(&rb->wakeup);
5455 }
5456 }
5457 }
5622f295
MM
5458}
5459
5460void perf_prepare_sample(struct perf_event_header *header,
5461 struct perf_sample_data *data,
cdd6c482 5462 struct perf_event *event,
5622f295 5463 struct pt_regs *regs)
7b732a75 5464{
cdd6c482 5465 u64 sample_type = event->attr.sample_type;
7b732a75 5466
cdd6c482 5467 header->type = PERF_RECORD_SAMPLE;
c320c7b7 5468 header->size = sizeof(*header) + event->header_size;
5622f295
MM
5469
5470 header->misc = 0;
5471 header->misc |= perf_misc_flags(regs);
6fab0192 5472
c980d109 5473 __perf_event_header__init_id(header, data, event);
6844c09d 5474
c320c7b7 5475 if (sample_type & PERF_SAMPLE_IP)
5622f295
MM
5476 data->ip = perf_instruction_pointer(regs);
5477
b23f3325 5478 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
5622f295 5479 int size = 1;
394ee076 5480
e6dab5ff 5481 data->callchain = perf_callchain(event, regs);
5622f295
MM
5482
5483 if (data->callchain)
5484 size += data->callchain->nr;
5485
5486 header->size += size * sizeof(u64);
394ee076
PZ
5487 }
5488
3a43ce68 5489 if (sample_type & PERF_SAMPLE_RAW) {
a044560c
PZ
5490 int size = sizeof(u32);
5491
5492 if (data->raw)
5493 size += data->raw->size;
5494 else
5495 size += sizeof(u32);
5496
fa128e6a 5497 header->size += round_up(size, sizeof(u64));
7f453c24 5498 }
bce38cd5
SE
5499
5500 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
5501 int size = sizeof(u64); /* nr */
5502 if (data->br_stack) {
5503 size += data->br_stack->nr
5504 * sizeof(struct perf_branch_entry);
5505 }
5506 header->size += size;
5507 }
4018994f 5508
2565711f 5509 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
88a7c26a
AL
5510 perf_sample_regs_user(&data->regs_user, regs,
5511 &data->regs_user_copy);
2565711f 5512
4018994f
JO
5513 if (sample_type & PERF_SAMPLE_REGS_USER) {
5514 /* regs dump ABI info */
5515 int size = sizeof(u64);
5516
4018994f
JO
5517 if (data->regs_user.regs) {
5518 u64 mask = event->attr.sample_regs_user;
5519 size += hweight64(mask) * sizeof(u64);
5520 }
5521
5522 header->size += size;
5523 }
c5ebcedb
JO
5524
5525 if (sample_type & PERF_SAMPLE_STACK_USER) {
5526 /*
5527 * Either we need PERF_SAMPLE_STACK_USER bit to be allways
5528 * processed as the last one or have additional check added
5529 * in case new sample type is added, because we could eat
5530 * up the rest of the sample size.
5531 */
c5ebcedb
JO
5532 u16 stack_size = event->attr.sample_stack_user;
5533 u16 size = sizeof(u64);
5534
c5ebcedb 5535 stack_size = perf_sample_ustack_size(stack_size, header->size,
2565711f 5536 data->regs_user.regs);
c5ebcedb
JO
5537
5538 /*
5539 * If there is something to dump, add space for the dump
5540 * itself and for the field that tells the dynamic size,
5541 * which is how many have been actually dumped.
5542 */
5543 if (stack_size)
5544 size += sizeof(u64) + stack_size;
5545
5546 data->stack_user_size = stack_size;
5547 header->size += size;
5548 }
60e2364e
SE
5549
5550 if (sample_type & PERF_SAMPLE_REGS_INTR) {
5551 /* regs dump ABI info */
5552 int size = sizeof(u64);
5553
5554 perf_sample_regs_intr(&data->regs_intr, regs);
5555
5556 if (data->regs_intr.regs) {
5557 u64 mask = event->attr.sample_regs_intr;
5558
5559 size += hweight64(mask) * sizeof(u64);
5560 }
5561
5562 header->size += size;
5563 }
5622f295 5564}
7f453c24 5565
21509084
YZ
5566void perf_event_output(struct perf_event *event,
5567 struct perf_sample_data *data,
5568 struct pt_regs *regs)
5622f295
MM
5569{
5570 struct perf_output_handle handle;
5571 struct perf_event_header header;
689802b2 5572
927c7a9e
FW
5573 /* protect the callchain buffers */
5574 rcu_read_lock();
5575
cdd6c482 5576 perf_prepare_sample(&header, data, event, regs);
5c148194 5577
a7ac67ea 5578 if (perf_output_begin(&handle, event, header.size))
927c7a9e 5579 goto exit;
0322cd6e 5580
cdd6c482 5581 perf_output_sample(&handle, &header, data, event);
f413cdb8 5582
8a057d84 5583 perf_output_end(&handle);
927c7a9e
FW
5584
5585exit:
5586 rcu_read_unlock();
0322cd6e
PZ
5587}
5588
38b200d6 5589/*
cdd6c482 5590 * read event_id
38b200d6
PZ
5591 */
5592
5593struct perf_read_event {
5594 struct perf_event_header header;
5595
5596 u32 pid;
5597 u32 tid;
38b200d6
PZ
5598};
5599
5600static void
cdd6c482 5601perf_event_read_event(struct perf_event *event,
38b200d6
PZ
5602 struct task_struct *task)
5603{
5604 struct perf_output_handle handle;
c980d109 5605 struct perf_sample_data sample;
dfc65094 5606 struct perf_read_event read_event = {
38b200d6 5607 .header = {
cdd6c482 5608 .type = PERF_RECORD_READ,
38b200d6 5609 .misc = 0,
c320c7b7 5610 .size = sizeof(read_event) + event->read_size,
38b200d6 5611 },
cdd6c482
IM
5612 .pid = perf_event_pid(event, task),
5613 .tid = perf_event_tid(event, task),
38b200d6 5614 };
3dab77fb 5615 int ret;
38b200d6 5616
c980d109 5617 perf_event_header__init_id(&read_event.header, &sample, event);
a7ac67ea 5618 ret = perf_output_begin(&handle, event, read_event.header.size);
38b200d6
PZ
5619 if (ret)
5620 return;
5621
dfc65094 5622 perf_output_put(&handle, read_event);
cdd6c482 5623 perf_output_read(&handle, event);
c980d109 5624 perf_event__output_id_sample(event, &handle, &sample);
3dab77fb 5625
38b200d6
PZ
5626 perf_output_end(&handle);
5627}
5628
52d857a8
JO
5629typedef void (perf_event_aux_output_cb)(struct perf_event *event, void *data);
5630
5631static void
5632perf_event_aux_ctx(struct perf_event_context *ctx,
52d857a8
JO
5633 perf_event_aux_output_cb output,
5634 void *data)
5635{
5636 struct perf_event *event;
5637
5638 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
5639 if (event->state < PERF_EVENT_STATE_INACTIVE)
5640 continue;
5641 if (!event_filter_match(event))
5642 continue;
67516844 5643 output(event, data);
52d857a8
JO
5644 }
5645}
5646
4e93ad60
JO
5647static void
5648perf_event_aux_task_ctx(perf_event_aux_output_cb output, void *data,
5649 struct perf_event_context *task_ctx)
5650{
5651 rcu_read_lock();
5652 preempt_disable();
5653 perf_event_aux_ctx(task_ctx, output, data);
5654 preempt_enable();
5655 rcu_read_unlock();
5656}
5657
52d857a8 5658static void
67516844 5659perf_event_aux(perf_event_aux_output_cb output, void *data,
52d857a8
JO
5660 struct perf_event_context *task_ctx)
5661{
5662 struct perf_cpu_context *cpuctx;
5663 struct perf_event_context *ctx;
5664 struct pmu *pmu;
5665 int ctxn;
5666
4e93ad60
JO
5667 /*
5668 * If we have task_ctx != NULL we only notify
5669 * the task context itself. The task_ctx is set
5670 * only for EXIT events before releasing task
5671 * context.
5672 */
5673 if (task_ctx) {
5674 perf_event_aux_task_ctx(output, data, task_ctx);
5675 return;
5676 }
5677
52d857a8
JO
5678 rcu_read_lock();
5679 list_for_each_entry_rcu(pmu, &pmus, entry) {
5680 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
5681 if (cpuctx->unique_pmu != pmu)
5682 goto next;
67516844 5683 perf_event_aux_ctx(&cpuctx->ctx, output, data);
52d857a8
JO
5684 ctxn = pmu->task_ctx_nr;
5685 if (ctxn < 0)
5686 goto next;
5687 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
5688 if (ctx)
67516844 5689 perf_event_aux_ctx(ctx, output, data);
52d857a8
JO
5690next:
5691 put_cpu_ptr(pmu->pmu_cpu_context);
5692 }
52d857a8
JO
5693 rcu_read_unlock();
5694}
5695
60313ebe 5696/*
9f498cc5
PZ
5697 * task tracking -- fork/exit
5698 *
13d7a241 5699 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
60313ebe
PZ
5700 */
5701
9f498cc5 5702struct perf_task_event {
3a80b4a3 5703 struct task_struct *task;
cdd6c482 5704 struct perf_event_context *task_ctx;
60313ebe
PZ
5705
5706 struct {
5707 struct perf_event_header header;
5708
5709 u32 pid;
5710 u32 ppid;
9f498cc5
PZ
5711 u32 tid;
5712 u32 ptid;
393b2ad8 5713 u64 time;
cdd6c482 5714 } event_id;
60313ebe
PZ
5715};
5716
67516844
JO
5717static int perf_event_task_match(struct perf_event *event)
5718{
13d7a241
SE
5719 return event->attr.comm || event->attr.mmap ||
5720 event->attr.mmap2 || event->attr.mmap_data ||
5721 event->attr.task;
67516844
JO
5722}
5723
cdd6c482 5724static void perf_event_task_output(struct perf_event *event,
52d857a8 5725 void *data)
60313ebe 5726{
52d857a8 5727 struct perf_task_event *task_event = data;
60313ebe 5728 struct perf_output_handle handle;
c980d109 5729 struct perf_sample_data sample;
9f498cc5 5730 struct task_struct *task = task_event->task;
c980d109 5731 int ret, size = task_event->event_id.header.size;
8bb39f9a 5732
67516844
JO
5733 if (!perf_event_task_match(event))
5734 return;
5735
c980d109 5736 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
60313ebe 5737
c980d109 5738 ret = perf_output_begin(&handle, event,
a7ac67ea 5739 task_event->event_id.header.size);
ef60777c 5740 if (ret)
c980d109 5741 goto out;
60313ebe 5742
cdd6c482
IM
5743 task_event->event_id.pid = perf_event_pid(event, task);
5744 task_event->event_id.ppid = perf_event_pid(event, current);
60313ebe 5745
cdd6c482
IM
5746 task_event->event_id.tid = perf_event_tid(event, task);
5747 task_event->event_id.ptid = perf_event_tid(event, current);
9f498cc5 5748
34f43927
PZ
5749 task_event->event_id.time = perf_event_clock(event);
5750
cdd6c482 5751 perf_output_put(&handle, task_event->event_id);
393b2ad8 5752
c980d109
ACM
5753 perf_event__output_id_sample(event, &handle, &sample);
5754
60313ebe 5755 perf_output_end(&handle);
c980d109
ACM
5756out:
5757 task_event->event_id.header.size = size;
60313ebe
PZ
5758}
5759
cdd6c482
IM
5760static void perf_event_task(struct task_struct *task,
5761 struct perf_event_context *task_ctx,
3a80b4a3 5762 int new)
60313ebe 5763{
9f498cc5 5764 struct perf_task_event task_event;
60313ebe 5765
cdd6c482
IM
5766 if (!atomic_read(&nr_comm_events) &&
5767 !atomic_read(&nr_mmap_events) &&
5768 !atomic_read(&nr_task_events))
60313ebe
PZ
5769 return;
5770
9f498cc5 5771 task_event = (struct perf_task_event){
3a80b4a3
PZ
5772 .task = task,
5773 .task_ctx = task_ctx,
cdd6c482 5774 .event_id = {
60313ebe 5775 .header = {
cdd6c482 5776 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
573402db 5777 .misc = 0,
cdd6c482 5778 .size = sizeof(task_event.event_id),
60313ebe 5779 },
573402db
PZ
5780 /* .pid */
5781 /* .ppid */
9f498cc5
PZ
5782 /* .tid */
5783 /* .ptid */
34f43927 5784 /* .time */
60313ebe
PZ
5785 },
5786 };
5787
67516844 5788 perf_event_aux(perf_event_task_output,
52d857a8
JO
5789 &task_event,
5790 task_ctx);
9f498cc5
PZ
5791}
5792
cdd6c482 5793void perf_event_fork(struct task_struct *task)
9f498cc5 5794{
cdd6c482 5795 perf_event_task(task, NULL, 1);
60313ebe
PZ
5796}
5797
8d1b2d93
PZ
5798/*
5799 * comm tracking
5800 */
5801
5802struct perf_comm_event {
22a4f650
IM
5803 struct task_struct *task;
5804 char *comm;
8d1b2d93
PZ
5805 int comm_size;
5806
5807 struct {
5808 struct perf_event_header header;
5809
5810 u32 pid;
5811 u32 tid;
cdd6c482 5812 } event_id;
8d1b2d93
PZ
5813};
5814
67516844
JO
5815static int perf_event_comm_match(struct perf_event *event)
5816{
5817 return event->attr.comm;
5818}
5819
cdd6c482 5820static void perf_event_comm_output(struct perf_event *event,
52d857a8 5821 void *data)
8d1b2d93 5822{
52d857a8 5823 struct perf_comm_event *comm_event = data;
8d1b2d93 5824 struct perf_output_handle handle;
c980d109 5825 struct perf_sample_data sample;
cdd6c482 5826 int size = comm_event->event_id.header.size;
c980d109
ACM
5827 int ret;
5828
67516844
JO
5829 if (!perf_event_comm_match(event))
5830 return;
5831
c980d109
ACM
5832 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
5833 ret = perf_output_begin(&handle, event,
a7ac67ea 5834 comm_event->event_id.header.size);
8d1b2d93
PZ
5835
5836 if (ret)
c980d109 5837 goto out;
8d1b2d93 5838
cdd6c482
IM
5839 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
5840 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
709e50cf 5841
cdd6c482 5842 perf_output_put(&handle, comm_event->event_id);
76369139 5843 __output_copy(&handle, comm_event->comm,
8d1b2d93 5844 comm_event->comm_size);
c980d109
ACM
5845
5846 perf_event__output_id_sample(event, &handle, &sample);
5847
8d1b2d93 5848 perf_output_end(&handle);
c980d109
ACM
5849out:
5850 comm_event->event_id.header.size = size;
8d1b2d93
PZ
5851}
5852
cdd6c482 5853static void perf_event_comm_event(struct perf_comm_event *comm_event)
8d1b2d93 5854{
413ee3b4 5855 char comm[TASK_COMM_LEN];
8d1b2d93 5856 unsigned int size;
8d1b2d93 5857
413ee3b4 5858 memset(comm, 0, sizeof(comm));
96b02d78 5859 strlcpy(comm, comm_event->task->comm, sizeof(comm));
888fcee0 5860 size = ALIGN(strlen(comm)+1, sizeof(u64));
8d1b2d93
PZ
5861
5862 comm_event->comm = comm;
5863 comm_event->comm_size = size;
5864
cdd6c482 5865 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
8dc85d54 5866
67516844 5867 perf_event_aux(perf_event_comm_output,
52d857a8
JO
5868 comm_event,
5869 NULL);
8d1b2d93
PZ
5870}
5871
82b89778 5872void perf_event_comm(struct task_struct *task, bool exec)
8d1b2d93 5873{
9ee318a7
PZ
5874 struct perf_comm_event comm_event;
5875
cdd6c482 5876 if (!atomic_read(&nr_comm_events))
9ee318a7 5877 return;
a63eaf34 5878
9ee318a7 5879 comm_event = (struct perf_comm_event){
8d1b2d93 5880 .task = task,
573402db
PZ
5881 /* .comm */
5882 /* .comm_size */
cdd6c482 5883 .event_id = {
573402db 5884 .header = {
cdd6c482 5885 .type = PERF_RECORD_COMM,
82b89778 5886 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
573402db
PZ
5887 /* .size */
5888 },
5889 /* .pid */
5890 /* .tid */
8d1b2d93
PZ
5891 },
5892 };
5893
cdd6c482 5894 perf_event_comm_event(&comm_event);
8d1b2d93
PZ
5895}
5896
0a4a9391
PZ
5897/*
5898 * mmap tracking
5899 */
5900
5901struct perf_mmap_event {
089dd79d
PZ
5902 struct vm_area_struct *vma;
5903
5904 const char *file_name;
5905 int file_size;
13d7a241
SE
5906 int maj, min;
5907 u64 ino;
5908 u64 ino_generation;
f972eb63 5909 u32 prot, flags;
0a4a9391
PZ
5910
5911 struct {
5912 struct perf_event_header header;
5913
5914 u32 pid;
5915 u32 tid;
5916 u64 start;
5917 u64 len;
5918 u64 pgoff;
cdd6c482 5919 } event_id;
0a4a9391
PZ
5920};
5921
67516844
JO
5922static int perf_event_mmap_match(struct perf_event *event,
5923 void *data)
5924{
5925 struct perf_mmap_event *mmap_event = data;
5926 struct vm_area_struct *vma = mmap_event->vma;
5927 int executable = vma->vm_flags & VM_EXEC;
5928
5929 return (!executable && event->attr.mmap_data) ||
13d7a241 5930 (executable && (event->attr.mmap || event->attr.mmap2));
67516844
JO
5931}
5932
cdd6c482 5933static void perf_event_mmap_output(struct perf_event *event,
52d857a8 5934 void *data)
0a4a9391 5935{
52d857a8 5936 struct perf_mmap_event *mmap_event = data;
0a4a9391 5937 struct perf_output_handle handle;
c980d109 5938 struct perf_sample_data sample;
cdd6c482 5939 int size = mmap_event->event_id.header.size;
c980d109 5940 int ret;
0a4a9391 5941
67516844
JO
5942 if (!perf_event_mmap_match(event, data))
5943 return;
5944
13d7a241
SE
5945 if (event->attr.mmap2) {
5946 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
5947 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
5948 mmap_event->event_id.header.size += sizeof(mmap_event->min);
5949 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
d008d525 5950 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
f972eb63
PZ
5951 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
5952 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
13d7a241
SE
5953 }
5954
c980d109
ACM
5955 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
5956 ret = perf_output_begin(&handle, event,
a7ac67ea 5957 mmap_event->event_id.header.size);
0a4a9391 5958 if (ret)
c980d109 5959 goto out;
0a4a9391 5960
cdd6c482
IM
5961 mmap_event->event_id.pid = perf_event_pid(event, current);
5962 mmap_event->event_id.tid = perf_event_tid(event, current);
709e50cf 5963
cdd6c482 5964 perf_output_put(&handle, mmap_event->event_id);
13d7a241
SE
5965
5966 if (event->attr.mmap2) {
5967 perf_output_put(&handle, mmap_event->maj);
5968 perf_output_put(&handle, mmap_event->min);
5969 perf_output_put(&handle, mmap_event->ino);
5970 perf_output_put(&handle, mmap_event->ino_generation);
f972eb63
PZ
5971 perf_output_put(&handle, mmap_event->prot);
5972 perf_output_put(&handle, mmap_event->flags);
13d7a241
SE
5973 }
5974
76369139 5975 __output_copy(&handle, mmap_event->file_name,
0a4a9391 5976 mmap_event->file_size);
c980d109
ACM
5977
5978 perf_event__output_id_sample(event, &handle, &sample);
5979
78d613eb 5980 perf_output_end(&handle);
c980d109
ACM
5981out:
5982 mmap_event->event_id.header.size = size;
0a4a9391
PZ
5983}
5984
cdd6c482 5985static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
0a4a9391 5986{
089dd79d
PZ
5987 struct vm_area_struct *vma = mmap_event->vma;
5988 struct file *file = vma->vm_file;
13d7a241
SE
5989 int maj = 0, min = 0;
5990 u64 ino = 0, gen = 0;
f972eb63 5991 u32 prot = 0, flags = 0;
0a4a9391
PZ
5992 unsigned int size;
5993 char tmp[16];
5994 char *buf = NULL;
2c42cfbf 5995 char *name;
413ee3b4 5996
0a4a9391 5997 if (file) {
13d7a241
SE
5998 struct inode *inode;
5999 dev_t dev;
3ea2f2b9 6000
2c42cfbf 6001 buf = kmalloc(PATH_MAX, GFP_KERNEL);
0a4a9391 6002 if (!buf) {
c7e548b4
ON
6003 name = "//enomem";
6004 goto cpy_name;
0a4a9391 6005 }
413ee3b4 6006 /*
3ea2f2b9 6007 * d_path() works from the end of the rb backwards, so we
413ee3b4
AB
6008 * need to add enough zero bytes after the string to handle
6009 * the 64bit alignment we do later.
6010 */
9bf39ab2 6011 name = file_path(file, buf, PATH_MAX - sizeof(u64));
0a4a9391 6012 if (IS_ERR(name)) {
c7e548b4
ON
6013 name = "//toolong";
6014 goto cpy_name;
0a4a9391 6015 }
13d7a241
SE
6016 inode = file_inode(vma->vm_file);
6017 dev = inode->i_sb->s_dev;
6018 ino = inode->i_ino;
6019 gen = inode->i_generation;
6020 maj = MAJOR(dev);
6021 min = MINOR(dev);
f972eb63
PZ
6022
6023 if (vma->vm_flags & VM_READ)
6024 prot |= PROT_READ;
6025 if (vma->vm_flags & VM_WRITE)
6026 prot |= PROT_WRITE;
6027 if (vma->vm_flags & VM_EXEC)
6028 prot |= PROT_EXEC;
6029
6030 if (vma->vm_flags & VM_MAYSHARE)
6031 flags = MAP_SHARED;
6032 else
6033 flags = MAP_PRIVATE;
6034
6035 if (vma->vm_flags & VM_DENYWRITE)
6036 flags |= MAP_DENYWRITE;
6037 if (vma->vm_flags & VM_MAYEXEC)
6038 flags |= MAP_EXECUTABLE;
6039 if (vma->vm_flags & VM_LOCKED)
6040 flags |= MAP_LOCKED;
6041 if (vma->vm_flags & VM_HUGETLB)
6042 flags |= MAP_HUGETLB;
6043
c7e548b4 6044 goto got_name;
0a4a9391 6045 } else {
fbe26abe
JO
6046 if (vma->vm_ops && vma->vm_ops->name) {
6047 name = (char *) vma->vm_ops->name(vma);
6048 if (name)
6049 goto cpy_name;
6050 }
6051
2c42cfbf 6052 name = (char *)arch_vma_name(vma);
c7e548b4
ON
6053 if (name)
6054 goto cpy_name;
089dd79d 6055
32c5fb7e 6056 if (vma->vm_start <= vma->vm_mm->start_brk &&
3af9e859 6057 vma->vm_end >= vma->vm_mm->brk) {
c7e548b4
ON
6058 name = "[heap]";
6059 goto cpy_name;
32c5fb7e
ON
6060 }
6061 if (vma->vm_start <= vma->vm_mm->start_stack &&
3af9e859 6062 vma->vm_end >= vma->vm_mm->start_stack) {
c7e548b4
ON
6063 name = "[stack]";
6064 goto cpy_name;
089dd79d
PZ
6065 }
6066
c7e548b4
ON
6067 name = "//anon";
6068 goto cpy_name;
0a4a9391
PZ
6069 }
6070
c7e548b4
ON
6071cpy_name:
6072 strlcpy(tmp, name, sizeof(tmp));
6073 name = tmp;
0a4a9391 6074got_name:
2c42cfbf
PZ
6075 /*
6076 * Since our buffer works in 8 byte units we need to align our string
6077 * size to a multiple of 8. However, we must guarantee the tail end is
6078 * zero'd out to avoid leaking random bits to userspace.
6079 */
6080 size = strlen(name)+1;
6081 while (!IS_ALIGNED(size, sizeof(u64)))
6082 name[size++] = '\0';
0a4a9391
PZ
6083
6084 mmap_event->file_name = name;
6085 mmap_event->file_size = size;
13d7a241
SE
6086 mmap_event->maj = maj;
6087 mmap_event->min = min;
6088 mmap_event->ino = ino;
6089 mmap_event->ino_generation = gen;
f972eb63
PZ
6090 mmap_event->prot = prot;
6091 mmap_event->flags = flags;
0a4a9391 6092
2fe85427
SE
6093 if (!(vma->vm_flags & VM_EXEC))
6094 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
6095
cdd6c482 6096 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
0a4a9391 6097
67516844 6098 perf_event_aux(perf_event_mmap_output,
52d857a8
JO
6099 mmap_event,
6100 NULL);
665c2142 6101
0a4a9391
PZ
6102 kfree(buf);
6103}
6104
3af9e859 6105void perf_event_mmap(struct vm_area_struct *vma)
0a4a9391 6106{
9ee318a7
PZ
6107 struct perf_mmap_event mmap_event;
6108
cdd6c482 6109 if (!atomic_read(&nr_mmap_events))
9ee318a7
PZ
6110 return;
6111
6112 mmap_event = (struct perf_mmap_event){
089dd79d 6113 .vma = vma,
573402db
PZ
6114 /* .file_name */
6115 /* .file_size */
cdd6c482 6116 .event_id = {
573402db 6117 .header = {
cdd6c482 6118 .type = PERF_RECORD_MMAP,
39447b38 6119 .misc = PERF_RECORD_MISC_USER,
573402db
PZ
6120 /* .size */
6121 },
6122 /* .pid */
6123 /* .tid */
089dd79d
PZ
6124 .start = vma->vm_start,
6125 .len = vma->vm_end - vma->vm_start,
3a0304e9 6126 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
0a4a9391 6127 },
13d7a241
SE
6128 /* .maj (attr_mmap2 only) */
6129 /* .min (attr_mmap2 only) */
6130 /* .ino (attr_mmap2 only) */
6131 /* .ino_generation (attr_mmap2 only) */
f972eb63
PZ
6132 /* .prot (attr_mmap2 only) */
6133 /* .flags (attr_mmap2 only) */
0a4a9391
PZ
6134 };
6135
cdd6c482 6136 perf_event_mmap_event(&mmap_event);
0a4a9391
PZ
6137}
6138
68db7e98
AS
6139void perf_event_aux_event(struct perf_event *event, unsigned long head,
6140 unsigned long size, u64 flags)
6141{
6142 struct perf_output_handle handle;
6143 struct perf_sample_data sample;
6144 struct perf_aux_event {
6145 struct perf_event_header header;
6146 u64 offset;
6147 u64 size;
6148 u64 flags;
6149 } rec = {
6150 .header = {
6151 .type = PERF_RECORD_AUX,
6152 .misc = 0,
6153 .size = sizeof(rec),
6154 },
6155 .offset = head,
6156 .size = size,
6157 .flags = flags,
6158 };
6159 int ret;
6160
6161 perf_event_header__init_id(&rec.header, &sample, event);
6162 ret = perf_output_begin(&handle, event, rec.header.size);
6163
6164 if (ret)
6165 return;
6166
6167 perf_output_put(&handle, rec);
6168 perf_event__output_id_sample(event, &handle, &sample);
6169
6170 perf_output_end(&handle);
6171}
6172
f38b0dbb
KL
6173/*
6174 * Lost/dropped samples logging
6175 */
6176void perf_log_lost_samples(struct perf_event *event, u64 lost)
6177{
6178 struct perf_output_handle handle;
6179 struct perf_sample_data sample;
6180 int ret;
6181
6182 struct {
6183 struct perf_event_header header;
6184 u64 lost;
6185 } lost_samples_event = {
6186 .header = {
6187 .type = PERF_RECORD_LOST_SAMPLES,
6188 .misc = 0,
6189 .size = sizeof(lost_samples_event),
6190 },
6191 .lost = lost,
6192 };
6193
6194 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
6195
6196 ret = perf_output_begin(&handle, event,
6197 lost_samples_event.header.size);
6198 if (ret)
6199 return;
6200
6201 perf_output_put(&handle, lost_samples_event);
6202 perf_event__output_id_sample(event, &handle, &sample);
6203 perf_output_end(&handle);
6204}
6205
45ac1403
AH
6206/*
6207 * context_switch tracking
6208 */
6209
6210struct perf_switch_event {
6211 struct task_struct *task;
6212 struct task_struct *next_prev;
6213
6214 struct {
6215 struct perf_event_header header;
6216 u32 next_prev_pid;
6217 u32 next_prev_tid;
6218 } event_id;
6219};
6220
6221static int perf_event_switch_match(struct perf_event *event)
6222{
6223 return event->attr.context_switch;
6224}
6225
6226static void perf_event_switch_output(struct perf_event *event, void *data)
6227{
6228 struct perf_switch_event *se = data;
6229 struct perf_output_handle handle;
6230 struct perf_sample_data sample;
6231 int ret;
6232
6233 if (!perf_event_switch_match(event))
6234 return;
6235
6236 /* Only CPU-wide events are allowed to see next/prev pid/tid */
6237 if (event->ctx->task) {
6238 se->event_id.header.type = PERF_RECORD_SWITCH;
6239 se->event_id.header.size = sizeof(se->event_id.header);
6240 } else {
6241 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
6242 se->event_id.header.size = sizeof(se->event_id);
6243 se->event_id.next_prev_pid =
6244 perf_event_pid(event, se->next_prev);
6245 se->event_id.next_prev_tid =
6246 perf_event_tid(event, se->next_prev);
6247 }
6248
6249 perf_event_header__init_id(&se->event_id.header, &sample, event);
6250
6251 ret = perf_output_begin(&handle, event, se->event_id.header.size);
6252 if (ret)
6253 return;
6254
6255 if (event->ctx->task)
6256 perf_output_put(&handle, se->event_id.header);
6257 else
6258 perf_output_put(&handle, se->event_id);
6259
6260 perf_event__output_id_sample(event, &handle, &sample);
6261
6262 perf_output_end(&handle);
6263}
6264
6265static void perf_event_switch(struct task_struct *task,
6266 struct task_struct *next_prev, bool sched_in)
6267{
6268 struct perf_switch_event switch_event;
6269
6270 /* N.B. caller checks nr_switch_events != 0 */
6271
6272 switch_event = (struct perf_switch_event){
6273 .task = task,
6274 .next_prev = next_prev,
6275 .event_id = {
6276 .header = {
6277 /* .type */
6278 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
6279 /* .size */
6280 },
6281 /* .next_prev_pid */
6282 /* .next_prev_tid */
6283 },
6284 };
6285
6286 perf_event_aux(perf_event_switch_output,
6287 &switch_event,
6288 NULL);
6289}
6290
a78ac325
PZ
6291/*
6292 * IRQ throttle logging
6293 */
6294
cdd6c482 6295static void perf_log_throttle(struct perf_event *event, int enable)
a78ac325
PZ
6296{
6297 struct perf_output_handle handle;
c980d109 6298 struct perf_sample_data sample;
a78ac325
PZ
6299 int ret;
6300
6301 struct {
6302 struct perf_event_header header;
6303 u64 time;
cca3f454 6304 u64 id;
7f453c24 6305 u64 stream_id;
a78ac325
PZ
6306 } throttle_event = {
6307 .header = {
cdd6c482 6308 .type = PERF_RECORD_THROTTLE,
a78ac325
PZ
6309 .misc = 0,
6310 .size = sizeof(throttle_event),
6311 },
34f43927 6312 .time = perf_event_clock(event),
cdd6c482
IM
6313 .id = primary_event_id(event),
6314 .stream_id = event->id,
a78ac325
PZ
6315 };
6316
966ee4d6 6317 if (enable)
cdd6c482 6318 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
966ee4d6 6319
c980d109
ACM
6320 perf_event_header__init_id(&throttle_event.header, &sample, event);
6321
6322 ret = perf_output_begin(&handle, event,
a7ac67ea 6323 throttle_event.header.size);
a78ac325
PZ
6324 if (ret)
6325 return;
6326
6327 perf_output_put(&handle, throttle_event);
c980d109 6328 perf_event__output_id_sample(event, &handle, &sample);
a78ac325
PZ
6329 perf_output_end(&handle);
6330}
6331
ec0d7729
AS
6332static void perf_log_itrace_start(struct perf_event *event)
6333{
6334 struct perf_output_handle handle;
6335 struct perf_sample_data sample;
6336 struct perf_aux_event {
6337 struct perf_event_header header;
6338 u32 pid;
6339 u32 tid;
6340 } rec;
6341 int ret;
6342
6343 if (event->parent)
6344 event = event->parent;
6345
6346 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
6347 event->hw.itrace_started)
6348 return;
6349
ec0d7729
AS
6350 rec.header.type = PERF_RECORD_ITRACE_START;
6351 rec.header.misc = 0;
6352 rec.header.size = sizeof(rec);
6353 rec.pid = perf_event_pid(event, current);
6354 rec.tid = perf_event_tid(event, current);
6355
6356 perf_event_header__init_id(&rec.header, &sample, event);
6357 ret = perf_output_begin(&handle, event, rec.header.size);
6358
6359 if (ret)
6360 return;
6361
6362 perf_output_put(&handle, rec);
6363 perf_event__output_id_sample(event, &handle, &sample);
6364
6365 perf_output_end(&handle);
6366}
6367
f6c7d5fe 6368/*
cdd6c482 6369 * Generic event overflow handling, sampling.
f6c7d5fe
PZ
6370 */
6371
a8b0ca17 6372static int __perf_event_overflow(struct perf_event *event,
5622f295
MM
6373 int throttle, struct perf_sample_data *data,
6374 struct pt_regs *regs)
f6c7d5fe 6375{
cdd6c482
IM
6376 int events = atomic_read(&event->event_limit);
6377 struct hw_perf_event *hwc = &event->hw;
e050e3f0 6378 u64 seq;
79f14641
PZ
6379 int ret = 0;
6380
96398826
PZ
6381 /*
6382 * Non-sampling counters might still use the PMI to fold short
6383 * hardware counters, ignore those.
6384 */
6385 if (unlikely(!is_sampling_event(event)))
6386 return 0;
6387
e050e3f0
SE
6388 seq = __this_cpu_read(perf_throttled_seq);
6389 if (seq != hwc->interrupts_seq) {
6390 hwc->interrupts_seq = seq;
6391 hwc->interrupts = 1;
6392 } else {
6393 hwc->interrupts++;
6394 if (unlikely(throttle
6395 && hwc->interrupts >= max_samples_per_tick)) {
6396 __this_cpu_inc(perf_throttled_count);
163ec435
PZ
6397 hwc->interrupts = MAX_INTERRUPTS;
6398 perf_log_throttle(event, 0);
d84153d6 6399 tick_nohz_full_kick();
a78ac325
PZ
6400 ret = 1;
6401 }
e050e3f0 6402 }
60db5e09 6403
cdd6c482 6404 if (event->attr.freq) {
def0a9b2 6405 u64 now = perf_clock();
abd50713 6406 s64 delta = now - hwc->freq_time_stamp;
bd2b5b12 6407
abd50713 6408 hwc->freq_time_stamp = now;
bd2b5b12 6409
abd50713 6410 if (delta > 0 && delta < 2*TICK_NSEC)
f39d47ff 6411 perf_adjust_period(event, delta, hwc->last_period, true);
bd2b5b12
PZ
6412 }
6413
2023b359
PZ
6414 /*
6415 * XXX event_limit might not quite work as expected on inherited
cdd6c482 6416 * events
2023b359
PZ
6417 */
6418
cdd6c482
IM
6419 event->pending_kill = POLL_IN;
6420 if (events && atomic_dec_and_test(&event->event_limit)) {
79f14641 6421 ret = 1;
cdd6c482 6422 event->pending_kill = POLL_HUP;
a8b0ca17
PZ
6423 event->pending_disable = 1;
6424 irq_work_queue(&event->pending);
79f14641
PZ
6425 }
6426
453f19ee 6427 if (event->overflow_handler)
a8b0ca17 6428 event->overflow_handler(event, data, regs);
453f19ee 6429 else
a8b0ca17 6430 perf_event_output(event, data, regs);
453f19ee 6431
fed66e2c 6432 if (*perf_event_fasync(event) && event->pending_kill) {
a8b0ca17
PZ
6433 event->pending_wakeup = 1;
6434 irq_work_queue(&event->pending);
f506b3dc
PZ
6435 }
6436
79f14641 6437 return ret;
f6c7d5fe
PZ
6438}
6439
a8b0ca17 6440int perf_event_overflow(struct perf_event *event,
5622f295
MM
6441 struct perf_sample_data *data,
6442 struct pt_regs *regs)
850bc73f 6443{
a8b0ca17 6444 return __perf_event_overflow(event, 1, data, regs);
850bc73f
PZ
6445}
6446
15dbf27c 6447/*
cdd6c482 6448 * Generic software event infrastructure
15dbf27c
PZ
6449 */
6450
b28ab83c
PZ
6451struct swevent_htable {
6452 struct swevent_hlist *swevent_hlist;
6453 struct mutex hlist_mutex;
6454 int hlist_refcount;
6455
6456 /* Recursion avoidance in each contexts */
6457 int recursion[PERF_NR_CONTEXTS];
6458};
6459
6460static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
6461
7b4b6658 6462/*
cdd6c482
IM
6463 * We directly increment event->count and keep a second value in
6464 * event->hw.period_left to count intervals. This period event
7b4b6658
PZ
6465 * is kept in the range [-sample_period, 0] so that we can use the
6466 * sign as trigger.
6467 */
6468
ab573844 6469u64 perf_swevent_set_period(struct perf_event *event)
15dbf27c 6470{
cdd6c482 6471 struct hw_perf_event *hwc = &event->hw;
7b4b6658
PZ
6472 u64 period = hwc->last_period;
6473 u64 nr, offset;
6474 s64 old, val;
6475
6476 hwc->last_period = hwc->sample_period;
15dbf27c
PZ
6477
6478again:
e7850595 6479 old = val = local64_read(&hwc->period_left);
7b4b6658
PZ
6480 if (val < 0)
6481 return 0;
15dbf27c 6482
7b4b6658
PZ
6483 nr = div64_u64(period + val, period);
6484 offset = nr * period;
6485 val -= offset;
e7850595 6486 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
7b4b6658 6487 goto again;
15dbf27c 6488
7b4b6658 6489 return nr;
15dbf27c
PZ
6490}
6491
0cff784a 6492static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
a8b0ca17 6493 struct perf_sample_data *data,
5622f295 6494 struct pt_regs *regs)
15dbf27c 6495{
cdd6c482 6496 struct hw_perf_event *hwc = &event->hw;
850bc73f 6497 int throttle = 0;
15dbf27c 6498
0cff784a
PZ
6499 if (!overflow)
6500 overflow = perf_swevent_set_period(event);
15dbf27c 6501
7b4b6658
PZ
6502 if (hwc->interrupts == MAX_INTERRUPTS)
6503 return;
15dbf27c 6504
7b4b6658 6505 for (; overflow; overflow--) {
a8b0ca17 6506 if (__perf_event_overflow(event, throttle,
5622f295 6507 data, regs)) {
7b4b6658
PZ
6508 /*
6509 * We inhibit the overflow from happening when
6510 * hwc->interrupts == MAX_INTERRUPTS.
6511 */
6512 break;
6513 }
cf450a73 6514 throttle = 1;
7b4b6658 6515 }
15dbf27c
PZ
6516}
6517
a4eaf7f1 6518static void perf_swevent_event(struct perf_event *event, u64 nr,
a8b0ca17 6519 struct perf_sample_data *data,
5622f295 6520 struct pt_regs *regs)
7b4b6658 6521{
cdd6c482 6522 struct hw_perf_event *hwc = &event->hw;
d6d020e9 6523
e7850595 6524 local64_add(nr, &event->count);
d6d020e9 6525
0cff784a
PZ
6526 if (!regs)
6527 return;
6528
6c7e550f 6529 if (!is_sampling_event(event))
7b4b6658 6530 return;
d6d020e9 6531
5d81e5cf
AV
6532 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
6533 data->period = nr;
6534 return perf_swevent_overflow(event, 1, data, regs);
6535 } else
6536 data->period = event->hw.last_period;
6537
0cff784a 6538 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
a8b0ca17 6539 return perf_swevent_overflow(event, 1, data, regs);
0cff784a 6540
e7850595 6541 if (local64_add_negative(nr, &hwc->period_left))
7b4b6658 6542 return;
df1a132b 6543
a8b0ca17 6544 perf_swevent_overflow(event, 0, data, regs);
d6d020e9
PZ
6545}
6546
f5ffe02e
FW
6547static int perf_exclude_event(struct perf_event *event,
6548 struct pt_regs *regs)
6549{
a4eaf7f1 6550 if (event->hw.state & PERF_HES_STOPPED)
91b2f482 6551 return 1;
a4eaf7f1 6552
f5ffe02e
FW
6553 if (regs) {
6554 if (event->attr.exclude_user && user_mode(regs))
6555 return 1;
6556
6557 if (event->attr.exclude_kernel && !user_mode(regs))
6558 return 1;
6559 }
6560
6561 return 0;
6562}
6563
cdd6c482 6564static int perf_swevent_match(struct perf_event *event,
1c432d89 6565 enum perf_type_id type,
6fb2915d
LZ
6566 u32 event_id,
6567 struct perf_sample_data *data,
6568 struct pt_regs *regs)
15dbf27c 6569{
cdd6c482 6570 if (event->attr.type != type)
a21ca2ca 6571 return 0;
f5ffe02e 6572
cdd6c482 6573 if (event->attr.config != event_id)
15dbf27c
PZ
6574 return 0;
6575
f5ffe02e
FW
6576 if (perf_exclude_event(event, regs))
6577 return 0;
15dbf27c
PZ
6578
6579 return 1;
6580}
6581
76e1d904
FW
6582static inline u64 swevent_hash(u64 type, u32 event_id)
6583{
6584 u64 val = event_id | (type << 32);
6585
6586 return hash_64(val, SWEVENT_HLIST_BITS);
6587}
6588
49f135ed
FW
6589static inline struct hlist_head *
6590__find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
76e1d904 6591{
49f135ed
FW
6592 u64 hash = swevent_hash(type, event_id);
6593
6594 return &hlist->heads[hash];
6595}
76e1d904 6596
49f135ed
FW
6597/* For the read side: events when they trigger */
6598static inline struct hlist_head *
b28ab83c 6599find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
49f135ed
FW
6600{
6601 struct swevent_hlist *hlist;
76e1d904 6602
b28ab83c 6603 hlist = rcu_dereference(swhash->swevent_hlist);
76e1d904
FW
6604 if (!hlist)
6605 return NULL;
6606
49f135ed
FW
6607 return __find_swevent_head(hlist, type, event_id);
6608}
6609
6610/* For the event head insertion and removal in the hlist */
6611static inline struct hlist_head *
b28ab83c 6612find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
49f135ed
FW
6613{
6614 struct swevent_hlist *hlist;
6615 u32 event_id = event->attr.config;
6616 u64 type = event->attr.type;
6617
6618 /*
6619 * Event scheduling is always serialized against hlist allocation
6620 * and release. Which makes the protected version suitable here.
6621 * The context lock guarantees that.
6622 */
b28ab83c 6623 hlist = rcu_dereference_protected(swhash->swevent_hlist,
49f135ed
FW
6624 lockdep_is_held(&event->ctx->lock));
6625 if (!hlist)
6626 return NULL;
6627
6628 return __find_swevent_head(hlist, type, event_id);
76e1d904
FW
6629}
6630
6631static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
a8b0ca17 6632 u64 nr,
76e1d904
FW
6633 struct perf_sample_data *data,
6634 struct pt_regs *regs)
15dbf27c 6635{
4a32fea9 6636 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
cdd6c482 6637 struct perf_event *event;
76e1d904 6638 struct hlist_head *head;
15dbf27c 6639
76e1d904 6640 rcu_read_lock();
b28ab83c 6641 head = find_swevent_head_rcu(swhash, type, event_id);
76e1d904
FW
6642 if (!head)
6643 goto end;
6644
b67bfe0d 6645 hlist_for_each_entry_rcu(event, head, hlist_entry) {
6fb2915d 6646 if (perf_swevent_match(event, type, event_id, data, regs))
a8b0ca17 6647 perf_swevent_event(event, nr, data, regs);
15dbf27c 6648 }
76e1d904
FW
6649end:
6650 rcu_read_unlock();
15dbf27c
PZ
6651}
6652
86038c5e
PZI
6653DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
6654
4ed7c92d 6655int perf_swevent_get_recursion_context(void)
96f6d444 6656{
4a32fea9 6657 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
96f6d444 6658
b28ab83c 6659 return get_recursion_context(swhash->recursion);
96f6d444 6660}
645e8cc0 6661EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
96f6d444 6662
fa9f90be 6663inline void perf_swevent_put_recursion_context(int rctx)
15dbf27c 6664{
4a32fea9 6665 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
927c7a9e 6666
b28ab83c 6667 put_recursion_context(swhash->recursion, rctx);
ce71b9df 6668}
15dbf27c 6669
86038c5e 6670void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
b8e83514 6671{
a4234bfc 6672 struct perf_sample_data data;
4ed7c92d 6673
86038c5e 6674 if (WARN_ON_ONCE(!regs))
4ed7c92d 6675 return;
a4234bfc 6676
fd0d000b 6677 perf_sample_data_init(&data, addr, 0);
a8b0ca17 6678 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
86038c5e
PZI
6679}
6680
6681void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
6682{
6683 int rctx;
6684
6685 preempt_disable_notrace();
6686 rctx = perf_swevent_get_recursion_context();
6687 if (unlikely(rctx < 0))
6688 goto fail;
6689
6690 ___perf_sw_event(event_id, nr, regs, addr);
4ed7c92d
PZ
6691
6692 perf_swevent_put_recursion_context(rctx);
86038c5e 6693fail:
1c024eca 6694 preempt_enable_notrace();
b8e83514
PZ
6695}
6696
cdd6c482 6697static void perf_swevent_read(struct perf_event *event)
15dbf27c 6698{
15dbf27c
PZ
6699}
6700
a4eaf7f1 6701static int perf_swevent_add(struct perf_event *event, int flags)
15dbf27c 6702{
4a32fea9 6703 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
cdd6c482 6704 struct hw_perf_event *hwc = &event->hw;
76e1d904
FW
6705 struct hlist_head *head;
6706
6c7e550f 6707 if (is_sampling_event(event)) {
7b4b6658 6708 hwc->last_period = hwc->sample_period;
cdd6c482 6709 perf_swevent_set_period(event);
7b4b6658 6710 }
76e1d904 6711
a4eaf7f1
PZ
6712 hwc->state = !(flags & PERF_EF_START);
6713
b28ab83c 6714 head = find_swevent_head(swhash, event);
12ca6ad2 6715 if (WARN_ON_ONCE(!head))
76e1d904
FW
6716 return -EINVAL;
6717
6718 hlist_add_head_rcu(&event->hlist_entry, head);
6a694a60 6719 perf_event_update_userpage(event);
76e1d904 6720
15dbf27c
PZ
6721 return 0;
6722}
6723
a4eaf7f1 6724static void perf_swevent_del(struct perf_event *event, int flags)
15dbf27c 6725{
76e1d904 6726 hlist_del_rcu(&event->hlist_entry);
15dbf27c
PZ
6727}
6728
a4eaf7f1 6729static void perf_swevent_start(struct perf_event *event, int flags)
5c92d124 6730{
a4eaf7f1 6731 event->hw.state = 0;
d6d020e9 6732}
aa9c4c0f 6733
a4eaf7f1 6734static void perf_swevent_stop(struct perf_event *event, int flags)
d6d020e9 6735{
a4eaf7f1 6736 event->hw.state = PERF_HES_STOPPED;
bae43c99
IM
6737}
6738
49f135ed
FW
6739/* Deref the hlist from the update side */
6740static inline struct swevent_hlist *
b28ab83c 6741swevent_hlist_deref(struct swevent_htable *swhash)
49f135ed 6742{
b28ab83c
PZ
6743 return rcu_dereference_protected(swhash->swevent_hlist,
6744 lockdep_is_held(&swhash->hlist_mutex));
49f135ed
FW
6745}
6746
b28ab83c 6747static void swevent_hlist_release(struct swevent_htable *swhash)
76e1d904 6748{
b28ab83c 6749 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
76e1d904 6750
49f135ed 6751 if (!hlist)
76e1d904
FW
6752 return;
6753
70691d4a 6754 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
fa4bbc4c 6755 kfree_rcu(hlist, rcu_head);
76e1d904
FW
6756}
6757
6758static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
6759{
b28ab83c 6760 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
76e1d904 6761
b28ab83c 6762 mutex_lock(&swhash->hlist_mutex);
76e1d904 6763
b28ab83c
PZ
6764 if (!--swhash->hlist_refcount)
6765 swevent_hlist_release(swhash);
76e1d904 6766
b28ab83c 6767 mutex_unlock(&swhash->hlist_mutex);
76e1d904
FW
6768}
6769
6770static void swevent_hlist_put(struct perf_event *event)
6771{
6772 int cpu;
6773
76e1d904
FW
6774 for_each_possible_cpu(cpu)
6775 swevent_hlist_put_cpu(event, cpu);
6776}
6777
6778static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
6779{
b28ab83c 6780 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
76e1d904
FW
6781 int err = 0;
6782
b28ab83c 6783 mutex_lock(&swhash->hlist_mutex);
b28ab83c 6784 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
76e1d904
FW
6785 struct swevent_hlist *hlist;
6786
6787 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
6788 if (!hlist) {
6789 err = -ENOMEM;
6790 goto exit;
6791 }
b28ab83c 6792 rcu_assign_pointer(swhash->swevent_hlist, hlist);
76e1d904 6793 }
b28ab83c 6794 swhash->hlist_refcount++;
9ed6060d 6795exit:
b28ab83c 6796 mutex_unlock(&swhash->hlist_mutex);
76e1d904
FW
6797
6798 return err;
6799}
6800
6801static int swevent_hlist_get(struct perf_event *event)
6802{
6803 int err;
6804 int cpu, failed_cpu;
6805
76e1d904
FW
6806 get_online_cpus();
6807 for_each_possible_cpu(cpu) {
6808 err = swevent_hlist_get_cpu(event, cpu);
6809 if (err) {
6810 failed_cpu = cpu;
6811 goto fail;
6812 }
6813 }
6814 put_online_cpus();
6815
6816 return 0;
9ed6060d 6817fail:
76e1d904
FW
6818 for_each_possible_cpu(cpu) {
6819 if (cpu == failed_cpu)
6820 break;
6821 swevent_hlist_put_cpu(event, cpu);
6822 }
6823
6824 put_online_cpus();
6825 return err;
6826}
6827
c5905afb 6828struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
95476b64 6829
b0a873eb
PZ
6830static void sw_perf_event_destroy(struct perf_event *event)
6831{
6832 u64 event_id = event->attr.config;
95476b64 6833
b0a873eb
PZ
6834 WARN_ON(event->parent);
6835
c5905afb 6836 static_key_slow_dec(&perf_swevent_enabled[event_id]);
b0a873eb
PZ
6837 swevent_hlist_put(event);
6838}
6839
6840static int perf_swevent_init(struct perf_event *event)
6841{
8176cced 6842 u64 event_id = event->attr.config;
b0a873eb
PZ
6843
6844 if (event->attr.type != PERF_TYPE_SOFTWARE)
6845 return -ENOENT;
6846
2481c5fa
SE
6847 /*
6848 * no branch sampling for software events
6849 */
6850 if (has_branch_stack(event))
6851 return -EOPNOTSUPP;
6852
b0a873eb
PZ
6853 switch (event_id) {
6854 case PERF_COUNT_SW_CPU_CLOCK:
6855 case PERF_COUNT_SW_TASK_CLOCK:
6856 return -ENOENT;
6857
6858 default:
6859 break;
6860 }
6861
ce677831 6862 if (event_id >= PERF_COUNT_SW_MAX)
b0a873eb
PZ
6863 return -ENOENT;
6864
6865 if (!event->parent) {
6866 int err;
6867
6868 err = swevent_hlist_get(event);
6869 if (err)
6870 return err;
6871
c5905afb 6872 static_key_slow_inc(&perf_swevent_enabled[event_id]);
b0a873eb
PZ
6873 event->destroy = sw_perf_event_destroy;
6874 }
6875
6876 return 0;
6877}
6878
6879static struct pmu perf_swevent = {
89a1e187 6880 .task_ctx_nr = perf_sw_context,
95476b64 6881
34f43927
PZ
6882 .capabilities = PERF_PMU_CAP_NO_NMI,
6883
b0a873eb 6884 .event_init = perf_swevent_init,
a4eaf7f1
PZ
6885 .add = perf_swevent_add,
6886 .del = perf_swevent_del,
6887 .start = perf_swevent_start,
6888 .stop = perf_swevent_stop,
1c024eca 6889 .read = perf_swevent_read,
1c024eca
PZ
6890};
6891
b0a873eb
PZ
6892#ifdef CONFIG_EVENT_TRACING
6893
1c024eca
PZ
6894static int perf_tp_filter_match(struct perf_event *event,
6895 struct perf_sample_data *data)
6896{
6897 void *record = data->raw->data;
6898
b71b437e
PZ
6899 /* only top level events have filters set */
6900 if (event->parent)
6901 event = event->parent;
6902
1c024eca
PZ
6903 if (likely(!event->filter) || filter_match_preds(event->filter, record))
6904 return 1;
6905 return 0;
6906}
6907
6908static int perf_tp_event_match(struct perf_event *event,
6909 struct perf_sample_data *data,
6910 struct pt_regs *regs)
6911{
a0f7d0f7
FW
6912 if (event->hw.state & PERF_HES_STOPPED)
6913 return 0;
580d607c
PZ
6914 /*
6915 * All tracepoints are from kernel-space.
6916 */
6917 if (event->attr.exclude_kernel)
1c024eca
PZ
6918 return 0;
6919
6920 if (!perf_tp_filter_match(event, data))
6921 return 0;
6922
6923 return 1;
6924}
6925
6926void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
e6dab5ff
AV
6927 struct pt_regs *regs, struct hlist_head *head, int rctx,
6928 struct task_struct *task)
95476b64
FW
6929{
6930 struct perf_sample_data data;
1c024eca 6931 struct perf_event *event;
1c024eca 6932
95476b64
FW
6933 struct perf_raw_record raw = {
6934 .size = entry_size,
6935 .data = record,
6936 };
6937
fd0d000b 6938 perf_sample_data_init(&data, addr, 0);
95476b64
FW
6939 data.raw = &raw;
6940
b67bfe0d 6941 hlist_for_each_entry_rcu(event, head, hlist_entry) {
1c024eca 6942 if (perf_tp_event_match(event, &data, regs))
a8b0ca17 6943 perf_swevent_event(event, count, &data, regs);
4f41c013 6944 }
ecc55f84 6945
e6dab5ff
AV
6946 /*
6947 * If we got specified a target task, also iterate its context and
6948 * deliver this event there too.
6949 */
6950 if (task && task != current) {
6951 struct perf_event_context *ctx;
6952 struct trace_entry *entry = record;
6953
6954 rcu_read_lock();
6955 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
6956 if (!ctx)
6957 goto unlock;
6958
6959 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6960 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6961 continue;
6962 if (event->attr.config != entry->type)
6963 continue;
6964 if (perf_tp_event_match(event, &data, regs))
6965 perf_swevent_event(event, count, &data, regs);
6966 }
6967unlock:
6968 rcu_read_unlock();
6969 }
6970
ecc55f84 6971 perf_swevent_put_recursion_context(rctx);
95476b64
FW
6972}
6973EXPORT_SYMBOL_GPL(perf_tp_event);
6974
cdd6c482 6975static void tp_perf_event_destroy(struct perf_event *event)
e077df4f 6976{
1c024eca 6977 perf_trace_destroy(event);
e077df4f
PZ
6978}
6979
b0a873eb 6980static int perf_tp_event_init(struct perf_event *event)
e077df4f 6981{
76e1d904
FW
6982 int err;
6983
b0a873eb
PZ
6984 if (event->attr.type != PERF_TYPE_TRACEPOINT)
6985 return -ENOENT;
6986
2481c5fa
SE
6987 /*
6988 * no branch sampling for tracepoint events
6989 */
6990 if (has_branch_stack(event))
6991 return -EOPNOTSUPP;
6992
1c024eca
PZ
6993 err = perf_trace_init(event);
6994 if (err)
b0a873eb 6995 return err;
e077df4f 6996
cdd6c482 6997 event->destroy = tp_perf_event_destroy;
e077df4f 6998
b0a873eb
PZ
6999 return 0;
7000}
7001
7002static struct pmu perf_tracepoint = {
89a1e187
PZ
7003 .task_ctx_nr = perf_sw_context,
7004
b0a873eb 7005 .event_init = perf_tp_event_init,
a4eaf7f1
PZ
7006 .add = perf_trace_add,
7007 .del = perf_trace_del,
7008 .start = perf_swevent_start,
7009 .stop = perf_swevent_stop,
b0a873eb 7010 .read = perf_swevent_read,
b0a873eb
PZ
7011};
7012
7013static inline void perf_tp_register(void)
7014{
2e80a82a 7015 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
e077df4f 7016}
6fb2915d
LZ
7017
7018static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7019{
7020 char *filter_str;
7021 int ret;
7022
7023 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7024 return -EINVAL;
7025
7026 filter_str = strndup_user(arg, PAGE_SIZE);
7027 if (IS_ERR(filter_str))
7028 return PTR_ERR(filter_str);
7029
7030 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
7031
7032 kfree(filter_str);
7033 return ret;
7034}
7035
7036static void perf_event_free_filter(struct perf_event *event)
7037{
7038 ftrace_profile_free_filter(event);
7039}
7040
2541517c
AS
7041static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7042{
7043 struct bpf_prog *prog;
7044
7045 if (event->attr.type != PERF_TYPE_TRACEPOINT)
7046 return -EINVAL;
7047
7048 if (event->tp_event->prog)
7049 return -EEXIST;
7050
04a22fae
WN
7051 if (!(event->tp_event->flags & TRACE_EVENT_FL_UKPROBE))
7052 /* bpf programs can only be attached to u/kprobes */
2541517c
AS
7053 return -EINVAL;
7054
7055 prog = bpf_prog_get(prog_fd);
7056 if (IS_ERR(prog))
7057 return PTR_ERR(prog);
7058
6c373ca8 7059 if (prog->type != BPF_PROG_TYPE_KPROBE) {
2541517c
AS
7060 /* valid fd, but invalid bpf program type */
7061 bpf_prog_put(prog);
7062 return -EINVAL;
7063 }
7064
7065 event->tp_event->prog = prog;
7066
7067 return 0;
7068}
7069
7070static void perf_event_free_bpf_prog(struct perf_event *event)
7071{
7072 struct bpf_prog *prog;
7073
7074 if (!event->tp_event)
7075 return;
7076
7077 prog = event->tp_event->prog;
7078 if (prog) {
7079 event->tp_event->prog = NULL;
7080 bpf_prog_put(prog);
7081 }
7082}
7083
e077df4f 7084#else
6fb2915d 7085
b0a873eb 7086static inline void perf_tp_register(void)
e077df4f 7087{
e077df4f 7088}
6fb2915d
LZ
7089
7090static int perf_event_set_filter(struct perf_event *event, void __user *arg)
7091{
7092 return -ENOENT;
7093}
7094
7095static void perf_event_free_filter(struct perf_event *event)
7096{
7097}
7098
2541517c
AS
7099static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
7100{
7101 return -ENOENT;
7102}
7103
7104static void perf_event_free_bpf_prog(struct perf_event *event)
7105{
7106}
07b139c8 7107#endif /* CONFIG_EVENT_TRACING */
e077df4f 7108
24f1e32c 7109#ifdef CONFIG_HAVE_HW_BREAKPOINT
f5ffe02e 7110void perf_bp_event(struct perf_event *bp, void *data)
24f1e32c 7111{
f5ffe02e
FW
7112 struct perf_sample_data sample;
7113 struct pt_regs *regs = data;
7114
fd0d000b 7115 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
f5ffe02e 7116
a4eaf7f1 7117 if (!bp->hw.state && !perf_exclude_event(bp, regs))
a8b0ca17 7118 perf_swevent_event(bp, 1, &sample, regs);
24f1e32c
FW
7119}
7120#endif
7121
b0a873eb
PZ
7122/*
7123 * hrtimer based swevent callback
7124 */
f29ac756 7125
b0a873eb 7126static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
f29ac756 7127{
b0a873eb
PZ
7128 enum hrtimer_restart ret = HRTIMER_RESTART;
7129 struct perf_sample_data data;
7130 struct pt_regs *regs;
7131 struct perf_event *event;
7132 u64 period;
f29ac756 7133
b0a873eb 7134 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
ba3dd36c
PZ
7135
7136 if (event->state != PERF_EVENT_STATE_ACTIVE)
7137 return HRTIMER_NORESTART;
7138
b0a873eb 7139 event->pmu->read(event);
f344011c 7140
fd0d000b 7141 perf_sample_data_init(&data, 0, event->hw.last_period);
b0a873eb
PZ
7142 regs = get_irq_regs();
7143
7144 if (regs && !perf_exclude_event(event, regs)) {
77aeeebd 7145 if (!(event->attr.exclude_idle && is_idle_task(current)))
33b07b8b 7146 if (__perf_event_overflow(event, 1, &data, regs))
b0a873eb
PZ
7147 ret = HRTIMER_NORESTART;
7148 }
24f1e32c 7149
b0a873eb
PZ
7150 period = max_t(u64, 10000, event->hw.sample_period);
7151 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
24f1e32c 7152
b0a873eb 7153 return ret;
f29ac756
PZ
7154}
7155
b0a873eb 7156static void perf_swevent_start_hrtimer(struct perf_event *event)
5c92d124 7157{
b0a873eb 7158 struct hw_perf_event *hwc = &event->hw;
5d508e82
FBH
7159 s64 period;
7160
7161 if (!is_sampling_event(event))
7162 return;
f5ffe02e 7163
5d508e82
FBH
7164 period = local64_read(&hwc->period_left);
7165 if (period) {
7166 if (period < 0)
7167 period = 10000;
fa407f35 7168
5d508e82
FBH
7169 local64_set(&hwc->period_left, 0);
7170 } else {
7171 period = max_t(u64, 10000, hwc->sample_period);
7172 }
3497d206
TG
7173 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
7174 HRTIMER_MODE_REL_PINNED);
24f1e32c 7175}
b0a873eb
PZ
7176
7177static void perf_swevent_cancel_hrtimer(struct perf_event *event)
24f1e32c 7178{
b0a873eb
PZ
7179 struct hw_perf_event *hwc = &event->hw;
7180
6c7e550f 7181 if (is_sampling_event(event)) {
b0a873eb 7182 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
fa407f35 7183 local64_set(&hwc->period_left, ktime_to_ns(remaining));
b0a873eb
PZ
7184
7185 hrtimer_cancel(&hwc->hrtimer);
7186 }
24f1e32c
FW
7187}
7188
ba3dd36c
PZ
7189static void perf_swevent_init_hrtimer(struct perf_event *event)
7190{
7191 struct hw_perf_event *hwc = &event->hw;
7192
7193 if (!is_sampling_event(event))
7194 return;
7195
7196 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
7197 hwc->hrtimer.function = perf_swevent_hrtimer;
7198
7199 /*
7200 * Since hrtimers have a fixed rate, we can do a static freq->period
7201 * mapping and avoid the whole period adjust feedback stuff.
7202 */
7203 if (event->attr.freq) {
7204 long freq = event->attr.sample_freq;
7205
7206 event->attr.sample_period = NSEC_PER_SEC / freq;
7207 hwc->sample_period = event->attr.sample_period;
7208 local64_set(&hwc->period_left, hwc->sample_period);
778141e3 7209 hwc->last_period = hwc->sample_period;
ba3dd36c
PZ
7210 event->attr.freq = 0;
7211 }
7212}
7213
b0a873eb
PZ
7214/*
7215 * Software event: cpu wall time clock
7216 */
7217
7218static void cpu_clock_event_update(struct perf_event *event)
24f1e32c 7219{
b0a873eb
PZ
7220 s64 prev;
7221 u64 now;
7222
a4eaf7f1 7223 now = local_clock();
b0a873eb
PZ
7224 prev = local64_xchg(&event->hw.prev_count, now);
7225 local64_add(now - prev, &event->count);
24f1e32c 7226}
24f1e32c 7227
a4eaf7f1 7228static void cpu_clock_event_start(struct perf_event *event, int flags)
b0a873eb 7229{
a4eaf7f1 7230 local64_set(&event->hw.prev_count, local_clock());
b0a873eb 7231 perf_swevent_start_hrtimer(event);
b0a873eb
PZ
7232}
7233
a4eaf7f1 7234static void cpu_clock_event_stop(struct perf_event *event, int flags)
f29ac756 7235{
b0a873eb
PZ
7236 perf_swevent_cancel_hrtimer(event);
7237 cpu_clock_event_update(event);
7238}
f29ac756 7239
a4eaf7f1
PZ
7240static int cpu_clock_event_add(struct perf_event *event, int flags)
7241{
7242 if (flags & PERF_EF_START)
7243 cpu_clock_event_start(event, flags);
6a694a60 7244 perf_event_update_userpage(event);
a4eaf7f1
PZ
7245
7246 return 0;
7247}
7248
7249static void cpu_clock_event_del(struct perf_event *event, int flags)
7250{
7251 cpu_clock_event_stop(event, flags);
7252}
7253
b0a873eb
PZ
7254static void cpu_clock_event_read(struct perf_event *event)
7255{
7256 cpu_clock_event_update(event);
7257}
f344011c 7258
b0a873eb
PZ
7259static int cpu_clock_event_init(struct perf_event *event)
7260{
7261 if (event->attr.type != PERF_TYPE_SOFTWARE)
7262 return -ENOENT;
7263
7264 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
7265 return -ENOENT;
7266
2481c5fa
SE
7267 /*
7268 * no branch sampling for software events
7269 */
7270 if (has_branch_stack(event))
7271 return -EOPNOTSUPP;
7272
ba3dd36c
PZ
7273 perf_swevent_init_hrtimer(event);
7274
b0a873eb 7275 return 0;
f29ac756
PZ
7276}
7277
b0a873eb 7278static struct pmu perf_cpu_clock = {
89a1e187
PZ
7279 .task_ctx_nr = perf_sw_context,
7280
34f43927
PZ
7281 .capabilities = PERF_PMU_CAP_NO_NMI,
7282
b0a873eb 7283 .event_init = cpu_clock_event_init,
a4eaf7f1
PZ
7284 .add = cpu_clock_event_add,
7285 .del = cpu_clock_event_del,
7286 .start = cpu_clock_event_start,
7287 .stop = cpu_clock_event_stop,
b0a873eb
PZ
7288 .read = cpu_clock_event_read,
7289};
7290
7291/*
7292 * Software event: task time clock
7293 */
7294
7295static void task_clock_event_update(struct perf_event *event, u64 now)
5c92d124 7296{
b0a873eb
PZ
7297 u64 prev;
7298 s64 delta;
5c92d124 7299
b0a873eb
PZ
7300 prev = local64_xchg(&event->hw.prev_count, now);
7301 delta = now - prev;
7302 local64_add(delta, &event->count);
7303}
5c92d124 7304
a4eaf7f1 7305static void task_clock_event_start(struct perf_event *event, int flags)
b0a873eb 7306{
a4eaf7f1 7307 local64_set(&event->hw.prev_count, event->ctx->time);
b0a873eb 7308 perf_swevent_start_hrtimer(event);
b0a873eb
PZ
7309}
7310
a4eaf7f1 7311static void task_clock_event_stop(struct perf_event *event, int flags)
b0a873eb
PZ
7312{
7313 perf_swevent_cancel_hrtimer(event);
7314 task_clock_event_update(event, event->ctx->time);
a4eaf7f1
PZ
7315}
7316
7317static int task_clock_event_add(struct perf_event *event, int flags)
7318{
7319 if (flags & PERF_EF_START)
7320 task_clock_event_start(event, flags);
6a694a60 7321 perf_event_update_userpage(event);
b0a873eb 7322
a4eaf7f1
PZ
7323 return 0;
7324}
7325
7326static void task_clock_event_del(struct perf_event *event, int flags)
7327{
7328 task_clock_event_stop(event, PERF_EF_UPDATE);
b0a873eb
PZ
7329}
7330
7331static void task_clock_event_read(struct perf_event *event)
7332{
768a06e2
PZ
7333 u64 now = perf_clock();
7334 u64 delta = now - event->ctx->timestamp;
7335 u64 time = event->ctx->time + delta;
b0a873eb
PZ
7336
7337 task_clock_event_update(event, time);
7338}
7339
7340static int task_clock_event_init(struct perf_event *event)
6fb2915d 7341{
b0a873eb
PZ
7342 if (event->attr.type != PERF_TYPE_SOFTWARE)
7343 return -ENOENT;
7344
7345 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
7346 return -ENOENT;
7347
2481c5fa
SE
7348 /*
7349 * no branch sampling for software events
7350 */
7351 if (has_branch_stack(event))
7352 return -EOPNOTSUPP;
7353
ba3dd36c
PZ
7354 perf_swevent_init_hrtimer(event);
7355
b0a873eb 7356 return 0;
6fb2915d
LZ
7357}
7358
b0a873eb 7359static struct pmu perf_task_clock = {
89a1e187
PZ
7360 .task_ctx_nr = perf_sw_context,
7361
34f43927
PZ
7362 .capabilities = PERF_PMU_CAP_NO_NMI,
7363
b0a873eb 7364 .event_init = task_clock_event_init,
a4eaf7f1
PZ
7365 .add = task_clock_event_add,
7366 .del = task_clock_event_del,
7367 .start = task_clock_event_start,
7368 .stop = task_clock_event_stop,
b0a873eb
PZ
7369 .read = task_clock_event_read,
7370};
6fb2915d 7371
ad5133b7 7372static void perf_pmu_nop_void(struct pmu *pmu)
e077df4f 7373{
e077df4f 7374}
6fb2915d 7375
fbbe0701
SB
7376static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
7377{
7378}
7379
ad5133b7 7380static int perf_pmu_nop_int(struct pmu *pmu)
6fb2915d 7381{
ad5133b7 7382 return 0;
6fb2915d
LZ
7383}
7384
18ab2cd3 7385static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
fbbe0701
SB
7386
7387static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
6fb2915d 7388{
fbbe0701
SB
7389 __this_cpu_write(nop_txn_flags, flags);
7390
7391 if (flags & ~PERF_PMU_TXN_ADD)
7392 return;
7393
ad5133b7 7394 perf_pmu_disable(pmu);
6fb2915d
LZ
7395}
7396
ad5133b7
PZ
7397static int perf_pmu_commit_txn(struct pmu *pmu)
7398{
fbbe0701
SB
7399 unsigned int flags = __this_cpu_read(nop_txn_flags);
7400
7401 __this_cpu_write(nop_txn_flags, 0);
7402
7403 if (flags & ~PERF_PMU_TXN_ADD)
7404 return 0;
7405
ad5133b7
PZ
7406 perf_pmu_enable(pmu);
7407 return 0;
7408}
e077df4f 7409
ad5133b7 7410static void perf_pmu_cancel_txn(struct pmu *pmu)
24f1e32c 7411{
fbbe0701
SB
7412 unsigned int flags = __this_cpu_read(nop_txn_flags);
7413
7414 __this_cpu_write(nop_txn_flags, 0);
7415
7416 if (flags & ~PERF_PMU_TXN_ADD)
7417 return;
7418
ad5133b7 7419 perf_pmu_enable(pmu);
24f1e32c
FW
7420}
7421
35edc2a5
PZ
7422static int perf_event_idx_default(struct perf_event *event)
7423{
c719f560 7424 return 0;
35edc2a5
PZ
7425}
7426
8dc85d54
PZ
7427/*
7428 * Ensures all contexts with the same task_ctx_nr have the same
7429 * pmu_cpu_context too.
7430 */
9e317041 7431static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
24f1e32c 7432{
8dc85d54 7433 struct pmu *pmu;
b326e956 7434
8dc85d54
PZ
7435 if (ctxn < 0)
7436 return NULL;
24f1e32c 7437
8dc85d54
PZ
7438 list_for_each_entry(pmu, &pmus, entry) {
7439 if (pmu->task_ctx_nr == ctxn)
7440 return pmu->pmu_cpu_context;
7441 }
24f1e32c 7442
8dc85d54 7443 return NULL;
24f1e32c
FW
7444}
7445
51676957 7446static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
24f1e32c 7447{
51676957
PZ
7448 int cpu;
7449
7450 for_each_possible_cpu(cpu) {
7451 struct perf_cpu_context *cpuctx;
7452
7453 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7454
3f1f3320
PZ
7455 if (cpuctx->unique_pmu == old_pmu)
7456 cpuctx->unique_pmu = pmu;
51676957
PZ
7457 }
7458}
7459
7460static void free_pmu_context(struct pmu *pmu)
7461{
7462 struct pmu *i;
f5ffe02e 7463
8dc85d54 7464 mutex_lock(&pmus_lock);
0475f9ea 7465 /*
8dc85d54 7466 * Like a real lame refcount.
0475f9ea 7467 */
51676957
PZ
7468 list_for_each_entry(i, &pmus, entry) {
7469 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
7470 update_pmu_context(i, pmu);
8dc85d54 7471 goto out;
51676957 7472 }
8dc85d54 7473 }
d6d020e9 7474
51676957 7475 free_percpu(pmu->pmu_cpu_context);
8dc85d54
PZ
7476out:
7477 mutex_unlock(&pmus_lock);
24f1e32c 7478}
2e80a82a 7479static struct idr pmu_idr;
d6d020e9 7480
abe43400
PZ
7481static ssize_t
7482type_show(struct device *dev, struct device_attribute *attr, char *page)
7483{
7484 struct pmu *pmu = dev_get_drvdata(dev);
7485
7486 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
7487}
90826ca7 7488static DEVICE_ATTR_RO(type);
abe43400 7489
62b85639
SE
7490static ssize_t
7491perf_event_mux_interval_ms_show(struct device *dev,
7492 struct device_attribute *attr,
7493 char *page)
7494{
7495 struct pmu *pmu = dev_get_drvdata(dev);
7496
7497 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
7498}
7499
272325c4
PZ
7500static DEFINE_MUTEX(mux_interval_mutex);
7501
62b85639
SE
7502static ssize_t
7503perf_event_mux_interval_ms_store(struct device *dev,
7504 struct device_attribute *attr,
7505 const char *buf, size_t count)
7506{
7507 struct pmu *pmu = dev_get_drvdata(dev);
7508 int timer, cpu, ret;
7509
7510 ret = kstrtoint(buf, 0, &timer);
7511 if (ret)
7512 return ret;
7513
7514 if (timer < 1)
7515 return -EINVAL;
7516
7517 /* same value, noting to do */
7518 if (timer == pmu->hrtimer_interval_ms)
7519 return count;
7520
272325c4 7521 mutex_lock(&mux_interval_mutex);
62b85639
SE
7522 pmu->hrtimer_interval_ms = timer;
7523
7524 /* update all cpuctx for this PMU */
272325c4
PZ
7525 get_online_cpus();
7526 for_each_online_cpu(cpu) {
62b85639
SE
7527 struct perf_cpu_context *cpuctx;
7528 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
7529 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
7530
272325c4
PZ
7531 cpu_function_call(cpu,
7532 (remote_function_f)perf_mux_hrtimer_restart, cpuctx);
62b85639 7533 }
272325c4
PZ
7534 put_online_cpus();
7535 mutex_unlock(&mux_interval_mutex);
62b85639
SE
7536
7537 return count;
7538}
90826ca7 7539static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
62b85639 7540
90826ca7
GKH
7541static struct attribute *pmu_dev_attrs[] = {
7542 &dev_attr_type.attr,
7543 &dev_attr_perf_event_mux_interval_ms.attr,
7544 NULL,
abe43400 7545};
90826ca7 7546ATTRIBUTE_GROUPS(pmu_dev);
abe43400
PZ
7547
7548static int pmu_bus_running;
7549static struct bus_type pmu_bus = {
7550 .name = "event_source",
90826ca7 7551 .dev_groups = pmu_dev_groups,
abe43400
PZ
7552};
7553
7554static void pmu_dev_release(struct device *dev)
7555{
7556 kfree(dev);
7557}
7558
7559static int pmu_dev_alloc(struct pmu *pmu)
7560{
7561 int ret = -ENOMEM;
7562
7563 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
7564 if (!pmu->dev)
7565 goto out;
7566
0c9d42ed 7567 pmu->dev->groups = pmu->attr_groups;
abe43400
PZ
7568 device_initialize(pmu->dev);
7569 ret = dev_set_name(pmu->dev, "%s", pmu->name);
7570 if (ret)
7571 goto free_dev;
7572
7573 dev_set_drvdata(pmu->dev, pmu);
7574 pmu->dev->bus = &pmu_bus;
7575 pmu->dev->release = pmu_dev_release;
7576 ret = device_add(pmu->dev);
7577 if (ret)
7578 goto free_dev;
7579
7580out:
7581 return ret;
7582
7583free_dev:
7584 put_device(pmu->dev);
7585 goto out;
7586}
7587
547e9fd7 7588static struct lock_class_key cpuctx_mutex;
facc4307 7589static struct lock_class_key cpuctx_lock;
547e9fd7 7590
03d8e80b 7591int perf_pmu_register(struct pmu *pmu, const char *name, int type)
24f1e32c 7592{
108b02cf 7593 int cpu, ret;
24f1e32c 7594
b0a873eb 7595 mutex_lock(&pmus_lock);
33696fc0
PZ
7596 ret = -ENOMEM;
7597 pmu->pmu_disable_count = alloc_percpu(int);
7598 if (!pmu->pmu_disable_count)
7599 goto unlock;
f29ac756 7600
2e80a82a
PZ
7601 pmu->type = -1;
7602 if (!name)
7603 goto skip_type;
7604 pmu->name = name;
7605
7606 if (type < 0) {
0e9c3be2
TH
7607 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
7608 if (type < 0) {
7609 ret = type;
2e80a82a
PZ
7610 goto free_pdc;
7611 }
7612 }
7613 pmu->type = type;
7614
abe43400
PZ
7615 if (pmu_bus_running) {
7616 ret = pmu_dev_alloc(pmu);
7617 if (ret)
7618 goto free_idr;
7619 }
7620
2e80a82a 7621skip_type:
8dc85d54
PZ
7622 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
7623 if (pmu->pmu_cpu_context)
7624 goto got_cpu_context;
f29ac756 7625
c4814202 7626 ret = -ENOMEM;
108b02cf
PZ
7627 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
7628 if (!pmu->pmu_cpu_context)
abe43400 7629 goto free_dev;
f344011c 7630
108b02cf
PZ
7631 for_each_possible_cpu(cpu) {
7632 struct perf_cpu_context *cpuctx;
7633
7634 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
eb184479 7635 __perf_event_init_context(&cpuctx->ctx);
547e9fd7 7636 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
facc4307 7637 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
108b02cf 7638 cpuctx->ctx.pmu = pmu;
9e630205 7639
272325c4 7640 __perf_mux_hrtimer_init(cpuctx, cpu);
9e630205 7641
3f1f3320 7642 cpuctx->unique_pmu = pmu;
108b02cf 7643 }
76e1d904 7644
8dc85d54 7645got_cpu_context:
ad5133b7
PZ
7646 if (!pmu->start_txn) {
7647 if (pmu->pmu_enable) {
7648 /*
7649 * If we have pmu_enable/pmu_disable calls, install
7650 * transaction stubs that use that to try and batch
7651 * hardware accesses.
7652 */
7653 pmu->start_txn = perf_pmu_start_txn;
7654 pmu->commit_txn = perf_pmu_commit_txn;
7655 pmu->cancel_txn = perf_pmu_cancel_txn;
7656 } else {
fbbe0701 7657 pmu->start_txn = perf_pmu_nop_txn;
ad5133b7
PZ
7658 pmu->commit_txn = perf_pmu_nop_int;
7659 pmu->cancel_txn = perf_pmu_nop_void;
f344011c 7660 }
5c92d124 7661 }
15dbf27c 7662
ad5133b7
PZ
7663 if (!pmu->pmu_enable) {
7664 pmu->pmu_enable = perf_pmu_nop_void;
7665 pmu->pmu_disable = perf_pmu_nop_void;
7666 }
7667
35edc2a5
PZ
7668 if (!pmu->event_idx)
7669 pmu->event_idx = perf_event_idx_default;
7670
b0a873eb 7671 list_add_rcu(&pmu->entry, &pmus);
bed5b25a 7672 atomic_set(&pmu->exclusive_cnt, 0);
33696fc0
PZ
7673 ret = 0;
7674unlock:
b0a873eb
PZ
7675 mutex_unlock(&pmus_lock);
7676
33696fc0 7677 return ret;
108b02cf 7678
abe43400
PZ
7679free_dev:
7680 device_del(pmu->dev);
7681 put_device(pmu->dev);
7682
2e80a82a
PZ
7683free_idr:
7684 if (pmu->type >= PERF_TYPE_MAX)
7685 idr_remove(&pmu_idr, pmu->type);
7686
108b02cf
PZ
7687free_pdc:
7688 free_percpu(pmu->pmu_disable_count);
7689 goto unlock;
f29ac756 7690}
c464c76e 7691EXPORT_SYMBOL_GPL(perf_pmu_register);
f29ac756 7692
b0a873eb 7693void perf_pmu_unregister(struct pmu *pmu)
5c92d124 7694{
b0a873eb
PZ
7695 mutex_lock(&pmus_lock);
7696 list_del_rcu(&pmu->entry);
7697 mutex_unlock(&pmus_lock);
5c92d124 7698
0475f9ea 7699 /*
cde8e884
PZ
7700 * We dereference the pmu list under both SRCU and regular RCU, so
7701 * synchronize against both of those.
0475f9ea 7702 */
b0a873eb 7703 synchronize_srcu(&pmus_srcu);
cde8e884 7704 synchronize_rcu();
d6d020e9 7705
33696fc0 7706 free_percpu(pmu->pmu_disable_count);
2e80a82a
PZ
7707 if (pmu->type >= PERF_TYPE_MAX)
7708 idr_remove(&pmu_idr, pmu->type);
abe43400
PZ
7709 device_del(pmu->dev);
7710 put_device(pmu->dev);
51676957 7711 free_pmu_context(pmu);
b0a873eb 7712}
c464c76e 7713EXPORT_SYMBOL_GPL(perf_pmu_unregister);
d6d020e9 7714
cc34b98b
MR
7715static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
7716{
ccd41c86 7717 struct perf_event_context *ctx = NULL;
cc34b98b
MR
7718 int ret;
7719
7720 if (!try_module_get(pmu->module))
7721 return -ENODEV;
ccd41c86
PZ
7722
7723 if (event->group_leader != event) {
8b10c5e2
PZ
7724 /*
7725 * This ctx->mutex can nest when we're called through
7726 * inheritance. See the perf_event_ctx_lock_nested() comment.
7727 */
7728 ctx = perf_event_ctx_lock_nested(event->group_leader,
7729 SINGLE_DEPTH_NESTING);
ccd41c86
PZ
7730 BUG_ON(!ctx);
7731 }
7732
cc34b98b
MR
7733 event->pmu = pmu;
7734 ret = pmu->event_init(event);
ccd41c86
PZ
7735
7736 if (ctx)
7737 perf_event_ctx_unlock(event->group_leader, ctx);
7738
cc34b98b
MR
7739 if (ret)
7740 module_put(pmu->module);
7741
7742 return ret;
7743}
7744
18ab2cd3 7745static struct pmu *perf_init_event(struct perf_event *event)
b0a873eb
PZ
7746{
7747 struct pmu *pmu = NULL;
7748 int idx;
940c5b29 7749 int ret;
b0a873eb
PZ
7750
7751 idx = srcu_read_lock(&pmus_srcu);
2e80a82a
PZ
7752
7753 rcu_read_lock();
7754 pmu = idr_find(&pmu_idr, event->attr.type);
7755 rcu_read_unlock();
940c5b29 7756 if (pmu) {
cc34b98b 7757 ret = perf_try_init_event(pmu, event);
940c5b29
LM
7758 if (ret)
7759 pmu = ERR_PTR(ret);
2e80a82a 7760 goto unlock;
940c5b29 7761 }
2e80a82a 7762
b0a873eb 7763 list_for_each_entry_rcu(pmu, &pmus, entry) {
cc34b98b 7764 ret = perf_try_init_event(pmu, event);
b0a873eb 7765 if (!ret)
e5f4d339 7766 goto unlock;
76e1d904 7767
b0a873eb
PZ
7768 if (ret != -ENOENT) {
7769 pmu = ERR_PTR(ret);
e5f4d339 7770 goto unlock;
f344011c 7771 }
5c92d124 7772 }
e5f4d339
PZ
7773 pmu = ERR_PTR(-ENOENT);
7774unlock:
b0a873eb 7775 srcu_read_unlock(&pmus_srcu, idx);
15dbf27c 7776
4aeb0b42 7777 return pmu;
5c92d124
IM
7778}
7779
4beb31f3
FW
7780static void account_event_cpu(struct perf_event *event, int cpu)
7781{
7782 if (event->parent)
7783 return;
7784
4beb31f3
FW
7785 if (is_cgroup_event(event))
7786 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
7787}
7788
766d6c07
FW
7789static void account_event(struct perf_event *event)
7790{
25432ae9
PZ
7791 bool inc = false;
7792
4beb31f3
FW
7793 if (event->parent)
7794 return;
7795
766d6c07 7796 if (event->attach_state & PERF_ATTACH_TASK)
25432ae9 7797 inc = true;
766d6c07
FW
7798 if (event->attr.mmap || event->attr.mmap_data)
7799 atomic_inc(&nr_mmap_events);
7800 if (event->attr.comm)
7801 atomic_inc(&nr_comm_events);
7802 if (event->attr.task)
7803 atomic_inc(&nr_task_events);
948b26b6
FW
7804 if (event->attr.freq) {
7805 if (atomic_inc_return(&nr_freq_events) == 1)
7806 tick_nohz_full_kick_all();
7807 }
45ac1403
AH
7808 if (event->attr.context_switch) {
7809 atomic_inc(&nr_switch_events);
25432ae9 7810 inc = true;
45ac1403 7811 }
4beb31f3 7812 if (has_branch_stack(event))
25432ae9 7813 inc = true;
4beb31f3 7814 if (is_cgroup_event(event))
25432ae9
PZ
7815 inc = true;
7816
9107c89e
PZ
7817 if (inc) {
7818 if (atomic_inc_not_zero(&perf_sched_count))
7819 goto enabled;
7820
7821 mutex_lock(&perf_sched_mutex);
7822 if (!atomic_read(&perf_sched_count)) {
7823 static_branch_enable(&perf_sched_events);
7824 /*
7825 * Guarantee that all CPUs observe they key change and
7826 * call the perf scheduling hooks before proceeding to
7827 * install events that need them.
7828 */
7829 synchronize_sched();
7830 }
7831 /*
7832 * Now that we have waited for the sync_sched(), allow further
7833 * increments to by-pass the mutex.
7834 */
7835 atomic_inc(&perf_sched_count);
7836 mutex_unlock(&perf_sched_mutex);
7837 }
7838enabled:
4beb31f3
FW
7839
7840 account_event_cpu(event, event->cpu);
766d6c07
FW
7841}
7842
0793a61d 7843/*
cdd6c482 7844 * Allocate and initialize a event structure
0793a61d 7845 */
cdd6c482 7846static struct perf_event *
c3f00c70 7847perf_event_alloc(struct perf_event_attr *attr, int cpu,
d580ff86
PZ
7848 struct task_struct *task,
7849 struct perf_event *group_leader,
7850 struct perf_event *parent_event,
4dc0da86 7851 perf_overflow_handler_t overflow_handler,
79dff51e 7852 void *context, int cgroup_fd)
0793a61d 7853{
51b0fe39 7854 struct pmu *pmu;
cdd6c482
IM
7855 struct perf_event *event;
7856 struct hw_perf_event *hwc;
90983b16 7857 long err = -EINVAL;
0793a61d 7858
66832eb4
ON
7859 if ((unsigned)cpu >= nr_cpu_ids) {
7860 if (!task || cpu != -1)
7861 return ERR_PTR(-EINVAL);
7862 }
7863
c3f00c70 7864 event = kzalloc(sizeof(*event), GFP_KERNEL);
cdd6c482 7865 if (!event)
d5d2bc0d 7866 return ERR_PTR(-ENOMEM);
0793a61d 7867
04289bb9 7868 /*
cdd6c482 7869 * Single events are their own group leaders, with an
04289bb9
IM
7870 * empty sibling list:
7871 */
7872 if (!group_leader)
cdd6c482 7873 group_leader = event;
04289bb9 7874
cdd6c482
IM
7875 mutex_init(&event->child_mutex);
7876 INIT_LIST_HEAD(&event->child_list);
fccc714b 7877
cdd6c482
IM
7878 INIT_LIST_HEAD(&event->group_entry);
7879 INIT_LIST_HEAD(&event->event_entry);
7880 INIT_LIST_HEAD(&event->sibling_list);
10c6db11 7881 INIT_LIST_HEAD(&event->rb_entry);
71ad88ef 7882 INIT_LIST_HEAD(&event->active_entry);
f3ae75de
SE
7883 INIT_HLIST_NODE(&event->hlist_entry);
7884
10c6db11 7885
cdd6c482 7886 init_waitqueue_head(&event->waitq);
e360adbe 7887 init_irq_work(&event->pending, perf_pending_event);
0793a61d 7888
cdd6c482 7889 mutex_init(&event->mmap_mutex);
7b732a75 7890
a6fa941d 7891 atomic_long_set(&event->refcount, 1);
cdd6c482
IM
7892 event->cpu = cpu;
7893 event->attr = *attr;
7894 event->group_leader = group_leader;
7895 event->pmu = NULL;
cdd6c482 7896 event->oncpu = -1;
a96bbc16 7897
cdd6c482 7898 event->parent = parent_event;
b84fbc9f 7899
17cf22c3 7900 event->ns = get_pid_ns(task_active_pid_ns(current));
cdd6c482 7901 event->id = atomic64_inc_return(&perf_event_id);
a96bbc16 7902
cdd6c482 7903 event->state = PERF_EVENT_STATE_INACTIVE;
329d876d 7904
d580ff86
PZ
7905 if (task) {
7906 event->attach_state = PERF_ATTACH_TASK;
d580ff86 7907 /*
50f16a8b
PZ
7908 * XXX pmu::event_init needs to know what task to account to
7909 * and we cannot use the ctx information because we need the
7910 * pmu before we get a ctx.
d580ff86 7911 */
50f16a8b 7912 event->hw.target = task;
d580ff86
PZ
7913 }
7914
34f43927
PZ
7915 event->clock = &local_clock;
7916 if (parent_event)
7917 event->clock = parent_event->clock;
7918
4dc0da86 7919 if (!overflow_handler && parent_event) {
b326e956 7920 overflow_handler = parent_event->overflow_handler;
4dc0da86
AK
7921 context = parent_event->overflow_handler_context;
7922 }
66832eb4 7923
b326e956 7924 event->overflow_handler = overflow_handler;
4dc0da86 7925 event->overflow_handler_context = context;
97eaf530 7926
0231bb53 7927 perf_event__state_init(event);
a86ed508 7928
4aeb0b42 7929 pmu = NULL;
b8e83514 7930
cdd6c482 7931 hwc = &event->hw;
bd2b5b12 7932 hwc->sample_period = attr->sample_period;
0d48696f 7933 if (attr->freq && attr->sample_freq)
bd2b5b12 7934 hwc->sample_period = 1;
eced1dfc 7935 hwc->last_period = hwc->sample_period;
bd2b5b12 7936
e7850595 7937 local64_set(&hwc->period_left, hwc->sample_period);
60db5e09 7938
2023b359 7939 /*
cdd6c482 7940 * we currently do not support PERF_FORMAT_GROUP on inherited events
2023b359 7941 */
3dab77fb 7942 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
90983b16 7943 goto err_ns;
a46a2300
YZ
7944
7945 if (!has_branch_stack(event))
7946 event->attr.branch_sample_type = 0;
2023b359 7947
79dff51e
MF
7948 if (cgroup_fd != -1) {
7949 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
7950 if (err)
7951 goto err_ns;
7952 }
7953
b0a873eb 7954 pmu = perf_init_event(event);
4aeb0b42 7955 if (!pmu)
90983b16
FW
7956 goto err_ns;
7957 else if (IS_ERR(pmu)) {
4aeb0b42 7958 err = PTR_ERR(pmu);
90983b16 7959 goto err_ns;
621a01ea 7960 }
d5d2bc0d 7961
bed5b25a
AS
7962 err = exclusive_event_init(event);
7963 if (err)
7964 goto err_pmu;
7965
cdd6c482 7966 if (!event->parent) {
927c7a9e
FW
7967 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
7968 err = get_callchain_buffers();
90983b16 7969 if (err)
bed5b25a 7970 goto err_per_task;
d010b332 7971 }
f344011c 7972 }
9ee318a7 7973
cdd6c482 7974 return event;
90983b16 7975
bed5b25a
AS
7976err_per_task:
7977 exclusive_event_destroy(event);
7978
90983b16
FW
7979err_pmu:
7980 if (event->destroy)
7981 event->destroy(event);
c464c76e 7982 module_put(pmu->module);
90983b16 7983err_ns:
79dff51e
MF
7984 if (is_cgroup_event(event))
7985 perf_detach_cgroup(event);
90983b16
FW
7986 if (event->ns)
7987 put_pid_ns(event->ns);
7988 kfree(event);
7989
7990 return ERR_PTR(err);
0793a61d
TG
7991}
7992
cdd6c482
IM
7993static int perf_copy_attr(struct perf_event_attr __user *uattr,
7994 struct perf_event_attr *attr)
974802ea 7995{
974802ea 7996 u32 size;
cdf8073d 7997 int ret;
974802ea
PZ
7998
7999 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
8000 return -EFAULT;
8001
8002 /*
8003 * zero the full structure, so that a short copy will be nice.
8004 */
8005 memset(attr, 0, sizeof(*attr));
8006
8007 ret = get_user(size, &uattr->size);
8008 if (ret)
8009 return ret;
8010
8011 if (size > PAGE_SIZE) /* silly large */
8012 goto err_size;
8013
8014 if (!size) /* abi compat */
8015 size = PERF_ATTR_SIZE_VER0;
8016
8017 if (size < PERF_ATTR_SIZE_VER0)
8018 goto err_size;
8019
8020 /*
8021 * If we're handed a bigger struct than we know of,
cdf8073d
IS
8022 * ensure all the unknown bits are 0 - i.e. new
8023 * user-space does not rely on any kernel feature
8024 * extensions we dont know about yet.
974802ea
PZ
8025 */
8026 if (size > sizeof(*attr)) {
cdf8073d
IS
8027 unsigned char __user *addr;
8028 unsigned char __user *end;
8029 unsigned char val;
974802ea 8030
cdf8073d
IS
8031 addr = (void __user *)uattr + sizeof(*attr);
8032 end = (void __user *)uattr + size;
974802ea 8033
cdf8073d 8034 for (; addr < end; addr++) {
974802ea
PZ
8035 ret = get_user(val, addr);
8036 if (ret)
8037 return ret;
8038 if (val)
8039 goto err_size;
8040 }
b3e62e35 8041 size = sizeof(*attr);
974802ea
PZ
8042 }
8043
8044 ret = copy_from_user(attr, uattr, size);
8045 if (ret)
8046 return -EFAULT;
8047
cd757645 8048 if (attr->__reserved_1)
974802ea
PZ
8049 return -EINVAL;
8050
8051 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
8052 return -EINVAL;
8053
8054 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
8055 return -EINVAL;
8056
bce38cd5
SE
8057 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
8058 u64 mask = attr->branch_sample_type;
8059
8060 /* only using defined bits */
8061 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
8062 return -EINVAL;
8063
8064 /* at least one branch bit must be set */
8065 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
8066 return -EINVAL;
8067
bce38cd5
SE
8068 /* propagate priv level, when not set for branch */
8069 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
8070
8071 /* exclude_kernel checked on syscall entry */
8072 if (!attr->exclude_kernel)
8073 mask |= PERF_SAMPLE_BRANCH_KERNEL;
8074
8075 if (!attr->exclude_user)
8076 mask |= PERF_SAMPLE_BRANCH_USER;
8077
8078 if (!attr->exclude_hv)
8079 mask |= PERF_SAMPLE_BRANCH_HV;
8080 /*
8081 * adjust user setting (for HW filter setup)
8082 */
8083 attr->branch_sample_type = mask;
8084 }
e712209a
SE
8085 /* privileged levels capture (kernel, hv): check permissions */
8086 if ((mask & PERF_SAMPLE_BRANCH_PERM_PLM)
2b923c8f
SE
8087 && perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8088 return -EACCES;
bce38cd5 8089 }
4018994f 8090
c5ebcedb 8091 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
4018994f 8092 ret = perf_reg_validate(attr->sample_regs_user);
c5ebcedb
JO
8093 if (ret)
8094 return ret;
8095 }
8096
8097 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
8098 if (!arch_perf_have_user_stack_dump())
8099 return -ENOSYS;
8100
8101 /*
8102 * We have __u32 type for the size, but so far
8103 * we can only use __u16 as maximum due to the
8104 * __u16 sample size limit.
8105 */
8106 if (attr->sample_stack_user >= USHRT_MAX)
8107 ret = -EINVAL;
8108 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
8109 ret = -EINVAL;
8110 }
4018994f 8111
60e2364e
SE
8112 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
8113 ret = perf_reg_validate(attr->sample_regs_intr);
974802ea
PZ
8114out:
8115 return ret;
8116
8117err_size:
8118 put_user(sizeof(*attr), &uattr->size);
8119 ret = -E2BIG;
8120 goto out;
8121}
8122
ac9721f3
PZ
8123static int
8124perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
a4be7c27 8125{
b69cf536 8126 struct ring_buffer *rb = NULL;
a4be7c27
PZ
8127 int ret = -EINVAL;
8128
ac9721f3 8129 if (!output_event)
a4be7c27
PZ
8130 goto set;
8131
ac9721f3
PZ
8132 /* don't allow circular references */
8133 if (event == output_event)
a4be7c27
PZ
8134 goto out;
8135
0f139300
PZ
8136 /*
8137 * Don't allow cross-cpu buffers
8138 */
8139 if (output_event->cpu != event->cpu)
8140 goto out;
8141
8142 /*
76369139 8143 * If its not a per-cpu rb, it must be the same task.
0f139300
PZ
8144 */
8145 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
8146 goto out;
8147
34f43927
PZ
8148 /*
8149 * Mixing clocks in the same buffer is trouble you don't need.
8150 */
8151 if (output_event->clock != event->clock)
8152 goto out;
8153
45bfb2e5
PZ
8154 /*
8155 * If both events generate aux data, they must be on the same PMU
8156 */
8157 if (has_aux(event) && has_aux(output_event) &&
8158 event->pmu != output_event->pmu)
8159 goto out;
8160
a4be7c27 8161set:
cdd6c482 8162 mutex_lock(&event->mmap_mutex);
ac9721f3
PZ
8163 /* Can't redirect output if we've got an active mmap() */
8164 if (atomic_read(&event->mmap_count))
8165 goto unlock;
a4be7c27 8166
ac9721f3 8167 if (output_event) {
76369139
FW
8168 /* get the rb we want to redirect to */
8169 rb = ring_buffer_get(output_event);
8170 if (!rb)
ac9721f3 8171 goto unlock;
a4be7c27
PZ
8172 }
8173
b69cf536 8174 ring_buffer_attach(event, rb);
9bb5d40c 8175
a4be7c27 8176 ret = 0;
ac9721f3
PZ
8177unlock:
8178 mutex_unlock(&event->mmap_mutex);
8179
a4be7c27 8180out:
a4be7c27
PZ
8181 return ret;
8182}
8183
f63a8daa
PZ
8184static void mutex_lock_double(struct mutex *a, struct mutex *b)
8185{
8186 if (b < a)
8187 swap(a, b);
8188
8189 mutex_lock(a);
8190 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
8191}
8192
34f43927
PZ
8193static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
8194{
8195 bool nmi_safe = false;
8196
8197 switch (clk_id) {
8198 case CLOCK_MONOTONIC:
8199 event->clock = &ktime_get_mono_fast_ns;
8200 nmi_safe = true;
8201 break;
8202
8203 case CLOCK_MONOTONIC_RAW:
8204 event->clock = &ktime_get_raw_fast_ns;
8205 nmi_safe = true;
8206 break;
8207
8208 case CLOCK_REALTIME:
8209 event->clock = &ktime_get_real_ns;
8210 break;
8211
8212 case CLOCK_BOOTTIME:
8213 event->clock = &ktime_get_boot_ns;
8214 break;
8215
8216 case CLOCK_TAI:
8217 event->clock = &ktime_get_tai_ns;
8218 break;
8219
8220 default:
8221 return -EINVAL;
8222 }
8223
8224 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
8225 return -EINVAL;
8226
8227 return 0;
8228}
8229
0793a61d 8230/**
cdd6c482 8231 * sys_perf_event_open - open a performance event, associate it to a task/cpu
9f66a381 8232 *
cdd6c482 8233 * @attr_uptr: event_id type attributes for monitoring/sampling
0793a61d 8234 * @pid: target pid
9f66a381 8235 * @cpu: target cpu
cdd6c482 8236 * @group_fd: group leader event fd
0793a61d 8237 */
cdd6c482
IM
8238SYSCALL_DEFINE5(perf_event_open,
8239 struct perf_event_attr __user *, attr_uptr,
2743a5b0 8240 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
0793a61d 8241{
b04243ef
PZ
8242 struct perf_event *group_leader = NULL, *output_event = NULL;
8243 struct perf_event *event, *sibling;
cdd6c482 8244 struct perf_event_attr attr;
f63a8daa 8245 struct perf_event_context *ctx, *uninitialized_var(gctx);
cdd6c482 8246 struct file *event_file = NULL;
2903ff01 8247 struct fd group = {NULL, 0};
38a81da2 8248 struct task_struct *task = NULL;
89a1e187 8249 struct pmu *pmu;
ea635c64 8250 int event_fd;
b04243ef 8251 int move_group = 0;
dc86cabe 8252 int err;
a21b0b35 8253 int f_flags = O_RDWR;
79dff51e 8254 int cgroup_fd = -1;
0793a61d 8255
2743a5b0 8256 /* for future expandability... */
e5d1367f 8257 if (flags & ~PERF_FLAG_ALL)
2743a5b0
PM
8258 return -EINVAL;
8259
dc86cabe
IM
8260 err = perf_copy_attr(attr_uptr, &attr);
8261 if (err)
8262 return err;
eab656ae 8263
0764771d
PZ
8264 if (!attr.exclude_kernel) {
8265 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
8266 return -EACCES;
8267 }
8268
df58ab24 8269 if (attr.freq) {
cdd6c482 8270 if (attr.sample_freq > sysctl_perf_event_sample_rate)
df58ab24 8271 return -EINVAL;
0819b2e3
PZ
8272 } else {
8273 if (attr.sample_period & (1ULL << 63))
8274 return -EINVAL;
df58ab24
PZ
8275 }
8276
e5d1367f
SE
8277 /*
8278 * In cgroup mode, the pid argument is used to pass the fd
8279 * opened to the cgroup directory in cgroupfs. The cpu argument
8280 * designates the cpu on which to monitor threads from that
8281 * cgroup.
8282 */
8283 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
8284 return -EINVAL;
8285
a21b0b35
YD
8286 if (flags & PERF_FLAG_FD_CLOEXEC)
8287 f_flags |= O_CLOEXEC;
8288
8289 event_fd = get_unused_fd_flags(f_flags);
ea635c64
AV
8290 if (event_fd < 0)
8291 return event_fd;
8292
ac9721f3 8293 if (group_fd != -1) {
2903ff01
AV
8294 err = perf_fget_light(group_fd, &group);
8295 if (err)
d14b12d7 8296 goto err_fd;
2903ff01 8297 group_leader = group.file->private_data;
ac9721f3
PZ
8298 if (flags & PERF_FLAG_FD_OUTPUT)
8299 output_event = group_leader;
8300 if (flags & PERF_FLAG_FD_NO_GROUP)
8301 group_leader = NULL;
8302 }
8303
e5d1367f 8304 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
c6be5a5c
PZ
8305 task = find_lively_task_by_vpid(pid);
8306 if (IS_ERR(task)) {
8307 err = PTR_ERR(task);
8308 goto err_group_fd;
8309 }
8310 }
8311
1f4ee503
PZ
8312 if (task && group_leader &&
8313 group_leader->attr.inherit != attr.inherit) {
8314 err = -EINVAL;
8315 goto err_task;
8316 }
8317
fbfc623f
YZ
8318 get_online_cpus();
8319
79dff51e
MF
8320 if (flags & PERF_FLAG_PID_CGROUP)
8321 cgroup_fd = pid;
8322
4dc0da86 8323 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
79dff51e 8324 NULL, NULL, cgroup_fd);
d14b12d7
SE
8325 if (IS_ERR(event)) {
8326 err = PTR_ERR(event);
1f4ee503 8327 goto err_cpus;
d14b12d7
SE
8328 }
8329
53b25335
VW
8330 if (is_sampling_event(event)) {
8331 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
8332 err = -ENOTSUPP;
8333 goto err_alloc;
8334 }
8335 }
8336
766d6c07
FW
8337 account_event(event);
8338
89a1e187
PZ
8339 /*
8340 * Special case software events and allow them to be part of
8341 * any hardware group.
8342 */
8343 pmu = event->pmu;
b04243ef 8344
34f43927
PZ
8345 if (attr.use_clockid) {
8346 err = perf_event_set_clock(event, attr.clockid);
8347 if (err)
8348 goto err_alloc;
8349 }
8350
b04243ef
PZ
8351 if (group_leader &&
8352 (is_software_event(event) != is_software_event(group_leader))) {
8353 if (is_software_event(event)) {
8354 /*
8355 * If event and group_leader are not both a software
8356 * event, and event is, then group leader is not.
8357 *
8358 * Allow the addition of software events to !software
8359 * groups, this is safe because software events never
8360 * fail to schedule.
8361 */
8362 pmu = group_leader->pmu;
8363 } else if (is_software_event(group_leader) &&
8364 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
8365 /*
8366 * In case the group is a pure software group, and we
8367 * try to add a hardware event, move the whole group to
8368 * the hardware context.
8369 */
8370 move_group = 1;
8371 }
8372 }
89a1e187
PZ
8373
8374 /*
8375 * Get the target context (task or percpu):
8376 */
4af57ef2 8377 ctx = find_get_context(pmu, task, event);
89a1e187
PZ
8378 if (IS_ERR(ctx)) {
8379 err = PTR_ERR(ctx);
c6be5a5c 8380 goto err_alloc;
89a1e187
PZ
8381 }
8382
bed5b25a
AS
8383 if ((pmu->capabilities & PERF_PMU_CAP_EXCLUSIVE) && group_leader) {
8384 err = -EBUSY;
8385 goto err_context;
8386 }
8387
fd1edb3a
PZ
8388 if (task) {
8389 put_task_struct(task);
8390 task = NULL;
8391 }
8392
ccff286d 8393 /*
cdd6c482 8394 * Look up the group leader (we will attach this event to it):
04289bb9 8395 */
ac9721f3 8396 if (group_leader) {
dc86cabe 8397 err = -EINVAL;
04289bb9 8398
04289bb9 8399 /*
ccff286d
IM
8400 * Do not allow a recursive hierarchy (this new sibling
8401 * becoming part of another group-sibling):
8402 */
8403 if (group_leader->group_leader != group_leader)
c3f00c70 8404 goto err_context;
34f43927
PZ
8405
8406 /* All events in a group should have the same clock */
8407 if (group_leader->clock != event->clock)
8408 goto err_context;
8409
ccff286d
IM
8410 /*
8411 * Do not allow to attach to a group in a different
8412 * task or CPU context:
04289bb9 8413 */
b04243ef 8414 if (move_group) {
c3c87e77
PZ
8415 /*
8416 * Make sure we're both on the same task, or both
8417 * per-cpu events.
8418 */
8419 if (group_leader->ctx->task != ctx->task)
8420 goto err_context;
8421
8422 /*
8423 * Make sure we're both events for the same CPU;
8424 * grouping events for different CPUs is broken; since
8425 * you can never concurrently schedule them anyhow.
8426 */
8427 if (group_leader->cpu != event->cpu)
b04243ef
PZ
8428 goto err_context;
8429 } else {
8430 if (group_leader->ctx != ctx)
8431 goto err_context;
8432 }
8433
3b6f9e5c
PM
8434 /*
8435 * Only a group leader can be exclusive or pinned
8436 */
0d48696f 8437 if (attr.exclusive || attr.pinned)
c3f00c70 8438 goto err_context;
ac9721f3
PZ
8439 }
8440
8441 if (output_event) {
8442 err = perf_event_set_output(event, output_event);
8443 if (err)
c3f00c70 8444 goto err_context;
ac9721f3 8445 }
0793a61d 8446
a21b0b35
YD
8447 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
8448 f_flags);
ea635c64
AV
8449 if (IS_ERR(event_file)) {
8450 err = PTR_ERR(event_file);
c3f00c70 8451 goto err_context;
ea635c64 8452 }
9b51f66d 8453
b04243ef 8454 if (move_group) {
f63a8daa 8455 gctx = group_leader->ctx;
f55fc2a5 8456 mutex_lock_double(&gctx->mutex, &ctx->mutex);
84c4e620
PZ
8457 if (gctx->task == TASK_TOMBSTONE) {
8458 err = -ESRCH;
8459 goto err_locked;
8460 }
f55fc2a5
PZ
8461 } else {
8462 mutex_lock(&ctx->mutex);
8463 }
8464
84c4e620
PZ
8465 if (ctx->task == TASK_TOMBSTONE) {
8466 err = -ESRCH;
8467 goto err_locked;
8468 }
8469
a723968c
PZ
8470 if (!perf_event_validate_size(event)) {
8471 err = -E2BIG;
8472 goto err_locked;
8473 }
8474
f55fc2a5
PZ
8475 /*
8476 * Must be under the same ctx::mutex as perf_install_in_context(),
8477 * because we need to serialize with concurrent event creation.
8478 */
8479 if (!exclusive_event_installable(event, ctx)) {
8480 /* exclusive and group stuff are assumed mutually exclusive */
8481 WARN_ON_ONCE(move_group);
f63a8daa 8482
f55fc2a5
PZ
8483 err = -EBUSY;
8484 goto err_locked;
8485 }
f63a8daa 8486
f55fc2a5
PZ
8487 WARN_ON_ONCE(ctx->parent_ctx);
8488
8489 if (move_group) {
f63a8daa
PZ
8490 /*
8491 * See perf_event_ctx_lock() for comments on the details
8492 * of swizzling perf_event::ctx.
8493 */
45a0e07a 8494 perf_remove_from_context(group_leader, 0);
0231bb53 8495
b04243ef
PZ
8496 list_for_each_entry(sibling, &group_leader->sibling_list,
8497 group_entry) {
45a0e07a 8498 perf_remove_from_context(sibling, 0);
b04243ef
PZ
8499 put_ctx(gctx);
8500 }
b04243ef 8501
f63a8daa
PZ
8502 /*
8503 * Wait for everybody to stop referencing the events through
8504 * the old lists, before installing it on new lists.
8505 */
0cda4c02 8506 synchronize_rcu();
f63a8daa 8507
8f95b435
PZI
8508 /*
8509 * Install the group siblings before the group leader.
8510 *
8511 * Because a group leader will try and install the entire group
8512 * (through the sibling list, which is still in-tact), we can
8513 * end up with siblings installed in the wrong context.
8514 *
8515 * By installing siblings first we NO-OP because they're not
8516 * reachable through the group lists.
8517 */
b04243ef
PZ
8518 list_for_each_entry(sibling, &group_leader->sibling_list,
8519 group_entry) {
8f95b435 8520 perf_event__state_init(sibling);
9fc81d87 8521 perf_install_in_context(ctx, sibling, sibling->cpu);
b04243ef
PZ
8522 get_ctx(ctx);
8523 }
8f95b435
PZI
8524
8525 /*
8526 * Removing from the context ends up with disabled
8527 * event. What we want here is event in the initial
8528 * startup state, ready to be add into new context.
8529 */
8530 perf_event__state_init(group_leader);
8531 perf_install_in_context(ctx, group_leader, group_leader->cpu);
8532 get_ctx(ctx);
b04243ef 8533
f55fc2a5
PZ
8534 /*
8535 * Now that all events are installed in @ctx, nothing
8536 * references @gctx anymore, so drop the last reference we have
8537 * on it.
8538 */
8539 put_ctx(gctx);
bed5b25a
AS
8540 }
8541
f73e22ab
PZ
8542 /*
8543 * Precalculate sample_data sizes; do while holding ctx::mutex such
8544 * that we're serialized against further additions and before
8545 * perf_install_in_context() which is the point the event is active and
8546 * can use these values.
8547 */
8548 perf_event__header_size(event);
8549 perf_event__id_header_size(event);
8550
78cd2c74
PZ
8551 event->owner = current;
8552
e2d37cd2 8553 perf_install_in_context(ctx, event, event->cpu);
fe4b04fa 8554 perf_unpin_context(ctx);
f63a8daa 8555
f55fc2a5 8556 if (move_group)
f63a8daa 8557 mutex_unlock(&gctx->mutex);
d859e29f 8558 mutex_unlock(&ctx->mutex);
9b51f66d 8559
fbfc623f
YZ
8560 put_online_cpus();
8561
cdd6c482
IM
8562 mutex_lock(&current->perf_event_mutex);
8563 list_add_tail(&event->owner_entry, &current->perf_event_list);
8564 mutex_unlock(&current->perf_event_mutex);
082ff5a2 8565
8a49542c
PZ
8566 /*
8567 * Drop the reference on the group_event after placing the
8568 * new event on the sibling_list. This ensures destruction
8569 * of the group leader will find the pointer to itself in
8570 * perf_group_detach().
8571 */
2903ff01 8572 fdput(group);
ea635c64
AV
8573 fd_install(event_fd, event_file);
8574 return event_fd;
0793a61d 8575
f55fc2a5
PZ
8576err_locked:
8577 if (move_group)
8578 mutex_unlock(&gctx->mutex);
8579 mutex_unlock(&ctx->mutex);
8580/* err_file: */
8581 fput(event_file);
c3f00c70 8582err_context:
fe4b04fa 8583 perf_unpin_context(ctx);
ea635c64 8584 put_ctx(ctx);
c6be5a5c 8585err_alloc:
13005627
PZ
8586 /*
8587 * If event_file is set, the fput() above will have called ->release()
8588 * and that will take care of freeing the event.
8589 */
8590 if (!event_file)
8591 free_event(event);
1f4ee503 8592err_cpus:
fbfc623f 8593 put_online_cpus();
1f4ee503 8594err_task:
e7d0bc04
PZ
8595 if (task)
8596 put_task_struct(task);
89a1e187 8597err_group_fd:
2903ff01 8598 fdput(group);
ea635c64
AV
8599err_fd:
8600 put_unused_fd(event_fd);
dc86cabe 8601 return err;
0793a61d
TG
8602}
8603
fb0459d7
AV
8604/**
8605 * perf_event_create_kernel_counter
8606 *
8607 * @attr: attributes of the counter to create
8608 * @cpu: cpu in which the counter is bound
38a81da2 8609 * @task: task to profile (NULL for percpu)
fb0459d7
AV
8610 */
8611struct perf_event *
8612perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
38a81da2 8613 struct task_struct *task,
4dc0da86
AK
8614 perf_overflow_handler_t overflow_handler,
8615 void *context)
fb0459d7 8616{
fb0459d7 8617 struct perf_event_context *ctx;
c3f00c70 8618 struct perf_event *event;
fb0459d7 8619 int err;
d859e29f 8620
fb0459d7
AV
8621 /*
8622 * Get the target context (task or percpu):
8623 */
d859e29f 8624
4dc0da86 8625 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
79dff51e 8626 overflow_handler, context, -1);
c3f00c70
PZ
8627 if (IS_ERR(event)) {
8628 err = PTR_ERR(event);
8629 goto err;
8630 }
d859e29f 8631
f8697762 8632 /* Mark owner so we could distinguish it from user events. */
63b6da39 8633 event->owner = TASK_TOMBSTONE;
f8697762 8634
766d6c07
FW
8635 account_event(event);
8636
4af57ef2 8637 ctx = find_get_context(event->pmu, task, event);
c6567f64
FW
8638 if (IS_ERR(ctx)) {
8639 err = PTR_ERR(ctx);
c3f00c70 8640 goto err_free;
d859e29f 8641 }
fb0459d7 8642
fb0459d7
AV
8643 WARN_ON_ONCE(ctx->parent_ctx);
8644 mutex_lock(&ctx->mutex);
84c4e620
PZ
8645 if (ctx->task == TASK_TOMBSTONE) {
8646 err = -ESRCH;
8647 goto err_unlock;
8648 }
8649
bed5b25a 8650 if (!exclusive_event_installable(event, ctx)) {
bed5b25a 8651 err = -EBUSY;
84c4e620 8652 goto err_unlock;
bed5b25a
AS
8653 }
8654
fb0459d7 8655 perf_install_in_context(ctx, event, cpu);
fe4b04fa 8656 perf_unpin_context(ctx);
fb0459d7
AV
8657 mutex_unlock(&ctx->mutex);
8658
fb0459d7
AV
8659 return event;
8660
84c4e620
PZ
8661err_unlock:
8662 mutex_unlock(&ctx->mutex);
8663 perf_unpin_context(ctx);
8664 put_ctx(ctx);
c3f00c70
PZ
8665err_free:
8666 free_event(event);
8667err:
c6567f64 8668 return ERR_PTR(err);
9b51f66d 8669}
fb0459d7 8670EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
9b51f66d 8671
0cda4c02
YZ
8672void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
8673{
8674 struct perf_event_context *src_ctx;
8675 struct perf_event_context *dst_ctx;
8676 struct perf_event *event, *tmp;
8677 LIST_HEAD(events);
8678
8679 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
8680 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
8681
f63a8daa
PZ
8682 /*
8683 * See perf_event_ctx_lock() for comments on the details
8684 * of swizzling perf_event::ctx.
8685 */
8686 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
0cda4c02
YZ
8687 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
8688 event_entry) {
45a0e07a 8689 perf_remove_from_context(event, 0);
9a545de0 8690 unaccount_event_cpu(event, src_cpu);
0cda4c02 8691 put_ctx(src_ctx);
9886167d 8692 list_add(&event->migrate_entry, &events);
0cda4c02 8693 }
0cda4c02 8694
8f95b435
PZI
8695 /*
8696 * Wait for the events to quiesce before re-instating them.
8697 */
0cda4c02
YZ
8698 synchronize_rcu();
8699
8f95b435
PZI
8700 /*
8701 * Re-instate events in 2 passes.
8702 *
8703 * Skip over group leaders and only install siblings on this first
8704 * pass, siblings will not get enabled without a leader, however a
8705 * leader will enable its siblings, even if those are still on the old
8706 * context.
8707 */
8708 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8709 if (event->group_leader == event)
8710 continue;
8711
8712 list_del(&event->migrate_entry);
8713 if (event->state >= PERF_EVENT_STATE_OFF)
8714 event->state = PERF_EVENT_STATE_INACTIVE;
8715 account_event_cpu(event, dst_cpu);
8716 perf_install_in_context(dst_ctx, event, dst_cpu);
8717 get_ctx(dst_ctx);
8718 }
8719
8720 /*
8721 * Once all the siblings are setup properly, install the group leaders
8722 * to make it go.
8723 */
9886167d
PZ
8724 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
8725 list_del(&event->migrate_entry);
0cda4c02
YZ
8726 if (event->state >= PERF_EVENT_STATE_OFF)
8727 event->state = PERF_EVENT_STATE_INACTIVE;
9a545de0 8728 account_event_cpu(event, dst_cpu);
0cda4c02
YZ
8729 perf_install_in_context(dst_ctx, event, dst_cpu);
8730 get_ctx(dst_ctx);
8731 }
8732 mutex_unlock(&dst_ctx->mutex);
f63a8daa 8733 mutex_unlock(&src_ctx->mutex);
0cda4c02
YZ
8734}
8735EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
8736
cdd6c482 8737static void sync_child_event(struct perf_event *child_event,
38b200d6 8738 struct task_struct *child)
d859e29f 8739{
cdd6c482 8740 struct perf_event *parent_event = child_event->parent;
8bc20959 8741 u64 child_val;
d859e29f 8742
cdd6c482
IM
8743 if (child_event->attr.inherit_stat)
8744 perf_event_read_event(child_event, child);
38b200d6 8745
b5e58793 8746 child_val = perf_event_count(child_event);
d859e29f
PM
8747
8748 /*
8749 * Add back the child's count to the parent's count:
8750 */
a6e6dea6 8751 atomic64_add(child_val, &parent_event->child_count);
cdd6c482
IM
8752 atomic64_add(child_event->total_time_enabled,
8753 &parent_event->child_total_time_enabled);
8754 atomic64_add(child_event->total_time_running,
8755 &parent_event->child_total_time_running);
d859e29f
PM
8756}
8757
9b51f66d 8758static void
8ba289b8
PZ
8759perf_event_exit_event(struct perf_event *child_event,
8760 struct perf_event_context *child_ctx,
8761 struct task_struct *child)
9b51f66d 8762{
8ba289b8
PZ
8763 struct perf_event *parent_event = child_event->parent;
8764
1903d50c
PZ
8765 /*
8766 * Do not destroy the 'original' grouping; because of the context
8767 * switch optimization the original events could've ended up in a
8768 * random child task.
8769 *
8770 * If we were to destroy the original group, all group related
8771 * operations would cease to function properly after this random
8772 * child dies.
8773 *
8774 * Do destroy all inherited groups, we don't care about those
8775 * and being thorough is better.
8776 */
32132a3d
PZ
8777 raw_spin_lock_irq(&child_ctx->lock);
8778 WARN_ON_ONCE(child_ctx->is_active);
8779
8ba289b8 8780 if (parent_event)
32132a3d
PZ
8781 perf_group_detach(child_event);
8782 list_del_event(child_event, child_ctx);
a69b0ca4 8783 child_event->state = PERF_EVENT_STATE_EXIT; /* is_event_hup() */
32132a3d 8784 raw_spin_unlock_irq(&child_ctx->lock);
0cc0c027 8785
9b51f66d 8786 /*
8ba289b8 8787 * Parent events are governed by their filedesc, retain them.
9b51f66d 8788 */
8ba289b8 8789 if (!parent_event) {
179033b3 8790 perf_event_wakeup(child_event);
8ba289b8 8791 return;
4bcf349a 8792 }
8ba289b8
PZ
8793 /*
8794 * Child events can be cleaned up.
8795 */
8796
8797 sync_child_event(child_event, child);
8798
8799 /*
8800 * Remove this event from the parent's list
8801 */
8802 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
8803 mutex_lock(&parent_event->child_mutex);
8804 list_del_init(&child_event->child_list);
8805 mutex_unlock(&parent_event->child_mutex);
8806
8807 /*
8808 * Kick perf_poll() for is_event_hup().
8809 */
8810 perf_event_wakeup(parent_event);
8811 free_event(child_event);
8812 put_event(parent_event);
9b51f66d
IM
8813}
8814
8dc85d54 8815static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
9b51f66d 8816{
211de6eb 8817 struct perf_event_context *child_ctx, *clone_ctx = NULL;
63b6da39 8818 struct perf_event *child_event, *next;
63b6da39
PZ
8819
8820 WARN_ON_ONCE(child != current);
9b51f66d 8821
6a3351b6 8822 child_ctx = perf_pin_task_context(child, ctxn);
63b6da39 8823 if (!child_ctx)
9b51f66d
IM
8824 return;
8825
ad3a37de 8826 /*
6a3351b6
PZ
8827 * In order to reduce the amount of tricky in ctx tear-down, we hold
8828 * ctx::mutex over the entire thing. This serializes against almost
8829 * everything that wants to access the ctx.
8830 *
8831 * The exception is sys_perf_event_open() /
8832 * perf_event_create_kernel_count() which does find_get_context()
8833 * without ctx::mutex (it cannot because of the move_group double mutex
8834 * lock thing). See the comments in perf_install_in_context().
ad3a37de 8835 */
6a3351b6 8836 mutex_lock(&child_ctx->mutex);
c93f7669
PM
8837
8838 /*
6a3351b6
PZ
8839 * In a single ctx::lock section, de-schedule the events and detach the
8840 * context from the task such that we cannot ever get it scheduled back
8841 * in.
c93f7669 8842 */
6a3351b6 8843 raw_spin_lock_irq(&child_ctx->lock);
63b6da39 8844 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx);
4a1c0f26 8845
71a851b4 8846 /*
63b6da39
PZ
8847 * Now that the context is inactive, destroy the task <-> ctx relation
8848 * and mark the context dead.
71a851b4 8849 */
63b6da39
PZ
8850 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
8851 put_ctx(child_ctx); /* cannot be last */
8852 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
8853 put_task_struct(current); /* cannot be last */
4a1c0f26 8854
211de6eb 8855 clone_ctx = unclone_ctx(child_ctx);
6a3351b6 8856 raw_spin_unlock_irq(&child_ctx->lock);
9f498cc5 8857
211de6eb
PZ
8858 if (clone_ctx)
8859 put_ctx(clone_ctx);
4a1c0f26 8860
9f498cc5 8861 /*
cdd6c482
IM
8862 * Report the task dead after unscheduling the events so that we
8863 * won't get any samples after PERF_RECORD_EXIT. We can however still
8864 * get a few PERF_RECORD_READ events.
9f498cc5 8865 */
cdd6c482 8866 perf_event_task(child, child_ctx, 0);
a63eaf34 8867
ebf905fc 8868 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
8ba289b8 8869 perf_event_exit_event(child_event, child_ctx, child);
8bc20959 8870
a63eaf34
PM
8871 mutex_unlock(&child_ctx->mutex);
8872
8873 put_ctx(child_ctx);
9b51f66d
IM
8874}
8875
8dc85d54
PZ
8876/*
8877 * When a child task exits, feed back event values to parent events.
8878 */
8879void perf_event_exit_task(struct task_struct *child)
8880{
8882135b 8881 struct perf_event *event, *tmp;
8dc85d54
PZ
8882 int ctxn;
8883
8882135b
PZ
8884 mutex_lock(&child->perf_event_mutex);
8885 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
8886 owner_entry) {
8887 list_del_init(&event->owner_entry);
8888
8889 /*
8890 * Ensure the list deletion is visible before we clear
8891 * the owner, closes a race against perf_release() where
8892 * we need to serialize on the owner->perf_event_mutex.
8893 */
f47c02c0 8894 smp_store_release(&event->owner, NULL);
8882135b
PZ
8895 }
8896 mutex_unlock(&child->perf_event_mutex);
8897
8dc85d54
PZ
8898 for_each_task_context_nr(ctxn)
8899 perf_event_exit_task_context(child, ctxn);
4e93ad60
JO
8900
8901 /*
8902 * The perf_event_exit_task_context calls perf_event_task
8903 * with child's task_ctx, which generates EXIT events for
8904 * child contexts and sets child->perf_event_ctxp[] to NULL.
8905 * At this point we need to send EXIT events to cpu contexts.
8906 */
8907 perf_event_task(child, NULL, 0);
8dc85d54
PZ
8908}
8909
889ff015
FW
8910static void perf_free_event(struct perf_event *event,
8911 struct perf_event_context *ctx)
8912{
8913 struct perf_event *parent = event->parent;
8914
8915 if (WARN_ON_ONCE(!parent))
8916 return;
8917
8918 mutex_lock(&parent->child_mutex);
8919 list_del_init(&event->child_list);
8920 mutex_unlock(&parent->child_mutex);
8921
a6fa941d 8922 put_event(parent);
889ff015 8923
652884fe 8924 raw_spin_lock_irq(&ctx->lock);
8a49542c 8925 perf_group_detach(event);
889ff015 8926 list_del_event(event, ctx);
652884fe 8927 raw_spin_unlock_irq(&ctx->lock);
889ff015
FW
8928 free_event(event);
8929}
8930
bbbee908 8931/*
652884fe 8932 * Free an unexposed, unused context as created by inheritance by
8dc85d54 8933 * perf_event_init_task below, used by fork() in case of fail.
652884fe
PZ
8934 *
8935 * Not all locks are strictly required, but take them anyway to be nice and
8936 * help out with the lockdep assertions.
bbbee908 8937 */
cdd6c482 8938void perf_event_free_task(struct task_struct *task)
bbbee908 8939{
8dc85d54 8940 struct perf_event_context *ctx;
cdd6c482 8941 struct perf_event *event, *tmp;
8dc85d54 8942 int ctxn;
bbbee908 8943
8dc85d54
PZ
8944 for_each_task_context_nr(ctxn) {
8945 ctx = task->perf_event_ctxp[ctxn];
8946 if (!ctx)
8947 continue;
bbbee908 8948
8dc85d54 8949 mutex_lock(&ctx->mutex);
bbbee908 8950again:
8dc85d54
PZ
8951 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
8952 group_entry)
8953 perf_free_event(event, ctx);
bbbee908 8954
8dc85d54
PZ
8955 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
8956 group_entry)
8957 perf_free_event(event, ctx);
bbbee908 8958
8dc85d54
PZ
8959 if (!list_empty(&ctx->pinned_groups) ||
8960 !list_empty(&ctx->flexible_groups))
8961 goto again;
bbbee908 8962
8dc85d54 8963 mutex_unlock(&ctx->mutex);
bbbee908 8964
8dc85d54
PZ
8965 put_ctx(ctx);
8966 }
889ff015
FW
8967}
8968
4e231c79
PZ
8969void perf_event_delayed_put(struct task_struct *task)
8970{
8971 int ctxn;
8972
8973 for_each_task_context_nr(ctxn)
8974 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
8975}
8976
e03e7ee3 8977struct file *perf_event_get(unsigned int fd)
ffe8690c 8978{
e03e7ee3 8979 struct file *file;
ffe8690c 8980
e03e7ee3
AS
8981 file = fget_raw(fd);
8982 if (!file)
8983 return ERR_PTR(-EBADF);
ffe8690c 8984
e03e7ee3
AS
8985 if (file->f_op != &perf_fops) {
8986 fput(file);
8987 return ERR_PTR(-EBADF);
8988 }
ffe8690c 8989
e03e7ee3 8990 return file;
ffe8690c
KX
8991}
8992
8993const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
8994{
8995 if (!event)
8996 return ERR_PTR(-EINVAL);
8997
8998 return &event->attr;
8999}
9000
97dee4f3
PZ
9001/*
9002 * inherit a event from parent task to child task:
9003 */
9004static struct perf_event *
9005inherit_event(struct perf_event *parent_event,
9006 struct task_struct *parent,
9007 struct perf_event_context *parent_ctx,
9008 struct task_struct *child,
9009 struct perf_event *group_leader,
9010 struct perf_event_context *child_ctx)
9011{
1929def9 9012 enum perf_event_active_state parent_state = parent_event->state;
97dee4f3 9013 struct perf_event *child_event;
cee010ec 9014 unsigned long flags;
97dee4f3
PZ
9015
9016 /*
9017 * Instead of creating recursive hierarchies of events,
9018 * we link inherited events back to the original parent,
9019 * which has a filp for sure, which we use as the reference
9020 * count:
9021 */
9022 if (parent_event->parent)
9023 parent_event = parent_event->parent;
9024
9025 child_event = perf_event_alloc(&parent_event->attr,
9026 parent_event->cpu,
d580ff86 9027 child,
97dee4f3 9028 group_leader, parent_event,
79dff51e 9029 NULL, NULL, -1);
97dee4f3
PZ
9030 if (IS_ERR(child_event))
9031 return child_event;
a6fa941d 9032
c6e5b732
PZ
9033 /*
9034 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
9035 * must be under the same lock in order to serialize against
9036 * perf_event_release_kernel(), such that either we must observe
9037 * is_orphaned_event() or they will observe us on the child_list.
9038 */
9039 mutex_lock(&parent_event->child_mutex);
fadfe7be
JO
9040 if (is_orphaned_event(parent_event) ||
9041 !atomic_long_inc_not_zero(&parent_event->refcount)) {
c6e5b732 9042 mutex_unlock(&parent_event->child_mutex);
a6fa941d
AV
9043 free_event(child_event);
9044 return NULL;
9045 }
9046
97dee4f3
PZ
9047 get_ctx(child_ctx);
9048
9049 /*
9050 * Make the child state follow the state of the parent event,
9051 * not its attr.disabled bit. We hold the parent's mutex,
9052 * so we won't race with perf_event_{en, dis}able_family.
9053 */
1929def9 9054 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
97dee4f3
PZ
9055 child_event->state = PERF_EVENT_STATE_INACTIVE;
9056 else
9057 child_event->state = PERF_EVENT_STATE_OFF;
9058
9059 if (parent_event->attr.freq) {
9060 u64 sample_period = parent_event->hw.sample_period;
9061 struct hw_perf_event *hwc = &child_event->hw;
9062
9063 hwc->sample_period = sample_period;
9064 hwc->last_period = sample_period;
9065
9066 local64_set(&hwc->period_left, sample_period);
9067 }
9068
9069 child_event->ctx = child_ctx;
9070 child_event->overflow_handler = parent_event->overflow_handler;
4dc0da86
AK
9071 child_event->overflow_handler_context
9072 = parent_event->overflow_handler_context;
97dee4f3 9073
614b6780
TG
9074 /*
9075 * Precalculate sample_data sizes
9076 */
9077 perf_event__header_size(child_event);
6844c09d 9078 perf_event__id_header_size(child_event);
614b6780 9079
97dee4f3
PZ
9080 /*
9081 * Link it up in the child's context:
9082 */
cee010ec 9083 raw_spin_lock_irqsave(&child_ctx->lock, flags);
97dee4f3 9084 add_event_to_ctx(child_event, child_ctx);
cee010ec 9085 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
97dee4f3 9086
97dee4f3
PZ
9087 /*
9088 * Link this into the parent event's child list
9089 */
97dee4f3
PZ
9090 list_add_tail(&child_event->child_list, &parent_event->child_list);
9091 mutex_unlock(&parent_event->child_mutex);
9092
9093 return child_event;
9094}
9095
9096static int inherit_group(struct perf_event *parent_event,
9097 struct task_struct *parent,
9098 struct perf_event_context *parent_ctx,
9099 struct task_struct *child,
9100 struct perf_event_context *child_ctx)
9101{
9102 struct perf_event *leader;
9103 struct perf_event *sub;
9104 struct perf_event *child_ctr;
9105
9106 leader = inherit_event(parent_event, parent, parent_ctx,
9107 child, NULL, child_ctx);
9108 if (IS_ERR(leader))
9109 return PTR_ERR(leader);
9110 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
9111 child_ctr = inherit_event(sub, parent, parent_ctx,
9112 child, leader, child_ctx);
9113 if (IS_ERR(child_ctr))
9114 return PTR_ERR(child_ctr);
9115 }
9116 return 0;
889ff015
FW
9117}
9118
9119static int
9120inherit_task_group(struct perf_event *event, struct task_struct *parent,
9121 struct perf_event_context *parent_ctx,
8dc85d54 9122 struct task_struct *child, int ctxn,
889ff015
FW
9123 int *inherited_all)
9124{
9125 int ret;
8dc85d54 9126 struct perf_event_context *child_ctx;
889ff015
FW
9127
9128 if (!event->attr.inherit) {
9129 *inherited_all = 0;
9130 return 0;
bbbee908
PZ
9131 }
9132
fe4b04fa 9133 child_ctx = child->perf_event_ctxp[ctxn];
889ff015
FW
9134 if (!child_ctx) {
9135 /*
9136 * This is executed from the parent task context, so
9137 * inherit events that have been marked for cloning.
9138 * First allocate and initialize a context for the
9139 * child.
9140 */
bbbee908 9141
734df5ab 9142 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
889ff015
FW
9143 if (!child_ctx)
9144 return -ENOMEM;
bbbee908 9145
8dc85d54 9146 child->perf_event_ctxp[ctxn] = child_ctx;
889ff015
FW
9147 }
9148
9149 ret = inherit_group(event, parent, parent_ctx,
9150 child, child_ctx);
9151
9152 if (ret)
9153 *inherited_all = 0;
9154
9155 return ret;
bbbee908
PZ
9156}
9157
9b51f66d 9158/*
cdd6c482 9159 * Initialize the perf_event context in task_struct
9b51f66d 9160 */
985c8dcb 9161static int perf_event_init_context(struct task_struct *child, int ctxn)
9b51f66d 9162{
889ff015 9163 struct perf_event_context *child_ctx, *parent_ctx;
cdd6c482
IM
9164 struct perf_event_context *cloned_ctx;
9165 struct perf_event *event;
9b51f66d 9166 struct task_struct *parent = current;
564c2b21 9167 int inherited_all = 1;
dddd3379 9168 unsigned long flags;
6ab423e0 9169 int ret = 0;
9b51f66d 9170
8dc85d54 9171 if (likely(!parent->perf_event_ctxp[ctxn]))
6ab423e0
PZ
9172 return 0;
9173
ad3a37de 9174 /*
25346b93
PM
9175 * If the parent's context is a clone, pin it so it won't get
9176 * swapped under us.
ad3a37de 9177 */
8dc85d54 9178 parent_ctx = perf_pin_task_context(parent, ctxn);
ffb4ef21
PZ
9179 if (!parent_ctx)
9180 return 0;
25346b93 9181
ad3a37de
PM
9182 /*
9183 * No need to check if parent_ctx != NULL here; since we saw
9184 * it non-NULL earlier, the only reason for it to become NULL
9185 * is if we exit, and since we're currently in the middle of
9186 * a fork we can't be exiting at the same time.
9187 */
ad3a37de 9188
9b51f66d
IM
9189 /*
9190 * Lock the parent list. No need to lock the child - not PID
9191 * hashed yet and not running, so nobody can access it.
9192 */
d859e29f 9193 mutex_lock(&parent_ctx->mutex);
9b51f66d
IM
9194
9195 /*
9196 * We dont have to disable NMIs - we are only looking at
9197 * the list, not manipulating it:
9198 */
889ff015 9199 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
8dc85d54
PZ
9200 ret = inherit_task_group(event, parent, parent_ctx,
9201 child, ctxn, &inherited_all);
889ff015
FW
9202 if (ret)
9203 break;
9204 }
b93f7978 9205
dddd3379
TG
9206 /*
9207 * We can't hold ctx->lock when iterating the ->flexible_group list due
9208 * to allocations, but we need to prevent rotation because
9209 * rotate_ctx() will change the list from interrupt context.
9210 */
9211 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9212 parent_ctx->rotate_disable = 1;
9213 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
9214
889ff015 9215 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
8dc85d54
PZ
9216 ret = inherit_task_group(event, parent, parent_ctx,
9217 child, ctxn, &inherited_all);
889ff015 9218 if (ret)
9b51f66d 9219 break;
564c2b21
PM
9220 }
9221
dddd3379
TG
9222 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
9223 parent_ctx->rotate_disable = 0;
dddd3379 9224
8dc85d54 9225 child_ctx = child->perf_event_ctxp[ctxn];
889ff015 9226
05cbaa28 9227 if (child_ctx && inherited_all) {
564c2b21
PM
9228 /*
9229 * Mark the child context as a clone of the parent
9230 * context, or of whatever the parent is a clone of.
c5ed5145
PZ
9231 *
9232 * Note that if the parent is a clone, the holding of
9233 * parent_ctx->lock avoids it from being uncloned.
564c2b21 9234 */
c5ed5145 9235 cloned_ctx = parent_ctx->parent_ctx;
ad3a37de
PM
9236 if (cloned_ctx) {
9237 child_ctx->parent_ctx = cloned_ctx;
25346b93 9238 child_ctx->parent_gen = parent_ctx->parent_gen;
564c2b21
PM
9239 } else {
9240 child_ctx->parent_ctx = parent_ctx;
9241 child_ctx->parent_gen = parent_ctx->generation;
9242 }
9243 get_ctx(child_ctx->parent_ctx);
9b51f66d
IM
9244 }
9245
c5ed5145 9246 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
d859e29f 9247 mutex_unlock(&parent_ctx->mutex);
6ab423e0 9248
25346b93 9249 perf_unpin_context(parent_ctx);
fe4b04fa 9250 put_ctx(parent_ctx);
ad3a37de 9251
6ab423e0 9252 return ret;
9b51f66d
IM
9253}
9254
8dc85d54
PZ
9255/*
9256 * Initialize the perf_event context in task_struct
9257 */
9258int perf_event_init_task(struct task_struct *child)
9259{
9260 int ctxn, ret;
9261
8550d7cb
ON
9262 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
9263 mutex_init(&child->perf_event_mutex);
9264 INIT_LIST_HEAD(&child->perf_event_list);
9265
8dc85d54
PZ
9266 for_each_task_context_nr(ctxn) {
9267 ret = perf_event_init_context(child, ctxn);
6c72e350
PZ
9268 if (ret) {
9269 perf_event_free_task(child);
8dc85d54 9270 return ret;
6c72e350 9271 }
8dc85d54
PZ
9272 }
9273
9274 return 0;
9275}
9276
220b140b
PM
9277static void __init perf_event_init_all_cpus(void)
9278{
b28ab83c 9279 struct swevent_htable *swhash;
220b140b 9280 int cpu;
220b140b
PM
9281
9282 for_each_possible_cpu(cpu) {
b28ab83c
PZ
9283 swhash = &per_cpu(swevent_htable, cpu);
9284 mutex_init(&swhash->hlist_mutex);
2fde4f94 9285 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
220b140b
PM
9286 }
9287}
9288
0db0628d 9289static void perf_event_init_cpu(int cpu)
0793a61d 9290{
108b02cf 9291 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
0793a61d 9292
b28ab83c 9293 mutex_lock(&swhash->hlist_mutex);
059fcd8c 9294 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
76e1d904
FW
9295 struct swevent_hlist *hlist;
9296
b28ab83c
PZ
9297 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
9298 WARN_ON(!hlist);
9299 rcu_assign_pointer(swhash->swevent_hlist, hlist);
76e1d904 9300 }
b28ab83c 9301 mutex_unlock(&swhash->hlist_mutex);
0793a61d
TG
9302}
9303
2965faa5 9304#if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
108b02cf 9305static void __perf_event_exit_context(void *__info)
0793a61d 9306{
108b02cf 9307 struct perf_event_context *ctx = __info;
fae3fde6
PZ
9308 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
9309 struct perf_event *event;
0793a61d 9310
fae3fde6
PZ
9311 raw_spin_lock(&ctx->lock);
9312 list_for_each_entry(event, &ctx->event_list, event_entry)
45a0e07a 9313 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
fae3fde6 9314 raw_spin_unlock(&ctx->lock);
0793a61d 9315}
108b02cf
PZ
9316
9317static void perf_event_exit_cpu_context(int cpu)
9318{
9319 struct perf_event_context *ctx;
9320 struct pmu *pmu;
9321 int idx;
9322
9323 idx = srcu_read_lock(&pmus_srcu);
9324 list_for_each_entry_rcu(pmu, &pmus, entry) {
917bdd1c 9325 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
108b02cf
PZ
9326
9327 mutex_lock(&ctx->mutex);
9328 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
9329 mutex_unlock(&ctx->mutex);
9330 }
9331 srcu_read_unlock(&pmus_srcu, idx);
108b02cf
PZ
9332}
9333
cdd6c482 9334static void perf_event_exit_cpu(int cpu)
0793a61d 9335{
e3703f8c 9336 perf_event_exit_cpu_context(cpu);
0793a61d
TG
9337}
9338#else
cdd6c482 9339static inline void perf_event_exit_cpu(int cpu) { }
0793a61d
TG
9340#endif
9341
c277443c
PZ
9342static int
9343perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
9344{
9345 int cpu;
9346
9347 for_each_online_cpu(cpu)
9348 perf_event_exit_cpu(cpu);
9349
9350 return NOTIFY_OK;
9351}
9352
9353/*
9354 * Run the perf reboot notifier at the very last possible moment so that
9355 * the generic watchdog code runs as long as possible.
9356 */
9357static struct notifier_block perf_reboot_notifier = {
9358 .notifier_call = perf_reboot,
9359 .priority = INT_MIN,
9360};
9361
0db0628d 9362static int
0793a61d
TG
9363perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
9364{
9365 unsigned int cpu = (long)hcpu;
9366
4536e4d1 9367 switch (action & ~CPU_TASKS_FROZEN) {
0793a61d
TG
9368
9369 case CPU_UP_PREPARE:
cdd6c482 9370 perf_event_init_cpu(cpu);
0793a61d
TG
9371 break;
9372
9373 case CPU_DOWN_PREPARE:
cdd6c482 9374 perf_event_exit_cpu(cpu);
0793a61d 9375 break;
0793a61d
TG
9376 default:
9377 break;
9378 }
9379
9380 return NOTIFY_OK;
9381}
9382
cdd6c482 9383void __init perf_event_init(void)
0793a61d 9384{
3c502e7a
JW
9385 int ret;
9386
2e80a82a
PZ
9387 idr_init(&pmu_idr);
9388
220b140b 9389 perf_event_init_all_cpus();
b0a873eb 9390 init_srcu_struct(&pmus_srcu);
2e80a82a
PZ
9391 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
9392 perf_pmu_register(&perf_cpu_clock, NULL, -1);
9393 perf_pmu_register(&perf_task_clock, NULL, -1);
b0a873eb
PZ
9394 perf_tp_register();
9395 perf_cpu_notifier(perf_cpu_notify);
c277443c 9396 register_reboot_notifier(&perf_reboot_notifier);
3c502e7a
JW
9397
9398 ret = init_hw_breakpoint();
9399 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
b2029520 9400
b01c3a00
JO
9401 /*
9402 * Build time assertion that we keep the data_head at the intended
9403 * location. IOW, validation we got the __reserved[] size right.
9404 */
9405 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
9406 != 1024);
0793a61d 9407}
abe43400 9408
fd979c01
CS
9409ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
9410 char *page)
9411{
9412 struct perf_pmu_events_attr *pmu_attr =
9413 container_of(attr, struct perf_pmu_events_attr, attr);
9414
9415 if (pmu_attr->event_str)
9416 return sprintf(page, "%s\n", pmu_attr->event_str);
9417
9418 return 0;
9419}
9420
abe43400
PZ
9421static int __init perf_event_sysfs_init(void)
9422{
9423 struct pmu *pmu;
9424 int ret;
9425
9426 mutex_lock(&pmus_lock);
9427
9428 ret = bus_register(&pmu_bus);
9429 if (ret)
9430 goto unlock;
9431
9432 list_for_each_entry(pmu, &pmus, entry) {
9433 if (!pmu->name || pmu->type < 0)
9434 continue;
9435
9436 ret = pmu_dev_alloc(pmu);
9437 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
9438 }
9439 pmu_bus_running = 1;
9440 ret = 0;
9441
9442unlock:
9443 mutex_unlock(&pmus_lock);
9444
9445 return ret;
9446}
9447device_initcall(perf_event_sysfs_init);
e5d1367f
SE
9448
9449#ifdef CONFIG_CGROUP_PERF
eb95419b
TH
9450static struct cgroup_subsys_state *
9451perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
e5d1367f
SE
9452{
9453 struct perf_cgroup *jc;
e5d1367f 9454
1b15d055 9455 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
e5d1367f
SE
9456 if (!jc)
9457 return ERR_PTR(-ENOMEM);
9458
e5d1367f
SE
9459 jc->info = alloc_percpu(struct perf_cgroup_info);
9460 if (!jc->info) {
9461 kfree(jc);
9462 return ERR_PTR(-ENOMEM);
9463 }
9464
e5d1367f
SE
9465 return &jc->css;
9466}
9467
eb95419b 9468static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
e5d1367f 9469{
eb95419b
TH
9470 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
9471
e5d1367f
SE
9472 free_percpu(jc->info);
9473 kfree(jc);
9474}
9475
9476static int __perf_cgroup_move(void *info)
9477{
9478 struct task_struct *task = info;
ddaaf4e2 9479 rcu_read_lock();
e5d1367f 9480 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
ddaaf4e2 9481 rcu_read_unlock();
e5d1367f
SE
9482 return 0;
9483}
9484
1f7dd3e5 9485static void perf_cgroup_attach(struct cgroup_taskset *tset)
e5d1367f 9486{
bb9d97b6 9487 struct task_struct *task;
1f7dd3e5 9488 struct cgroup_subsys_state *css;
bb9d97b6 9489
1f7dd3e5 9490 cgroup_taskset_for_each(task, css, tset)
bb9d97b6 9491 task_function_call(task, __perf_cgroup_move, task);
e5d1367f
SE
9492}
9493
073219e9 9494struct cgroup_subsys perf_event_cgrp_subsys = {
92fb9748
TH
9495 .css_alloc = perf_cgroup_css_alloc,
9496 .css_free = perf_cgroup_css_free,
bb9d97b6 9497 .attach = perf_cgroup_attach,
e5d1367f
SE
9498};
9499#endif /* CONFIG_CGROUP_PERF */