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