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