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