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