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