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