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