1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * Performance events core code:
4 *
5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar
7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra
8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 */
10
11 #include <linux/fs.h>
12 #include <linux/mm.h>
13 #include <linux/cpu.h>
14 #include <linux/smp.h>
15 #include <linux/idr.h>
16 #include <linux/file.h>
17 #include <linux/poll.h>
18 #include <linux/slab.h>
19 #include <linux/hash.h>
20 #include <linux/tick.h>
21 #include <linux/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/export.h>
29 #include <linux/vmalloc.h>
30 #include <linux/hardirq.h>
31 #include <linux/rculist.h>
32 #include <linux/uaccess.h>
33 #include <linux/syscalls.h>
34 #include <linux/anon_inodes.h>
35 #include <linux/kernel_stat.h>
36 #include <linux/cgroup.h>
37 #include <linux/perf_event.h>
38 #include <linux/trace_events.h>
39 #include <linux/hw_breakpoint.h>
40 #include <linux/mm_types.h>
41 #include <linux/module.h>
42 #include <linux/mman.h>
43 #include <linux/compat.h>
44 #include <linux/bpf.h>
45 #include <linux/filter.h>
46 #include <linux/namei.h>
47 #include <linux/parser.h>
48 #include <linux/sched/clock.h>
49 #include <linux/sched/mm.h>
50 #include <linux/proc_ns.h>
51 #include <linux/mount.h>
52
53 #include "internal.h"
54
55 #include <asm/irq_regs.h>
56
57 typedef int (*remote_function_f)(void *);
58
59 struct remote_function_call {
60 struct task_struct *p;
61 remote_function_f func;
62 void *info;
63 int ret;
64 };
65
remote_function(void * data)66 static void remote_function(void *data)
67 {
68 struct remote_function_call *tfc = data;
69 struct task_struct *p = tfc->p;
70
71 if (p) {
72 /* -EAGAIN */
73 if (task_cpu(p) != smp_processor_id())
74 return;
75
76 /*
77 * Now that we're on right CPU with IRQs disabled, we can test
78 * if we hit the right task without races.
79 */
80
81 tfc->ret = -ESRCH; /* No such (running) process */
82 if (p != current)
83 return;
84 }
85
86 tfc->ret = tfc->func(tfc->info);
87 }
88
89 /**
90 * task_function_call - call a function on the cpu on which a task runs
91 * @p: the task to evaluate
92 * @func: the function to be called
93 * @info: the function call argument
94 *
95 * Calls the function @func when the task is currently running. This might
96 * be on the current CPU, which just calls the function directly. This will
97 * retry due to any failures in smp_call_function_single(), such as if the
98 * task_cpu() goes offline concurrently.
99 *
100 * returns @func return value or -ESRCH or -ENXIO when the process isn't running
101 */
102 static int
task_function_call(struct task_struct * p,remote_function_f func,void * info)103 task_function_call(struct task_struct *p, remote_function_f func, void *info)
104 {
105 struct remote_function_call data = {
106 .p = p,
107 .func = func,
108 .info = info,
109 .ret = -EAGAIN,
110 };
111 int ret;
112
113 for (;;) {
114 ret = smp_call_function_single(task_cpu(p), remote_function,
115 &data, 1);
116 if (!ret)
117 ret = data.ret;
118
119 if (ret != -EAGAIN)
120 break;
121
122 cond_resched();
123 }
124
125 return ret;
126 }
127
128 /**
129 * cpu_function_call - call a function on the cpu
130 * @func: the function to be called
131 * @info: the function call argument
132 *
133 * Calls the function @func on the remote cpu.
134 *
135 * returns: @func return value or -ENXIO when the cpu is offline
136 */
cpu_function_call(int cpu,remote_function_f func,void * info)137 static int cpu_function_call(int cpu, remote_function_f func, void *info)
138 {
139 struct remote_function_call data = {
140 .p = NULL,
141 .func = func,
142 .info = info,
143 .ret = -ENXIO, /* No such CPU */
144 };
145
146 smp_call_function_single(cpu, remote_function, &data, 1);
147
148 return data.ret;
149 }
150
151 static inline struct perf_cpu_context *
__get_cpu_context(struct perf_event_context * ctx)152 __get_cpu_context(struct perf_event_context *ctx)
153 {
154 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
155 }
156
perf_ctx_lock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)157 static void perf_ctx_lock(struct perf_cpu_context *cpuctx,
158 struct perf_event_context *ctx)
159 {
160 raw_spin_lock(&cpuctx->ctx.lock);
161 if (ctx)
162 raw_spin_lock(&ctx->lock);
163 }
164
perf_ctx_unlock(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)165 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx,
166 struct perf_event_context *ctx)
167 {
168 if (ctx)
169 raw_spin_unlock(&ctx->lock);
170 raw_spin_unlock(&cpuctx->ctx.lock);
171 }
172
173 #define TASK_TOMBSTONE ((void *)-1L)
174
is_kernel_event(struct perf_event * event)175 static bool is_kernel_event(struct perf_event *event)
176 {
177 return READ_ONCE(event->owner) == TASK_TOMBSTONE;
178 }
179
180 /*
181 * On task ctx scheduling...
182 *
183 * When !ctx->nr_events a task context will not be scheduled. This means
184 * we can disable the scheduler hooks (for performance) without leaving
185 * pending task ctx state.
186 *
187 * This however results in two special cases:
188 *
189 * - removing the last event from a task ctx; this is relatively straight
190 * forward and is done in __perf_remove_from_context.
191 *
192 * - adding the first event to a task ctx; this is tricky because we cannot
193 * rely on ctx->is_active and therefore cannot use event_function_call().
194 * See perf_install_in_context().
195 *
196 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set.
197 */
198
199 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *,
200 struct perf_event_context *, void *);
201
202 struct event_function_struct {
203 struct perf_event *event;
204 event_f func;
205 void *data;
206 };
207
event_function(void * info)208 static int event_function(void *info)
209 {
210 struct event_function_struct *efs = info;
211 struct perf_event *event = efs->event;
212 struct perf_event_context *ctx = event->ctx;
213 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
214 struct perf_event_context *task_ctx = cpuctx->task_ctx;
215 int ret = 0;
216
217 lockdep_assert_irqs_disabled();
218
219 perf_ctx_lock(cpuctx, task_ctx);
220 /*
221 * Since we do the IPI call without holding ctx->lock things can have
222 * changed, double check we hit the task we set out to hit.
223 */
224 if (ctx->task) {
225 if (ctx->task != current) {
226 ret = -ESRCH;
227 goto unlock;
228 }
229
230 /*
231 * We only use event_function_call() on established contexts,
232 * and event_function() is only ever called when active (or
233 * rather, we'll have bailed in task_function_call() or the
234 * above ctx->task != current test), therefore we must have
235 * ctx->is_active here.
236 */
237 WARN_ON_ONCE(!ctx->is_active);
238 /*
239 * And since we have ctx->is_active, cpuctx->task_ctx must
240 * match.
241 */
242 WARN_ON_ONCE(task_ctx != ctx);
243 } else {
244 WARN_ON_ONCE(&cpuctx->ctx != ctx);
245 }
246
247 efs->func(event, cpuctx, ctx, efs->data);
248 unlock:
249 perf_ctx_unlock(cpuctx, task_ctx);
250
251 return ret;
252 }
253
event_function_call(struct perf_event * event,event_f func,void * data)254 static void event_function_call(struct perf_event *event, event_f func, void *data)
255 {
256 struct perf_event_context *ctx = event->ctx;
257 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */
258 struct event_function_struct efs = {
259 .event = event,
260 .func = func,
261 .data = data,
262 };
263
264 if (!event->parent) {
265 /*
266 * If this is a !child event, we must hold ctx::mutex to
267 * stabilize the the event->ctx relation. See
268 * perf_event_ctx_lock().
269 */
270 lockdep_assert_held(&ctx->mutex);
271 }
272
273 if (!task) {
274 cpu_function_call(event->cpu, event_function, &efs);
275 return;
276 }
277
278 if (task == TASK_TOMBSTONE)
279 return;
280
281 again:
282 if (!task_function_call(task, event_function, &efs))
283 return;
284
285 raw_spin_lock_irq(&ctx->lock);
286 /*
287 * Reload the task pointer, it might have been changed by
288 * a concurrent perf_event_context_sched_out().
289 */
290 task = ctx->task;
291 if (task == TASK_TOMBSTONE) {
292 raw_spin_unlock_irq(&ctx->lock);
293 return;
294 }
295 if (ctx->is_active) {
296 raw_spin_unlock_irq(&ctx->lock);
297 goto again;
298 }
299 func(event, NULL, ctx, data);
300 raw_spin_unlock_irq(&ctx->lock);
301 }
302
303 /*
304 * Similar to event_function_call() + event_function(), but hard assumes IRQs
305 * are already disabled and we're on the right CPU.
306 */
event_function_local(struct perf_event * event,event_f func,void * data)307 static void event_function_local(struct perf_event *event, event_f func, void *data)
308 {
309 struct perf_event_context *ctx = event->ctx;
310 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
311 struct task_struct *task = READ_ONCE(ctx->task);
312 struct perf_event_context *task_ctx = NULL;
313
314 lockdep_assert_irqs_disabled();
315
316 if (task) {
317 if (task == TASK_TOMBSTONE)
318 return;
319
320 task_ctx = ctx;
321 }
322
323 perf_ctx_lock(cpuctx, task_ctx);
324
325 task = ctx->task;
326 if (task == TASK_TOMBSTONE)
327 goto unlock;
328
329 if (task) {
330 /*
331 * We must be either inactive or active and the right task,
332 * otherwise we're screwed, since we cannot IPI to somewhere
333 * else.
334 */
335 if (ctx->is_active) {
336 if (WARN_ON_ONCE(task != current))
337 goto unlock;
338
339 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx))
340 goto unlock;
341 }
342 } else {
343 WARN_ON_ONCE(&cpuctx->ctx != ctx);
344 }
345
346 func(event, cpuctx, ctx, data);
347 unlock:
348 perf_ctx_unlock(cpuctx, task_ctx);
349 }
350
351 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\
352 PERF_FLAG_FD_OUTPUT |\
353 PERF_FLAG_PID_CGROUP |\
354 PERF_FLAG_FD_CLOEXEC)
355
356 /*
357 * branch priv levels that need permission checks
358 */
359 #define PERF_SAMPLE_BRANCH_PERM_PLM \
360 (PERF_SAMPLE_BRANCH_KERNEL |\
361 PERF_SAMPLE_BRANCH_HV)
362
363 enum event_type_t {
364 EVENT_FLEXIBLE = 0x1,
365 EVENT_PINNED = 0x2,
366 EVENT_TIME = 0x4,
367 /* see ctx_resched() for details */
368 EVENT_CPU = 0x8,
369 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
370 };
371
372 /*
373 * perf_sched_events : >0 events exist
374 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu
375 */
376
377 static void perf_sched_delayed(struct work_struct *work);
378 DEFINE_STATIC_KEY_FALSE(perf_sched_events);
379 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed);
380 static DEFINE_MUTEX(perf_sched_mutex);
381 static atomic_t perf_sched_count;
382
383 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events);
384 static DEFINE_PER_CPU(int, perf_sched_cb_usages);
385 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events);
386
387 static atomic_t nr_mmap_events __read_mostly;
388 static atomic_t nr_comm_events __read_mostly;
389 static atomic_t nr_namespaces_events __read_mostly;
390 static atomic_t nr_task_events __read_mostly;
391 static atomic_t nr_freq_events __read_mostly;
392 static atomic_t nr_switch_events __read_mostly;
393 static atomic_t nr_ksymbol_events __read_mostly;
394 static atomic_t nr_bpf_events __read_mostly;
395
396 static LIST_HEAD(pmus);
397 static DEFINE_MUTEX(pmus_lock);
398 static struct srcu_struct pmus_srcu;
399 static cpumask_var_t perf_online_mask;
400
401 /*
402 * perf event paranoia level:
403 * -1 - not paranoid at all
404 * 0 - disallow raw tracepoint access for unpriv
405 * 1 - disallow cpu events for unpriv
406 * 2 - disallow kernel profiling for unpriv
407 */
408 int sysctl_perf_event_paranoid __read_mostly = 2;
409
410 /* Minimum for 512 kiB + 1 user control page */
411 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */
412
413 /*
414 * max perf event sample rate
415 */
416 #define DEFAULT_MAX_SAMPLE_RATE 100000
417 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE)
418 #define DEFAULT_CPU_TIME_MAX_PERCENT 25
419
420 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE;
421
422 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ);
423 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS;
424
425 static int perf_sample_allowed_ns __read_mostly =
426 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100;
427
update_perf_cpu_limits(void)428 static void update_perf_cpu_limits(void)
429 {
430 u64 tmp = perf_sample_period_ns;
431
432 tmp *= sysctl_perf_cpu_time_max_percent;
433 tmp = div_u64(tmp, 100);
434 if (!tmp)
435 tmp = 1;
436
437 WRITE_ONCE(perf_sample_allowed_ns, tmp);
438 }
439
440 static bool perf_rotate_context(struct perf_cpu_context *cpuctx);
441
perf_proc_update_handler(struct ctl_table * table,int write,void __user * buffer,size_t * lenp,loff_t * ppos)442 int perf_proc_update_handler(struct ctl_table *table, int write,
443 void __user *buffer, size_t *lenp,
444 loff_t *ppos)
445 {
446 int ret;
447 int perf_cpu = sysctl_perf_cpu_time_max_percent;
448 /*
449 * If throttling is disabled don't allow the write:
450 */
451 if (write && (perf_cpu == 100 || perf_cpu == 0))
452 return -EINVAL;
453
454 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
455 if (ret || !write)
456 return ret;
457
458 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ);
459 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
460 update_perf_cpu_limits();
461
462 return 0;
463 }
464
465 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT;
466
perf_cpu_time_max_percent_handler(struct ctl_table * table,int write,void __user * buffer,size_t * lenp,loff_t * ppos)467 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write,
468 void __user *buffer, size_t *lenp,
469 loff_t *ppos)
470 {
471 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
472
473 if (ret || !write)
474 return ret;
475
476 if (sysctl_perf_cpu_time_max_percent == 100 ||
477 sysctl_perf_cpu_time_max_percent == 0) {
478 printk(KERN_WARNING
479 "perf: Dynamic interrupt throttling disabled, can hang your system!\n");
480 WRITE_ONCE(perf_sample_allowed_ns, 0);
481 } else {
482 update_perf_cpu_limits();
483 }
484
485 return 0;
486 }
487
488 /*
489 * perf samples are done in some very critical code paths (NMIs).
490 * If they take too much CPU time, the system can lock up and not
491 * get any real work done. This will drop the sample rate when
492 * we detect that events are taking too long.
493 */
494 #define NR_ACCUMULATED_SAMPLES 128
495 static DEFINE_PER_CPU(u64, running_sample_length);
496
497 static u64 __report_avg;
498 static u64 __report_allowed;
499
perf_duration_warn(struct irq_work * w)500 static void perf_duration_warn(struct irq_work *w)
501 {
502 printk_ratelimited(KERN_INFO
503 "perf: interrupt took too long (%lld > %lld), lowering "
504 "kernel.perf_event_max_sample_rate to %d\n",
505 __report_avg, __report_allowed,
506 sysctl_perf_event_sample_rate);
507 }
508
509 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn);
510
perf_sample_event_took(u64 sample_len_ns)511 void perf_sample_event_took(u64 sample_len_ns)
512 {
513 u64 max_len = READ_ONCE(perf_sample_allowed_ns);
514 u64 running_len;
515 u64 avg_len;
516 u32 max;
517
518 if (max_len == 0)
519 return;
520
521 /* Decay the counter by 1 average sample. */
522 running_len = __this_cpu_read(running_sample_length);
523 running_len -= running_len/NR_ACCUMULATED_SAMPLES;
524 running_len += sample_len_ns;
525 __this_cpu_write(running_sample_length, running_len);
526
527 /*
528 * Note: this will be biased artifically low until we have
529 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us
530 * from having to maintain a count.
531 */
532 avg_len = running_len/NR_ACCUMULATED_SAMPLES;
533 if (avg_len <= max_len)
534 return;
535
536 __report_avg = avg_len;
537 __report_allowed = max_len;
538
539 /*
540 * Compute a throttle threshold 25% below the current duration.
541 */
542 avg_len += avg_len / 4;
543 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent;
544 if (avg_len < max)
545 max /= (u32)avg_len;
546 else
547 max = 1;
548
549 WRITE_ONCE(perf_sample_allowed_ns, avg_len);
550 WRITE_ONCE(max_samples_per_tick, max);
551
552 sysctl_perf_event_sample_rate = max * HZ;
553 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate;
554
555 if (!irq_work_queue(&perf_duration_work)) {
556 early_printk("perf: interrupt took too long (%lld > %lld), lowering "
557 "kernel.perf_event_max_sample_rate to %d\n",
558 __report_avg, __report_allowed,
559 sysctl_perf_event_sample_rate);
560 }
561 }
562
563 static atomic64_t perf_event_id;
564
565 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
566 enum event_type_t event_type);
567
568 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
569 enum event_type_t event_type,
570 struct task_struct *task);
571
572 static void update_context_time(struct perf_event_context *ctx);
573 static u64 perf_event_time(struct perf_event *event);
574
perf_event_print_debug(void)575 void __weak perf_event_print_debug(void) { }
576
perf_pmu_name(void)577 extern __weak const char *perf_pmu_name(void)
578 {
579 return "pmu";
580 }
581
perf_clock(void)582 static inline u64 perf_clock(void)
583 {
584 return local_clock();
585 }
586
perf_event_clock(struct perf_event * event)587 static inline u64 perf_event_clock(struct perf_event *event)
588 {
589 return event->clock();
590 }
591
592 /*
593 * State based event timekeeping...
594 *
595 * The basic idea is to use event->state to determine which (if any) time
596 * fields to increment with the current delta. This means we only need to
597 * update timestamps when we change state or when they are explicitly requested
598 * (read).
599 *
600 * Event groups make things a little more complicated, but not terribly so. The
601 * rules for a group are that if the group leader is OFF the entire group is
602 * OFF, irrespecive of what the group member states are. This results in
603 * __perf_effective_state().
604 *
605 * A futher ramification is that when a group leader flips between OFF and
606 * !OFF, we need to update all group member times.
607 *
608 *
609 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we
610 * need to make sure the relevant context time is updated before we try and
611 * update our timestamps.
612 */
613
614 static __always_inline enum perf_event_state
__perf_effective_state(struct perf_event * event)615 __perf_effective_state(struct perf_event *event)
616 {
617 struct perf_event *leader = event->group_leader;
618
619 if (leader->state <= PERF_EVENT_STATE_OFF)
620 return leader->state;
621
622 return event->state;
623 }
624
625 static __always_inline void
__perf_update_times(struct perf_event * event,u64 now,u64 * enabled,u64 * running)626 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running)
627 {
628 enum perf_event_state state = __perf_effective_state(event);
629 u64 delta = now - event->tstamp;
630
631 *enabled = event->total_time_enabled;
632 if (state >= PERF_EVENT_STATE_INACTIVE)
633 *enabled += delta;
634
635 *running = event->total_time_running;
636 if (state >= PERF_EVENT_STATE_ACTIVE)
637 *running += delta;
638 }
639
perf_event_update_time(struct perf_event * event)640 static void perf_event_update_time(struct perf_event *event)
641 {
642 u64 now = perf_event_time(event);
643
644 __perf_update_times(event, now, &event->total_time_enabled,
645 &event->total_time_running);
646 event->tstamp = now;
647 }
648
perf_event_update_sibling_time(struct perf_event * leader)649 static void perf_event_update_sibling_time(struct perf_event *leader)
650 {
651 struct perf_event *sibling;
652
653 for_each_sibling_event(sibling, leader)
654 perf_event_update_time(sibling);
655 }
656
657 static void
perf_event_set_state(struct perf_event * event,enum perf_event_state state)658 perf_event_set_state(struct perf_event *event, enum perf_event_state state)
659 {
660 if (event->state == state)
661 return;
662
663 perf_event_update_time(event);
664 /*
665 * If a group leader gets enabled/disabled all its siblings
666 * are affected too.
667 */
668 if ((event->state < 0) ^ (state < 0))
669 perf_event_update_sibling_time(event);
670
671 WRITE_ONCE(event->state, state);
672 }
673
674 #ifdef CONFIG_CGROUP_PERF
675
676 static inline bool
perf_cgroup_match(struct perf_event * event)677 perf_cgroup_match(struct perf_event *event)
678 {
679 struct perf_event_context *ctx = event->ctx;
680 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
681
682 /* @event doesn't care about cgroup */
683 if (!event->cgrp)
684 return true;
685
686 /* wants specific cgroup scope but @cpuctx isn't associated with any */
687 if (!cpuctx->cgrp)
688 return false;
689
690 /*
691 * Cgroup scoping is recursive. An event enabled for a cgroup is
692 * also enabled for all its descendant cgroups. If @cpuctx's
693 * cgroup is a descendant of @event's (the test covers identity
694 * case), it's a match.
695 */
696 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup,
697 event->cgrp->css.cgroup);
698 }
699
perf_detach_cgroup(struct perf_event * event)700 static inline void perf_detach_cgroup(struct perf_event *event)
701 {
702 css_put(&event->cgrp->css);
703 event->cgrp = NULL;
704 }
705
is_cgroup_event(struct perf_event * event)706 static inline int is_cgroup_event(struct perf_event *event)
707 {
708 return event->cgrp != NULL;
709 }
710
perf_cgroup_event_time(struct perf_event * event)711 static inline u64 perf_cgroup_event_time(struct perf_event *event)
712 {
713 struct perf_cgroup_info *t;
714
715 t = per_cpu_ptr(event->cgrp->info, event->cpu);
716 return t->time;
717 }
718
__update_cgrp_time(struct perf_cgroup * cgrp)719 static inline void __update_cgrp_time(struct perf_cgroup *cgrp)
720 {
721 struct perf_cgroup_info *info;
722 u64 now;
723
724 now = perf_clock();
725
726 info = this_cpu_ptr(cgrp->info);
727
728 info->time += now - info->timestamp;
729 info->timestamp = now;
730 }
731
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx)732 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
733 {
734 struct perf_cgroup *cgrp = cpuctx->cgrp;
735 struct cgroup_subsys_state *css;
736
737 if (cgrp) {
738 for (css = &cgrp->css; css; css = css->parent) {
739 cgrp = container_of(css, struct perf_cgroup, css);
740 __update_cgrp_time(cgrp);
741 }
742 }
743 }
744
update_cgrp_time_from_event(struct perf_event * event)745 static inline void update_cgrp_time_from_event(struct perf_event *event)
746 {
747 struct perf_cgroup *cgrp;
748
749 /*
750 * ensure we access cgroup data only when needed and
751 * when we know the cgroup is pinned (css_get)
752 */
753 if (!is_cgroup_event(event))
754 return;
755
756 cgrp = perf_cgroup_from_task(current, event->ctx);
757 /*
758 * Do not update time when cgroup is not active
759 */
760 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
761 __update_cgrp_time(event->cgrp);
762 }
763
764 static inline void
perf_cgroup_set_timestamp(struct task_struct * task,struct perf_event_context * ctx)765 perf_cgroup_set_timestamp(struct task_struct *task,
766 struct perf_event_context *ctx)
767 {
768 struct perf_cgroup *cgrp;
769 struct perf_cgroup_info *info;
770 struct cgroup_subsys_state *css;
771
772 /*
773 * ctx->lock held by caller
774 * ensure we do not access cgroup data
775 * unless we have the cgroup pinned (css_get)
776 */
777 if (!task || !ctx->nr_cgroups)
778 return;
779
780 cgrp = perf_cgroup_from_task(task, ctx);
781
782 for (css = &cgrp->css; css; css = css->parent) {
783 cgrp = container_of(css, struct perf_cgroup, css);
784 info = this_cpu_ptr(cgrp->info);
785 info->timestamp = ctx->timestamp;
786 }
787 }
788
789 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list);
790
791 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */
792 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */
793
794 /*
795 * reschedule events based on the cgroup constraint of task.
796 *
797 * mode SWOUT : schedule out everything
798 * mode SWIN : schedule in based on cgroup for next
799 */
perf_cgroup_switch(struct task_struct * task,int mode)800 static void perf_cgroup_switch(struct task_struct *task, int mode)
801 {
802 struct perf_cpu_context *cpuctx, *tmp;
803 struct list_head *list;
804 unsigned long flags;
805
806 /*
807 * Disable interrupts and preemption to avoid this CPU's
808 * cgrp_cpuctx_entry to change under us.
809 */
810 local_irq_save(flags);
811
812 list = this_cpu_ptr(&cgrp_cpuctx_list);
813 list_for_each_entry_safe(cpuctx, tmp, list, cgrp_cpuctx_entry) {
814 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0);
815
816 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
817 perf_pmu_disable(cpuctx->ctx.pmu);
818
819 if (mode & PERF_CGROUP_SWOUT) {
820 cpu_ctx_sched_out(cpuctx, EVENT_ALL);
821 /*
822 * must not be done before ctxswout due
823 * to event_filter_match() in event_sched_out()
824 */
825 cpuctx->cgrp = NULL;
826 }
827
828 if (mode & PERF_CGROUP_SWIN) {
829 WARN_ON_ONCE(cpuctx->cgrp);
830 /*
831 * set cgrp before ctxsw in to allow
832 * event_filter_match() to not have to pass
833 * task around
834 * we pass the cpuctx->ctx to perf_cgroup_from_task()
835 * because cgorup events are only per-cpu
836 */
837 cpuctx->cgrp = perf_cgroup_from_task(task,
838 &cpuctx->ctx);
839 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task);
840 }
841 perf_pmu_enable(cpuctx->ctx.pmu);
842 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
843 }
844
845 local_irq_restore(flags);
846 }
847
perf_cgroup_sched_out(struct task_struct * task,struct task_struct * next)848 static inline void perf_cgroup_sched_out(struct task_struct *task,
849 struct task_struct *next)
850 {
851 struct perf_cgroup *cgrp1;
852 struct perf_cgroup *cgrp2 = NULL;
853
854 rcu_read_lock();
855 /*
856 * we come here when we know perf_cgroup_events > 0
857 * we do not need to pass the ctx here because we know
858 * we are holding the rcu lock
859 */
860 cgrp1 = perf_cgroup_from_task(task, NULL);
861 cgrp2 = perf_cgroup_from_task(next, NULL);
862
863 /*
864 * only schedule out current cgroup events if we know
865 * that we are switching to a different cgroup. Otherwise,
866 * do no touch the cgroup events.
867 */
868 if (cgrp1 != cgrp2)
869 perf_cgroup_switch(task, PERF_CGROUP_SWOUT);
870
871 rcu_read_unlock();
872 }
873
perf_cgroup_sched_in(struct task_struct * prev,struct task_struct * task)874 static inline void perf_cgroup_sched_in(struct task_struct *prev,
875 struct task_struct *task)
876 {
877 struct perf_cgroup *cgrp1;
878 struct perf_cgroup *cgrp2 = NULL;
879
880 rcu_read_lock();
881 /*
882 * we come here when we know perf_cgroup_events > 0
883 * we do not need to pass the ctx here because we know
884 * we are holding the rcu lock
885 */
886 cgrp1 = perf_cgroup_from_task(task, NULL);
887 cgrp2 = perf_cgroup_from_task(prev, NULL);
888
889 /*
890 * only need to schedule in cgroup events if we are changing
891 * cgroup during ctxsw. Cgroup events were not scheduled
892 * out of ctxsw out if that was not the case.
893 */
894 if (cgrp1 != cgrp2)
895 perf_cgroup_switch(task, PERF_CGROUP_SWIN);
896
897 rcu_read_unlock();
898 }
899
perf_cgroup_connect(int fd,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)900 static inline int perf_cgroup_connect(int fd, struct perf_event *event,
901 struct perf_event_attr *attr,
902 struct perf_event *group_leader)
903 {
904 struct perf_cgroup *cgrp;
905 struct cgroup_subsys_state *css;
906 struct fd f = fdget(fd);
907 int ret = 0;
908
909 if (!f.file)
910 return -EBADF;
911
912 css = css_tryget_online_from_dir(f.file->f_path.dentry,
913 &perf_event_cgrp_subsys);
914 if (IS_ERR(css)) {
915 ret = PTR_ERR(css);
916 goto out;
917 }
918
919 cgrp = container_of(css, struct perf_cgroup, css);
920 event->cgrp = cgrp;
921
922 /*
923 * all events in a group must monitor
924 * the same cgroup because a task belongs
925 * to only one perf cgroup at a time
926 */
927 if (group_leader && group_leader->cgrp != cgrp) {
928 perf_detach_cgroup(event);
929 ret = -EINVAL;
930 }
931 out:
932 fdput(f);
933 return ret;
934 }
935
936 static inline void
perf_cgroup_set_shadow_time(struct perf_event * event,u64 now)937 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
938 {
939 struct perf_cgroup_info *t;
940 t = per_cpu_ptr(event->cgrp->info, event->cpu);
941 event->shadow_ctx_time = now - t->timestamp;
942 }
943
944 /*
945 * Update cpuctx->cgrp so that it is set when first cgroup event is added and
946 * cleared when last cgroup event is removed.
947 */
948 static inline void
list_update_cgroup_event(struct perf_event * event,struct perf_event_context * ctx,bool add)949 list_update_cgroup_event(struct perf_event *event,
950 struct perf_event_context *ctx, bool add)
951 {
952 struct perf_cpu_context *cpuctx;
953 struct list_head *cpuctx_entry;
954
955 if (!is_cgroup_event(event))
956 return;
957
958 /*
959 * Because cgroup events are always per-cpu events,
960 * this will always be called from the right CPU.
961 */
962 cpuctx = __get_cpu_context(ctx);
963
964 /*
965 * Since setting cpuctx->cgrp is conditional on the current @cgrp
966 * matching the event's cgroup, we must do this for every new event,
967 * because if the first would mismatch, the second would not try again
968 * and we would leave cpuctx->cgrp unset.
969 */
970 if (add && !cpuctx->cgrp) {
971 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
972
973 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup))
974 cpuctx->cgrp = cgrp;
975 }
976
977 if (add && ctx->nr_cgroups++)
978 return;
979 else if (!add && --ctx->nr_cgroups)
980 return;
981
982 /* no cgroup running */
983 if (!add)
984 cpuctx->cgrp = NULL;
985
986 cpuctx_entry = &cpuctx->cgrp_cpuctx_entry;
987 if (add)
988 list_add(cpuctx_entry, this_cpu_ptr(&cgrp_cpuctx_list));
989 else
990 list_del(cpuctx_entry);
991 }
992
993 #else /* !CONFIG_CGROUP_PERF */
994
995 static inline bool
perf_cgroup_match(struct perf_event * event)996 perf_cgroup_match(struct perf_event *event)
997 {
998 return true;
999 }
1000
perf_detach_cgroup(struct perf_event * event)1001 static inline void perf_detach_cgroup(struct perf_event *event)
1002 {}
1003
is_cgroup_event(struct perf_event * event)1004 static inline int is_cgroup_event(struct perf_event *event)
1005 {
1006 return 0;
1007 }
1008
update_cgrp_time_from_event(struct perf_event * event)1009 static inline void update_cgrp_time_from_event(struct perf_event *event)
1010 {
1011 }
1012
update_cgrp_time_from_cpuctx(struct perf_cpu_context * cpuctx)1013 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx)
1014 {
1015 }
1016
perf_cgroup_sched_out(struct task_struct * task,struct task_struct * next)1017 static inline void perf_cgroup_sched_out(struct task_struct *task,
1018 struct task_struct *next)
1019 {
1020 }
1021
perf_cgroup_sched_in(struct task_struct * prev,struct task_struct * task)1022 static inline void perf_cgroup_sched_in(struct task_struct *prev,
1023 struct task_struct *task)
1024 {
1025 }
1026
perf_cgroup_connect(pid_t pid,struct perf_event * event,struct perf_event_attr * attr,struct perf_event * group_leader)1027 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event,
1028 struct perf_event_attr *attr,
1029 struct perf_event *group_leader)
1030 {
1031 return -EINVAL;
1032 }
1033
1034 static inline void
perf_cgroup_set_timestamp(struct task_struct * task,struct perf_event_context * ctx)1035 perf_cgroup_set_timestamp(struct task_struct *task,
1036 struct perf_event_context *ctx)
1037 {
1038 }
1039
1040 static inline void
perf_cgroup_switch(struct task_struct * task,struct task_struct * next)1041 perf_cgroup_switch(struct task_struct *task, struct task_struct *next)
1042 {
1043 }
1044
1045 static inline void
perf_cgroup_set_shadow_time(struct perf_event * event,u64 now)1046 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now)
1047 {
1048 }
1049
perf_cgroup_event_time(struct perf_event * event)1050 static inline u64 perf_cgroup_event_time(struct perf_event *event)
1051 {
1052 return 0;
1053 }
1054
1055 static inline void
list_update_cgroup_event(struct perf_event * event,struct perf_event_context * ctx,bool add)1056 list_update_cgroup_event(struct perf_event *event,
1057 struct perf_event_context *ctx, bool add)
1058 {
1059 }
1060
1061 #endif
1062
1063 /*
1064 * set default to be dependent on timer tick just
1065 * like original code
1066 */
1067 #define PERF_CPU_HRTIMER (1000 / HZ)
1068 /*
1069 * function must be called with interrupts disabled
1070 */
perf_mux_hrtimer_handler(struct hrtimer * hr)1071 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr)
1072 {
1073 struct perf_cpu_context *cpuctx;
1074 bool rotations;
1075
1076 lockdep_assert_irqs_disabled();
1077
1078 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer);
1079 rotations = perf_rotate_context(cpuctx);
1080
1081 raw_spin_lock(&cpuctx->hrtimer_lock);
1082 if (rotations)
1083 hrtimer_forward_now(hr, cpuctx->hrtimer_interval);
1084 else
1085 cpuctx->hrtimer_active = 0;
1086 raw_spin_unlock(&cpuctx->hrtimer_lock);
1087
1088 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART;
1089 }
1090
__perf_mux_hrtimer_init(struct perf_cpu_context * cpuctx,int cpu)1091 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu)
1092 {
1093 struct hrtimer *timer = &cpuctx->hrtimer;
1094 struct pmu *pmu = cpuctx->ctx.pmu;
1095 u64 interval;
1096
1097 /* no multiplexing needed for SW PMU */
1098 if (pmu->task_ctx_nr == perf_sw_context)
1099 return;
1100
1101 /*
1102 * check default is sane, if not set then force to
1103 * default interval (1/tick)
1104 */
1105 interval = pmu->hrtimer_interval_ms;
1106 if (interval < 1)
1107 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER;
1108
1109 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval);
1110
1111 raw_spin_lock_init(&cpuctx->hrtimer_lock);
1112 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD);
1113 timer->function = perf_mux_hrtimer_handler;
1114 }
1115
perf_mux_hrtimer_restart(struct perf_cpu_context * cpuctx)1116 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx)
1117 {
1118 struct hrtimer *timer = &cpuctx->hrtimer;
1119 struct pmu *pmu = cpuctx->ctx.pmu;
1120 unsigned long flags;
1121
1122 /* not for SW PMU */
1123 if (pmu->task_ctx_nr == perf_sw_context)
1124 return 0;
1125
1126 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags);
1127 if (!cpuctx->hrtimer_active) {
1128 cpuctx->hrtimer_active = 1;
1129 hrtimer_forward_now(timer, cpuctx->hrtimer_interval);
1130 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD);
1131 }
1132 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags);
1133
1134 return 0;
1135 }
1136
perf_mux_hrtimer_restart_ipi(void * arg)1137 static int perf_mux_hrtimer_restart_ipi(void *arg)
1138 {
1139 return perf_mux_hrtimer_restart(arg);
1140 }
1141
perf_pmu_disable(struct pmu * pmu)1142 void perf_pmu_disable(struct pmu *pmu)
1143 {
1144 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1145 if (!(*count)++)
1146 pmu->pmu_disable(pmu);
1147 }
1148
perf_pmu_enable(struct pmu * pmu)1149 void perf_pmu_enable(struct pmu *pmu)
1150 {
1151 int *count = this_cpu_ptr(pmu->pmu_disable_count);
1152 if (!--(*count))
1153 pmu->pmu_enable(pmu);
1154 }
1155
1156 static DEFINE_PER_CPU(struct list_head, active_ctx_list);
1157
1158 /*
1159 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and
1160 * perf_event_task_tick() are fully serialized because they're strictly cpu
1161 * affine and perf_event_ctx{activate,deactivate} are called with IRQs
1162 * disabled, while perf_event_task_tick is called from IRQ context.
1163 */
perf_event_ctx_activate(struct perf_event_context * ctx)1164 static void perf_event_ctx_activate(struct perf_event_context *ctx)
1165 {
1166 struct list_head *head = this_cpu_ptr(&active_ctx_list);
1167
1168 lockdep_assert_irqs_disabled();
1169
1170 WARN_ON(!list_empty(&ctx->active_ctx_list));
1171
1172 list_add(&ctx->active_ctx_list, head);
1173 }
1174
perf_event_ctx_deactivate(struct perf_event_context * ctx)1175 static void perf_event_ctx_deactivate(struct perf_event_context *ctx)
1176 {
1177 lockdep_assert_irqs_disabled();
1178
1179 WARN_ON(list_empty(&ctx->active_ctx_list));
1180
1181 list_del_init(&ctx->active_ctx_list);
1182 }
1183
get_ctx(struct perf_event_context * ctx)1184 static void get_ctx(struct perf_event_context *ctx)
1185 {
1186 refcount_inc(&ctx->refcount);
1187 }
1188
free_ctx(struct rcu_head * head)1189 static void free_ctx(struct rcu_head *head)
1190 {
1191 struct perf_event_context *ctx;
1192
1193 ctx = container_of(head, struct perf_event_context, rcu_head);
1194 kfree(ctx->task_ctx_data);
1195 kfree(ctx);
1196 }
1197
put_ctx(struct perf_event_context * ctx)1198 static void put_ctx(struct perf_event_context *ctx)
1199 {
1200 if (refcount_dec_and_test(&ctx->refcount)) {
1201 if (ctx->parent_ctx)
1202 put_ctx(ctx->parent_ctx);
1203 if (ctx->task && ctx->task != TASK_TOMBSTONE)
1204 put_task_struct(ctx->task);
1205 call_rcu(&ctx->rcu_head, free_ctx);
1206 }
1207 }
1208
1209 /*
1210 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and
1211 * perf_pmu_migrate_context() we need some magic.
1212 *
1213 * Those places that change perf_event::ctx will hold both
1214 * perf_event_ctx::mutex of the 'old' and 'new' ctx value.
1215 *
1216 * Lock ordering is by mutex address. There are two other sites where
1217 * perf_event_context::mutex nests and those are:
1218 *
1219 * - perf_event_exit_task_context() [ child , 0 ]
1220 * perf_event_exit_event()
1221 * put_event() [ parent, 1 ]
1222 *
1223 * - perf_event_init_context() [ parent, 0 ]
1224 * inherit_task_group()
1225 * inherit_group()
1226 * inherit_event()
1227 * perf_event_alloc()
1228 * perf_init_event()
1229 * perf_try_init_event() [ child , 1 ]
1230 *
1231 * While it appears there is an obvious deadlock here -- the parent and child
1232 * nesting levels are inverted between the two. This is in fact safe because
1233 * life-time rules separate them. That is an exiting task cannot fork, and a
1234 * spawning task cannot (yet) exit.
1235 *
1236 * But remember that that these are parent<->child context relations, and
1237 * migration does not affect children, therefore these two orderings should not
1238 * interact.
1239 *
1240 * The change in perf_event::ctx does not affect children (as claimed above)
1241 * because the sys_perf_event_open() case will install a new event and break
1242 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only
1243 * concerned with cpuctx and that doesn't have children.
1244 *
1245 * The places that change perf_event::ctx will issue:
1246 *
1247 * perf_remove_from_context();
1248 * synchronize_rcu();
1249 * perf_install_in_context();
1250 *
1251 * to affect the change. The remove_from_context() + synchronize_rcu() should
1252 * quiesce the event, after which we can install it in the new location. This
1253 * means that only external vectors (perf_fops, prctl) can perturb the event
1254 * while in transit. Therefore all such accessors should also acquire
1255 * perf_event_context::mutex to serialize against this.
1256 *
1257 * However; because event->ctx can change while we're waiting to acquire
1258 * ctx->mutex we must be careful and use the below perf_event_ctx_lock()
1259 * function.
1260 *
1261 * Lock order:
1262 * cred_guard_mutex
1263 * task_struct::perf_event_mutex
1264 * perf_event_context::mutex
1265 * perf_event::child_mutex;
1266 * perf_event_context::lock
1267 * perf_event::mmap_mutex
1268 * mmap_sem
1269 * perf_addr_filters_head::lock
1270 *
1271 * cpu_hotplug_lock
1272 * pmus_lock
1273 * cpuctx->mutex / perf_event_context::mutex
1274 */
1275 static struct perf_event_context *
perf_event_ctx_lock_nested(struct perf_event * event,int nesting)1276 perf_event_ctx_lock_nested(struct perf_event *event, int nesting)
1277 {
1278 struct perf_event_context *ctx;
1279
1280 again:
1281 rcu_read_lock();
1282 ctx = READ_ONCE(event->ctx);
1283 if (!refcount_inc_not_zero(&ctx->refcount)) {
1284 rcu_read_unlock();
1285 goto again;
1286 }
1287 rcu_read_unlock();
1288
1289 mutex_lock_nested(&ctx->mutex, nesting);
1290 if (event->ctx != ctx) {
1291 mutex_unlock(&ctx->mutex);
1292 put_ctx(ctx);
1293 goto again;
1294 }
1295
1296 return ctx;
1297 }
1298
1299 static inline struct perf_event_context *
perf_event_ctx_lock(struct perf_event * event)1300 perf_event_ctx_lock(struct perf_event *event)
1301 {
1302 return perf_event_ctx_lock_nested(event, 0);
1303 }
1304
perf_event_ctx_unlock(struct perf_event * event,struct perf_event_context * ctx)1305 static void perf_event_ctx_unlock(struct perf_event *event,
1306 struct perf_event_context *ctx)
1307 {
1308 mutex_unlock(&ctx->mutex);
1309 put_ctx(ctx);
1310 }
1311
1312 /*
1313 * This must be done under the ctx->lock, such as to serialize against
1314 * context_equiv(), therefore we cannot call put_ctx() since that might end up
1315 * calling scheduler related locks and ctx->lock nests inside those.
1316 */
1317 static __must_check struct perf_event_context *
unclone_ctx(struct perf_event_context * ctx)1318 unclone_ctx(struct perf_event_context *ctx)
1319 {
1320 struct perf_event_context *parent_ctx = ctx->parent_ctx;
1321
1322 lockdep_assert_held(&ctx->lock);
1323
1324 if (parent_ctx)
1325 ctx->parent_ctx = NULL;
1326 ctx->generation++;
1327
1328 return parent_ctx;
1329 }
1330
perf_event_pid_type(struct perf_event * event,struct task_struct * p,enum pid_type type)1331 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p,
1332 enum pid_type type)
1333 {
1334 u32 nr;
1335 /*
1336 * only top level events have the pid namespace they were created in
1337 */
1338 if (event->parent)
1339 event = event->parent;
1340
1341 nr = __task_pid_nr_ns(p, type, event->ns);
1342 /* avoid -1 if it is idle thread or runs in another ns */
1343 if (!nr && !pid_alive(p))
1344 nr = -1;
1345 return nr;
1346 }
1347
perf_event_pid(struct perf_event * event,struct task_struct * p)1348 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
1349 {
1350 return perf_event_pid_type(event, p, PIDTYPE_TGID);
1351 }
1352
perf_event_tid(struct perf_event * event,struct task_struct * p)1353 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
1354 {
1355 return perf_event_pid_type(event, p, PIDTYPE_PID);
1356 }
1357
1358 /*
1359 * If we inherit events we want to return the parent event id
1360 * to userspace.
1361 */
primary_event_id(struct perf_event * event)1362 static u64 primary_event_id(struct perf_event *event)
1363 {
1364 u64 id = event->id;
1365
1366 if (event->parent)
1367 id = event->parent->id;
1368
1369 return id;
1370 }
1371
1372 /*
1373 * Get the perf_event_context for a task and lock it.
1374 *
1375 * This has to cope with with the fact that until it is locked,
1376 * the context could get moved to another task.
1377 */
1378 static struct perf_event_context *
perf_lock_task_context(struct task_struct * task,int ctxn,unsigned long * flags)1379 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
1380 {
1381 struct perf_event_context *ctx;
1382
1383 retry:
1384 /*
1385 * One of the few rules of preemptible RCU is that one cannot do
1386 * rcu_read_unlock() while holding a scheduler (or nested) lock when
1387 * part of the read side critical section was irqs-enabled -- see
1388 * rcu_read_unlock_special().
1389 *
1390 * Since ctx->lock nests under rq->lock we must ensure the entire read
1391 * side critical section has interrupts disabled.
1392 */
1393 local_irq_save(*flags);
1394 rcu_read_lock();
1395 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
1396 if (ctx) {
1397 /*
1398 * If this context is a clone of another, it might
1399 * get swapped for another underneath us by
1400 * perf_event_task_sched_out, though the
1401 * rcu_read_lock() protects us from any context
1402 * getting freed. Lock the context and check if it
1403 * got swapped before we could get the lock, and retry
1404 * if so. If we locked the right context, then it
1405 * can't get swapped on us any more.
1406 */
1407 raw_spin_lock(&ctx->lock);
1408 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
1409 raw_spin_unlock(&ctx->lock);
1410 rcu_read_unlock();
1411 local_irq_restore(*flags);
1412 goto retry;
1413 }
1414
1415 if (ctx->task == TASK_TOMBSTONE ||
1416 !refcount_inc_not_zero(&ctx->refcount)) {
1417 raw_spin_unlock(&ctx->lock);
1418 ctx = NULL;
1419 } else {
1420 WARN_ON_ONCE(ctx->task != task);
1421 }
1422 }
1423 rcu_read_unlock();
1424 if (!ctx)
1425 local_irq_restore(*flags);
1426 return ctx;
1427 }
1428
1429 /*
1430 * Get the context for a task and increment its pin_count so it
1431 * can't get swapped to another task. This also increments its
1432 * reference count so that the context can't get freed.
1433 */
1434 static struct perf_event_context *
perf_pin_task_context(struct task_struct * task,int ctxn)1435 perf_pin_task_context(struct task_struct *task, int ctxn)
1436 {
1437 struct perf_event_context *ctx;
1438 unsigned long flags;
1439
1440 ctx = perf_lock_task_context(task, ctxn, &flags);
1441 if (ctx) {
1442 ++ctx->pin_count;
1443 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1444 }
1445 return ctx;
1446 }
1447
perf_unpin_context(struct perf_event_context * ctx)1448 static void perf_unpin_context(struct perf_event_context *ctx)
1449 {
1450 unsigned long flags;
1451
1452 raw_spin_lock_irqsave(&ctx->lock, flags);
1453 --ctx->pin_count;
1454 raw_spin_unlock_irqrestore(&ctx->lock, flags);
1455 }
1456
1457 /*
1458 * Update the record of the current time in a context.
1459 */
update_context_time(struct perf_event_context * ctx)1460 static void update_context_time(struct perf_event_context *ctx)
1461 {
1462 u64 now = perf_clock();
1463
1464 ctx->time += now - ctx->timestamp;
1465 ctx->timestamp = now;
1466 }
1467
perf_event_time(struct perf_event * event)1468 static u64 perf_event_time(struct perf_event *event)
1469 {
1470 struct perf_event_context *ctx = event->ctx;
1471
1472 if (is_cgroup_event(event))
1473 return perf_cgroup_event_time(event);
1474
1475 return ctx ? ctx->time : 0;
1476 }
1477
get_event_type(struct perf_event * event)1478 static enum event_type_t get_event_type(struct perf_event *event)
1479 {
1480 struct perf_event_context *ctx = event->ctx;
1481 enum event_type_t event_type;
1482
1483 lockdep_assert_held(&ctx->lock);
1484
1485 /*
1486 * It's 'group type', really, because if our group leader is
1487 * pinned, so are we.
1488 */
1489 if (event->group_leader != event)
1490 event = event->group_leader;
1491
1492 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE;
1493 if (!ctx->task)
1494 event_type |= EVENT_CPU;
1495
1496 return event_type;
1497 }
1498
1499 /*
1500 * Helper function to initialize event group nodes.
1501 */
init_event_group(struct perf_event * event)1502 static void init_event_group(struct perf_event *event)
1503 {
1504 RB_CLEAR_NODE(&event->group_node);
1505 event->group_index = 0;
1506 }
1507
1508 /*
1509 * Extract pinned or flexible groups from the context
1510 * based on event attrs bits.
1511 */
1512 static struct perf_event_groups *
get_event_groups(struct perf_event * event,struct perf_event_context * ctx)1513 get_event_groups(struct perf_event *event, struct perf_event_context *ctx)
1514 {
1515 if (event->attr.pinned)
1516 return &ctx->pinned_groups;
1517 else
1518 return &ctx->flexible_groups;
1519 }
1520
1521 /*
1522 * Helper function to initializes perf_event_group trees.
1523 */
perf_event_groups_init(struct perf_event_groups * groups)1524 static void perf_event_groups_init(struct perf_event_groups *groups)
1525 {
1526 groups->tree = RB_ROOT;
1527 groups->index = 0;
1528 }
1529
1530 /*
1531 * Compare function for event groups;
1532 *
1533 * Implements complex key that first sorts by CPU and then by virtual index
1534 * which provides ordering when rotating groups for the same CPU.
1535 */
1536 static bool
perf_event_groups_less(struct perf_event * left,struct perf_event * right)1537 perf_event_groups_less(struct perf_event *left, struct perf_event *right)
1538 {
1539 if (left->cpu < right->cpu)
1540 return true;
1541 if (left->cpu > right->cpu)
1542 return false;
1543
1544 if (left->group_index < right->group_index)
1545 return true;
1546 if (left->group_index > right->group_index)
1547 return false;
1548
1549 return false;
1550 }
1551
1552 /*
1553 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for
1554 * key (see perf_event_groups_less). This places it last inside the CPU
1555 * subtree.
1556 */
1557 static void
perf_event_groups_insert(struct perf_event_groups * groups,struct perf_event * event)1558 perf_event_groups_insert(struct perf_event_groups *groups,
1559 struct perf_event *event)
1560 {
1561 struct perf_event *node_event;
1562 struct rb_node *parent;
1563 struct rb_node **node;
1564
1565 event->group_index = ++groups->index;
1566
1567 node = &groups->tree.rb_node;
1568 parent = *node;
1569
1570 while (*node) {
1571 parent = *node;
1572 node_event = container_of(*node, struct perf_event, group_node);
1573
1574 if (perf_event_groups_less(event, node_event))
1575 node = &parent->rb_left;
1576 else
1577 node = &parent->rb_right;
1578 }
1579
1580 rb_link_node(&event->group_node, parent, node);
1581 rb_insert_color(&event->group_node, &groups->tree);
1582 }
1583
1584 /*
1585 * Helper function to insert event into the pinned or flexible groups.
1586 */
1587 static void
add_event_to_groups(struct perf_event * event,struct perf_event_context * ctx)1588 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx)
1589 {
1590 struct perf_event_groups *groups;
1591
1592 groups = get_event_groups(event, ctx);
1593 perf_event_groups_insert(groups, event);
1594 }
1595
1596 /*
1597 * Delete a group from a tree.
1598 */
1599 static void
perf_event_groups_delete(struct perf_event_groups * groups,struct perf_event * event)1600 perf_event_groups_delete(struct perf_event_groups *groups,
1601 struct perf_event *event)
1602 {
1603 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) ||
1604 RB_EMPTY_ROOT(&groups->tree));
1605
1606 rb_erase(&event->group_node, &groups->tree);
1607 init_event_group(event);
1608 }
1609
1610 /*
1611 * Helper function to delete event from its groups.
1612 */
1613 static void
del_event_from_groups(struct perf_event * event,struct perf_event_context * ctx)1614 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx)
1615 {
1616 struct perf_event_groups *groups;
1617
1618 groups = get_event_groups(event, ctx);
1619 perf_event_groups_delete(groups, event);
1620 }
1621
1622 /*
1623 * Get the leftmost event in the @cpu subtree.
1624 */
1625 static struct perf_event *
perf_event_groups_first(struct perf_event_groups * groups,int cpu)1626 perf_event_groups_first(struct perf_event_groups *groups, int cpu)
1627 {
1628 struct perf_event *node_event = NULL, *match = NULL;
1629 struct rb_node *node = groups->tree.rb_node;
1630
1631 while (node) {
1632 node_event = container_of(node, struct perf_event, group_node);
1633
1634 if (cpu < node_event->cpu) {
1635 node = node->rb_left;
1636 } else if (cpu > node_event->cpu) {
1637 node = node->rb_right;
1638 } else {
1639 match = node_event;
1640 node = node->rb_left;
1641 }
1642 }
1643
1644 return match;
1645 }
1646
1647 /*
1648 * Like rb_entry_next_safe() for the @cpu subtree.
1649 */
1650 static struct perf_event *
perf_event_groups_next(struct perf_event * event)1651 perf_event_groups_next(struct perf_event *event)
1652 {
1653 struct perf_event *next;
1654
1655 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node);
1656 if (next && next->cpu == event->cpu)
1657 return next;
1658
1659 return NULL;
1660 }
1661
1662 /*
1663 * Iterate through the whole groups tree.
1664 */
1665 #define perf_event_groups_for_each(event, groups) \
1666 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \
1667 typeof(*event), group_node); event; \
1668 event = rb_entry_safe(rb_next(&event->group_node), \
1669 typeof(*event), group_node))
1670
1671 /*
1672 * Add an event from the lists for its context.
1673 * Must be called with ctx->mutex and ctx->lock held.
1674 */
1675 static void
list_add_event(struct perf_event * event,struct perf_event_context * ctx)1676 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
1677 {
1678 lockdep_assert_held(&ctx->lock);
1679
1680 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
1681 event->attach_state |= PERF_ATTACH_CONTEXT;
1682
1683 event->tstamp = perf_event_time(event);
1684
1685 /*
1686 * If we're a stand alone event or group leader, we go to the context
1687 * list, group events are kept attached to the group so that
1688 * perf_group_detach can, at all times, locate all siblings.
1689 */
1690 if (event->group_leader == event) {
1691 event->group_caps = event->event_caps;
1692 add_event_to_groups(event, ctx);
1693 }
1694
1695 list_update_cgroup_event(event, ctx, true);
1696
1697 list_add_rcu(&event->event_entry, &ctx->event_list);
1698 ctx->nr_events++;
1699 if (event->attr.inherit_stat)
1700 ctx->nr_stat++;
1701
1702 ctx->generation++;
1703 }
1704
1705 /*
1706 * Initialize event state based on the perf_event_attr::disabled.
1707 */
perf_event__state_init(struct perf_event * event)1708 static inline void perf_event__state_init(struct perf_event *event)
1709 {
1710 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF :
1711 PERF_EVENT_STATE_INACTIVE;
1712 }
1713
__perf_event_read_size(u64 read_format,int nr_siblings)1714 static int __perf_event_read_size(u64 read_format, int nr_siblings)
1715 {
1716 int entry = sizeof(u64); /* value */
1717 int size = 0;
1718 int nr = 1;
1719
1720 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1721 size += sizeof(u64);
1722
1723 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1724 size += sizeof(u64);
1725
1726 if (read_format & PERF_FORMAT_ID)
1727 entry += sizeof(u64);
1728
1729 if (read_format & PERF_FORMAT_GROUP) {
1730 nr += nr_siblings;
1731 size += sizeof(u64);
1732 }
1733
1734 /*
1735 * Since perf_event_validate_size() limits this to 16k and inhibits
1736 * adding more siblings, this will never overflow.
1737 */
1738 return size + nr * entry;
1739 }
1740
__perf_event_header_size(struct perf_event * event,u64 sample_type)1741 static void __perf_event_header_size(struct perf_event *event, u64 sample_type)
1742 {
1743 struct perf_sample_data *data;
1744 u16 size = 0;
1745
1746 if (sample_type & PERF_SAMPLE_IP)
1747 size += sizeof(data->ip);
1748
1749 if (sample_type & PERF_SAMPLE_ADDR)
1750 size += sizeof(data->addr);
1751
1752 if (sample_type & PERF_SAMPLE_PERIOD)
1753 size += sizeof(data->period);
1754
1755 if (sample_type & PERF_SAMPLE_WEIGHT)
1756 size += sizeof(data->weight);
1757
1758 if (sample_type & PERF_SAMPLE_READ)
1759 size += event->read_size;
1760
1761 if (sample_type & PERF_SAMPLE_DATA_SRC)
1762 size += sizeof(data->data_src.val);
1763
1764 if (sample_type & PERF_SAMPLE_TRANSACTION)
1765 size += sizeof(data->txn);
1766
1767 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
1768 size += sizeof(data->phys_addr);
1769
1770 event->header_size = size;
1771 }
1772
1773 /*
1774 * Called at perf_event creation and when events are attached/detached from a
1775 * group.
1776 */
perf_event__header_size(struct perf_event * event)1777 static void perf_event__header_size(struct perf_event *event)
1778 {
1779 event->read_size =
1780 __perf_event_read_size(event->attr.read_format,
1781 event->group_leader->nr_siblings);
1782 __perf_event_header_size(event, event->attr.sample_type);
1783 }
1784
perf_event__id_header_size(struct perf_event * event)1785 static void perf_event__id_header_size(struct perf_event *event)
1786 {
1787 struct perf_sample_data *data;
1788 u64 sample_type = event->attr.sample_type;
1789 u16 size = 0;
1790
1791 if (sample_type & PERF_SAMPLE_TID)
1792 size += sizeof(data->tid_entry);
1793
1794 if (sample_type & PERF_SAMPLE_TIME)
1795 size += sizeof(data->time);
1796
1797 if (sample_type & PERF_SAMPLE_IDENTIFIER)
1798 size += sizeof(data->id);
1799
1800 if (sample_type & PERF_SAMPLE_ID)
1801 size += sizeof(data->id);
1802
1803 if (sample_type & PERF_SAMPLE_STREAM_ID)
1804 size += sizeof(data->stream_id);
1805
1806 if (sample_type & PERF_SAMPLE_CPU)
1807 size += sizeof(data->cpu_entry);
1808
1809 event->id_header_size = size;
1810 }
1811
1812 /*
1813 * Check that adding an event to the group does not result in anybody
1814 * overflowing the 64k event limit imposed by the output buffer.
1815 *
1816 * Specifically, check that the read_size for the event does not exceed 16k,
1817 * read_size being the one term that grows with groups size. Since read_size
1818 * depends on per-event read_format, also (re)check the existing events.
1819 *
1820 * This leaves 48k for the constant size fields and things like callchains,
1821 * branch stacks and register sets.
1822 */
perf_event_validate_size(struct perf_event * event)1823 static bool perf_event_validate_size(struct perf_event *event)
1824 {
1825 struct perf_event *sibling, *group_leader = event->group_leader;
1826
1827 if (__perf_event_read_size(event->attr.read_format,
1828 group_leader->nr_siblings + 1) > 16*1024)
1829 return false;
1830
1831 if (__perf_event_read_size(group_leader->attr.read_format,
1832 group_leader->nr_siblings + 1) > 16*1024)
1833 return false;
1834
1835 for_each_sibling_event(sibling, group_leader) {
1836 if (__perf_event_read_size(sibling->attr.read_format,
1837 group_leader->nr_siblings + 1) > 16*1024)
1838 return false;
1839 }
1840
1841 return true;
1842 }
1843
perf_group_attach(struct perf_event * event)1844 static void perf_group_attach(struct perf_event *event)
1845 {
1846 struct perf_event *group_leader = event->group_leader, *pos;
1847
1848 lockdep_assert_held(&event->ctx->lock);
1849
1850 /*
1851 * We can have double attach due to group movement in perf_event_open.
1852 */
1853 if (event->attach_state & PERF_ATTACH_GROUP)
1854 return;
1855
1856 event->attach_state |= PERF_ATTACH_GROUP;
1857
1858 if (group_leader == event)
1859 return;
1860
1861 WARN_ON_ONCE(group_leader->ctx != event->ctx);
1862
1863 group_leader->group_caps &= event->event_caps;
1864
1865 list_add_tail(&event->sibling_list, &group_leader->sibling_list);
1866 group_leader->nr_siblings++;
1867 group_leader->group_generation++;
1868
1869 perf_event__header_size(group_leader);
1870
1871 for_each_sibling_event(pos, group_leader)
1872 perf_event__header_size(pos);
1873 }
1874
1875 /*
1876 * Remove an event from the lists for its context.
1877 * Must be called with ctx->mutex and ctx->lock held.
1878 */
1879 static void
list_del_event(struct perf_event * event,struct perf_event_context * ctx)1880 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
1881 {
1882 WARN_ON_ONCE(event->ctx != ctx);
1883 lockdep_assert_held(&ctx->lock);
1884
1885 /*
1886 * We can have double detach due to exit/hot-unplug + close.
1887 */
1888 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
1889 return;
1890
1891 event->attach_state &= ~PERF_ATTACH_CONTEXT;
1892
1893 list_update_cgroup_event(event, ctx, false);
1894
1895 ctx->nr_events--;
1896 if (event->attr.inherit_stat)
1897 ctx->nr_stat--;
1898
1899 list_del_rcu(&event->event_entry);
1900
1901 if (event->group_leader == event)
1902 del_event_from_groups(event, ctx);
1903
1904 /*
1905 * If event was in error state, then keep it
1906 * that way, otherwise bogus counts will be
1907 * returned on read(). The only way to get out
1908 * of error state is by explicit re-enabling
1909 * of the event
1910 */
1911 if (event->state > PERF_EVENT_STATE_OFF)
1912 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
1913
1914 ctx->generation++;
1915 }
1916
1917 static int
perf_aux_output_match(struct perf_event * event,struct perf_event * aux_event)1918 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event)
1919 {
1920 if (!has_aux(aux_event))
1921 return 0;
1922
1923 if (!event->pmu->aux_output_match)
1924 return 0;
1925
1926 return event->pmu->aux_output_match(aux_event);
1927 }
1928
1929 static void put_event(struct perf_event *event);
1930 static void event_sched_out(struct perf_event *event,
1931 struct perf_cpu_context *cpuctx,
1932 struct perf_event_context *ctx);
1933
perf_put_aux_event(struct perf_event * event)1934 static void perf_put_aux_event(struct perf_event *event)
1935 {
1936 struct perf_event_context *ctx = event->ctx;
1937 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1938 struct perf_event *iter;
1939
1940 /*
1941 * If event uses aux_event tear down the link
1942 */
1943 if (event->aux_event) {
1944 iter = event->aux_event;
1945 event->aux_event = NULL;
1946 put_event(iter);
1947 return;
1948 }
1949
1950 /*
1951 * If the event is an aux_event, tear down all links to
1952 * it from other events.
1953 */
1954 for_each_sibling_event(iter, event->group_leader) {
1955 if (iter->aux_event != event)
1956 continue;
1957
1958 iter->aux_event = NULL;
1959 put_event(event);
1960
1961 /*
1962 * If it's ACTIVE, schedule it out and put it into ERROR
1963 * state so that we don't try to schedule it again. Note
1964 * that perf_event_enable() will clear the ERROR status.
1965 */
1966 event_sched_out(iter, cpuctx, ctx);
1967 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
1968 }
1969 }
1970
perf_get_aux_event(struct perf_event * event,struct perf_event * group_leader)1971 static int perf_get_aux_event(struct perf_event *event,
1972 struct perf_event *group_leader)
1973 {
1974 /*
1975 * Our group leader must be an aux event if we want to be
1976 * an aux_output. This way, the aux event will precede its
1977 * aux_output events in the group, and therefore will always
1978 * schedule first.
1979 */
1980 if (!group_leader)
1981 return 0;
1982
1983 if (!perf_aux_output_match(event, group_leader))
1984 return 0;
1985
1986 if (!atomic_long_inc_not_zero(&group_leader->refcount))
1987 return 0;
1988
1989 /*
1990 * Link aux_outputs to their aux event; this is undone in
1991 * perf_group_detach() by perf_put_aux_event(). When the
1992 * group in torn down, the aux_output events loose their
1993 * link to the aux_event and can't schedule any more.
1994 */
1995 event->aux_event = group_leader;
1996
1997 return 1;
1998 }
1999
perf_group_detach(struct perf_event * event)2000 static void perf_group_detach(struct perf_event *event)
2001 {
2002 struct perf_event *sibling, *tmp;
2003 struct perf_event_context *ctx = event->ctx;
2004
2005 lockdep_assert_held(&ctx->lock);
2006
2007 /*
2008 * We can have double detach due to exit/hot-unplug + close.
2009 */
2010 if (!(event->attach_state & PERF_ATTACH_GROUP))
2011 return;
2012
2013 event->attach_state &= ~PERF_ATTACH_GROUP;
2014
2015 perf_put_aux_event(event);
2016
2017 /*
2018 * If this is a sibling, remove it from its group.
2019 */
2020 if (event->group_leader != event) {
2021 list_del_init(&event->sibling_list);
2022 event->group_leader->nr_siblings--;
2023 event->group_leader->group_generation++;
2024 goto out;
2025 }
2026
2027 /*
2028 * If this was a group event with sibling events then
2029 * upgrade the siblings to singleton events by adding them
2030 * to whatever list we are on.
2031 */
2032 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) {
2033
2034 sibling->group_leader = sibling;
2035 list_del_init(&sibling->sibling_list);
2036
2037 /* Inherit group flags from the previous leader */
2038 sibling->group_caps = event->group_caps;
2039
2040 if (!RB_EMPTY_NODE(&event->group_node)) {
2041 add_event_to_groups(sibling, event->ctx);
2042
2043 if (sibling->state == PERF_EVENT_STATE_ACTIVE) {
2044 struct list_head *list = sibling->attr.pinned ?
2045 &ctx->pinned_active : &ctx->flexible_active;
2046
2047 list_add_tail(&sibling->active_list, list);
2048 }
2049 }
2050
2051 WARN_ON_ONCE(sibling->ctx != event->ctx);
2052 }
2053
2054 out:
2055 perf_event__header_size(event->group_leader);
2056
2057 for_each_sibling_event(tmp, event->group_leader)
2058 perf_event__header_size(tmp);
2059 }
2060
is_orphaned_event(struct perf_event * event)2061 static bool is_orphaned_event(struct perf_event *event)
2062 {
2063 return event->state == PERF_EVENT_STATE_DEAD;
2064 }
2065
__pmu_filter_match(struct perf_event * event)2066 static inline int __pmu_filter_match(struct perf_event *event)
2067 {
2068 struct pmu *pmu = event->pmu;
2069 return pmu->filter_match ? pmu->filter_match(event) : 1;
2070 }
2071
2072 /*
2073 * Check whether we should attempt to schedule an event group based on
2074 * PMU-specific filtering. An event group can consist of HW and SW events,
2075 * potentially with a SW leader, so we must check all the filters, to
2076 * determine whether a group is schedulable:
2077 */
pmu_filter_match(struct perf_event * event)2078 static inline int pmu_filter_match(struct perf_event *event)
2079 {
2080 struct perf_event *sibling;
2081
2082 if (!__pmu_filter_match(event))
2083 return 0;
2084
2085 for_each_sibling_event(sibling, event) {
2086 if (!__pmu_filter_match(sibling))
2087 return 0;
2088 }
2089
2090 return 1;
2091 }
2092
2093 static inline int
event_filter_match(struct perf_event * event)2094 event_filter_match(struct perf_event *event)
2095 {
2096 return (event->cpu == -1 || event->cpu == smp_processor_id()) &&
2097 perf_cgroup_match(event) && pmu_filter_match(event);
2098 }
2099
2100 static void
event_sched_out(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2101 event_sched_out(struct perf_event *event,
2102 struct perf_cpu_context *cpuctx,
2103 struct perf_event_context *ctx)
2104 {
2105 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE;
2106
2107 WARN_ON_ONCE(event->ctx != ctx);
2108 lockdep_assert_held(&ctx->lock);
2109
2110 if (event->state != PERF_EVENT_STATE_ACTIVE)
2111 return;
2112
2113 /*
2114 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but
2115 * we can schedule events _OUT_ individually through things like
2116 * __perf_remove_from_context().
2117 */
2118 list_del_init(&event->active_list);
2119
2120 perf_pmu_disable(event->pmu);
2121
2122 event->pmu->del(event, 0);
2123 event->oncpu = -1;
2124
2125 if (READ_ONCE(event->pending_disable) >= 0) {
2126 WRITE_ONCE(event->pending_disable, -1);
2127 state = PERF_EVENT_STATE_OFF;
2128 }
2129 perf_event_set_state(event, state);
2130
2131 if (!is_software_event(event))
2132 cpuctx->active_oncpu--;
2133 if (!--ctx->nr_active)
2134 perf_event_ctx_deactivate(ctx);
2135 if (event->attr.freq && event->attr.sample_freq)
2136 ctx->nr_freq--;
2137 if (event->attr.exclusive || !cpuctx->active_oncpu)
2138 cpuctx->exclusive = 0;
2139
2140 perf_pmu_enable(event->pmu);
2141 }
2142
2143 static void
group_sched_out(struct perf_event * group_event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2144 group_sched_out(struct perf_event *group_event,
2145 struct perf_cpu_context *cpuctx,
2146 struct perf_event_context *ctx)
2147 {
2148 struct perf_event *event;
2149
2150 if (group_event->state != PERF_EVENT_STATE_ACTIVE)
2151 return;
2152
2153 perf_pmu_disable(ctx->pmu);
2154
2155 event_sched_out(group_event, cpuctx, ctx);
2156
2157 /*
2158 * Schedule out siblings (if any):
2159 */
2160 for_each_sibling_event(event, group_event)
2161 event_sched_out(event, cpuctx, ctx);
2162
2163 perf_pmu_enable(ctx->pmu);
2164
2165 if (group_event->attr.exclusive)
2166 cpuctx->exclusive = 0;
2167 }
2168
2169 #define DETACH_GROUP 0x01UL
2170
2171 /*
2172 * Cross CPU call to remove a performance event
2173 *
2174 * We disable the event on the hardware level first. After that we
2175 * remove it from the context list.
2176 */
2177 static void
__perf_remove_from_context(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2178 __perf_remove_from_context(struct perf_event *event,
2179 struct perf_cpu_context *cpuctx,
2180 struct perf_event_context *ctx,
2181 void *info)
2182 {
2183 unsigned long flags = (unsigned long)info;
2184
2185 if (ctx->is_active & EVENT_TIME) {
2186 update_context_time(ctx);
2187 update_cgrp_time_from_cpuctx(cpuctx);
2188 }
2189
2190 event_sched_out(event, cpuctx, ctx);
2191 if (flags & DETACH_GROUP)
2192 perf_group_detach(event);
2193 list_del_event(event, ctx);
2194
2195 if (!ctx->nr_events && ctx->is_active) {
2196 ctx->is_active = 0;
2197 ctx->rotate_necessary = 0;
2198 if (ctx->task) {
2199 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
2200 cpuctx->task_ctx = NULL;
2201 }
2202 }
2203 }
2204
2205 /*
2206 * Remove the event from a task's (or a CPU's) list of events.
2207 *
2208 * If event->ctx is a cloned context, callers must make sure that
2209 * every task struct that event->ctx->task could possibly point to
2210 * remains valid. This is OK when called from perf_release since
2211 * that only calls us on the top-level context, which can't be a clone.
2212 * When called from perf_event_exit_task, it's OK because the
2213 * context has been detached from its task.
2214 */
perf_remove_from_context(struct perf_event * event,unsigned long flags)2215 static void perf_remove_from_context(struct perf_event *event, unsigned long flags)
2216 {
2217 struct perf_event_context *ctx = event->ctx;
2218
2219 lockdep_assert_held(&ctx->mutex);
2220
2221 event_function_call(event, __perf_remove_from_context, (void *)flags);
2222
2223 /*
2224 * The above event_function_call() can NO-OP when it hits
2225 * TASK_TOMBSTONE. In that case we must already have been detached
2226 * from the context (by perf_event_exit_event()) but the grouping
2227 * might still be in-tact.
2228 */
2229 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
2230 if ((flags & DETACH_GROUP) &&
2231 (event->attach_state & PERF_ATTACH_GROUP)) {
2232 /*
2233 * Since in that case we cannot possibly be scheduled, simply
2234 * detach now.
2235 */
2236 raw_spin_lock_irq(&ctx->lock);
2237 perf_group_detach(event);
2238 raw_spin_unlock_irq(&ctx->lock);
2239 }
2240 }
2241
2242 /*
2243 * Cross CPU call to disable a performance event
2244 */
__perf_event_disable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2245 static void __perf_event_disable(struct perf_event *event,
2246 struct perf_cpu_context *cpuctx,
2247 struct perf_event_context *ctx,
2248 void *info)
2249 {
2250 if (event->state < PERF_EVENT_STATE_INACTIVE)
2251 return;
2252
2253 if (ctx->is_active & EVENT_TIME) {
2254 update_context_time(ctx);
2255 update_cgrp_time_from_event(event);
2256 }
2257
2258 if (event == event->group_leader)
2259 group_sched_out(event, cpuctx, ctx);
2260 else
2261 event_sched_out(event, cpuctx, ctx);
2262
2263 perf_event_set_state(event, PERF_EVENT_STATE_OFF);
2264 }
2265
2266 /*
2267 * Disable an event.
2268 *
2269 * If event->ctx is a cloned context, callers must make sure that
2270 * every task struct that event->ctx->task could possibly point to
2271 * remains valid. This condition is satisfied when called through
2272 * perf_event_for_each_child or perf_event_for_each because they
2273 * hold the top-level event's child_mutex, so any descendant that
2274 * goes to exit will block in perf_event_exit_event().
2275 *
2276 * When called from perf_pending_event it's OK because event->ctx
2277 * is the current context on this CPU and preemption is disabled,
2278 * hence we can't get into perf_event_task_sched_out for this context.
2279 */
_perf_event_disable(struct perf_event * event)2280 static void _perf_event_disable(struct perf_event *event)
2281 {
2282 struct perf_event_context *ctx = event->ctx;
2283
2284 raw_spin_lock_irq(&ctx->lock);
2285 if (event->state <= PERF_EVENT_STATE_OFF) {
2286 raw_spin_unlock_irq(&ctx->lock);
2287 return;
2288 }
2289 raw_spin_unlock_irq(&ctx->lock);
2290
2291 event_function_call(event, __perf_event_disable, NULL);
2292 }
2293
perf_event_disable_local(struct perf_event * event)2294 void perf_event_disable_local(struct perf_event *event)
2295 {
2296 event_function_local(event, __perf_event_disable, NULL);
2297 }
2298
2299 /*
2300 * Strictly speaking kernel users cannot create groups and therefore this
2301 * interface does not need the perf_event_ctx_lock() magic.
2302 */
perf_event_disable(struct perf_event * event)2303 void perf_event_disable(struct perf_event *event)
2304 {
2305 struct perf_event_context *ctx;
2306
2307 ctx = perf_event_ctx_lock(event);
2308 _perf_event_disable(event);
2309 perf_event_ctx_unlock(event, ctx);
2310 }
2311 EXPORT_SYMBOL_GPL(perf_event_disable);
2312
perf_event_disable_inatomic(struct perf_event * event)2313 void perf_event_disable_inatomic(struct perf_event *event)
2314 {
2315 WRITE_ONCE(event->pending_disable, smp_processor_id());
2316 /* can fail, see perf_pending_event_disable() */
2317 irq_work_queue(&event->pending);
2318 }
2319
perf_set_shadow_time(struct perf_event * event,struct perf_event_context * ctx)2320 static void perf_set_shadow_time(struct perf_event *event,
2321 struct perf_event_context *ctx)
2322 {
2323 /*
2324 * use the correct time source for the time snapshot
2325 *
2326 * We could get by without this by leveraging the
2327 * fact that to get to this function, the caller
2328 * has most likely already called update_context_time()
2329 * and update_cgrp_time_xx() and thus both timestamp
2330 * are identical (or very close). Given that tstamp is,
2331 * already adjusted for cgroup, we could say that:
2332 * tstamp - ctx->timestamp
2333 * is equivalent to
2334 * tstamp - cgrp->timestamp.
2335 *
2336 * Then, in perf_output_read(), the calculation would
2337 * work with no changes because:
2338 * - event is guaranteed scheduled in
2339 * - no scheduled out in between
2340 * - thus the timestamp would be the same
2341 *
2342 * But this is a bit hairy.
2343 *
2344 * So instead, we have an explicit cgroup call to remain
2345 * within the time time source all along. We believe it
2346 * is cleaner and simpler to understand.
2347 */
2348 if (is_cgroup_event(event))
2349 perf_cgroup_set_shadow_time(event, event->tstamp);
2350 else
2351 event->shadow_ctx_time = event->tstamp - ctx->timestamp;
2352 }
2353
2354 #define MAX_INTERRUPTS (~0ULL)
2355
2356 static void perf_log_throttle(struct perf_event *event, int enable);
2357 static void perf_log_itrace_start(struct perf_event *event);
2358
2359 static int
event_sched_in(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2360 event_sched_in(struct perf_event *event,
2361 struct perf_cpu_context *cpuctx,
2362 struct perf_event_context *ctx)
2363 {
2364 int ret = 0;
2365
2366 lockdep_assert_held(&ctx->lock);
2367
2368 if (event->state <= PERF_EVENT_STATE_OFF)
2369 return 0;
2370
2371 WRITE_ONCE(event->oncpu, smp_processor_id());
2372 /*
2373 * Order event::oncpu write to happen before the ACTIVE state is
2374 * visible. This allows perf_event_{stop,read}() to observe the correct
2375 * ->oncpu if it sees ACTIVE.
2376 */
2377 smp_wmb();
2378 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE);
2379
2380 /*
2381 * Unthrottle events, since we scheduled we might have missed several
2382 * ticks already, also for a heavily scheduling task there is little
2383 * guarantee it'll get a tick in a timely manner.
2384 */
2385 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) {
2386 perf_log_throttle(event, 1);
2387 event->hw.interrupts = 0;
2388 }
2389
2390 perf_pmu_disable(event->pmu);
2391
2392 perf_set_shadow_time(event, ctx);
2393
2394 perf_log_itrace_start(event);
2395
2396 if (event->pmu->add(event, PERF_EF_START)) {
2397 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2398 event->oncpu = -1;
2399 ret = -EAGAIN;
2400 goto out;
2401 }
2402
2403 if (!is_software_event(event))
2404 cpuctx->active_oncpu++;
2405 if (!ctx->nr_active++)
2406 perf_event_ctx_activate(ctx);
2407 if (event->attr.freq && event->attr.sample_freq)
2408 ctx->nr_freq++;
2409
2410 if (event->attr.exclusive)
2411 cpuctx->exclusive = 1;
2412
2413 out:
2414 perf_pmu_enable(event->pmu);
2415
2416 return ret;
2417 }
2418
2419 static int
group_sched_in(struct perf_event * group_event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx)2420 group_sched_in(struct perf_event *group_event,
2421 struct perf_cpu_context *cpuctx,
2422 struct perf_event_context *ctx)
2423 {
2424 struct perf_event *event, *partial_group = NULL;
2425 struct pmu *pmu = ctx->pmu;
2426
2427 if (group_event->state == PERF_EVENT_STATE_OFF)
2428 return 0;
2429
2430 pmu->start_txn(pmu, PERF_PMU_TXN_ADD);
2431
2432 if (event_sched_in(group_event, cpuctx, ctx)) {
2433 pmu->cancel_txn(pmu);
2434 perf_mux_hrtimer_restart(cpuctx);
2435 return -EAGAIN;
2436 }
2437
2438 /*
2439 * Schedule in siblings as one group (if any):
2440 */
2441 for_each_sibling_event(event, group_event) {
2442 if (event_sched_in(event, cpuctx, ctx)) {
2443 partial_group = event;
2444 goto group_error;
2445 }
2446 }
2447
2448 if (!pmu->commit_txn(pmu))
2449 return 0;
2450
2451 group_error:
2452 /*
2453 * Groups can be scheduled in as one unit only, so undo any
2454 * partial group before returning:
2455 * The events up to the failed event are scheduled out normally.
2456 */
2457 for_each_sibling_event(event, group_event) {
2458 if (event == partial_group)
2459 break;
2460
2461 event_sched_out(event, cpuctx, ctx);
2462 }
2463 event_sched_out(group_event, cpuctx, ctx);
2464
2465 pmu->cancel_txn(pmu);
2466
2467 perf_mux_hrtimer_restart(cpuctx);
2468
2469 return -EAGAIN;
2470 }
2471
2472 /*
2473 * Work out whether we can put this event group on the CPU now.
2474 */
group_can_go_on(struct perf_event * event,struct perf_cpu_context * cpuctx,int can_add_hw)2475 static int group_can_go_on(struct perf_event *event,
2476 struct perf_cpu_context *cpuctx,
2477 int can_add_hw)
2478 {
2479 /*
2480 * Groups consisting entirely of software events can always go on.
2481 */
2482 if (event->group_caps & PERF_EV_CAP_SOFTWARE)
2483 return 1;
2484 /*
2485 * If an exclusive group is already on, no other hardware
2486 * events can go on.
2487 */
2488 if (cpuctx->exclusive)
2489 return 0;
2490 /*
2491 * If this group is exclusive and there are already
2492 * events on the CPU, it can't go on.
2493 */
2494 if (event->attr.exclusive && cpuctx->active_oncpu)
2495 return 0;
2496 /*
2497 * Otherwise, try to add it if all previous groups were able
2498 * to go on.
2499 */
2500 return can_add_hw;
2501 }
2502
add_event_to_ctx(struct perf_event * event,struct perf_event_context * ctx)2503 static void add_event_to_ctx(struct perf_event *event,
2504 struct perf_event_context *ctx)
2505 {
2506 list_add_event(event, ctx);
2507 perf_group_attach(event);
2508 }
2509
2510 static void ctx_sched_out(struct perf_event_context *ctx,
2511 struct perf_cpu_context *cpuctx,
2512 enum event_type_t event_type);
2513 static void
2514 ctx_sched_in(struct perf_event_context *ctx,
2515 struct perf_cpu_context *cpuctx,
2516 enum event_type_t event_type,
2517 struct task_struct *task);
2518
task_ctx_sched_out(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,enum event_type_t event_type)2519 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx,
2520 struct perf_event_context *ctx,
2521 enum event_type_t event_type)
2522 {
2523 if (!cpuctx->task_ctx)
2524 return;
2525
2526 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
2527 return;
2528
2529 ctx_sched_out(ctx, cpuctx, event_type);
2530 }
2531
perf_event_sched_in(struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,struct task_struct * task)2532 static void perf_event_sched_in(struct perf_cpu_context *cpuctx,
2533 struct perf_event_context *ctx,
2534 struct task_struct *task)
2535 {
2536 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task);
2537 if (ctx)
2538 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task);
2539 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task);
2540 if (ctx)
2541 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task);
2542 }
2543
2544 /*
2545 * We want to maintain the following priority of scheduling:
2546 * - CPU pinned (EVENT_CPU | EVENT_PINNED)
2547 * - task pinned (EVENT_PINNED)
2548 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE)
2549 * - task flexible (EVENT_FLEXIBLE).
2550 *
2551 * In order to avoid unscheduling and scheduling back in everything every
2552 * time an event is added, only do it for the groups of equal priority and
2553 * below.
2554 *
2555 * This can be called after a batch operation on task events, in which case
2556 * event_type is a bit mask of the types of events involved. For CPU events,
2557 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE.
2558 */
ctx_resched(struct perf_cpu_context * cpuctx,struct perf_event_context * task_ctx,enum event_type_t event_type)2559 static void ctx_resched(struct perf_cpu_context *cpuctx,
2560 struct perf_event_context *task_ctx,
2561 enum event_type_t event_type)
2562 {
2563 enum event_type_t ctx_event_type;
2564 bool cpu_event = !!(event_type & EVENT_CPU);
2565
2566 /*
2567 * If pinned groups are involved, flexible groups also need to be
2568 * scheduled out.
2569 */
2570 if (event_type & EVENT_PINNED)
2571 event_type |= EVENT_FLEXIBLE;
2572
2573 ctx_event_type = event_type & EVENT_ALL;
2574
2575 perf_pmu_disable(cpuctx->ctx.pmu);
2576 if (task_ctx)
2577 task_ctx_sched_out(cpuctx, task_ctx, event_type);
2578
2579 /*
2580 * Decide which cpu ctx groups to schedule out based on the types
2581 * of events that caused rescheduling:
2582 * - EVENT_CPU: schedule out corresponding groups;
2583 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups;
2584 * - otherwise, do nothing more.
2585 */
2586 if (cpu_event)
2587 cpu_ctx_sched_out(cpuctx, ctx_event_type);
2588 else if (ctx_event_type & EVENT_PINNED)
2589 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
2590
2591 perf_event_sched_in(cpuctx, task_ctx, current);
2592 perf_pmu_enable(cpuctx->ctx.pmu);
2593 }
2594
perf_pmu_resched(struct pmu * pmu)2595 void perf_pmu_resched(struct pmu *pmu)
2596 {
2597 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
2598 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2599
2600 perf_ctx_lock(cpuctx, task_ctx);
2601 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU);
2602 perf_ctx_unlock(cpuctx, task_ctx);
2603 }
2604
2605 /*
2606 * Cross CPU call to install and enable a performance event
2607 *
2608 * Very similar to remote_function() + event_function() but cannot assume that
2609 * things like ctx->is_active and cpuctx->task_ctx are set.
2610 */
__perf_install_in_context(void * info)2611 static int __perf_install_in_context(void *info)
2612 {
2613 struct perf_event *event = info;
2614 struct perf_event_context *ctx = event->ctx;
2615 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
2616 struct perf_event_context *task_ctx = cpuctx->task_ctx;
2617 bool reprogram = true;
2618 int ret = 0;
2619
2620 raw_spin_lock(&cpuctx->ctx.lock);
2621 if (ctx->task) {
2622 raw_spin_lock(&ctx->lock);
2623 task_ctx = ctx;
2624
2625 reprogram = (ctx->task == current);
2626
2627 /*
2628 * If the task is running, it must be running on this CPU,
2629 * otherwise we cannot reprogram things.
2630 *
2631 * If its not running, we don't care, ctx->lock will
2632 * serialize against it becoming runnable.
2633 */
2634 if (task_curr(ctx->task) && !reprogram) {
2635 ret = -ESRCH;
2636 goto unlock;
2637 }
2638
2639 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx);
2640 } else if (task_ctx) {
2641 raw_spin_lock(&task_ctx->lock);
2642 }
2643
2644 #ifdef CONFIG_CGROUP_PERF
2645 if (is_cgroup_event(event)) {
2646 /*
2647 * If the current cgroup doesn't match the event's
2648 * cgroup, we should not try to schedule it.
2649 */
2650 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx);
2651 reprogram = cgroup_is_descendant(cgrp->css.cgroup,
2652 event->cgrp->css.cgroup);
2653 }
2654 #endif
2655
2656 if (reprogram) {
2657 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2658 add_event_to_ctx(event, ctx);
2659 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2660 } else {
2661 add_event_to_ctx(event, ctx);
2662 }
2663
2664 unlock:
2665 perf_ctx_unlock(cpuctx, task_ctx);
2666
2667 return ret;
2668 }
2669
2670 static bool exclusive_event_installable(struct perf_event *event,
2671 struct perf_event_context *ctx);
2672
2673 /*
2674 * Attach a performance event to a context.
2675 *
2676 * Very similar to event_function_call, see comment there.
2677 */
2678 static void
perf_install_in_context(struct perf_event_context * ctx,struct perf_event * event,int cpu)2679 perf_install_in_context(struct perf_event_context *ctx,
2680 struct perf_event *event,
2681 int cpu)
2682 {
2683 struct task_struct *task = READ_ONCE(ctx->task);
2684
2685 lockdep_assert_held(&ctx->mutex);
2686
2687 WARN_ON_ONCE(!exclusive_event_installable(event, ctx));
2688
2689 if (event->cpu != -1)
2690 event->cpu = cpu;
2691
2692 /*
2693 * Ensures that if we can observe event->ctx, both the event and ctx
2694 * will be 'complete'. See perf_iterate_sb_cpu().
2695 */
2696 smp_store_release(&event->ctx, ctx);
2697
2698 if (!task) {
2699 cpu_function_call(cpu, __perf_install_in_context, event);
2700 return;
2701 }
2702
2703 /*
2704 * Should not happen, we validate the ctx is still alive before calling.
2705 */
2706 if (WARN_ON_ONCE(task == TASK_TOMBSTONE))
2707 return;
2708
2709 /*
2710 * Installing events is tricky because we cannot rely on ctx->is_active
2711 * to be set in case this is the nr_events 0 -> 1 transition.
2712 *
2713 * Instead we use task_curr(), which tells us if the task is running.
2714 * However, since we use task_curr() outside of rq::lock, we can race
2715 * against the actual state. This means the result can be wrong.
2716 *
2717 * If we get a false positive, we retry, this is harmless.
2718 *
2719 * If we get a false negative, things are complicated. If we are after
2720 * perf_event_context_sched_in() ctx::lock will serialize us, and the
2721 * value must be correct. If we're before, it doesn't matter since
2722 * perf_event_context_sched_in() will program the counter.
2723 *
2724 * However, this hinges on the remote context switch having observed
2725 * our task->perf_event_ctxp[] store, such that it will in fact take
2726 * ctx::lock in perf_event_context_sched_in().
2727 *
2728 * We do this by task_function_call(), if the IPI fails to hit the task
2729 * we know any future context switch of task must see the
2730 * perf_event_ctpx[] store.
2731 */
2732
2733 /*
2734 * This smp_mb() orders the task->perf_event_ctxp[] store with the
2735 * task_cpu() load, such that if the IPI then does not find the task
2736 * running, a future context switch of that task must observe the
2737 * store.
2738 */
2739 smp_mb();
2740 again:
2741 if (!task_function_call(task, __perf_install_in_context, event))
2742 return;
2743
2744 raw_spin_lock_irq(&ctx->lock);
2745 task = ctx->task;
2746 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) {
2747 /*
2748 * Cannot happen because we already checked above (which also
2749 * cannot happen), and we hold ctx->mutex, which serializes us
2750 * against perf_event_exit_task_context().
2751 */
2752 raw_spin_unlock_irq(&ctx->lock);
2753 return;
2754 }
2755 /*
2756 * If the task is not running, ctx->lock will avoid it becoming so,
2757 * thus we can safely install the event.
2758 */
2759 if (task_curr(task)) {
2760 raw_spin_unlock_irq(&ctx->lock);
2761 goto again;
2762 }
2763 add_event_to_ctx(event, ctx);
2764 raw_spin_unlock_irq(&ctx->lock);
2765 }
2766
2767 /*
2768 * Cross CPU call to enable a performance event
2769 */
__perf_event_enable(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)2770 static void __perf_event_enable(struct perf_event *event,
2771 struct perf_cpu_context *cpuctx,
2772 struct perf_event_context *ctx,
2773 void *info)
2774 {
2775 struct perf_event *leader = event->group_leader;
2776 struct perf_event_context *task_ctx;
2777
2778 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2779 event->state <= PERF_EVENT_STATE_ERROR)
2780 return;
2781
2782 if (ctx->is_active)
2783 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
2784
2785 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
2786
2787 if (!ctx->is_active)
2788 return;
2789
2790 if (!event_filter_match(event)) {
2791 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2792 return;
2793 }
2794
2795 /*
2796 * If the event is in a group and isn't the group leader,
2797 * then don't put it on unless the group is on.
2798 */
2799 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) {
2800 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
2801 return;
2802 }
2803
2804 task_ctx = cpuctx->task_ctx;
2805 if (ctx->task)
2806 WARN_ON_ONCE(task_ctx != ctx);
2807
2808 ctx_resched(cpuctx, task_ctx, get_event_type(event));
2809 }
2810
2811 /*
2812 * Enable an event.
2813 *
2814 * If event->ctx is a cloned context, callers must make sure that
2815 * every task struct that event->ctx->task could possibly point to
2816 * remains valid. This condition is satisfied when called through
2817 * perf_event_for_each_child or perf_event_for_each as described
2818 * for perf_event_disable.
2819 */
_perf_event_enable(struct perf_event * event)2820 static void _perf_event_enable(struct perf_event *event)
2821 {
2822 struct perf_event_context *ctx = event->ctx;
2823
2824 raw_spin_lock_irq(&ctx->lock);
2825 if (event->state >= PERF_EVENT_STATE_INACTIVE ||
2826 event->state < PERF_EVENT_STATE_ERROR) {
2827 raw_spin_unlock_irq(&ctx->lock);
2828 return;
2829 }
2830
2831 /*
2832 * If the event is in error state, clear that first.
2833 *
2834 * That way, if we see the event in error state below, we know that it
2835 * has gone back into error state, as distinct from the task having
2836 * been scheduled away before the cross-call arrived.
2837 */
2838 if (event->state == PERF_EVENT_STATE_ERROR)
2839 event->state = PERF_EVENT_STATE_OFF;
2840 raw_spin_unlock_irq(&ctx->lock);
2841
2842 event_function_call(event, __perf_event_enable, NULL);
2843 }
2844
2845 /*
2846 * See perf_event_disable();
2847 */
perf_event_enable(struct perf_event * event)2848 void perf_event_enable(struct perf_event *event)
2849 {
2850 struct perf_event_context *ctx;
2851
2852 ctx = perf_event_ctx_lock(event);
2853 _perf_event_enable(event);
2854 perf_event_ctx_unlock(event, ctx);
2855 }
2856 EXPORT_SYMBOL_GPL(perf_event_enable);
2857
2858 struct stop_event_data {
2859 struct perf_event *event;
2860 unsigned int restart;
2861 };
2862
__perf_event_stop(void * info)2863 static int __perf_event_stop(void *info)
2864 {
2865 struct stop_event_data *sd = info;
2866 struct perf_event *event = sd->event;
2867
2868 /* if it's already INACTIVE, do nothing */
2869 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2870 return 0;
2871
2872 /* matches smp_wmb() in event_sched_in() */
2873 smp_rmb();
2874
2875 /*
2876 * There is a window with interrupts enabled before we get here,
2877 * so we need to check again lest we try to stop another CPU's event.
2878 */
2879 if (READ_ONCE(event->oncpu) != smp_processor_id())
2880 return -EAGAIN;
2881
2882 event->pmu->stop(event, PERF_EF_UPDATE);
2883
2884 /*
2885 * May race with the actual stop (through perf_pmu_output_stop()),
2886 * but it is only used for events with AUX ring buffer, and such
2887 * events will refuse to restart because of rb::aux_mmap_count==0,
2888 * see comments in perf_aux_output_begin().
2889 *
2890 * Since this is happening on an event-local CPU, no trace is lost
2891 * while restarting.
2892 */
2893 if (sd->restart)
2894 event->pmu->start(event, 0);
2895
2896 return 0;
2897 }
2898
perf_event_stop(struct perf_event * event,int restart)2899 static int perf_event_stop(struct perf_event *event, int restart)
2900 {
2901 struct stop_event_data sd = {
2902 .event = event,
2903 .restart = restart,
2904 };
2905 int ret = 0;
2906
2907 do {
2908 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE)
2909 return 0;
2910
2911 /* matches smp_wmb() in event_sched_in() */
2912 smp_rmb();
2913
2914 /*
2915 * We only want to restart ACTIVE events, so if the event goes
2916 * inactive here (event->oncpu==-1), there's nothing more to do;
2917 * fall through with ret==-ENXIO.
2918 */
2919 ret = cpu_function_call(READ_ONCE(event->oncpu),
2920 __perf_event_stop, &sd);
2921 } while (ret == -EAGAIN);
2922
2923 return ret;
2924 }
2925
2926 /*
2927 * In order to contain the amount of racy and tricky in the address filter
2928 * configuration management, it is a two part process:
2929 *
2930 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below,
2931 * we update the addresses of corresponding vmas in
2932 * event::addr_filter_ranges array and bump the event::addr_filters_gen;
2933 * (p2) when an event is scheduled in (pmu::add), it calls
2934 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync()
2935 * if the generation has changed since the previous call.
2936 *
2937 * If (p1) happens while the event is active, we restart it to force (p2).
2938 *
2939 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on
2940 * pre-existing mappings, called once when new filters arrive via SET_FILTER
2941 * ioctl;
2942 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly
2943 * registered mapping, called for every new mmap(), with mm::mmap_sem down
2944 * for reading;
2945 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process
2946 * of exec.
2947 */
perf_event_addr_filters_sync(struct perf_event * event)2948 void perf_event_addr_filters_sync(struct perf_event *event)
2949 {
2950 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
2951
2952 if (!has_addr_filter(event))
2953 return;
2954
2955 raw_spin_lock(&ifh->lock);
2956 if (event->addr_filters_gen != event->hw.addr_filters_gen) {
2957 event->pmu->addr_filters_sync(event);
2958 event->hw.addr_filters_gen = event->addr_filters_gen;
2959 }
2960 raw_spin_unlock(&ifh->lock);
2961 }
2962 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync);
2963
_perf_event_refresh(struct perf_event * event,int refresh)2964 static int _perf_event_refresh(struct perf_event *event, int refresh)
2965 {
2966 /*
2967 * not supported on inherited events
2968 */
2969 if (event->attr.inherit || !is_sampling_event(event))
2970 return -EINVAL;
2971
2972 atomic_add(refresh, &event->event_limit);
2973 _perf_event_enable(event);
2974
2975 return 0;
2976 }
2977
2978 /*
2979 * See perf_event_disable()
2980 */
perf_event_refresh(struct perf_event * event,int refresh)2981 int perf_event_refresh(struct perf_event *event, int refresh)
2982 {
2983 struct perf_event_context *ctx;
2984 int ret;
2985
2986 ctx = perf_event_ctx_lock(event);
2987 ret = _perf_event_refresh(event, refresh);
2988 perf_event_ctx_unlock(event, ctx);
2989
2990 return ret;
2991 }
2992 EXPORT_SYMBOL_GPL(perf_event_refresh);
2993
perf_event_modify_breakpoint(struct perf_event * bp,struct perf_event_attr * attr)2994 static int perf_event_modify_breakpoint(struct perf_event *bp,
2995 struct perf_event_attr *attr)
2996 {
2997 int err;
2998
2999 _perf_event_disable(bp);
3000
3001 err = modify_user_hw_breakpoint_check(bp, attr, true);
3002
3003 if (!bp->attr.disabled)
3004 _perf_event_enable(bp);
3005
3006 return err;
3007 }
3008
perf_event_modify_attr(struct perf_event * event,struct perf_event_attr * attr)3009 static int perf_event_modify_attr(struct perf_event *event,
3010 struct perf_event_attr *attr)
3011 {
3012 if (event->attr.type != attr->type)
3013 return -EINVAL;
3014
3015 switch (event->attr.type) {
3016 case PERF_TYPE_BREAKPOINT:
3017 return perf_event_modify_breakpoint(event, attr);
3018 default:
3019 /* Place holder for future additions. */
3020 return -EOPNOTSUPP;
3021 }
3022 }
3023
ctx_sched_out(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx,enum event_type_t event_type)3024 static void ctx_sched_out(struct perf_event_context *ctx,
3025 struct perf_cpu_context *cpuctx,
3026 enum event_type_t event_type)
3027 {
3028 struct perf_event *event, *tmp;
3029 int is_active = ctx->is_active;
3030
3031 lockdep_assert_held(&ctx->lock);
3032
3033 if (likely(!ctx->nr_events)) {
3034 /*
3035 * See __perf_remove_from_context().
3036 */
3037 WARN_ON_ONCE(ctx->is_active);
3038 if (ctx->task)
3039 WARN_ON_ONCE(cpuctx->task_ctx);
3040 return;
3041 }
3042
3043 ctx->is_active &= ~event_type;
3044 if (!(ctx->is_active & EVENT_ALL))
3045 ctx->is_active = 0;
3046
3047 if (ctx->task) {
3048 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3049 if (!ctx->is_active)
3050 cpuctx->task_ctx = NULL;
3051 }
3052
3053 /*
3054 * Always update time if it was set; not only when it changes.
3055 * Otherwise we can 'forget' to update time for any but the last
3056 * context we sched out. For example:
3057 *
3058 * ctx_sched_out(.event_type = EVENT_FLEXIBLE)
3059 * ctx_sched_out(.event_type = EVENT_PINNED)
3060 *
3061 * would only update time for the pinned events.
3062 */
3063 if (is_active & EVENT_TIME) {
3064 /* update (and stop) ctx time */
3065 update_context_time(ctx);
3066 update_cgrp_time_from_cpuctx(cpuctx);
3067 }
3068
3069 is_active ^= ctx->is_active; /* changed bits */
3070
3071 if (!ctx->nr_active || !(is_active & EVENT_ALL))
3072 return;
3073
3074 perf_pmu_disable(ctx->pmu);
3075 if (is_active & EVENT_PINNED) {
3076 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list)
3077 group_sched_out(event, cpuctx, ctx);
3078 }
3079
3080 if (is_active & EVENT_FLEXIBLE) {
3081 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list)
3082 group_sched_out(event, cpuctx, ctx);
3083
3084 /*
3085 * Since we cleared EVENT_FLEXIBLE, also clear
3086 * rotate_necessary, is will be reset by
3087 * ctx_flexible_sched_in() when needed.
3088 */
3089 ctx->rotate_necessary = 0;
3090 }
3091 perf_pmu_enable(ctx->pmu);
3092 }
3093
3094 /*
3095 * Test whether two contexts are equivalent, i.e. whether they have both been
3096 * cloned from the same version of the same context.
3097 *
3098 * Equivalence is measured using a generation number in the context that is
3099 * incremented on each modification to it; see unclone_ctx(), list_add_event()
3100 * and list_del_event().
3101 */
context_equiv(struct perf_event_context * ctx1,struct perf_event_context * ctx2)3102 static int context_equiv(struct perf_event_context *ctx1,
3103 struct perf_event_context *ctx2)
3104 {
3105 lockdep_assert_held(&ctx1->lock);
3106 lockdep_assert_held(&ctx2->lock);
3107
3108 /* Pinning disables the swap optimization */
3109 if (ctx1->pin_count || ctx2->pin_count)
3110 return 0;
3111
3112 /* If ctx1 is the parent of ctx2 */
3113 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen)
3114 return 1;
3115
3116 /* If ctx2 is the parent of ctx1 */
3117 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation)
3118 return 1;
3119
3120 /*
3121 * If ctx1 and ctx2 have the same parent; we flatten the parent
3122 * hierarchy, see perf_event_init_context().
3123 */
3124 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx &&
3125 ctx1->parent_gen == ctx2->parent_gen)
3126 return 1;
3127
3128 /* Unmatched */
3129 return 0;
3130 }
3131
__perf_event_sync_stat(struct perf_event * event,struct perf_event * next_event)3132 static void __perf_event_sync_stat(struct perf_event *event,
3133 struct perf_event *next_event)
3134 {
3135 u64 value;
3136
3137 if (!event->attr.inherit_stat)
3138 return;
3139
3140 /*
3141 * Update the event value, we cannot use perf_event_read()
3142 * because we're in the middle of a context switch and have IRQs
3143 * disabled, which upsets smp_call_function_single(), however
3144 * we know the event must be on the current CPU, therefore we
3145 * don't need to use it.
3146 */
3147 if (event->state == PERF_EVENT_STATE_ACTIVE)
3148 event->pmu->read(event);
3149
3150 perf_event_update_time(event);
3151
3152 /*
3153 * In order to keep per-task stats reliable we need to flip the event
3154 * values when we flip the contexts.
3155 */
3156 value = local64_read(&next_event->count);
3157 value = local64_xchg(&event->count, value);
3158 local64_set(&next_event->count, value);
3159
3160 swap(event->total_time_enabled, next_event->total_time_enabled);
3161 swap(event->total_time_running, next_event->total_time_running);
3162
3163 /*
3164 * Since we swizzled the values, update the user visible data too.
3165 */
3166 perf_event_update_userpage(event);
3167 perf_event_update_userpage(next_event);
3168 }
3169
perf_event_sync_stat(struct perf_event_context * ctx,struct perf_event_context * next_ctx)3170 static void perf_event_sync_stat(struct perf_event_context *ctx,
3171 struct perf_event_context *next_ctx)
3172 {
3173 struct perf_event *event, *next_event;
3174
3175 if (!ctx->nr_stat)
3176 return;
3177
3178 update_context_time(ctx);
3179
3180 event = list_first_entry(&ctx->event_list,
3181 struct perf_event, event_entry);
3182
3183 next_event = list_first_entry(&next_ctx->event_list,
3184 struct perf_event, event_entry);
3185
3186 while (&event->event_entry != &ctx->event_list &&
3187 &next_event->event_entry != &next_ctx->event_list) {
3188
3189 __perf_event_sync_stat(event, next_event);
3190
3191 event = list_next_entry(event, event_entry);
3192 next_event = list_next_entry(next_event, event_entry);
3193 }
3194 }
3195
perf_event_context_sched_out(struct task_struct * task,int ctxn,struct task_struct * next)3196 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
3197 struct task_struct *next)
3198 {
3199 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
3200 struct perf_event_context *next_ctx;
3201 struct perf_event_context *parent, *next_parent;
3202 struct perf_cpu_context *cpuctx;
3203 int do_switch = 1;
3204
3205 if (likely(!ctx))
3206 return;
3207
3208 cpuctx = __get_cpu_context(ctx);
3209 if (!cpuctx->task_ctx)
3210 return;
3211
3212 rcu_read_lock();
3213 next_ctx = next->perf_event_ctxp[ctxn];
3214 if (!next_ctx)
3215 goto unlock;
3216
3217 parent = rcu_dereference(ctx->parent_ctx);
3218 next_parent = rcu_dereference(next_ctx->parent_ctx);
3219
3220 /* If neither context have a parent context; they cannot be clones. */
3221 if (!parent && !next_parent)
3222 goto unlock;
3223
3224 if (next_parent == ctx || next_ctx == parent || next_parent == parent) {
3225 /*
3226 * Looks like the two contexts are clones, so we might be
3227 * able to optimize the context switch. We lock both
3228 * contexts and check that they are clones under the
3229 * lock (including re-checking that neither has been
3230 * uncloned in the meantime). It doesn't matter which
3231 * order we take the locks because no other cpu could
3232 * be trying to lock both of these tasks.
3233 */
3234 raw_spin_lock(&ctx->lock);
3235 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
3236 if (context_equiv(ctx, next_ctx)) {
3237 WRITE_ONCE(ctx->task, next);
3238 WRITE_ONCE(next_ctx->task, task);
3239
3240 swap(ctx->task_ctx_data, next_ctx->task_ctx_data);
3241
3242 /*
3243 * RCU_INIT_POINTER here is safe because we've not
3244 * modified the ctx and the above modification of
3245 * ctx->task and ctx->task_ctx_data are immaterial
3246 * since those values are always verified under
3247 * ctx->lock which we're now holding.
3248 */
3249 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx);
3250 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx);
3251
3252 do_switch = 0;
3253
3254 perf_event_sync_stat(ctx, next_ctx);
3255 }
3256 raw_spin_unlock(&next_ctx->lock);
3257 raw_spin_unlock(&ctx->lock);
3258 }
3259 unlock:
3260 rcu_read_unlock();
3261
3262 if (do_switch) {
3263 raw_spin_lock(&ctx->lock);
3264 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL);
3265 raw_spin_unlock(&ctx->lock);
3266 }
3267 }
3268
3269 static DEFINE_PER_CPU(struct list_head, sched_cb_list);
3270
perf_sched_cb_dec(struct pmu * pmu)3271 void perf_sched_cb_dec(struct pmu *pmu)
3272 {
3273 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3274
3275 this_cpu_dec(perf_sched_cb_usages);
3276
3277 if (!--cpuctx->sched_cb_usage)
3278 list_del(&cpuctx->sched_cb_entry);
3279 }
3280
3281
perf_sched_cb_inc(struct pmu * pmu)3282 void perf_sched_cb_inc(struct pmu *pmu)
3283 {
3284 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
3285
3286 if (!cpuctx->sched_cb_usage++)
3287 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list));
3288
3289 this_cpu_inc(perf_sched_cb_usages);
3290 }
3291
3292 /*
3293 * This function provides the context switch callback to the lower code
3294 * layer. It is invoked ONLY when the context switch callback is enabled.
3295 *
3296 * This callback is relevant even to per-cpu events; for example multi event
3297 * PEBS requires this to provide PID/TID information. This requires we flush
3298 * all queued PEBS records before we context switch to a new task.
3299 */
perf_pmu_sched_task(struct task_struct * prev,struct task_struct * next,bool sched_in)3300 static void perf_pmu_sched_task(struct task_struct *prev,
3301 struct task_struct *next,
3302 bool sched_in)
3303 {
3304 struct perf_cpu_context *cpuctx;
3305 struct pmu *pmu;
3306
3307 if (prev == next)
3308 return;
3309
3310 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) {
3311 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */
3312
3313 if (WARN_ON_ONCE(!pmu->sched_task))
3314 continue;
3315
3316 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3317 perf_pmu_disable(pmu);
3318
3319 pmu->sched_task(cpuctx->task_ctx, sched_in);
3320
3321 perf_pmu_enable(pmu);
3322 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3323 }
3324 }
3325
3326 static void perf_event_switch(struct task_struct *task,
3327 struct task_struct *next_prev, bool sched_in);
3328
3329 #define for_each_task_context_nr(ctxn) \
3330 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
3331
3332 /*
3333 * Called from scheduler to remove the events of the current task,
3334 * with interrupts disabled.
3335 *
3336 * We stop each event and update the event value in event->count.
3337 *
3338 * This does not protect us against NMI, but disable()
3339 * sets the disabled bit in the control field of event _before_
3340 * accessing the event control register. If a NMI hits, then it will
3341 * not restart the event.
3342 */
__perf_event_task_sched_out(struct task_struct * task,struct task_struct * next)3343 void __perf_event_task_sched_out(struct task_struct *task,
3344 struct task_struct *next)
3345 {
3346 int ctxn;
3347
3348 if (__this_cpu_read(perf_sched_cb_usages))
3349 perf_pmu_sched_task(task, next, false);
3350
3351 if (atomic_read(&nr_switch_events))
3352 perf_event_switch(task, next, false);
3353
3354 for_each_task_context_nr(ctxn)
3355 perf_event_context_sched_out(task, ctxn, next);
3356
3357 /*
3358 * if cgroup events exist on this CPU, then we need
3359 * to check if we have to switch out PMU state.
3360 * cgroup event are system-wide mode only
3361 */
3362 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3363 perf_cgroup_sched_out(task, next);
3364 }
3365
3366 /*
3367 * Called with IRQs disabled
3368 */
cpu_ctx_sched_out(struct perf_cpu_context * cpuctx,enum event_type_t event_type)3369 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
3370 enum event_type_t event_type)
3371 {
3372 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
3373 }
3374
visit_groups_merge(struct perf_event_groups * groups,int cpu,int (* func)(struct perf_event *,void *),void * data)3375 static int visit_groups_merge(struct perf_event_groups *groups, int cpu,
3376 int (*func)(struct perf_event *, void *), void *data)
3377 {
3378 struct perf_event **evt, *evt1, *evt2;
3379 int ret;
3380
3381 evt1 = perf_event_groups_first(groups, -1);
3382 evt2 = perf_event_groups_first(groups, cpu);
3383
3384 while (evt1 || evt2) {
3385 if (evt1 && evt2) {
3386 if (evt1->group_index < evt2->group_index)
3387 evt = &evt1;
3388 else
3389 evt = &evt2;
3390 } else if (evt1) {
3391 evt = &evt1;
3392 } else {
3393 evt = &evt2;
3394 }
3395
3396 ret = func(*evt, data);
3397 if (ret)
3398 return ret;
3399
3400 *evt = perf_event_groups_next(*evt);
3401 }
3402
3403 return 0;
3404 }
3405
3406 struct sched_in_data {
3407 struct perf_event_context *ctx;
3408 struct perf_cpu_context *cpuctx;
3409 int can_add_hw;
3410 };
3411
pinned_sched_in(struct perf_event * event,void * data)3412 static int pinned_sched_in(struct perf_event *event, void *data)
3413 {
3414 struct sched_in_data *sid = data;
3415
3416 if (event->state <= PERF_EVENT_STATE_OFF)
3417 return 0;
3418
3419 if (!event_filter_match(event))
3420 return 0;
3421
3422 if (group_can_go_on(event, sid->cpuctx, sid->can_add_hw)) {
3423 if (!group_sched_in(event, sid->cpuctx, sid->ctx))
3424 list_add_tail(&event->active_list, &sid->ctx->pinned_active);
3425 }
3426
3427 /*
3428 * If this pinned group hasn't been scheduled,
3429 * put it in error state.
3430 */
3431 if (event->state == PERF_EVENT_STATE_INACTIVE)
3432 perf_event_set_state(event, PERF_EVENT_STATE_ERROR);
3433
3434 return 0;
3435 }
3436
flexible_sched_in(struct perf_event * event,void * data)3437 static int flexible_sched_in(struct perf_event *event, void *data)
3438 {
3439 struct sched_in_data *sid = data;
3440
3441 if (event->state <= PERF_EVENT_STATE_OFF)
3442 return 0;
3443
3444 if (!event_filter_match(event))
3445 return 0;
3446
3447 if (group_can_go_on(event, sid->cpuctx, sid->can_add_hw)) {
3448 int ret = group_sched_in(event, sid->cpuctx, sid->ctx);
3449 if (ret) {
3450 sid->can_add_hw = 0;
3451 sid->ctx->rotate_necessary = 1;
3452 return 0;
3453 }
3454 list_add_tail(&event->active_list, &sid->ctx->flexible_active);
3455 }
3456
3457 return 0;
3458 }
3459
3460 static void
ctx_pinned_sched_in(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx)3461 ctx_pinned_sched_in(struct perf_event_context *ctx,
3462 struct perf_cpu_context *cpuctx)
3463 {
3464 struct sched_in_data sid = {
3465 .ctx = ctx,
3466 .cpuctx = cpuctx,
3467 .can_add_hw = 1,
3468 };
3469
3470 visit_groups_merge(&ctx->pinned_groups,
3471 smp_processor_id(),
3472 pinned_sched_in, &sid);
3473 }
3474
3475 static void
ctx_flexible_sched_in(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx)3476 ctx_flexible_sched_in(struct perf_event_context *ctx,
3477 struct perf_cpu_context *cpuctx)
3478 {
3479 struct sched_in_data sid = {
3480 .ctx = ctx,
3481 .cpuctx = cpuctx,
3482 .can_add_hw = 1,
3483 };
3484
3485 visit_groups_merge(&ctx->flexible_groups,
3486 smp_processor_id(),
3487 flexible_sched_in, &sid);
3488 }
3489
3490 static void
ctx_sched_in(struct perf_event_context * ctx,struct perf_cpu_context * cpuctx,enum event_type_t event_type,struct task_struct * task)3491 ctx_sched_in(struct perf_event_context *ctx,
3492 struct perf_cpu_context *cpuctx,
3493 enum event_type_t event_type,
3494 struct task_struct *task)
3495 {
3496 int is_active = ctx->is_active;
3497 u64 now;
3498
3499 lockdep_assert_held(&ctx->lock);
3500
3501 if (likely(!ctx->nr_events))
3502 return;
3503
3504 ctx->is_active |= (event_type | EVENT_TIME);
3505 if (ctx->task) {
3506 if (!is_active)
3507 cpuctx->task_ctx = ctx;
3508 else
3509 WARN_ON_ONCE(cpuctx->task_ctx != ctx);
3510 }
3511
3512 is_active ^= ctx->is_active; /* changed bits */
3513
3514 if (is_active & EVENT_TIME) {
3515 /* start ctx time */
3516 now = perf_clock();
3517 ctx->timestamp = now;
3518 perf_cgroup_set_timestamp(task, ctx);
3519 }
3520
3521 /*
3522 * First go through the list and put on any pinned groups
3523 * in order to give them the best chance of going on.
3524 */
3525 if (is_active & EVENT_PINNED)
3526 ctx_pinned_sched_in(ctx, cpuctx);
3527
3528 /* Then walk through the lower prio flexible groups */
3529 if (is_active & EVENT_FLEXIBLE)
3530 ctx_flexible_sched_in(ctx, cpuctx);
3531 }
3532
cpu_ctx_sched_in(struct perf_cpu_context * cpuctx,enum event_type_t event_type,struct task_struct * task)3533 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
3534 enum event_type_t event_type,
3535 struct task_struct *task)
3536 {
3537 struct perf_event_context *ctx = &cpuctx->ctx;
3538
3539 ctx_sched_in(ctx, cpuctx, event_type, task);
3540 }
3541
perf_event_context_sched_in(struct perf_event_context * ctx,struct task_struct * task)3542 static void perf_event_context_sched_in(struct perf_event_context *ctx,
3543 struct task_struct *task)
3544 {
3545 struct perf_cpu_context *cpuctx;
3546
3547 cpuctx = __get_cpu_context(ctx);
3548 if (cpuctx->task_ctx == ctx)
3549 return;
3550
3551 perf_ctx_lock(cpuctx, ctx);
3552 /*
3553 * We must check ctx->nr_events while holding ctx->lock, such
3554 * that we serialize against perf_install_in_context().
3555 */
3556 if (!ctx->nr_events)
3557 goto unlock;
3558
3559 perf_pmu_disable(ctx->pmu);
3560 /*
3561 * We want to keep the following priority order:
3562 * cpu pinned (that don't need to move), task pinned,
3563 * cpu flexible, task flexible.
3564 *
3565 * However, if task's ctx is not carrying any pinned
3566 * events, no need to flip the cpuctx's events around.
3567 */
3568 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree))
3569 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3570 perf_event_sched_in(cpuctx, ctx, task);
3571 perf_pmu_enable(ctx->pmu);
3572
3573 unlock:
3574 perf_ctx_unlock(cpuctx, ctx);
3575 }
3576
3577 /*
3578 * Called from scheduler to add the events of the current task
3579 * with interrupts disabled.
3580 *
3581 * We restore the event value and then enable it.
3582 *
3583 * This does not protect us against NMI, but enable()
3584 * sets the enabled bit in the control field of event _before_
3585 * accessing the event control register. If a NMI hits, then it will
3586 * keep the event running.
3587 */
__perf_event_task_sched_in(struct task_struct * prev,struct task_struct * task)3588 void __perf_event_task_sched_in(struct task_struct *prev,
3589 struct task_struct *task)
3590 {
3591 struct perf_event_context *ctx;
3592 int ctxn;
3593
3594 /*
3595 * If cgroup events exist on this CPU, then we need to check if we have
3596 * to switch in PMU state; cgroup event are system-wide mode only.
3597 *
3598 * Since cgroup events are CPU events, we must schedule these in before
3599 * we schedule in the task events.
3600 */
3601 if (atomic_read(this_cpu_ptr(&perf_cgroup_events)))
3602 perf_cgroup_sched_in(prev, task);
3603
3604 for_each_task_context_nr(ctxn) {
3605 ctx = task->perf_event_ctxp[ctxn];
3606 if (likely(!ctx))
3607 continue;
3608
3609 perf_event_context_sched_in(ctx, task);
3610 }
3611
3612 if (atomic_read(&nr_switch_events))
3613 perf_event_switch(task, prev, true);
3614
3615 if (__this_cpu_read(perf_sched_cb_usages))
3616 perf_pmu_sched_task(prev, task, true);
3617 }
3618
perf_calculate_period(struct perf_event * event,u64 nsec,u64 count)3619 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
3620 {
3621 u64 frequency = event->attr.sample_freq;
3622 u64 sec = NSEC_PER_SEC;
3623 u64 divisor, dividend;
3624
3625 int count_fls, nsec_fls, frequency_fls, sec_fls;
3626
3627 count_fls = fls64(count);
3628 nsec_fls = fls64(nsec);
3629 frequency_fls = fls64(frequency);
3630 sec_fls = 30;
3631
3632 /*
3633 * We got @count in @nsec, with a target of sample_freq HZ
3634 * the target period becomes:
3635 *
3636 * @count * 10^9
3637 * period = -------------------
3638 * @nsec * sample_freq
3639 *
3640 */
3641
3642 /*
3643 * Reduce accuracy by one bit such that @a and @b converge
3644 * to a similar magnitude.
3645 */
3646 #define REDUCE_FLS(a, b) \
3647 do { \
3648 if (a##_fls > b##_fls) { \
3649 a >>= 1; \
3650 a##_fls--; \
3651 } else { \
3652 b >>= 1; \
3653 b##_fls--; \
3654 } \
3655 } while (0)
3656
3657 /*
3658 * Reduce accuracy until either term fits in a u64, then proceed with
3659 * the other, so that finally we can do a u64/u64 division.
3660 */
3661 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
3662 REDUCE_FLS(nsec, frequency);
3663 REDUCE_FLS(sec, count);
3664 }
3665
3666 if (count_fls + sec_fls > 64) {
3667 divisor = nsec * frequency;
3668
3669 while (count_fls + sec_fls > 64) {
3670 REDUCE_FLS(count, sec);
3671 divisor >>= 1;
3672 }
3673
3674 dividend = count * sec;
3675 } else {
3676 dividend = count * sec;
3677
3678 while (nsec_fls + frequency_fls > 64) {
3679 REDUCE_FLS(nsec, frequency);
3680 dividend >>= 1;
3681 }
3682
3683 divisor = nsec * frequency;
3684 }
3685
3686 if (!divisor)
3687 return dividend;
3688
3689 return div64_u64(dividend, divisor);
3690 }
3691
3692 static DEFINE_PER_CPU(int, perf_throttled_count);
3693 static DEFINE_PER_CPU(u64, perf_throttled_seq);
3694
perf_adjust_period(struct perf_event * event,u64 nsec,u64 count,bool disable)3695 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable)
3696 {
3697 struct hw_perf_event *hwc = &event->hw;
3698 s64 period, sample_period;
3699 s64 delta;
3700
3701 period = perf_calculate_period(event, nsec, count);
3702
3703 delta = (s64)(period - hwc->sample_period);
3704 delta = (delta + 7) / 8; /* low pass filter */
3705
3706 sample_period = hwc->sample_period + delta;
3707
3708 if (!sample_period)
3709 sample_period = 1;
3710
3711 hwc->sample_period = sample_period;
3712
3713 if (local64_read(&hwc->period_left) > 8*sample_period) {
3714 if (disable)
3715 event->pmu->stop(event, PERF_EF_UPDATE);
3716
3717 local64_set(&hwc->period_left, 0);
3718
3719 if (disable)
3720 event->pmu->start(event, PERF_EF_RELOAD);
3721 }
3722 }
3723
3724 /*
3725 * combine freq adjustment with unthrottling to avoid two passes over the
3726 * events. At the same time, make sure, having freq events does not change
3727 * the rate of unthrottling as that would introduce bias.
3728 */
perf_adjust_freq_unthr_context(struct perf_event_context * ctx,int needs_unthr)3729 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx,
3730 int needs_unthr)
3731 {
3732 struct perf_event *event;
3733 struct hw_perf_event *hwc;
3734 u64 now, period = TICK_NSEC;
3735 s64 delta;
3736
3737 /*
3738 * only need to iterate over all events iff:
3739 * - context have events in frequency mode (needs freq adjust)
3740 * - there are events to unthrottle on this cpu
3741 */
3742 if (!(ctx->nr_freq || needs_unthr))
3743 return;
3744
3745 raw_spin_lock(&ctx->lock);
3746 perf_pmu_disable(ctx->pmu);
3747
3748 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3749 if (event->state != PERF_EVENT_STATE_ACTIVE)
3750 continue;
3751
3752 if (!event_filter_match(event))
3753 continue;
3754
3755 perf_pmu_disable(event->pmu);
3756
3757 hwc = &event->hw;
3758
3759 if (hwc->interrupts == MAX_INTERRUPTS) {
3760 hwc->interrupts = 0;
3761 perf_log_throttle(event, 1);
3762 event->pmu->start(event, 0);
3763 }
3764
3765 if (!event->attr.freq || !event->attr.sample_freq)
3766 goto next;
3767
3768 /*
3769 * stop the event and update event->count
3770 */
3771 event->pmu->stop(event, PERF_EF_UPDATE);
3772
3773 now = local64_read(&event->count);
3774 delta = now - hwc->freq_count_stamp;
3775 hwc->freq_count_stamp = now;
3776
3777 /*
3778 * restart the event
3779 * reload only if value has changed
3780 * we have stopped the event so tell that
3781 * to perf_adjust_period() to avoid stopping it
3782 * twice.
3783 */
3784 if (delta > 0)
3785 perf_adjust_period(event, period, delta, false);
3786
3787 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0);
3788 next:
3789 perf_pmu_enable(event->pmu);
3790 }
3791
3792 perf_pmu_enable(ctx->pmu);
3793 raw_spin_unlock(&ctx->lock);
3794 }
3795
3796 /*
3797 * Move @event to the tail of the @ctx's elegible events.
3798 */
rotate_ctx(struct perf_event_context * ctx,struct perf_event * event)3799 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event)
3800 {
3801 /*
3802 * Rotate the first entry last of non-pinned groups. Rotation might be
3803 * disabled by the inheritance code.
3804 */
3805 if (ctx->rotate_disable)
3806 return;
3807
3808 perf_event_groups_delete(&ctx->flexible_groups, event);
3809 perf_event_groups_insert(&ctx->flexible_groups, event);
3810 }
3811
3812 /* pick an event from the flexible_groups to rotate */
3813 static inline struct perf_event *
ctx_event_to_rotate(struct perf_event_context * ctx)3814 ctx_event_to_rotate(struct perf_event_context *ctx)
3815 {
3816 struct perf_event *event;
3817
3818 /* pick the first active flexible event */
3819 event = list_first_entry_or_null(&ctx->flexible_active,
3820 struct perf_event, active_list);
3821
3822 /* if no active flexible event, pick the first event */
3823 if (!event) {
3824 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree),
3825 typeof(*event), group_node);
3826 }
3827
3828 /*
3829 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in()
3830 * finds there are unschedulable events, it will set it again.
3831 */
3832 ctx->rotate_necessary = 0;
3833
3834 return event;
3835 }
3836
perf_rotate_context(struct perf_cpu_context * cpuctx)3837 static bool perf_rotate_context(struct perf_cpu_context *cpuctx)
3838 {
3839 struct perf_event *cpu_event = NULL, *task_event = NULL;
3840 struct perf_event_context *task_ctx = NULL;
3841 int cpu_rotate, task_rotate;
3842
3843 /*
3844 * Since we run this from IRQ context, nobody can install new
3845 * events, thus the event count values are stable.
3846 */
3847
3848 cpu_rotate = cpuctx->ctx.rotate_necessary;
3849 task_ctx = cpuctx->task_ctx;
3850 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0;
3851
3852 if (!(cpu_rotate || task_rotate))
3853 return false;
3854
3855 perf_ctx_lock(cpuctx, cpuctx->task_ctx);
3856 perf_pmu_disable(cpuctx->ctx.pmu);
3857
3858 if (task_rotate)
3859 task_event = ctx_event_to_rotate(task_ctx);
3860 if (cpu_rotate)
3861 cpu_event = ctx_event_to_rotate(&cpuctx->ctx);
3862
3863 /*
3864 * As per the order given at ctx_resched() first 'pop' task flexible
3865 * and then, if needed CPU flexible.
3866 */
3867 if (task_event || (task_ctx && cpu_event))
3868 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE);
3869 if (cpu_event)
3870 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
3871
3872 if (task_event)
3873 rotate_ctx(task_ctx, task_event);
3874 if (cpu_event)
3875 rotate_ctx(&cpuctx->ctx, cpu_event);
3876
3877 perf_event_sched_in(cpuctx, task_ctx, current);
3878
3879 perf_pmu_enable(cpuctx->ctx.pmu);
3880 perf_ctx_unlock(cpuctx, cpuctx->task_ctx);
3881
3882 return true;
3883 }
3884
perf_event_task_tick(void)3885 void perf_event_task_tick(void)
3886 {
3887 struct list_head *head = this_cpu_ptr(&active_ctx_list);
3888 struct perf_event_context *ctx, *tmp;
3889 int throttled;
3890
3891 lockdep_assert_irqs_disabled();
3892
3893 __this_cpu_inc(perf_throttled_seq);
3894 throttled = __this_cpu_xchg(perf_throttled_count, 0);
3895 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
3896
3897 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list)
3898 perf_adjust_freq_unthr_context(ctx, throttled);
3899 }
3900
event_enable_on_exec(struct perf_event * event,struct perf_event_context * ctx)3901 static int event_enable_on_exec(struct perf_event *event,
3902 struct perf_event_context *ctx)
3903 {
3904 if (!event->attr.enable_on_exec)
3905 return 0;
3906
3907 event->attr.enable_on_exec = 0;
3908 if (event->state >= PERF_EVENT_STATE_INACTIVE)
3909 return 0;
3910
3911 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE);
3912
3913 return 1;
3914 }
3915
3916 /*
3917 * Enable all of a task's events that have been marked enable-on-exec.
3918 * This expects task == current.
3919 */
perf_event_enable_on_exec(int ctxn)3920 static void perf_event_enable_on_exec(int ctxn)
3921 {
3922 struct perf_event_context *ctx, *clone_ctx = NULL;
3923 enum event_type_t event_type = 0;
3924 struct perf_cpu_context *cpuctx;
3925 struct perf_event *event;
3926 unsigned long flags;
3927 int enabled = 0;
3928
3929 local_irq_save(flags);
3930 ctx = current->perf_event_ctxp[ctxn];
3931 if (!ctx || !ctx->nr_events)
3932 goto out;
3933
3934 cpuctx = __get_cpu_context(ctx);
3935 perf_ctx_lock(cpuctx, ctx);
3936 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
3937 list_for_each_entry(event, &ctx->event_list, event_entry) {
3938 enabled |= event_enable_on_exec(event, ctx);
3939 event_type |= get_event_type(event);
3940 }
3941
3942 /*
3943 * Unclone and reschedule this context if we enabled any event.
3944 */
3945 if (enabled) {
3946 clone_ctx = unclone_ctx(ctx);
3947 ctx_resched(cpuctx, ctx, event_type);
3948 } else {
3949 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current);
3950 }
3951 perf_ctx_unlock(cpuctx, ctx);
3952
3953 out:
3954 local_irq_restore(flags);
3955
3956 if (clone_ctx)
3957 put_ctx(clone_ctx);
3958 }
3959
3960 struct perf_read_data {
3961 struct perf_event *event;
3962 bool group;
3963 int ret;
3964 };
3965
__perf_event_read_cpu(struct perf_event * event,int event_cpu)3966 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu)
3967 {
3968 u16 local_pkg, event_pkg;
3969
3970 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) {
3971 int local_cpu = smp_processor_id();
3972
3973 event_pkg = topology_physical_package_id(event_cpu);
3974 local_pkg = topology_physical_package_id(local_cpu);
3975
3976 if (event_pkg == local_pkg)
3977 return local_cpu;
3978 }
3979
3980 return event_cpu;
3981 }
3982
3983 /*
3984 * Cross CPU call to read the hardware event
3985 */
__perf_event_read(void * info)3986 static void __perf_event_read(void *info)
3987 {
3988 struct perf_read_data *data = info;
3989 struct perf_event *sub, *event = data->event;
3990 struct perf_event_context *ctx = event->ctx;
3991 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
3992 struct pmu *pmu = event->pmu;
3993
3994 /*
3995 * If this is a task context, we need to check whether it is
3996 * the current task context of this cpu. If not it has been
3997 * scheduled out before the smp call arrived. In that case
3998 * event->count would have been updated to a recent sample
3999 * when the event was scheduled out.
4000 */
4001 if (ctx->task && cpuctx->task_ctx != ctx)
4002 return;
4003
4004 raw_spin_lock(&ctx->lock);
4005 if (ctx->is_active & EVENT_TIME) {
4006 update_context_time(ctx);
4007 update_cgrp_time_from_event(event);
4008 }
4009
4010 perf_event_update_time(event);
4011 if (data->group)
4012 perf_event_update_sibling_time(event);
4013
4014 if (event->state != PERF_EVENT_STATE_ACTIVE)
4015 goto unlock;
4016
4017 if (!data->group) {
4018 pmu->read(event);
4019 data->ret = 0;
4020 goto unlock;
4021 }
4022
4023 pmu->start_txn(pmu, PERF_PMU_TXN_READ);
4024
4025 pmu->read(event);
4026
4027 for_each_sibling_event(sub, event) {
4028 if (sub->state == PERF_EVENT_STATE_ACTIVE) {
4029 /*
4030 * Use sibling's PMU rather than @event's since
4031 * sibling could be on different (eg: software) PMU.
4032 */
4033 sub->pmu->read(sub);
4034 }
4035 }
4036
4037 data->ret = pmu->commit_txn(pmu);
4038
4039 unlock:
4040 raw_spin_unlock(&ctx->lock);
4041 }
4042
perf_event_count(struct perf_event * event)4043 static inline u64 perf_event_count(struct perf_event *event)
4044 {
4045 return local64_read(&event->count) + atomic64_read(&event->child_count);
4046 }
4047
4048 /*
4049 * NMI-safe method to read a local event, that is an event that
4050 * is:
4051 * - either for the current task, or for this CPU
4052 * - does not have inherit set, for inherited task events
4053 * will not be local and we cannot read them atomically
4054 * - must not have a pmu::count method
4055 */
perf_event_read_local(struct perf_event * event,u64 * value,u64 * enabled,u64 * running)4056 int perf_event_read_local(struct perf_event *event, u64 *value,
4057 u64 *enabled, u64 *running)
4058 {
4059 unsigned long flags;
4060 int ret = 0;
4061
4062 /*
4063 * Disabling interrupts avoids all counter scheduling (context
4064 * switches, timer based rotation and IPIs).
4065 */
4066 local_irq_save(flags);
4067
4068 /*
4069 * It must not be an event with inherit set, we cannot read
4070 * all child counters from atomic context.
4071 */
4072 if (event->attr.inherit) {
4073 ret = -EOPNOTSUPP;
4074 goto out;
4075 }
4076
4077 /* If this is a per-task event, it must be for current */
4078 if ((event->attach_state & PERF_ATTACH_TASK) &&
4079 event->hw.target != current) {
4080 ret = -EINVAL;
4081 goto out;
4082 }
4083
4084 /* If this is a per-CPU event, it must be for this CPU */
4085 if (!(event->attach_state & PERF_ATTACH_TASK) &&
4086 event->cpu != smp_processor_id()) {
4087 ret = -EINVAL;
4088 goto out;
4089 }
4090
4091 /* If this is a pinned event it must be running on this CPU */
4092 if (event->attr.pinned && event->oncpu != smp_processor_id()) {
4093 ret = -EBUSY;
4094 goto out;
4095 }
4096
4097 /*
4098 * If the event is currently on this CPU, its either a per-task event,
4099 * or local to this CPU. Furthermore it means its ACTIVE (otherwise
4100 * oncpu == -1).
4101 */
4102 if (event->oncpu == smp_processor_id())
4103 event->pmu->read(event);
4104
4105 *value = local64_read(&event->count);
4106 if (enabled || running) {
4107 u64 now = event->shadow_ctx_time + perf_clock();
4108 u64 __enabled, __running;
4109
4110 __perf_update_times(event, now, &__enabled, &__running);
4111 if (enabled)
4112 *enabled = __enabled;
4113 if (running)
4114 *running = __running;
4115 }
4116 out:
4117 local_irq_restore(flags);
4118
4119 return ret;
4120 }
4121
perf_event_read(struct perf_event * event,bool group)4122 static int perf_event_read(struct perf_event *event, bool group)
4123 {
4124 enum perf_event_state state = READ_ONCE(event->state);
4125 int event_cpu, ret = 0;
4126
4127 /*
4128 * If event is enabled and currently active on a CPU, update the
4129 * value in the event structure:
4130 */
4131 again:
4132 if (state == PERF_EVENT_STATE_ACTIVE) {
4133 struct perf_read_data data;
4134
4135 /*
4136 * Orders the ->state and ->oncpu loads such that if we see
4137 * ACTIVE we must also see the right ->oncpu.
4138 *
4139 * Matches the smp_wmb() from event_sched_in().
4140 */
4141 smp_rmb();
4142
4143 event_cpu = READ_ONCE(event->oncpu);
4144 if ((unsigned)event_cpu >= nr_cpu_ids)
4145 return 0;
4146
4147 data = (struct perf_read_data){
4148 .event = event,
4149 .group = group,
4150 .ret = 0,
4151 };
4152
4153 preempt_disable();
4154 event_cpu = __perf_event_read_cpu(event, event_cpu);
4155
4156 /*
4157 * Purposely ignore the smp_call_function_single() return
4158 * value.
4159 *
4160 * If event_cpu isn't a valid CPU it means the event got
4161 * scheduled out and that will have updated the event count.
4162 *
4163 * Therefore, either way, we'll have an up-to-date event count
4164 * after this.
4165 */
4166 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1);
4167 preempt_enable();
4168 ret = data.ret;
4169
4170 } else if (state == PERF_EVENT_STATE_INACTIVE) {
4171 struct perf_event_context *ctx = event->ctx;
4172 unsigned long flags;
4173
4174 raw_spin_lock_irqsave(&ctx->lock, flags);
4175 state = event->state;
4176 if (state != PERF_EVENT_STATE_INACTIVE) {
4177 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4178 goto again;
4179 }
4180
4181 /*
4182 * May read while context is not active (e.g., thread is
4183 * blocked), in that case we cannot update context time
4184 */
4185 if (ctx->is_active & EVENT_TIME) {
4186 update_context_time(ctx);
4187 update_cgrp_time_from_event(event);
4188 }
4189
4190 perf_event_update_time(event);
4191 if (group)
4192 perf_event_update_sibling_time(event);
4193 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4194 }
4195
4196 return ret;
4197 }
4198
4199 /*
4200 * Initialize the perf_event context in a task_struct:
4201 */
__perf_event_init_context(struct perf_event_context * ctx)4202 static void __perf_event_init_context(struct perf_event_context *ctx)
4203 {
4204 raw_spin_lock_init(&ctx->lock);
4205 mutex_init(&ctx->mutex);
4206 INIT_LIST_HEAD(&ctx->active_ctx_list);
4207 perf_event_groups_init(&ctx->pinned_groups);
4208 perf_event_groups_init(&ctx->flexible_groups);
4209 INIT_LIST_HEAD(&ctx->event_list);
4210 INIT_LIST_HEAD(&ctx->pinned_active);
4211 INIT_LIST_HEAD(&ctx->flexible_active);
4212 refcount_set(&ctx->refcount, 1);
4213 }
4214
4215 static struct perf_event_context *
alloc_perf_context(struct pmu * pmu,struct task_struct * task)4216 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
4217 {
4218 struct perf_event_context *ctx;
4219
4220 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4221 if (!ctx)
4222 return NULL;
4223
4224 __perf_event_init_context(ctx);
4225 if (task)
4226 ctx->task = get_task_struct(task);
4227 ctx->pmu = pmu;
4228
4229 return ctx;
4230 }
4231
4232 static struct task_struct *
find_lively_task_by_vpid(pid_t vpid)4233 find_lively_task_by_vpid(pid_t vpid)
4234 {
4235 struct task_struct *task;
4236
4237 rcu_read_lock();
4238 if (!vpid)
4239 task = current;
4240 else
4241 task = find_task_by_vpid(vpid);
4242 if (task)
4243 get_task_struct(task);
4244 rcu_read_unlock();
4245
4246 if (!task)
4247 return ERR_PTR(-ESRCH);
4248
4249 return task;
4250 }
4251
4252 /*
4253 * Returns a matching context with refcount and pincount.
4254 */
4255 static struct perf_event_context *
find_get_context(struct pmu * pmu,struct task_struct * task,struct perf_event * event)4256 find_get_context(struct pmu *pmu, struct task_struct *task,
4257 struct perf_event *event)
4258 {
4259 struct perf_event_context *ctx, *clone_ctx = NULL;
4260 struct perf_cpu_context *cpuctx;
4261 void *task_ctx_data = NULL;
4262 unsigned long flags;
4263 int ctxn, err;
4264 int cpu = event->cpu;
4265
4266 if (!task) {
4267 /* Must be root to operate on a CPU event: */
4268 err = perf_allow_cpu(&event->attr);
4269 if (err)
4270 return ERR_PTR(err);
4271
4272 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
4273 ctx = &cpuctx->ctx;
4274 get_ctx(ctx);
4275 raw_spin_lock_irqsave(&ctx->lock, flags);
4276 ++ctx->pin_count;
4277 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4278
4279 return ctx;
4280 }
4281
4282 err = -EINVAL;
4283 ctxn = pmu->task_ctx_nr;
4284 if (ctxn < 0)
4285 goto errout;
4286
4287 if (event->attach_state & PERF_ATTACH_TASK_DATA) {
4288 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL);
4289 if (!task_ctx_data) {
4290 err = -ENOMEM;
4291 goto errout;
4292 }
4293 }
4294
4295 retry:
4296 ctx = perf_lock_task_context(task, ctxn, &flags);
4297 if (ctx) {
4298 clone_ctx = unclone_ctx(ctx);
4299 ++ctx->pin_count;
4300
4301 if (task_ctx_data && !ctx->task_ctx_data) {
4302 ctx->task_ctx_data = task_ctx_data;
4303 task_ctx_data = NULL;
4304 }
4305 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4306
4307 if (clone_ctx)
4308 put_ctx(clone_ctx);
4309 } else {
4310 ctx = alloc_perf_context(pmu, task);
4311 err = -ENOMEM;
4312 if (!ctx)
4313 goto errout;
4314
4315 if (task_ctx_data) {
4316 ctx->task_ctx_data = task_ctx_data;
4317 task_ctx_data = NULL;
4318 }
4319
4320 err = 0;
4321 mutex_lock(&task->perf_event_mutex);
4322 /*
4323 * If it has already passed perf_event_exit_task().
4324 * we must see PF_EXITING, it takes this mutex too.
4325 */
4326 if (task->flags & PF_EXITING)
4327 err = -ESRCH;
4328 else if (task->perf_event_ctxp[ctxn])
4329 err = -EAGAIN;
4330 else {
4331 get_ctx(ctx);
4332 ++ctx->pin_count;
4333 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
4334 }
4335 mutex_unlock(&task->perf_event_mutex);
4336
4337 if (unlikely(err)) {
4338 put_ctx(ctx);
4339
4340 if (err == -EAGAIN)
4341 goto retry;
4342 goto errout;
4343 }
4344 }
4345
4346 kfree(task_ctx_data);
4347 return ctx;
4348
4349 errout:
4350 kfree(task_ctx_data);
4351 return ERR_PTR(err);
4352 }
4353
4354 static void perf_event_free_filter(struct perf_event *event);
4355 static void perf_event_free_bpf_prog(struct perf_event *event);
4356
free_event_rcu(struct rcu_head * head)4357 static void free_event_rcu(struct rcu_head *head)
4358 {
4359 struct perf_event *event;
4360
4361 event = container_of(head, struct perf_event, rcu_head);
4362 if (event->ns)
4363 put_pid_ns(event->ns);
4364 perf_event_free_filter(event);
4365 kfree(event);
4366 }
4367
4368 static void ring_buffer_attach(struct perf_event *event,
4369 struct ring_buffer *rb);
4370
detach_sb_event(struct perf_event * event)4371 static void detach_sb_event(struct perf_event *event)
4372 {
4373 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
4374
4375 raw_spin_lock(&pel->lock);
4376 list_del_rcu(&event->sb_list);
4377 raw_spin_unlock(&pel->lock);
4378 }
4379
is_sb_event(struct perf_event * event)4380 static bool is_sb_event(struct perf_event *event)
4381 {
4382 struct perf_event_attr *attr = &event->attr;
4383
4384 if (event->parent)
4385 return false;
4386
4387 if (event->attach_state & PERF_ATTACH_TASK)
4388 return false;
4389
4390 if (attr->mmap || attr->mmap_data || attr->mmap2 ||
4391 attr->comm || attr->comm_exec ||
4392 attr->task || attr->ksymbol ||
4393 attr->context_switch ||
4394 attr->bpf_event)
4395 return true;
4396 return false;
4397 }
4398
unaccount_pmu_sb_event(struct perf_event * event)4399 static void unaccount_pmu_sb_event(struct perf_event *event)
4400 {
4401 if (is_sb_event(event))
4402 detach_sb_event(event);
4403 }
4404
unaccount_event_cpu(struct perf_event * event,int cpu)4405 static void unaccount_event_cpu(struct perf_event *event, int cpu)
4406 {
4407 if (event->parent)
4408 return;
4409
4410 if (is_cgroup_event(event))
4411 atomic_dec(&per_cpu(perf_cgroup_events, cpu));
4412 }
4413
4414 #ifdef CONFIG_NO_HZ_FULL
4415 static DEFINE_SPINLOCK(nr_freq_lock);
4416 #endif
4417
unaccount_freq_event_nohz(void)4418 static void unaccount_freq_event_nohz(void)
4419 {
4420 #ifdef CONFIG_NO_HZ_FULL
4421 spin_lock(&nr_freq_lock);
4422 if (atomic_dec_and_test(&nr_freq_events))
4423 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS);
4424 spin_unlock(&nr_freq_lock);
4425 #endif
4426 }
4427
unaccount_freq_event(void)4428 static void unaccount_freq_event(void)
4429 {
4430 if (tick_nohz_full_enabled())
4431 unaccount_freq_event_nohz();
4432 else
4433 atomic_dec(&nr_freq_events);
4434 }
4435
unaccount_event(struct perf_event * event)4436 static void unaccount_event(struct perf_event *event)
4437 {
4438 bool dec = false;
4439
4440 if (event->parent)
4441 return;
4442
4443 if (event->attach_state & PERF_ATTACH_TASK)
4444 dec = true;
4445 if (event->attr.mmap || event->attr.mmap_data)
4446 atomic_dec(&nr_mmap_events);
4447 if (event->attr.comm)
4448 atomic_dec(&nr_comm_events);
4449 if (event->attr.namespaces)
4450 atomic_dec(&nr_namespaces_events);
4451 if (event->attr.task)
4452 atomic_dec(&nr_task_events);
4453 if (event->attr.freq)
4454 unaccount_freq_event();
4455 if (event->attr.context_switch) {
4456 dec = true;
4457 atomic_dec(&nr_switch_events);
4458 }
4459 if (is_cgroup_event(event))
4460 dec = true;
4461 if (has_branch_stack(event))
4462 dec = true;
4463 if (event->attr.ksymbol)
4464 atomic_dec(&nr_ksymbol_events);
4465 if (event->attr.bpf_event)
4466 atomic_dec(&nr_bpf_events);
4467
4468 if (dec) {
4469 if (!atomic_add_unless(&perf_sched_count, -1, 1))
4470 schedule_delayed_work(&perf_sched_work, HZ);
4471 }
4472
4473 unaccount_event_cpu(event, event->cpu);
4474
4475 unaccount_pmu_sb_event(event);
4476 }
4477
perf_sched_delayed(struct work_struct * work)4478 static void perf_sched_delayed(struct work_struct *work)
4479 {
4480 mutex_lock(&perf_sched_mutex);
4481 if (atomic_dec_and_test(&perf_sched_count))
4482 static_branch_disable(&perf_sched_events);
4483 mutex_unlock(&perf_sched_mutex);
4484 }
4485
4486 /*
4487 * The following implement mutual exclusion of events on "exclusive" pmus
4488 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled
4489 * at a time, so we disallow creating events that might conflict, namely:
4490 *
4491 * 1) cpu-wide events in the presence of per-task events,
4492 * 2) per-task events in the presence of cpu-wide events,
4493 * 3) two matching events on the same context.
4494 *
4495 * The former two cases are handled in the allocation path (perf_event_alloc(),
4496 * _free_event()), the latter -- before the first perf_install_in_context().
4497 */
exclusive_event_init(struct perf_event * event)4498 static int exclusive_event_init(struct perf_event *event)
4499 {
4500 struct pmu *pmu = event->pmu;
4501
4502 if (!is_exclusive_pmu(pmu))
4503 return 0;
4504
4505 /*
4506 * Prevent co-existence of per-task and cpu-wide events on the
4507 * same exclusive pmu.
4508 *
4509 * Negative pmu::exclusive_cnt means there are cpu-wide
4510 * events on this "exclusive" pmu, positive means there are
4511 * per-task events.
4512 *
4513 * Since this is called in perf_event_alloc() path, event::ctx
4514 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK
4515 * to mean "per-task event", because unlike other attach states it
4516 * never gets cleared.
4517 */
4518 if (event->attach_state & PERF_ATTACH_TASK) {
4519 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt))
4520 return -EBUSY;
4521 } else {
4522 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt))
4523 return -EBUSY;
4524 }
4525
4526 return 0;
4527 }
4528
exclusive_event_destroy(struct perf_event * event)4529 static void exclusive_event_destroy(struct perf_event *event)
4530 {
4531 struct pmu *pmu = event->pmu;
4532
4533 if (!is_exclusive_pmu(pmu))
4534 return;
4535
4536 /* see comment in exclusive_event_init() */
4537 if (event->attach_state & PERF_ATTACH_TASK)
4538 atomic_dec(&pmu->exclusive_cnt);
4539 else
4540 atomic_inc(&pmu->exclusive_cnt);
4541 }
4542
exclusive_event_match(struct perf_event * e1,struct perf_event * e2)4543 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2)
4544 {
4545 if ((e1->pmu == e2->pmu) &&
4546 (e1->cpu == e2->cpu ||
4547 e1->cpu == -1 ||
4548 e2->cpu == -1))
4549 return true;
4550 return false;
4551 }
4552
exclusive_event_installable(struct perf_event * event,struct perf_event_context * ctx)4553 static bool exclusive_event_installable(struct perf_event *event,
4554 struct perf_event_context *ctx)
4555 {
4556 struct perf_event *iter_event;
4557 struct pmu *pmu = event->pmu;
4558
4559 lockdep_assert_held(&ctx->mutex);
4560
4561 if (!is_exclusive_pmu(pmu))
4562 return true;
4563
4564 list_for_each_entry(iter_event, &ctx->event_list, event_entry) {
4565 if (exclusive_event_match(iter_event, event))
4566 return false;
4567 }
4568
4569 return true;
4570 }
4571
4572 static void perf_addr_filters_splice(struct perf_event *event,
4573 struct list_head *head);
4574
_free_event(struct perf_event * event)4575 static void _free_event(struct perf_event *event)
4576 {
4577 irq_work_sync(&event->pending);
4578
4579 unaccount_event(event);
4580
4581 security_perf_event_free(event);
4582
4583 if (event->rb) {
4584 /*
4585 * Can happen when we close an event with re-directed output.
4586 *
4587 * Since we have a 0 refcount, perf_mmap_close() will skip
4588 * over us; possibly making our ring_buffer_put() the last.
4589 */
4590 mutex_lock(&event->mmap_mutex);
4591 ring_buffer_attach(event, NULL);
4592 mutex_unlock(&event->mmap_mutex);
4593 }
4594
4595 if (is_cgroup_event(event))
4596 perf_detach_cgroup(event);
4597
4598 if (!event->parent) {
4599 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
4600 put_callchain_buffers();
4601 }
4602
4603 perf_event_free_bpf_prog(event);
4604 perf_addr_filters_splice(event, NULL);
4605 kfree(event->addr_filter_ranges);
4606
4607 if (event->destroy)
4608 event->destroy(event);
4609
4610 /*
4611 * Must be after ->destroy(), due to uprobe_perf_close() using
4612 * hw.target.
4613 */
4614 if (event->hw.target)
4615 put_task_struct(event->hw.target);
4616
4617 /*
4618 * perf_event_free_task() relies on put_ctx() being 'last', in particular
4619 * all task references must be cleaned up.
4620 */
4621 if (event->ctx)
4622 put_ctx(event->ctx);
4623
4624 exclusive_event_destroy(event);
4625 module_put(event->pmu->module);
4626
4627 call_rcu(&event->rcu_head, free_event_rcu);
4628 }
4629
4630 /*
4631 * Used to free events which have a known refcount of 1, such as in error paths
4632 * where the event isn't exposed yet and inherited events.
4633 */
free_event(struct perf_event * event)4634 static void free_event(struct perf_event *event)
4635 {
4636 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1,
4637 "unexpected event refcount: %ld; ptr=%p\n",
4638 atomic_long_read(&event->refcount), event)) {
4639 /* leak to avoid use-after-free */
4640 return;
4641 }
4642
4643 _free_event(event);
4644 }
4645
4646 /*
4647 * Remove user event from the owner task.
4648 */
perf_remove_from_owner(struct perf_event * event)4649 static void perf_remove_from_owner(struct perf_event *event)
4650 {
4651 struct task_struct *owner;
4652
4653 rcu_read_lock();
4654 /*
4655 * Matches the smp_store_release() in perf_event_exit_task(). If we
4656 * observe !owner it means the list deletion is complete and we can
4657 * indeed free this event, otherwise we need to serialize on
4658 * owner->perf_event_mutex.
4659 */
4660 owner = READ_ONCE(event->owner);
4661 if (owner) {
4662 /*
4663 * Since delayed_put_task_struct() also drops the last
4664 * task reference we can safely take a new reference
4665 * while holding the rcu_read_lock().
4666 */
4667 get_task_struct(owner);
4668 }
4669 rcu_read_unlock();
4670
4671 if (owner) {
4672 /*
4673 * If we're here through perf_event_exit_task() we're already
4674 * holding ctx->mutex which would be an inversion wrt. the
4675 * normal lock order.
4676 *
4677 * However we can safely take this lock because its the child
4678 * ctx->mutex.
4679 */
4680 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING);
4681
4682 /*
4683 * We have to re-check the event->owner field, if it is cleared
4684 * we raced with perf_event_exit_task(), acquiring the mutex
4685 * ensured they're done, and we can proceed with freeing the
4686 * event.
4687 */
4688 if (event->owner) {
4689 list_del_init(&event->owner_entry);
4690 smp_store_release(&event->owner, NULL);
4691 }
4692 mutex_unlock(&owner->perf_event_mutex);
4693 put_task_struct(owner);
4694 }
4695 }
4696
put_event(struct perf_event * event)4697 static void put_event(struct perf_event *event)
4698 {
4699 if (!atomic_long_dec_and_test(&event->refcount))
4700 return;
4701
4702 _free_event(event);
4703 }
4704
4705 /*
4706 * Kill an event dead; while event:refcount will preserve the event
4707 * object, it will not preserve its functionality. Once the last 'user'
4708 * gives up the object, we'll destroy the thing.
4709 */
perf_event_release_kernel(struct perf_event * event)4710 int perf_event_release_kernel(struct perf_event *event)
4711 {
4712 struct perf_event_context *ctx = event->ctx;
4713 struct perf_event *child, *tmp;
4714 LIST_HEAD(free_list);
4715
4716 /*
4717 * If we got here through err_file: fput(event_file); we will not have
4718 * attached to a context yet.
4719 */
4720 if (!ctx) {
4721 WARN_ON_ONCE(event->attach_state &
4722 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP));
4723 goto no_ctx;
4724 }
4725
4726 if (!is_kernel_event(event))
4727 perf_remove_from_owner(event);
4728
4729 ctx = perf_event_ctx_lock(event);
4730 WARN_ON_ONCE(ctx->parent_ctx);
4731 perf_remove_from_context(event, DETACH_GROUP);
4732
4733 raw_spin_lock_irq(&ctx->lock);
4734 /*
4735 * Mark this event as STATE_DEAD, there is no external reference to it
4736 * anymore.
4737 *
4738 * Anybody acquiring event->child_mutex after the below loop _must_
4739 * also see this, most importantly inherit_event() which will avoid
4740 * placing more children on the list.
4741 *
4742 * Thus this guarantees that we will in fact observe and kill _ALL_
4743 * child events.
4744 */
4745 event->state = PERF_EVENT_STATE_DEAD;
4746 raw_spin_unlock_irq(&ctx->lock);
4747
4748 perf_event_ctx_unlock(event, ctx);
4749
4750 again:
4751 mutex_lock(&event->child_mutex);
4752 list_for_each_entry(child, &event->child_list, child_list) {
4753
4754 /*
4755 * Cannot change, child events are not migrated, see the
4756 * comment with perf_event_ctx_lock_nested().
4757 */
4758 ctx = READ_ONCE(child->ctx);
4759 /*
4760 * Since child_mutex nests inside ctx::mutex, we must jump
4761 * through hoops. We start by grabbing a reference on the ctx.
4762 *
4763 * Since the event cannot get freed while we hold the
4764 * child_mutex, the context must also exist and have a !0
4765 * reference count.
4766 */
4767 get_ctx(ctx);
4768
4769 /*
4770 * Now that we have a ctx ref, we can drop child_mutex, and
4771 * acquire ctx::mutex without fear of it going away. Then we
4772 * can re-acquire child_mutex.
4773 */
4774 mutex_unlock(&event->child_mutex);
4775 mutex_lock(&ctx->mutex);
4776 mutex_lock(&event->child_mutex);
4777
4778 /*
4779 * Now that we hold ctx::mutex and child_mutex, revalidate our
4780 * state, if child is still the first entry, it didn't get freed
4781 * and we can continue doing so.
4782 */
4783 tmp = list_first_entry_or_null(&event->child_list,
4784 struct perf_event, child_list);
4785 if (tmp == child) {
4786 perf_remove_from_context(child, DETACH_GROUP);
4787 list_move(&child->child_list, &free_list);
4788 /*
4789 * This matches the refcount bump in inherit_event();
4790 * this can't be the last reference.
4791 */
4792 put_event(event);
4793 }
4794
4795 mutex_unlock(&event->child_mutex);
4796 mutex_unlock(&ctx->mutex);
4797 put_ctx(ctx);
4798 goto again;
4799 }
4800 mutex_unlock(&event->child_mutex);
4801
4802 list_for_each_entry_safe(child, tmp, &free_list, child_list) {
4803 void *var = &child->ctx->refcount;
4804
4805 list_del(&child->child_list);
4806 free_event(child);
4807
4808 /*
4809 * Wake any perf_event_free_task() waiting for this event to be
4810 * freed.
4811 */
4812 smp_mb(); /* pairs with wait_var_event() */
4813 wake_up_var(var);
4814 }
4815
4816 no_ctx:
4817 put_event(event); /* Must be the 'last' reference */
4818 return 0;
4819 }
4820 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
4821
4822 /*
4823 * Called when the last reference to the file is gone.
4824 */
perf_release(struct inode * inode,struct file * file)4825 static int perf_release(struct inode *inode, struct file *file)
4826 {
4827 perf_event_release_kernel(file->private_data);
4828 return 0;
4829 }
4830
__perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)4831 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4832 {
4833 struct perf_event *child;
4834 u64 total = 0;
4835
4836 *enabled = 0;
4837 *running = 0;
4838
4839 mutex_lock(&event->child_mutex);
4840
4841 (void)perf_event_read(event, false);
4842 total += perf_event_count(event);
4843
4844 *enabled += event->total_time_enabled +
4845 atomic64_read(&event->child_total_time_enabled);
4846 *running += event->total_time_running +
4847 atomic64_read(&event->child_total_time_running);
4848
4849 list_for_each_entry(child, &event->child_list, child_list) {
4850 (void)perf_event_read(child, false);
4851 total += perf_event_count(child);
4852 *enabled += child->total_time_enabled;
4853 *running += child->total_time_running;
4854 }
4855 mutex_unlock(&event->child_mutex);
4856
4857 return total;
4858 }
4859
perf_event_read_value(struct perf_event * event,u64 * enabled,u64 * running)4860 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
4861 {
4862 struct perf_event_context *ctx;
4863 u64 count;
4864
4865 ctx = perf_event_ctx_lock(event);
4866 count = __perf_event_read_value(event, enabled, running);
4867 perf_event_ctx_unlock(event, ctx);
4868
4869 return count;
4870 }
4871 EXPORT_SYMBOL_GPL(perf_event_read_value);
4872
__perf_read_group_add(struct perf_event * leader,u64 read_format,u64 * values)4873 static int __perf_read_group_add(struct perf_event *leader,
4874 u64 read_format, u64 *values)
4875 {
4876 struct perf_event_context *ctx = leader->ctx;
4877 struct perf_event *sub, *parent;
4878 unsigned long flags;
4879 int n = 1; /* skip @nr */
4880 int ret;
4881
4882 ret = perf_event_read(leader, true);
4883 if (ret)
4884 return ret;
4885
4886 raw_spin_lock_irqsave(&ctx->lock, flags);
4887 /*
4888 * Verify the grouping between the parent and child (inherited)
4889 * events is still in tact.
4890 *
4891 * Specifically:
4892 * - leader->ctx->lock pins leader->sibling_list
4893 * - parent->child_mutex pins parent->child_list
4894 * - parent->ctx->mutex pins parent->sibling_list
4895 *
4896 * Because parent->ctx != leader->ctx (and child_list nests inside
4897 * ctx->mutex), group destruction is not atomic between children, also
4898 * see perf_event_release_kernel(). Additionally, parent can grow the
4899 * group.
4900 *
4901 * Therefore it is possible to have parent and child groups in a
4902 * different configuration and summing over such a beast makes no sense
4903 * what so ever.
4904 *
4905 * Reject this.
4906 */
4907 parent = leader->parent;
4908 if (parent &&
4909 (parent->group_generation != leader->group_generation ||
4910 parent->nr_siblings != leader->nr_siblings)) {
4911 ret = -ECHILD;
4912 goto unlock;
4913 }
4914
4915 /*
4916 * Since we co-schedule groups, {enabled,running} times of siblings
4917 * will be identical to those of the leader, so we only publish one
4918 * set.
4919 */
4920 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
4921 values[n++] += leader->total_time_enabled +
4922 atomic64_read(&leader->child_total_time_enabled);
4923 }
4924
4925 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
4926 values[n++] += leader->total_time_running +
4927 atomic64_read(&leader->child_total_time_running);
4928 }
4929
4930 /*
4931 * Write {count,id} tuples for every sibling.
4932 */
4933 values[n++] += perf_event_count(leader);
4934 if (read_format & PERF_FORMAT_ID)
4935 values[n++] = primary_event_id(leader);
4936
4937 for_each_sibling_event(sub, leader) {
4938 values[n++] += perf_event_count(sub);
4939 if (read_format & PERF_FORMAT_ID)
4940 values[n++] = primary_event_id(sub);
4941 }
4942
4943 unlock:
4944 raw_spin_unlock_irqrestore(&ctx->lock, flags);
4945 return ret;
4946 }
4947
perf_read_group(struct perf_event * event,u64 read_format,char __user * buf)4948 static int perf_read_group(struct perf_event *event,
4949 u64 read_format, char __user *buf)
4950 {
4951 struct perf_event *leader = event->group_leader, *child;
4952 struct perf_event_context *ctx = leader->ctx;
4953 int ret;
4954 u64 *values;
4955
4956 lockdep_assert_held(&ctx->mutex);
4957
4958 values = kzalloc(event->read_size, GFP_KERNEL);
4959 if (!values)
4960 return -ENOMEM;
4961
4962 values[0] = 1 + leader->nr_siblings;
4963
4964 mutex_lock(&leader->child_mutex);
4965
4966 ret = __perf_read_group_add(leader, read_format, values);
4967 if (ret)
4968 goto unlock;
4969
4970 list_for_each_entry(child, &leader->child_list, child_list) {
4971 ret = __perf_read_group_add(child, read_format, values);
4972 if (ret)
4973 goto unlock;
4974 }
4975
4976 mutex_unlock(&leader->child_mutex);
4977
4978 ret = event->read_size;
4979 if (copy_to_user(buf, values, event->read_size))
4980 ret = -EFAULT;
4981 goto out;
4982
4983 unlock:
4984 mutex_unlock(&leader->child_mutex);
4985 out:
4986 kfree(values);
4987 return ret;
4988 }
4989
perf_read_one(struct perf_event * event,u64 read_format,char __user * buf)4990 static int perf_read_one(struct perf_event *event,
4991 u64 read_format, char __user *buf)
4992 {
4993 u64 enabled, running;
4994 u64 values[4];
4995 int n = 0;
4996
4997 values[n++] = __perf_event_read_value(event, &enabled, &running);
4998 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
4999 values[n++] = enabled;
5000 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
5001 values[n++] = running;
5002 if (read_format & PERF_FORMAT_ID)
5003 values[n++] = primary_event_id(event);
5004
5005 if (copy_to_user(buf, values, n * sizeof(u64)))
5006 return -EFAULT;
5007
5008 return n * sizeof(u64);
5009 }
5010
is_event_hup(struct perf_event * event)5011 static bool is_event_hup(struct perf_event *event)
5012 {
5013 bool no_children;
5014
5015 if (event->state > PERF_EVENT_STATE_EXIT)
5016 return false;
5017
5018 mutex_lock(&event->child_mutex);
5019 no_children = list_empty(&event->child_list);
5020 mutex_unlock(&event->child_mutex);
5021 return no_children;
5022 }
5023
5024 /*
5025 * Read the performance event - simple non blocking version for now
5026 */
5027 static ssize_t
__perf_read(struct perf_event * event,char __user * buf,size_t count)5028 __perf_read(struct perf_event *event, char __user *buf, size_t count)
5029 {
5030 u64 read_format = event->attr.read_format;
5031 int ret;
5032
5033 /*
5034 * Return end-of-file for a read on an event that is in
5035 * error state (i.e. because it was pinned but it couldn't be
5036 * scheduled on to the CPU at some point).
5037 */
5038 if (event->state == PERF_EVENT_STATE_ERROR)
5039 return 0;
5040
5041 if (count < event->read_size)
5042 return -ENOSPC;
5043
5044 WARN_ON_ONCE(event->ctx->parent_ctx);
5045 if (read_format & PERF_FORMAT_GROUP)
5046 ret = perf_read_group(event, read_format, buf);
5047 else
5048 ret = perf_read_one(event, read_format, buf);
5049
5050 return ret;
5051 }
5052
5053 static ssize_t
perf_read(struct file * file,char __user * buf,size_t count,loff_t * ppos)5054 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
5055 {
5056 struct perf_event *event = file->private_data;
5057 struct perf_event_context *ctx;
5058 int ret;
5059
5060 ret = security_perf_event_read(event);
5061 if (ret)
5062 return ret;
5063
5064 ctx = perf_event_ctx_lock(event);
5065 ret = __perf_read(event, buf, count);
5066 perf_event_ctx_unlock(event, ctx);
5067
5068 return ret;
5069 }
5070
perf_poll(struct file * file,poll_table * wait)5071 static __poll_t perf_poll(struct file *file, poll_table *wait)
5072 {
5073 struct perf_event *event = file->private_data;
5074 struct ring_buffer *rb;
5075 __poll_t events = EPOLLHUP;
5076
5077 poll_wait(file, &event->waitq, wait);
5078
5079 if (is_event_hup(event))
5080 return events;
5081
5082 /*
5083 * Pin the event->rb by taking event->mmap_mutex; otherwise
5084 * perf_event_set_output() can swizzle our rb and make us miss wakeups.
5085 */
5086 mutex_lock(&event->mmap_mutex);
5087 rb = event->rb;
5088 if (rb)
5089 events = atomic_xchg(&rb->poll, 0);
5090 mutex_unlock(&event->mmap_mutex);
5091 return events;
5092 }
5093
_perf_event_reset(struct perf_event * event)5094 static void _perf_event_reset(struct perf_event *event)
5095 {
5096 (void)perf_event_read(event, false);
5097 local64_set(&event->count, 0);
5098 perf_event_update_userpage(event);
5099 }
5100
5101 /*
5102 * Holding the top-level event's child_mutex means that any
5103 * descendant process that has inherited this event will block
5104 * in perf_event_exit_event() if it goes to exit, thus satisfying the
5105 * task existence requirements of perf_event_enable/disable.
5106 */
perf_event_for_each_child(struct perf_event * event,void (* func)(struct perf_event *))5107 static void perf_event_for_each_child(struct perf_event *event,
5108 void (*func)(struct perf_event *))
5109 {
5110 struct perf_event *child;
5111
5112 WARN_ON_ONCE(event->ctx->parent_ctx);
5113
5114 mutex_lock(&event->child_mutex);
5115 func(event);
5116 list_for_each_entry(child, &event->child_list, child_list)
5117 func(child);
5118 mutex_unlock(&event->child_mutex);
5119 }
5120
perf_event_for_each(struct perf_event * event,void (* func)(struct perf_event *))5121 static void perf_event_for_each(struct perf_event *event,
5122 void (*func)(struct perf_event *))
5123 {
5124 struct perf_event_context *ctx = event->ctx;
5125 struct perf_event *sibling;
5126
5127 lockdep_assert_held(&ctx->mutex);
5128
5129 event = event->group_leader;
5130
5131 perf_event_for_each_child(event, func);
5132 for_each_sibling_event(sibling, event)
5133 perf_event_for_each_child(sibling, func);
5134 }
5135
__perf_event_period(struct perf_event * event,struct perf_cpu_context * cpuctx,struct perf_event_context * ctx,void * info)5136 static void __perf_event_period(struct perf_event *event,
5137 struct perf_cpu_context *cpuctx,
5138 struct perf_event_context *ctx,
5139 void *info)
5140 {
5141 u64 value = *((u64 *)info);
5142 bool active;
5143
5144 if (event->attr.freq) {
5145 event->attr.sample_freq = value;
5146 } else {
5147 event->attr.sample_period = value;
5148 event->hw.sample_period = value;
5149 }
5150
5151 active = (event->state == PERF_EVENT_STATE_ACTIVE);
5152 if (active) {
5153 perf_pmu_disable(ctx->pmu);
5154 /*
5155 * We could be throttled; unthrottle now to avoid the tick
5156 * trying to unthrottle while we already re-started the event.
5157 */
5158 if (event->hw.interrupts == MAX_INTERRUPTS) {
5159 event->hw.interrupts = 0;
5160 perf_log_throttle(event, 1);
5161 }
5162 event->pmu->stop(event, PERF_EF_UPDATE);
5163 }
5164
5165 local64_set(&event->hw.period_left, 0);
5166
5167 if (active) {
5168 event->pmu->start(event, PERF_EF_RELOAD);
5169 perf_pmu_enable(ctx->pmu);
5170 }
5171 }
5172
perf_event_check_period(struct perf_event * event,u64 value)5173 static int perf_event_check_period(struct perf_event *event, u64 value)
5174 {
5175 return event->pmu->check_period(event, value);
5176 }
5177
perf_event_period(struct perf_event * event,u64 __user * arg)5178 static int perf_event_period(struct perf_event *event, u64 __user *arg)
5179 {
5180 u64 value;
5181
5182 if (!is_sampling_event(event))
5183 return -EINVAL;
5184
5185 if (copy_from_user(&value, arg, sizeof(value)))
5186 return -EFAULT;
5187
5188 if (!value)
5189 return -EINVAL;
5190
5191 if (event->attr.freq && value > sysctl_perf_event_sample_rate)
5192 return -EINVAL;
5193
5194 if (perf_event_check_period(event, value))
5195 return -EINVAL;
5196
5197 if (!event->attr.freq && (value & (1ULL << 63)))
5198 return -EINVAL;
5199
5200 event_function_call(event, __perf_event_period, &value);
5201
5202 return 0;
5203 }
5204
5205 static const struct file_operations perf_fops;
5206
perf_fget_light(int fd,struct fd * p)5207 static inline int perf_fget_light(int fd, struct fd *p)
5208 {
5209 struct fd f = fdget(fd);
5210 if (!f.file)
5211 return -EBADF;
5212
5213 if (f.file->f_op != &perf_fops) {
5214 fdput(f);
5215 return -EBADF;
5216 }
5217 *p = f;
5218 return 0;
5219 }
5220
5221 static int perf_event_set_output(struct perf_event *event,
5222 struct perf_event *output_event);
5223 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
5224 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd);
5225 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5226 struct perf_event_attr *attr);
5227
_perf_ioctl(struct perf_event * event,unsigned int cmd,unsigned long arg)5228 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg)
5229 {
5230 void (*func)(struct perf_event *);
5231 u32 flags = arg;
5232
5233 switch (cmd) {
5234 case PERF_EVENT_IOC_ENABLE:
5235 func = _perf_event_enable;
5236 break;
5237 case PERF_EVENT_IOC_DISABLE:
5238 func = _perf_event_disable;
5239 break;
5240 case PERF_EVENT_IOC_RESET:
5241 func = _perf_event_reset;
5242 break;
5243
5244 case PERF_EVENT_IOC_REFRESH:
5245 return _perf_event_refresh(event, arg);
5246
5247 case PERF_EVENT_IOC_PERIOD:
5248 return perf_event_period(event, (u64 __user *)arg);
5249
5250 case PERF_EVENT_IOC_ID:
5251 {
5252 u64 id = primary_event_id(event);
5253
5254 if (copy_to_user((void __user *)arg, &id, sizeof(id)))
5255 return -EFAULT;
5256 return 0;
5257 }
5258
5259 case PERF_EVENT_IOC_SET_OUTPUT:
5260 {
5261 int ret;
5262 if (arg != -1) {
5263 struct perf_event *output_event;
5264 struct fd output;
5265 ret = perf_fget_light(arg, &output);
5266 if (ret)
5267 return ret;
5268 output_event = output.file->private_data;
5269 ret = perf_event_set_output(event, output_event);
5270 fdput(output);
5271 } else {
5272 ret = perf_event_set_output(event, NULL);
5273 }
5274 return ret;
5275 }
5276
5277 case PERF_EVENT_IOC_SET_FILTER:
5278 return perf_event_set_filter(event, (void __user *)arg);
5279
5280 case PERF_EVENT_IOC_SET_BPF:
5281 return perf_event_set_bpf_prog(event, arg);
5282
5283 case PERF_EVENT_IOC_PAUSE_OUTPUT: {
5284 struct ring_buffer *rb;
5285
5286 rcu_read_lock();
5287 rb = rcu_dereference(event->rb);
5288 if (!rb || !rb->nr_pages) {
5289 rcu_read_unlock();
5290 return -EINVAL;
5291 }
5292 rb_toggle_paused(rb, !!arg);
5293 rcu_read_unlock();
5294 return 0;
5295 }
5296
5297 case PERF_EVENT_IOC_QUERY_BPF:
5298 return perf_event_query_prog_array(event, (void __user *)arg);
5299
5300 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: {
5301 struct perf_event_attr new_attr;
5302 int err = perf_copy_attr((struct perf_event_attr __user *)arg,
5303 &new_attr);
5304
5305 if (err)
5306 return err;
5307
5308 return perf_event_modify_attr(event, &new_attr);
5309 }
5310 default:
5311 return -ENOTTY;
5312 }
5313
5314 if (flags & PERF_IOC_FLAG_GROUP)
5315 perf_event_for_each(event, func);
5316 else
5317 perf_event_for_each_child(event, func);
5318
5319 return 0;
5320 }
5321
perf_ioctl(struct file * file,unsigned int cmd,unsigned long arg)5322 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5323 {
5324 struct perf_event *event = file->private_data;
5325 struct perf_event_context *ctx;
5326 long ret;
5327
5328 /* Treat ioctl like writes as it is likely a mutating operation. */
5329 ret = security_perf_event_write(event);
5330 if (ret)
5331 return ret;
5332
5333 ctx = perf_event_ctx_lock(event);
5334 ret = _perf_ioctl(event, cmd, arg);
5335 perf_event_ctx_unlock(event, ctx);
5336
5337 return ret;
5338 }
5339
5340 #ifdef CONFIG_COMPAT
perf_compat_ioctl(struct file * file,unsigned int cmd,unsigned long arg)5341 static long perf_compat_ioctl(struct file *file, unsigned int cmd,
5342 unsigned long arg)
5343 {
5344 switch (_IOC_NR(cmd)) {
5345 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER):
5346 case _IOC_NR(PERF_EVENT_IOC_ID):
5347 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF):
5348 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES):
5349 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */
5350 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) {
5351 cmd &= ~IOCSIZE_MASK;
5352 cmd |= sizeof(void *) << IOCSIZE_SHIFT;
5353 }
5354 break;
5355 }
5356 return perf_ioctl(file, cmd, arg);
5357 }
5358 #else
5359 # define perf_compat_ioctl NULL
5360 #endif
5361
perf_event_task_enable(void)5362 int perf_event_task_enable(void)
5363 {
5364 struct perf_event_context *ctx;
5365 struct perf_event *event;
5366
5367 mutex_lock(¤t->perf_event_mutex);
5368 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5369 ctx = perf_event_ctx_lock(event);
5370 perf_event_for_each_child(event, _perf_event_enable);
5371 perf_event_ctx_unlock(event, ctx);
5372 }
5373 mutex_unlock(¤t->perf_event_mutex);
5374
5375 return 0;
5376 }
5377
perf_event_task_disable(void)5378 int perf_event_task_disable(void)
5379 {
5380 struct perf_event_context *ctx;
5381 struct perf_event *event;
5382
5383 mutex_lock(¤t->perf_event_mutex);
5384 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) {
5385 ctx = perf_event_ctx_lock(event);
5386 perf_event_for_each_child(event, _perf_event_disable);
5387 perf_event_ctx_unlock(event, ctx);
5388 }
5389 mutex_unlock(¤t->perf_event_mutex);
5390
5391 return 0;
5392 }
5393
perf_event_index(struct perf_event * event)5394 static int perf_event_index(struct perf_event *event)
5395 {
5396 if (event->hw.state & PERF_HES_STOPPED)
5397 return 0;
5398
5399 if (event->state != PERF_EVENT_STATE_ACTIVE)
5400 return 0;
5401
5402 return event->pmu->event_idx(event);
5403 }
5404
calc_timer_values(struct perf_event * event,u64 * now,u64 * enabled,u64 * running)5405 static void calc_timer_values(struct perf_event *event,
5406 u64 *now,
5407 u64 *enabled,
5408 u64 *running)
5409 {
5410 u64 ctx_time;
5411
5412 *now = perf_clock();
5413 ctx_time = event->shadow_ctx_time + *now;
5414 __perf_update_times(event, ctx_time, enabled, running);
5415 }
5416
perf_event_init_userpage(struct perf_event * event)5417 static void perf_event_init_userpage(struct perf_event *event)
5418 {
5419 struct perf_event_mmap_page *userpg;
5420 struct ring_buffer *rb;
5421
5422 rcu_read_lock();
5423 rb = rcu_dereference(event->rb);
5424 if (!rb)
5425 goto unlock;
5426
5427 userpg = rb->user_page;
5428
5429 /* Allow new userspace to detect that bit 0 is deprecated */
5430 userpg->cap_bit0_is_deprecated = 1;
5431 userpg->size = offsetof(struct perf_event_mmap_page, __reserved);
5432 userpg->data_offset = PAGE_SIZE;
5433 userpg->data_size = perf_data_size(rb);
5434
5435 unlock:
5436 rcu_read_unlock();
5437 }
5438
arch_perf_update_userpage(struct perf_event * event,struct perf_event_mmap_page * userpg,u64 now)5439 void __weak arch_perf_update_userpage(
5440 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now)
5441 {
5442 }
5443
5444 /*
5445 * Callers need to ensure there can be no nesting of this function, otherwise
5446 * the seqlock logic goes bad. We can not serialize this because the arch
5447 * code calls this from NMI context.
5448 */
perf_event_update_userpage(struct perf_event * event)5449 void perf_event_update_userpage(struct perf_event *event)
5450 {
5451 struct perf_event_mmap_page *userpg;
5452 struct ring_buffer *rb;
5453 u64 enabled, running, now;
5454
5455 rcu_read_lock();
5456 rb = rcu_dereference(event->rb);
5457 if (!rb)
5458 goto unlock;
5459
5460 /*
5461 * compute total_time_enabled, total_time_running
5462 * based on snapshot values taken when the event
5463 * was last scheduled in.
5464 *
5465 * we cannot simply called update_context_time()
5466 * because of locking issue as we can be called in
5467 * NMI context
5468 */
5469 calc_timer_values(event, &now, &enabled, &running);
5470
5471 userpg = rb->user_page;
5472 /*
5473 * Disable preemption to guarantee consistent time stamps are stored to
5474 * the user page.
5475 */
5476 preempt_disable();
5477 ++userpg->lock;
5478 barrier();
5479 userpg->index = perf_event_index(event);
5480 userpg->offset = perf_event_count(event);
5481 if (userpg->index)
5482 userpg->offset -= local64_read(&event->hw.prev_count);
5483
5484 userpg->time_enabled = enabled +
5485 atomic64_read(&event->child_total_time_enabled);
5486
5487 userpg->time_running = running +
5488 atomic64_read(&event->child_total_time_running);
5489
5490 arch_perf_update_userpage(event, userpg, now);
5491
5492 barrier();
5493 ++userpg->lock;
5494 preempt_enable();
5495 unlock:
5496 rcu_read_unlock();
5497 }
5498 EXPORT_SYMBOL_GPL(perf_event_update_userpage);
5499
perf_mmap_fault(struct vm_fault * vmf)5500 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf)
5501 {
5502 struct perf_event *event = vmf->vma->vm_file->private_data;
5503 struct ring_buffer *rb;
5504 vm_fault_t ret = VM_FAULT_SIGBUS;
5505
5506 if (vmf->flags & FAULT_FLAG_MKWRITE) {
5507 if (vmf->pgoff == 0)
5508 ret = 0;
5509 return ret;
5510 }
5511
5512 rcu_read_lock();
5513 rb = rcu_dereference(event->rb);
5514 if (!rb)
5515 goto unlock;
5516
5517 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
5518 goto unlock;
5519
5520 vmf->page = perf_mmap_to_page(rb, vmf->pgoff);
5521 if (!vmf->page)
5522 goto unlock;
5523
5524 get_page(vmf->page);
5525 vmf->page->mapping = vmf->vma->vm_file->f_mapping;
5526 vmf->page->index = vmf->pgoff;
5527
5528 ret = 0;
5529 unlock:
5530 rcu_read_unlock();
5531
5532 return ret;
5533 }
5534
ring_buffer_attach(struct perf_event * event,struct ring_buffer * rb)5535 static void ring_buffer_attach(struct perf_event *event,
5536 struct ring_buffer *rb)
5537 {
5538 struct ring_buffer *old_rb = NULL;
5539 unsigned long flags;
5540
5541 if (event->rb) {
5542 /*
5543 * Should be impossible, we set this when removing
5544 * event->rb_entry and wait/clear when adding event->rb_entry.
5545 */
5546 WARN_ON_ONCE(event->rcu_pending);
5547
5548 old_rb = event->rb;
5549 spin_lock_irqsave(&old_rb->event_lock, flags);
5550 list_del_rcu(&event->rb_entry);
5551 spin_unlock_irqrestore(&old_rb->event_lock, flags);
5552
5553 event->rcu_batches = get_state_synchronize_rcu();
5554 event->rcu_pending = 1;
5555 }
5556
5557 if (rb) {
5558 if (event->rcu_pending) {
5559 cond_synchronize_rcu(event->rcu_batches);
5560 event->rcu_pending = 0;
5561 }
5562
5563 spin_lock_irqsave(&rb->event_lock, flags);
5564 list_add_rcu(&event->rb_entry, &rb->event_list);
5565 spin_unlock_irqrestore(&rb->event_lock, flags);
5566 }
5567
5568 /*
5569 * Avoid racing with perf_mmap_close(AUX): stop the event
5570 * before swizzling the event::rb pointer; if it's getting
5571 * unmapped, its aux_mmap_count will be 0 and it won't
5572 * restart. See the comment in __perf_pmu_output_stop().
5573 *
5574 * Data will inevitably be lost when set_output is done in
5575 * mid-air, but then again, whoever does it like this is
5576 * not in for the data anyway.
5577 */
5578 if (has_aux(event))
5579 perf_event_stop(event, 0);
5580
5581 rcu_assign_pointer(event->rb, rb);
5582
5583 if (old_rb) {
5584 ring_buffer_put(old_rb);
5585 /*
5586 * Since we detached before setting the new rb, so that we
5587 * could attach the new rb, we could have missed a wakeup.
5588 * Provide it now.
5589 */
5590 wake_up_all(&event->waitq);
5591 }
5592 }
5593
ring_buffer_wakeup(struct perf_event * event)5594 static void ring_buffer_wakeup(struct perf_event *event)
5595 {
5596 struct ring_buffer *rb;
5597
5598 rcu_read_lock();
5599 rb = rcu_dereference(event->rb);
5600 if (rb) {
5601 list_for_each_entry_rcu(event, &rb->event_list, rb_entry)
5602 wake_up_all(&event->waitq);
5603 }
5604 rcu_read_unlock();
5605 }
5606
ring_buffer_get(struct perf_event * event)5607 struct ring_buffer *ring_buffer_get(struct perf_event *event)
5608 {
5609 struct ring_buffer *rb;
5610
5611 rcu_read_lock();
5612 rb = rcu_dereference(event->rb);
5613 if (rb) {
5614 if (!refcount_inc_not_zero(&rb->refcount))
5615 rb = NULL;
5616 }
5617 rcu_read_unlock();
5618
5619 return rb;
5620 }
5621
ring_buffer_put(struct ring_buffer * rb)5622 void ring_buffer_put(struct ring_buffer *rb)
5623 {
5624 if (!refcount_dec_and_test(&rb->refcount))
5625 return;
5626
5627 WARN_ON_ONCE(!list_empty(&rb->event_list));
5628
5629 call_rcu(&rb->rcu_head, rb_free_rcu);
5630 }
5631
perf_mmap_open(struct vm_area_struct * vma)5632 static void perf_mmap_open(struct vm_area_struct *vma)
5633 {
5634 struct perf_event *event = vma->vm_file->private_data;
5635
5636 atomic_inc(&event->mmap_count);
5637 atomic_inc(&event->rb->mmap_count);
5638
5639 if (vma->vm_pgoff)
5640 atomic_inc(&event->rb->aux_mmap_count);
5641
5642 if (event->pmu->event_mapped)
5643 event->pmu->event_mapped(event, vma->vm_mm);
5644 }
5645
5646 static void perf_pmu_output_stop(struct perf_event *event);
5647
5648 /*
5649 * A buffer can be mmap()ed multiple times; either directly through the same
5650 * event, or through other events by use of perf_event_set_output().
5651 *
5652 * In order to undo the VM accounting done by perf_mmap() we need to destroy
5653 * the buffer here, where we still have a VM context. This means we need
5654 * to detach all events redirecting to us.
5655 */
perf_mmap_close(struct vm_area_struct * vma)5656 static void perf_mmap_close(struct vm_area_struct *vma)
5657 {
5658 struct perf_event *event = vma->vm_file->private_data;
5659 struct ring_buffer *rb = ring_buffer_get(event);
5660 struct user_struct *mmap_user = rb->mmap_user;
5661 int mmap_locked = rb->mmap_locked;
5662 unsigned long size = perf_data_size(rb);
5663 bool detach_rest = false;
5664
5665 if (event->pmu->event_unmapped)
5666 event->pmu->event_unmapped(event, vma->vm_mm);
5667
5668 /*
5669 * rb->aux_mmap_count will always drop before rb->mmap_count and
5670 * event->mmap_count, so it is ok to use event->mmap_mutex to
5671 * serialize with perf_mmap here.
5672 */
5673 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff &&
5674 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) {
5675 /*
5676 * Stop all AUX events that are writing to this buffer,
5677 * so that we can free its AUX pages and corresponding PMU
5678 * data. Note that after rb::aux_mmap_count dropped to zero,
5679 * they won't start any more (see perf_aux_output_begin()).
5680 */
5681 perf_pmu_output_stop(event);
5682
5683 /* now it's safe to free the pages */
5684 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm);
5685 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm);
5686
5687 /* this has to be the last one */
5688 rb_free_aux(rb);
5689 WARN_ON_ONCE(refcount_read(&rb->aux_refcount));
5690
5691 mutex_unlock(&event->mmap_mutex);
5692 }
5693
5694 if (atomic_dec_and_test(&rb->mmap_count))
5695 detach_rest = true;
5696
5697 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex))
5698 goto out_put;
5699
5700 ring_buffer_attach(event, NULL);
5701 mutex_unlock(&event->mmap_mutex);
5702
5703 /* If there's still other mmap()s of this buffer, we're done. */
5704 if (!detach_rest)
5705 goto out_put;
5706
5707 /*
5708 * No other mmap()s, detach from all other events that might redirect
5709 * into the now unreachable buffer. Somewhat complicated by the
5710 * fact that rb::event_lock otherwise nests inside mmap_mutex.
5711 */
5712 again:
5713 rcu_read_lock();
5714 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) {
5715 if (!atomic_long_inc_not_zero(&event->refcount)) {
5716 /*
5717 * This event is en-route to free_event() which will
5718 * detach it and remove it from the list.
5719 */
5720 continue;
5721 }
5722 rcu_read_unlock();
5723
5724 mutex_lock(&event->mmap_mutex);
5725 /*
5726 * Check we didn't race with perf_event_set_output() which can
5727 * swizzle the rb from under us while we were waiting to
5728 * acquire mmap_mutex.
5729 *
5730 * If we find a different rb; ignore this event, a next
5731 * iteration will no longer find it on the list. We have to
5732 * still restart the iteration to make sure we're not now
5733 * iterating the wrong list.
5734 */
5735 if (event->rb == rb)
5736 ring_buffer_attach(event, NULL);
5737
5738 mutex_unlock(&event->mmap_mutex);
5739 put_event(event);
5740
5741 /*
5742 * Restart the iteration; either we're on the wrong list or
5743 * destroyed its integrity by doing a deletion.
5744 */
5745 goto again;
5746 }
5747 rcu_read_unlock();
5748
5749 /*
5750 * It could be there's still a few 0-ref events on the list; they'll
5751 * get cleaned up by free_event() -- they'll also still have their
5752 * ref on the rb and will free it whenever they are done with it.
5753 *
5754 * Aside from that, this buffer is 'fully' detached and unmapped,
5755 * undo the VM accounting.
5756 */
5757
5758 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked,
5759 &mmap_user->locked_vm);
5760 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm);
5761 free_uid(mmap_user);
5762
5763 out_put:
5764 ring_buffer_put(rb); /* could be last */
5765 }
5766
5767 static const struct vm_operations_struct perf_mmap_vmops = {
5768 .open = perf_mmap_open,
5769 .close = perf_mmap_close, /* non mergeable */
5770 .fault = perf_mmap_fault,
5771 .page_mkwrite = perf_mmap_fault,
5772 };
5773
perf_mmap(struct file * file,struct vm_area_struct * vma)5774 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
5775 {
5776 struct perf_event *event = file->private_data;
5777 unsigned long user_locked, user_lock_limit;
5778 struct user_struct *user = current_user();
5779 unsigned long locked, lock_limit;
5780 struct ring_buffer *rb = NULL;
5781 unsigned long vma_size;
5782 unsigned long nr_pages;
5783 long user_extra = 0, extra = 0;
5784 int ret = 0, flags = 0;
5785
5786 /*
5787 * Don't allow mmap() of inherited per-task counters. This would
5788 * create a performance issue due to all children writing to the
5789 * same rb.
5790 */
5791 if (event->cpu == -1 && event->attr.inherit)
5792 return -EINVAL;
5793
5794 if (!(vma->vm_flags & VM_SHARED))
5795 return -EINVAL;
5796
5797 ret = security_perf_event_read(event);
5798 if (ret)
5799 return ret;
5800
5801 vma_size = vma->vm_end - vma->vm_start;
5802
5803 if (vma->vm_pgoff == 0) {
5804 nr_pages = (vma_size / PAGE_SIZE) - 1;
5805 } else {
5806 /*
5807 * AUX area mapping: if rb->aux_nr_pages != 0, it's already
5808 * mapped, all subsequent mappings should have the same size
5809 * and offset. Must be above the normal perf buffer.
5810 */
5811 u64 aux_offset, aux_size;
5812
5813 if (!event->rb)
5814 return -EINVAL;
5815
5816 nr_pages = vma_size / PAGE_SIZE;
5817
5818 mutex_lock(&event->mmap_mutex);
5819 ret = -EINVAL;
5820
5821 rb = event->rb;
5822 if (!rb)
5823 goto aux_unlock;
5824
5825 aux_offset = READ_ONCE(rb->user_page->aux_offset);
5826 aux_size = READ_ONCE(rb->user_page->aux_size);
5827
5828 if (aux_offset < perf_data_size(rb) + PAGE_SIZE)
5829 goto aux_unlock;
5830
5831 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT)
5832 goto aux_unlock;
5833
5834 /* already mapped with a different offset */
5835 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff)
5836 goto aux_unlock;
5837
5838 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE)
5839 goto aux_unlock;
5840
5841 /* already mapped with a different size */
5842 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages)
5843 goto aux_unlock;
5844
5845 if (!is_power_of_2(nr_pages))
5846 goto aux_unlock;
5847
5848 if (!atomic_inc_not_zero(&rb->mmap_count))
5849 goto aux_unlock;
5850
5851 if (rb_has_aux(rb)) {
5852 atomic_inc(&rb->aux_mmap_count);
5853 ret = 0;
5854 goto unlock;
5855 }
5856
5857 atomic_set(&rb->aux_mmap_count, 1);
5858 user_extra = nr_pages;
5859
5860 goto accounting;
5861 }
5862
5863 /*
5864 * If we have rb pages ensure they're a power-of-two number, so we
5865 * can do bitmasks instead of modulo.
5866 */
5867 if (nr_pages != 0 && !is_power_of_2(nr_pages))
5868 return -EINVAL;
5869
5870 if (vma_size != PAGE_SIZE * (1 + nr_pages))
5871 return -EINVAL;
5872
5873 WARN_ON_ONCE(event->ctx->parent_ctx);
5874 again:
5875 mutex_lock(&event->mmap_mutex);
5876 if (event->rb) {
5877 if (event->rb->nr_pages != nr_pages) {
5878 ret = -EINVAL;
5879 goto unlock;
5880 }
5881
5882 if (!atomic_inc_not_zero(&event->rb->mmap_count)) {
5883 /*
5884 * Raced against perf_mmap_close(); remove the
5885 * event and try again.
5886 */
5887 ring_buffer_attach(event, NULL);
5888 mutex_unlock(&event->mmap_mutex);
5889 goto again;
5890 }
5891
5892 goto unlock;
5893 }
5894
5895 user_extra = nr_pages + 1;
5896
5897 accounting:
5898 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
5899
5900 /*
5901 * Increase the limit linearly with more CPUs:
5902 */
5903 user_lock_limit *= num_online_cpus();
5904
5905 user_locked = atomic_long_read(&user->locked_vm);
5906
5907 /*
5908 * sysctl_perf_event_mlock may have changed, so that
5909 * user->locked_vm > user_lock_limit
5910 */
5911 if (user_locked > user_lock_limit)
5912 user_locked = user_lock_limit;
5913 user_locked += user_extra;
5914
5915 if (user_locked <= user_lock_limit) {
5916 /* charge all to locked_vm */
5917 } else if (atomic_long_read(&user->locked_vm) >= user_lock_limit) {
5918 /* charge all to pinned_vm */
5919 extra = user_extra;
5920 user_extra = 0;
5921 } else {
5922 /*
5923 * charge locked_vm until it hits user_lock_limit;
5924 * charge the rest from pinned_vm
5925 */
5926 extra = user_locked - user_lock_limit;
5927 user_extra -= extra;
5928 }
5929
5930 lock_limit = rlimit(RLIMIT_MEMLOCK);
5931 lock_limit >>= PAGE_SHIFT;
5932 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra;
5933
5934 if ((locked > lock_limit) && perf_is_paranoid() &&
5935 !capable(CAP_IPC_LOCK)) {
5936 ret = -EPERM;
5937 goto unlock;
5938 }
5939
5940 WARN_ON(!rb && event->rb);
5941
5942 if (vma->vm_flags & VM_WRITE)
5943 flags |= RING_BUFFER_WRITABLE;
5944
5945 if (!rb) {
5946 rb = rb_alloc(nr_pages,
5947 event->attr.watermark ? event->attr.wakeup_watermark : 0,
5948 event->cpu, flags);
5949
5950 if (!rb) {
5951 ret = -ENOMEM;
5952 goto unlock;
5953 }
5954
5955 atomic_set(&rb->mmap_count, 1);
5956 rb->mmap_user = get_current_user();
5957 rb->mmap_locked = extra;
5958
5959 ring_buffer_attach(event, rb);
5960
5961 perf_event_init_userpage(event);
5962 perf_event_update_userpage(event);
5963 } else {
5964 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages,
5965 event->attr.aux_watermark, flags);
5966 if (!ret)
5967 rb->aux_mmap_locked = extra;
5968 }
5969
5970 unlock:
5971 if (!ret) {
5972 atomic_long_add(user_extra, &user->locked_vm);
5973 atomic64_add(extra, &vma->vm_mm->pinned_vm);
5974
5975 atomic_inc(&event->mmap_count);
5976 } else if (rb) {
5977 atomic_dec(&rb->mmap_count);
5978 }
5979 aux_unlock:
5980 mutex_unlock(&event->mmap_mutex);
5981
5982 /*
5983 * Since pinned accounting is per vm we cannot allow fork() to copy our
5984 * vma.
5985 */
5986 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP;
5987 vma->vm_ops = &perf_mmap_vmops;
5988
5989 if (event->pmu->event_mapped)
5990 event->pmu->event_mapped(event, vma->vm_mm);
5991
5992 return ret;
5993 }
5994
perf_fasync(int fd,struct file * filp,int on)5995 static int perf_fasync(int fd, struct file *filp, int on)
5996 {
5997 struct inode *inode = file_inode(filp);
5998 struct perf_event *event = filp->private_data;
5999 int retval;
6000
6001 inode_lock(inode);
6002 retval = fasync_helper(fd, filp, on, &event->fasync);
6003 inode_unlock(inode);
6004
6005 if (retval < 0)
6006 return retval;
6007
6008 return 0;
6009 }
6010
6011 static const struct file_operations perf_fops = {
6012 .llseek = no_llseek,
6013 .release = perf_release,
6014 .read = perf_read,
6015 .poll = perf_poll,
6016 .unlocked_ioctl = perf_ioctl,
6017 .compat_ioctl = perf_compat_ioctl,
6018 .mmap = perf_mmap,
6019 .fasync = perf_fasync,
6020 };
6021
6022 /*
6023 * Perf event wakeup
6024 *
6025 * If there's data, ensure we set the poll() state and publish everything
6026 * to user-space before waking everybody up.
6027 */
6028
perf_event_fasync(struct perf_event * event)6029 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event)
6030 {
6031 /* only the parent has fasync state */
6032 if (event->parent)
6033 event = event->parent;
6034 return &event->fasync;
6035 }
6036
perf_event_wakeup(struct perf_event * event)6037 void perf_event_wakeup(struct perf_event *event)
6038 {
6039 ring_buffer_wakeup(event);
6040
6041 if (event->pending_kill) {
6042 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill);
6043 event->pending_kill = 0;
6044 }
6045 }
6046
perf_pending_event_disable(struct perf_event * event)6047 static void perf_pending_event_disable(struct perf_event *event)
6048 {
6049 int cpu = READ_ONCE(event->pending_disable);
6050
6051 if (cpu < 0)
6052 return;
6053
6054 if (cpu == smp_processor_id()) {
6055 WRITE_ONCE(event->pending_disable, -1);
6056 perf_event_disable_local(event);
6057 return;
6058 }
6059
6060 /*
6061 * CPU-A CPU-B
6062 *
6063 * perf_event_disable_inatomic()
6064 * @pending_disable = CPU-A;
6065 * irq_work_queue();
6066 *
6067 * sched-out
6068 * @pending_disable = -1;
6069 *
6070 * sched-in
6071 * perf_event_disable_inatomic()
6072 * @pending_disable = CPU-B;
6073 * irq_work_queue(); // FAILS
6074 *
6075 * irq_work_run()
6076 * perf_pending_event()
6077 *
6078 * But the event runs on CPU-B and wants disabling there.
6079 */
6080 irq_work_queue_on(&event->pending, cpu);
6081 }
6082
perf_pending_event(struct irq_work * entry)6083 static void perf_pending_event(struct irq_work *entry)
6084 {
6085 struct perf_event *event = container_of(entry, struct perf_event, pending);
6086 int rctx;
6087
6088 rctx = perf_swevent_get_recursion_context();
6089 /*
6090 * If we 'fail' here, that's OK, it means recursion is already disabled
6091 * and we won't recurse 'further'.
6092 */
6093
6094 perf_pending_event_disable(event);
6095
6096 if (event->pending_wakeup) {
6097 event->pending_wakeup = 0;
6098 perf_event_wakeup(event);
6099 }
6100
6101 if (rctx >= 0)
6102 perf_swevent_put_recursion_context(rctx);
6103 }
6104
6105 /*
6106 * We assume there is only KVM supporting the callbacks.
6107 * Later on, we might change it to a list if there is
6108 * another virtualization implementation supporting the callbacks.
6109 */
6110 struct perf_guest_info_callbacks __rcu *perf_guest_cbs;
6111
perf_register_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)6112 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6113 {
6114 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs)))
6115 return -EBUSY;
6116
6117 rcu_assign_pointer(perf_guest_cbs, cbs);
6118 return 0;
6119 }
6120 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
6121
perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks * cbs)6122 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
6123 {
6124 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs))
6125 return -EINVAL;
6126
6127 rcu_assign_pointer(perf_guest_cbs, NULL);
6128 synchronize_rcu();
6129 return 0;
6130 }
6131 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
6132
6133 static void
perf_output_sample_regs(struct perf_output_handle * handle,struct pt_regs * regs,u64 mask)6134 perf_output_sample_regs(struct perf_output_handle *handle,
6135 struct pt_regs *regs, u64 mask)
6136 {
6137 int bit;
6138 DECLARE_BITMAP(_mask, 64);
6139
6140 bitmap_from_u64(_mask, mask);
6141 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) {
6142 u64 val;
6143
6144 val = perf_reg_value(regs, bit);
6145 perf_output_put(handle, val);
6146 }
6147 }
6148
perf_sample_regs_user(struct perf_regs * regs_user,struct pt_regs * regs,struct pt_regs * regs_user_copy)6149 static void perf_sample_regs_user(struct perf_regs *regs_user,
6150 struct pt_regs *regs,
6151 struct pt_regs *regs_user_copy)
6152 {
6153 if (user_mode(regs)) {
6154 regs_user->abi = perf_reg_abi(current);
6155 regs_user->regs = regs;
6156 } else if (!(current->flags & PF_KTHREAD)) {
6157 perf_get_regs_user(regs_user, regs, regs_user_copy);
6158 } else {
6159 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE;
6160 regs_user->regs = NULL;
6161 }
6162 }
6163
perf_sample_regs_intr(struct perf_regs * regs_intr,struct pt_regs * regs)6164 static void perf_sample_regs_intr(struct perf_regs *regs_intr,
6165 struct pt_regs *regs)
6166 {
6167 regs_intr->regs = regs;
6168 regs_intr->abi = perf_reg_abi(current);
6169 }
6170
6171
6172 /*
6173 * Get remaining task size from user stack pointer.
6174 *
6175 * It'd be better to take stack vma map and limit this more
6176 * precisely, but there's no way to get it safely under interrupt,
6177 * so using TASK_SIZE as limit.
6178 */
perf_ustack_task_size(struct pt_regs * regs)6179 static u64 perf_ustack_task_size(struct pt_regs *regs)
6180 {
6181 unsigned long addr = perf_user_stack_pointer(regs);
6182
6183 if (!addr || addr >= TASK_SIZE)
6184 return 0;
6185
6186 return TASK_SIZE - addr;
6187 }
6188
6189 static u16
perf_sample_ustack_size(u16 stack_size,u16 header_size,struct pt_regs * regs)6190 perf_sample_ustack_size(u16 stack_size, u16 header_size,
6191 struct pt_regs *regs)
6192 {
6193 u64 task_size;
6194
6195 /* No regs, no stack pointer, no dump. */
6196 if (!regs)
6197 return 0;
6198
6199 /*
6200 * Check if we fit in with the requested stack size into the:
6201 * - TASK_SIZE
6202 * If we don't, we limit the size to the TASK_SIZE.
6203 *
6204 * - remaining sample size
6205 * If we don't, we customize the stack size to
6206 * fit in to the remaining sample size.
6207 */
6208
6209 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs));
6210 stack_size = min(stack_size, (u16) task_size);
6211
6212 /* Current header size plus static size and dynamic size. */
6213 header_size += 2 * sizeof(u64);
6214
6215 /* Do we fit in with the current stack dump size? */
6216 if ((u16) (header_size + stack_size) < header_size) {
6217 /*
6218 * If we overflow the maximum size for the sample,
6219 * we customize the stack dump size to fit in.
6220 */
6221 stack_size = USHRT_MAX - header_size - sizeof(u64);
6222 stack_size = round_up(stack_size, sizeof(u64));
6223 }
6224
6225 return stack_size;
6226 }
6227
6228 static void
perf_output_sample_ustack(struct perf_output_handle * handle,u64 dump_size,struct pt_regs * regs)6229 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size,
6230 struct pt_regs *regs)
6231 {
6232 /* Case of a kernel thread, nothing to dump */
6233 if (!regs) {
6234 u64 size = 0;
6235 perf_output_put(handle, size);
6236 } else {
6237 unsigned long sp;
6238 unsigned int rem;
6239 u64 dyn_size;
6240 mm_segment_t fs;
6241
6242 /*
6243 * We dump:
6244 * static size
6245 * - the size requested by user or the best one we can fit
6246 * in to the sample max size
6247 * data
6248 * - user stack dump data
6249 * dynamic size
6250 * - the actual dumped size
6251 */
6252
6253 /* Static size. */
6254 perf_output_put(handle, dump_size);
6255
6256 /* Data. */
6257 sp = perf_user_stack_pointer(regs);
6258 fs = get_fs();
6259 set_fs(USER_DS);
6260 rem = __output_copy_user(handle, (void *) sp, dump_size);
6261 set_fs(fs);
6262 dyn_size = dump_size - rem;
6263
6264 perf_output_skip(handle, rem);
6265
6266 /* Dynamic size. */
6267 perf_output_put(handle, dyn_size);
6268 }
6269 }
6270
__perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)6271 static void __perf_event_header__init_id(struct perf_event_header *header,
6272 struct perf_sample_data *data,
6273 struct perf_event *event)
6274 {
6275 u64 sample_type = event->attr.sample_type;
6276
6277 data->type = sample_type;
6278 header->size += event->id_header_size;
6279
6280 if (sample_type & PERF_SAMPLE_TID) {
6281 /* namespace issues */
6282 data->tid_entry.pid = perf_event_pid(event, current);
6283 data->tid_entry.tid = perf_event_tid(event, current);
6284 }
6285
6286 if (sample_type & PERF_SAMPLE_TIME)
6287 data->time = perf_event_clock(event);
6288
6289 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER))
6290 data->id = primary_event_id(event);
6291
6292 if (sample_type & PERF_SAMPLE_STREAM_ID)
6293 data->stream_id = event->id;
6294
6295 if (sample_type & PERF_SAMPLE_CPU) {
6296 data->cpu_entry.cpu = raw_smp_processor_id();
6297 data->cpu_entry.reserved = 0;
6298 }
6299 }
6300
perf_event_header__init_id(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)6301 void perf_event_header__init_id(struct perf_event_header *header,
6302 struct perf_sample_data *data,
6303 struct perf_event *event)
6304 {
6305 if (event->attr.sample_id_all)
6306 __perf_event_header__init_id(header, data, event);
6307 }
6308
__perf_event__output_id_sample(struct perf_output_handle * handle,struct perf_sample_data * data)6309 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
6310 struct perf_sample_data *data)
6311 {
6312 u64 sample_type = data->type;
6313
6314 if (sample_type & PERF_SAMPLE_TID)
6315 perf_output_put(handle, data->tid_entry);
6316
6317 if (sample_type & PERF_SAMPLE_TIME)
6318 perf_output_put(handle, data->time);
6319
6320 if (sample_type & PERF_SAMPLE_ID)
6321 perf_output_put(handle, data->id);
6322
6323 if (sample_type & PERF_SAMPLE_STREAM_ID)
6324 perf_output_put(handle, data->stream_id);
6325
6326 if (sample_type & PERF_SAMPLE_CPU)
6327 perf_output_put(handle, data->cpu_entry);
6328
6329 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6330 perf_output_put(handle, data->id);
6331 }
6332
perf_event__output_id_sample(struct perf_event * event,struct perf_output_handle * handle,struct perf_sample_data * sample)6333 void perf_event__output_id_sample(struct perf_event *event,
6334 struct perf_output_handle *handle,
6335 struct perf_sample_data *sample)
6336 {
6337 if (event->attr.sample_id_all)
6338 __perf_event__output_id_sample(handle, sample);
6339 }
6340
perf_output_read_one(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)6341 static void perf_output_read_one(struct perf_output_handle *handle,
6342 struct perf_event *event,
6343 u64 enabled, u64 running)
6344 {
6345 u64 read_format = event->attr.read_format;
6346 u64 values[4];
6347 int n = 0;
6348
6349 values[n++] = perf_event_count(event);
6350 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
6351 values[n++] = enabled +
6352 atomic64_read(&event->child_total_time_enabled);
6353 }
6354 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
6355 values[n++] = running +
6356 atomic64_read(&event->child_total_time_running);
6357 }
6358 if (read_format & PERF_FORMAT_ID)
6359 values[n++] = primary_event_id(event);
6360
6361 __output_copy(handle, values, n * sizeof(u64));
6362 }
6363
perf_output_read_group(struct perf_output_handle * handle,struct perf_event * event,u64 enabled,u64 running)6364 static void perf_output_read_group(struct perf_output_handle *handle,
6365 struct perf_event *event,
6366 u64 enabled, u64 running)
6367 {
6368 struct perf_event *leader = event->group_leader, *sub;
6369 u64 read_format = event->attr.read_format;
6370 unsigned long flags;
6371 u64 values[5];
6372 int n = 0;
6373
6374 /*
6375 * Disabling interrupts avoids all counter scheduling
6376 * (context switches, timer based rotation and IPIs).
6377 */
6378 local_irq_save(flags);
6379
6380 values[n++] = 1 + leader->nr_siblings;
6381
6382 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
6383 values[n++] = enabled;
6384
6385 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
6386 values[n++] = running;
6387
6388 if ((leader != event) &&
6389 (leader->state == PERF_EVENT_STATE_ACTIVE))
6390 leader->pmu->read(leader);
6391
6392 values[n++] = perf_event_count(leader);
6393 if (read_format & PERF_FORMAT_ID)
6394 values[n++] = primary_event_id(leader);
6395
6396 __output_copy(handle, values, n * sizeof(u64));
6397
6398 for_each_sibling_event(sub, leader) {
6399 n = 0;
6400
6401 if ((sub != event) &&
6402 (sub->state == PERF_EVENT_STATE_ACTIVE))
6403 sub->pmu->read(sub);
6404
6405 values[n++] = perf_event_count(sub);
6406 if (read_format & PERF_FORMAT_ID)
6407 values[n++] = primary_event_id(sub);
6408
6409 __output_copy(handle, values, n * sizeof(u64));
6410 }
6411
6412 local_irq_restore(flags);
6413 }
6414
6415 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
6416 PERF_FORMAT_TOTAL_TIME_RUNNING)
6417
6418 /*
6419 * XXX PERF_SAMPLE_READ vs inherited events seems difficult.
6420 *
6421 * The problem is that its both hard and excessively expensive to iterate the
6422 * child list, not to mention that its impossible to IPI the children running
6423 * on another CPU, from interrupt/NMI context.
6424 */
perf_output_read(struct perf_output_handle * handle,struct perf_event * event)6425 static void perf_output_read(struct perf_output_handle *handle,
6426 struct perf_event *event)
6427 {
6428 u64 enabled = 0, running = 0, now;
6429 u64 read_format = event->attr.read_format;
6430
6431 /*
6432 * compute total_time_enabled, total_time_running
6433 * based on snapshot values taken when the event
6434 * was last scheduled in.
6435 *
6436 * we cannot simply called update_context_time()
6437 * because of locking issue as we are called in
6438 * NMI context
6439 */
6440 if (read_format & PERF_FORMAT_TOTAL_TIMES)
6441 calc_timer_values(event, &now, &enabled, &running);
6442
6443 if (event->attr.read_format & PERF_FORMAT_GROUP)
6444 perf_output_read_group(handle, event, enabled, running);
6445 else
6446 perf_output_read_one(handle, event, enabled, running);
6447 }
6448
perf_output_sample(struct perf_output_handle * handle,struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event)6449 void perf_output_sample(struct perf_output_handle *handle,
6450 struct perf_event_header *header,
6451 struct perf_sample_data *data,
6452 struct perf_event *event)
6453 {
6454 u64 sample_type = data->type;
6455
6456 perf_output_put(handle, *header);
6457
6458 if (sample_type & PERF_SAMPLE_IDENTIFIER)
6459 perf_output_put(handle, data->id);
6460
6461 if (sample_type & PERF_SAMPLE_IP)
6462 perf_output_put(handle, data->ip);
6463
6464 if (sample_type & PERF_SAMPLE_TID)
6465 perf_output_put(handle, data->tid_entry);
6466
6467 if (sample_type & PERF_SAMPLE_TIME)
6468 perf_output_put(handle, data->time);
6469
6470 if (sample_type & PERF_SAMPLE_ADDR)
6471 perf_output_put(handle, data->addr);
6472
6473 if (sample_type & PERF_SAMPLE_ID)
6474 perf_output_put(handle, data->id);
6475
6476 if (sample_type & PERF_SAMPLE_STREAM_ID)
6477 perf_output_put(handle, data->stream_id);
6478
6479 if (sample_type & PERF_SAMPLE_CPU)
6480 perf_output_put(handle, data->cpu_entry);
6481
6482 if (sample_type & PERF_SAMPLE_PERIOD)
6483 perf_output_put(handle, data->period);
6484
6485 if (sample_type & PERF_SAMPLE_READ)
6486 perf_output_read(handle, event);
6487
6488 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6489 int size = 1;
6490
6491 size += data->callchain->nr;
6492 size *= sizeof(u64);
6493 __output_copy(handle, data->callchain, size);
6494 }
6495
6496 if (sample_type & PERF_SAMPLE_RAW) {
6497 struct perf_raw_record *raw = data->raw;
6498
6499 if (raw) {
6500 struct perf_raw_frag *frag = &raw->frag;
6501
6502 perf_output_put(handle, raw->size);
6503 do {
6504 if (frag->copy) {
6505 __output_custom(handle, frag->copy,
6506 frag->data, frag->size);
6507 } else {
6508 __output_copy(handle, frag->data,
6509 frag->size);
6510 }
6511 if (perf_raw_frag_last(frag))
6512 break;
6513 frag = frag->next;
6514 } while (1);
6515 if (frag->pad)
6516 __output_skip(handle, NULL, frag->pad);
6517 } else {
6518 struct {
6519 u32 size;
6520 u32 data;
6521 } raw = {
6522 .size = sizeof(u32),
6523 .data = 0,
6524 };
6525 perf_output_put(handle, raw);
6526 }
6527 }
6528
6529 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6530 if (data->br_stack) {
6531 size_t size;
6532
6533 size = data->br_stack->nr
6534 * sizeof(struct perf_branch_entry);
6535
6536 perf_output_put(handle, data->br_stack->nr);
6537 perf_output_copy(handle, data->br_stack->entries, size);
6538 } else {
6539 /*
6540 * we always store at least the value of nr
6541 */
6542 u64 nr = 0;
6543 perf_output_put(handle, nr);
6544 }
6545 }
6546
6547 if (sample_type & PERF_SAMPLE_REGS_USER) {
6548 u64 abi = data->regs_user.abi;
6549
6550 /*
6551 * If there are no regs to dump, notice it through
6552 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6553 */
6554 perf_output_put(handle, abi);
6555
6556 if (abi) {
6557 u64 mask = event->attr.sample_regs_user;
6558 perf_output_sample_regs(handle,
6559 data->regs_user.regs,
6560 mask);
6561 }
6562 }
6563
6564 if (sample_type & PERF_SAMPLE_STACK_USER) {
6565 perf_output_sample_ustack(handle,
6566 data->stack_user_size,
6567 data->regs_user.regs);
6568 }
6569
6570 if (sample_type & PERF_SAMPLE_WEIGHT)
6571 perf_output_put(handle, data->weight);
6572
6573 if (sample_type & PERF_SAMPLE_DATA_SRC)
6574 perf_output_put(handle, data->data_src.val);
6575
6576 if (sample_type & PERF_SAMPLE_TRANSACTION)
6577 perf_output_put(handle, data->txn);
6578
6579 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6580 u64 abi = data->regs_intr.abi;
6581 /*
6582 * If there are no regs to dump, notice it through
6583 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE).
6584 */
6585 perf_output_put(handle, abi);
6586
6587 if (abi) {
6588 u64 mask = event->attr.sample_regs_intr;
6589
6590 perf_output_sample_regs(handle,
6591 data->regs_intr.regs,
6592 mask);
6593 }
6594 }
6595
6596 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6597 perf_output_put(handle, data->phys_addr);
6598
6599 if (!event->attr.watermark) {
6600 int wakeup_events = event->attr.wakeup_events;
6601
6602 if (wakeup_events) {
6603 struct ring_buffer *rb = handle->rb;
6604 int events = local_inc_return(&rb->events);
6605
6606 if (events >= wakeup_events) {
6607 local_sub(wakeup_events, &rb->events);
6608 local_inc(&rb->wakeup);
6609 }
6610 }
6611 }
6612 }
6613
perf_virt_to_phys(u64 virt)6614 static u64 perf_virt_to_phys(u64 virt)
6615 {
6616 u64 phys_addr = 0;
6617
6618 if (!virt)
6619 return 0;
6620
6621 if (virt >= TASK_SIZE) {
6622 /* If it's vmalloc()d memory, leave phys_addr as 0 */
6623 if (virt_addr_valid((void *)(uintptr_t)virt) &&
6624 !(virt >= VMALLOC_START && virt < VMALLOC_END))
6625 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt);
6626 } else {
6627 /*
6628 * Walking the pages tables for user address.
6629 * Interrupts are disabled, so it prevents any tear down
6630 * of the page tables.
6631 * Try IRQ-safe __get_user_pages_fast first.
6632 * If failed, leave phys_addr as 0.
6633 */
6634 if (current->mm != NULL) {
6635 struct page *p;
6636
6637 pagefault_disable();
6638 if (__get_user_pages_fast(virt, 1, 0, &p) == 1) {
6639 phys_addr = page_to_phys(p) + virt % PAGE_SIZE;
6640 put_page(p);
6641 }
6642 pagefault_enable();
6643 }
6644 }
6645
6646 return phys_addr;
6647 }
6648
6649 static struct perf_callchain_entry __empty_callchain = { .nr = 0, };
6650
6651 struct perf_callchain_entry *
perf_callchain(struct perf_event * event,struct pt_regs * regs)6652 perf_callchain(struct perf_event *event, struct pt_regs *regs)
6653 {
6654 bool kernel = !event->attr.exclude_callchain_kernel;
6655 bool user = !event->attr.exclude_callchain_user;
6656 /* Disallow cross-task user callchains. */
6657 bool crosstask = event->ctx->task && event->ctx->task != current;
6658 const u32 max_stack = event->attr.sample_max_stack;
6659 struct perf_callchain_entry *callchain;
6660
6661 if (!kernel && !user)
6662 return &__empty_callchain;
6663
6664 callchain = get_perf_callchain(regs, 0, kernel, user,
6665 max_stack, crosstask, true);
6666 return callchain ?: &__empty_callchain;
6667 }
6668
perf_prepare_sample(struct perf_event_header * header,struct perf_sample_data * data,struct perf_event * event,struct pt_regs * regs)6669 void perf_prepare_sample(struct perf_event_header *header,
6670 struct perf_sample_data *data,
6671 struct perf_event *event,
6672 struct pt_regs *regs)
6673 {
6674 u64 sample_type = event->attr.sample_type;
6675
6676 header->type = PERF_RECORD_SAMPLE;
6677 header->size = sizeof(*header) + event->header_size;
6678
6679 header->misc = 0;
6680 header->misc |= perf_misc_flags(regs);
6681
6682 __perf_event_header__init_id(header, data, event);
6683
6684 if (sample_type & PERF_SAMPLE_IP)
6685 data->ip = perf_instruction_pointer(regs);
6686
6687 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
6688 int size = 1;
6689
6690 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY))
6691 data->callchain = perf_callchain(event, regs);
6692
6693 size += data->callchain->nr;
6694
6695 header->size += size * sizeof(u64);
6696 }
6697
6698 if (sample_type & PERF_SAMPLE_RAW) {
6699 struct perf_raw_record *raw = data->raw;
6700 int size;
6701
6702 if (raw) {
6703 struct perf_raw_frag *frag = &raw->frag;
6704 u32 sum = 0;
6705
6706 do {
6707 sum += frag->size;
6708 if (perf_raw_frag_last(frag))
6709 break;
6710 frag = frag->next;
6711 } while (1);
6712
6713 size = round_up(sum + sizeof(u32), sizeof(u64));
6714 raw->size = size - sizeof(u32);
6715 frag->pad = raw->size - sum;
6716 } else {
6717 size = sizeof(u64);
6718 }
6719
6720 header->size += size;
6721 }
6722
6723 if (sample_type & PERF_SAMPLE_BRANCH_STACK) {
6724 int size = sizeof(u64); /* nr */
6725 if (data->br_stack) {
6726 size += data->br_stack->nr
6727 * sizeof(struct perf_branch_entry);
6728 }
6729 header->size += size;
6730 }
6731
6732 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER))
6733 perf_sample_regs_user(&data->regs_user, regs,
6734 &data->regs_user_copy);
6735
6736 if (sample_type & PERF_SAMPLE_REGS_USER) {
6737 /* regs dump ABI info */
6738 int size = sizeof(u64);
6739
6740 if (data->regs_user.regs) {
6741 u64 mask = event->attr.sample_regs_user;
6742 size += hweight64(mask) * sizeof(u64);
6743 }
6744
6745 header->size += size;
6746 }
6747
6748 if (sample_type & PERF_SAMPLE_STACK_USER) {
6749 /*
6750 * Either we need PERF_SAMPLE_STACK_USER bit to be always
6751 * processed as the last one or have additional check added
6752 * in case new sample type is added, because we could eat
6753 * up the rest of the sample size.
6754 */
6755 u16 stack_size = event->attr.sample_stack_user;
6756 u16 size = sizeof(u64);
6757
6758 stack_size = perf_sample_ustack_size(stack_size, header->size,
6759 data->regs_user.regs);
6760
6761 /*
6762 * If there is something to dump, add space for the dump
6763 * itself and for the field that tells the dynamic size,
6764 * which is how many have been actually dumped.
6765 */
6766 if (stack_size)
6767 size += sizeof(u64) + stack_size;
6768
6769 data->stack_user_size = stack_size;
6770 header->size += size;
6771 }
6772
6773 if (sample_type & PERF_SAMPLE_REGS_INTR) {
6774 /* regs dump ABI info */
6775 int size = sizeof(u64);
6776
6777 perf_sample_regs_intr(&data->regs_intr, regs);
6778
6779 if (data->regs_intr.regs) {
6780 u64 mask = event->attr.sample_regs_intr;
6781
6782 size += hweight64(mask) * sizeof(u64);
6783 }
6784
6785 header->size += size;
6786 }
6787
6788 if (sample_type & PERF_SAMPLE_PHYS_ADDR)
6789 data->phys_addr = perf_virt_to_phys(data->addr);
6790 }
6791
6792 static __always_inline int
__perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs,int (* output_begin)(struct perf_output_handle *,struct perf_event *,unsigned int))6793 __perf_event_output(struct perf_event *event,
6794 struct perf_sample_data *data,
6795 struct pt_regs *regs,
6796 int (*output_begin)(struct perf_output_handle *,
6797 struct perf_event *,
6798 unsigned int))
6799 {
6800 struct perf_output_handle handle;
6801 struct perf_event_header header;
6802 int err;
6803
6804 /* protect the callchain buffers */
6805 rcu_read_lock();
6806
6807 perf_prepare_sample(&header, data, event, regs);
6808
6809 err = output_begin(&handle, event, header.size);
6810 if (err)
6811 goto exit;
6812
6813 perf_output_sample(&handle, &header, data, event);
6814
6815 perf_output_end(&handle);
6816
6817 exit:
6818 rcu_read_unlock();
6819 return err;
6820 }
6821
6822 void
perf_event_output_forward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)6823 perf_event_output_forward(struct perf_event *event,
6824 struct perf_sample_data *data,
6825 struct pt_regs *regs)
6826 {
6827 __perf_event_output(event, data, regs, perf_output_begin_forward);
6828 }
6829
6830 void
perf_event_output_backward(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)6831 perf_event_output_backward(struct perf_event *event,
6832 struct perf_sample_data *data,
6833 struct pt_regs *regs)
6834 {
6835 __perf_event_output(event, data, regs, perf_output_begin_backward);
6836 }
6837
6838 int
perf_event_output(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)6839 perf_event_output(struct perf_event *event,
6840 struct perf_sample_data *data,
6841 struct pt_regs *regs)
6842 {
6843 return __perf_event_output(event, data, regs, perf_output_begin);
6844 }
6845
6846 /*
6847 * read event_id
6848 */
6849
6850 struct perf_read_event {
6851 struct perf_event_header header;
6852
6853 u32 pid;
6854 u32 tid;
6855 };
6856
6857 static void
perf_event_read_event(struct perf_event * event,struct task_struct * task)6858 perf_event_read_event(struct perf_event *event,
6859 struct task_struct *task)
6860 {
6861 struct perf_output_handle handle;
6862 struct perf_sample_data sample;
6863 struct perf_read_event read_event = {
6864 .header = {
6865 .type = PERF_RECORD_READ,
6866 .misc = 0,
6867 .size = sizeof(read_event) + event->read_size,
6868 },
6869 .pid = perf_event_pid(event, task),
6870 .tid = perf_event_tid(event, task),
6871 };
6872 int ret;
6873
6874 perf_event_header__init_id(&read_event.header, &sample, event);
6875 ret = perf_output_begin(&handle, event, read_event.header.size);
6876 if (ret)
6877 return;
6878
6879 perf_output_put(&handle, read_event);
6880 perf_output_read(&handle, event);
6881 perf_event__output_id_sample(event, &handle, &sample);
6882
6883 perf_output_end(&handle);
6884 }
6885
6886 typedef void (perf_iterate_f)(struct perf_event *event, void *data);
6887
6888 static void
perf_iterate_ctx(struct perf_event_context * ctx,perf_iterate_f output,void * data,bool all)6889 perf_iterate_ctx(struct perf_event_context *ctx,
6890 perf_iterate_f output,
6891 void *data, bool all)
6892 {
6893 struct perf_event *event;
6894
6895 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
6896 if (!all) {
6897 if (event->state < PERF_EVENT_STATE_INACTIVE)
6898 continue;
6899 if (!event_filter_match(event))
6900 continue;
6901 }
6902
6903 output(event, data);
6904 }
6905 }
6906
perf_iterate_sb_cpu(perf_iterate_f output,void * data)6907 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data)
6908 {
6909 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events);
6910 struct perf_event *event;
6911
6912 list_for_each_entry_rcu(event, &pel->list, sb_list) {
6913 /*
6914 * Skip events that are not fully formed yet; ensure that
6915 * if we observe event->ctx, both event and ctx will be
6916 * complete enough. See perf_install_in_context().
6917 */
6918 if (!smp_load_acquire(&event->ctx))
6919 continue;
6920
6921 if (event->state < PERF_EVENT_STATE_INACTIVE)
6922 continue;
6923 if (!event_filter_match(event))
6924 continue;
6925 output(event, data);
6926 }
6927 }
6928
6929 /*
6930 * Iterate all events that need to receive side-band events.
6931 *
6932 * For new callers; ensure that account_pmu_sb_event() includes
6933 * your event, otherwise it might not get delivered.
6934 */
6935 static void
perf_iterate_sb(perf_iterate_f output,void * data,struct perf_event_context * task_ctx)6936 perf_iterate_sb(perf_iterate_f output, void *data,
6937 struct perf_event_context *task_ctx)
6938 {
6939 struct perf_event_context *ctx;
6940 int ctxn;
6941
6942 rcu_read_lock();
6943 preempt_disable();
6944
6945 /*
6946 * If we have task_ctx != NULL we only notify the task context itself.
6947 * The task_ctx is set only for EXIT events before releasing task
6948 * context.
6949 */
6950 if (task_ctx) {
6951 perf_iterate_ctx(task_ctx, output, data, false);
6952 goto done;
6953 }
6954
6955 perf_iterate_sb_cpu(output, data);
6956
6957 for_each_task_context_nr(ctxn) {
6958 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
6959 if (ctx)
6960 perf_iterate_ctx(ctx, output, data, false);
6961 }
6962 done:
6963 preempt_enable();
6964 rcu_read_unlock();
6965 }
6966
6967 /*
6968 * Clear all file-based filters at exec, they'll have to be
6969 * re-instated when/if these objects are mmapped again.
6970 */
perf_event_addr_filters_exec(struct perf_event * event,void * data)6971 static void perf_event_addr_filters_exec(struct perf_event *event, void *data)
6972 {
6973 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
6974 struct perf_addr_filter *filter;
6975 unsigned int restart = 0, count = 0;
6976 unsigned long flags;
6977
6978 if (!has_addr_filter(event))
6979 return;
6980
6981 raw_spin_lock_irqsave(&ifh->lock, flags);
6982 list_for_each_entry(filter, &ifh->list, entry) {
6983 if (filter->path.dentry) {
6984 event->addr_filter_ranges[count].start = 0;
6985 event->addr_filter_ranges[count].size = 0;
6986 restart++;
6987 }
6988
6989 count++;
6990 }
6991
6992 if (restart)
6993 event->addr_filters_gen++;
6994 raw_spin_unlock_irqrestore(&ifh->lock, flags);
6995
6996 if (restart)
6997 perf_event_stop(event, 1);
6998 }
6999
perf_event_exec(void)7000 void perf_event_exec(void)
7001 {
7002 struct perf_event_context *ctx;
7003 int ctxn;
7004
7005 rcu_read_lock();
7006 for_each_task_context_nr(ctxn) {
7007 ctx = current->perf_event_ctxp[ctxn];
7008 if (!ctx)
7009 continue;
7010
7011 perf_event_enable_on_exec(ctxn);
7012
7013 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL,
7014 true);
7015 }
7016 rcu_read_unlock();
7017 }
7018
7019 struct remote_output {
7020 struct ring_buffer *rb;
7021 int err;
7022 };
7023
__perf_event_output_stop(struct perf_event * event,void * data)7024 static void __perf_event_output_stop(struct perf_event *event, void *data)
7025 {
7026 struct perf_event *parent = event->parent;
7027 struct remote_output *ro = data;
7028 struct ring_buffer *rb = ro->rb;
7029 struct stop_event_data sd = {
7030 .event = event,
7031 };
7032
7033 if (!has_aux(event))
7034 return;
7035
7036 if (!parent)
7037 parent = event;
7038
7039 /*
7040 * In case of inheritance, it will be the parent that links to the
7041 * ring-buffer, but it will be the child that's actually using it.
7042 *
7043 * We are using event::rb to determine if the event should be stopped,
7044 * however this may race with ring_buffer_attach() (through set_output),
7045 * which will make us skip the event that actually needs to be stopped.
7046 * So ring_buffer_attach() has to stop an aux event before re-assigning
7047 * its rb pointer.
7048 */
7049 if (rcu_dereference(parent->rb) == rb)
7050 ro->err = __perf_event_stop(&sd);
7051 }
7052
__perf_pmu_output_stop(void * info)7053 static int __perf_pmu_output_stop(void *info)
7054 {
7055 struct perf_event *event = info;
7056 struct pmu *pmu = event->ctx->pmu;
7057 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
7058 struct remote_output ro = {
7059 .rb = event->rb,
7060 };
7061
7062 rcu_read_lock();
7063 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false);
7064 if (cpuctx->task_ctx)
7065 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop,
7066 &ro, false);
7067 rcu_read_unlock();
7068
7069 return ro.err;
7070 }
7071
perf_pmu_output_stop(struct perf_event * event)7072 static void perf_pmu_output_stop(struct perf_event *event)
7073 {
7074 struct perf_event *iter;
7075 int err, cpu;
7076
7077 restart:
7078 rcu_read_lock();
7079 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) {
7080 /*
7081 * For per-CPU events, we need to make sure that neither they
7082 * nor their children are running; for cpu==-1 events it's
7083 * sufficient to stop the event itself if it's active, since
7084 * it can't have children.
7085 */
7086 cpu = iter->cpu;
7087 if (cpu == -1)
7088 cpu = READ_ONCE(iter->oncpu);
7089
7090 if (cpu == -1)
7091 continue;
7092
7093 err = cpu_function_call(cpu, __perf_pmu_output_stop, event);
7094 if (err == -EAGAIN) {
7095 rcu_read_unlock();
7096 goto restart;
7097 }
7098 }
7099 rcu_read_unlock();
7100 }
7101
7102 /*
7103 * task tracking -- fork/exit
7104 *
7105 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task
7106 */
7107
7108 struct perf_task_event {
7109 struct task_struct *task;
7110 struct perf_event_context *task_ctx;
7111
7112 struct {
7113 struct perf_event_header header;
7114
7115 u32 pid;
7116 u32 ppid;
7117 u32 tid;
7118 u32 ptid;
7119 u64 time;
7120 } event_id;
7121 };
7122
perf_event_task_match(struct perf_event * event)7123 static int perf_event_task_match(struct perf_event *event)
7124 {
7125 return event->attr.comm || event->attr.mmap ||
7126 event->attr.mmap2 || event->attr.mmap_data ||
7127 event->attr.task;
7128 }
7129
perf_event_task_output(struct perf_event * event,void * data)7130 static void perf_event_task_output(struct perf_event *event,
7131 void *data)
7132 {
7133 struct perf_task_event *task_event = data;
7134 struct perf_output_handle handle;
7135 struct perf_sample_data sample;
7136 struct task_struct *task = task_event->task;
7137 int ret, size = task_event->event_id.header.size;
7138
7139 if (!perf_event_task_match(event))
7140 return;
7141
7142 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
7143
7144 ret = perf_output_begin(&handle, event,
7145 task_event->event_id.header.size);
7146 if (ret)
7147 goto out;
7148
7149 task_event->event_id.pid = perf_event_pid(event, task);
7150 task_event->event_id.tid = perf_event_tid(event, task);
7151
7152 if (task_event->event_id.header.type == PERF_RECORD_EXIT) {
7153 task_event->event_id.ppid = perf_event_pid(event,
7154 task->real_parent);
7155 task_event->event_id.ptid = perf_event_pid(event,
7156 task->real_parent);
7157 } else { /* PERF_RECORD_FORK */
7158 task_event->event_id.ppid = perf_event_pid(event, current);
7159 task_event->event_id.ptid = perf_event_tid(event, current);
7160 }
7161
7162 task_event->event_id.time = perf_event_clock(event);
7163
7164 perf_output_put(&handle, task_event->event_id);
7165
7166 perf_event__output_id_sample(event, &handle, &sample);
7167
7168 perf_output_end(&handle);
7169 out:
7170 task_event->event_id.header.size = size;
7171 }
7172
perf_event_task(struct task_struct * task,struct perf_event_context * task_ctx,int new)7173 static void perf_event_task(struct task_struct *task,
7174 struct perf_event_context *task_ctx,
7175 int new)
7176 {
7177 struct perf_task_event task_event;
7178
7179 if (!atomic_read(&nr_comm_events) &&
7180 !atomic_read(&nr_mmap_events) &&
7181 !atomic_read(&nr_task_events))
7182 return;
7183
7184 task_event = (struct perf_task_event){
7185 .task = task,
7186 .task_ctx = task_ctx,
7187 .event_id = {
7188 .header = {
7189 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
7190 .misc = 0,
7191 .size = sizeof(task_event.event_id),
7192 },
7193 /* .pid */
7194 /* .ppid */
7195 /* .tid */
7196 /* .ptid */
7197 /* .time */
7198 },
7199 };
7200
7201 perf_iterate_sb(perf_event_task_output,
7202 &task_event,
7203 task_ctx);
7204 }
7205
perf_event_fork(struct task_struct * task)7206 void perf_event_fork(struct task_struct *task)
7207 {
7208 perf_event_task(task, NULL, 1);
7209 perf_event_namespaces(task);
7210 }
7211
7212 /*
7213 * comm tracking
7214 */
7215
7216 struct perf_comm_event {
7217 struct task_struct *task;
7218 char *comm;
7219 int comm_size;
7220
7221 struct {
7222 struct perf_event_header header;
7223
7224 u32 pid;
7225 u32 tid;
7226 } event_id;
7227 };
7228
perf_event_comm_match(struct perf_event * event)7229 static int perf_event_comm_match(struct perf_event *event)
7230 {
7231 return event->attr.comm;
7232 }
7233
perf_event_comm_output(struct perf_event * event,void * data)7234 static void perf_event_comm_output(struct perf_event *event,
7235 void *data)
7236 {
7237 struct perf_comm_event *comm_event = data;
7238 struct perf_output_handle handle;
7239 struct perf_sample_data sample;
7240 int size = comm_event->event_id.header.size;
7241 int ret;
7242
7243 if (!perf_event_comm_match(event))
7244 return;
7245
7246 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
7247 ret = perf_output_begin(&handle, event,
7248 comm_event->event_id.header.size);
7249
7250 if (ret)
7251 goto out;
7252
7253 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
7254 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
7255
7256 perf_output_put(&handle, comm_event->event_id);
7257 __output_copy(&handle, comm_event->comm,
7258 comm_event->comm_size);
7259
7260 perf_event__output_id_sample(event, &handle, &sample);
7261
7262 perf_output_end(&handle);
7263 out:
7264 comm_event->event_id.header.size = size;
7265 }
7266
perf_event_comm_event(struct perf_comm_event * comm_event)7267 static void perf_event_comm_event(struct perf_comm_event *comm_event)
7268 {
7269 char comm[TASK_COMM_LEN];
7270 unsigned int size;
7271
7272 memset(comm, 0, sizeof(comm));
7273 strlcpy(comm, comm_event->task->comm, sizeof(comm));
7274 size = ALIGN(strlen(comm)+1, sizeof(u64));
7275
7276 comm_event->comm = comm;
7277 comm_event->comm_size = size;
7278
7279 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
7280
7281 perf_iterate_sb(perf_event_comm_output,
7282 comm_event,
7283 NULL);
7284 }
7285
perf_event_comm(struct task_struct * task,bool exec)7286 void perf_event_comm(struct task_struct *task, bool exec)
7287 {
7288 struct perf_comm_event comm_event;
7289
7290 if (!atomic_read(&nr_comm_events))
7291 return;
7292
7293 comm_event = (struct perf_comm_event){
7294 .task = task,
7295 /* .comm */
7296 /* .comm_size */
7297 .event_id = {
7298 .header = {
7299 .type = PERF_RECORD_COMM,
7300 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0,
7301 /* .size */
7302 },
7303 /* .pid */
7304 /* .tid */
7305 },
7306 };
7307
7308 perf_event_comm_event(&comm_event);
7309 }
7310
7311 /*
7312 * namespaces tracking
7313 */
7314
7315 struct perf_namespaces_event {
7316 struct task_struct *task;
7317
7318 struct {
7319 struct perf_event_header header;
7320
7321 u32 pid;
7322 u32 tid;
7323 u64 nr_namespaces;
7324 struct perf_ns_link_info link_info[NR_NAMESPACES];
7325 } event_id;
7326 };
7327
perf_event_namespaces_match(struct perf_event * event)7328 static int perf_event_namespaces_match(struct perf_event *event)
7329 {
7330 return event->attr.namespaces;
7331 }
7332
perf_event_namespaces_output(struct perf_event * event,void * data)7333 static void perf_event_namespaces_output(struct perf_event *event,
7334 void *data)
7335 {
7336 struct perf_namespaces_event *namespaces_event = data;
7337 struct perf_output_handle handle;
7338 struct perf_sample_data sample;
7339 u16 header_size = namespaces_event->event_id.header.size;
7340 int ret;
7341
7342 if (!perf_event_namespaces_match(event))
7343 return;
7344
7345 perf_event_header__init_id(&namespaces_event->event_id.header,
7346 &sample, event);
7347 ret = perf_output_begin(&handle, event,
7348 namespaces_event->event_id.header.size);
7349 if (ret)
7350 goto out;
7351
7352 namespaces_event->event_id.pid = perf_event_pid(event,
7353 namespaces_event->task);
7354 namespaces_event->event_id.tid = perf_event_tid(event,
7355 namespaces_event->task);
7356
7357 perf_output_put(&handle, namespaces_event->event_id);
7358
7359 perf_event__output_id_sample(event, &handle, &sample);
7360
7361 perf_output_end(&handle);
7362 out:
7363 namespaces_event->event_id.header.size = header_size;
7364 }
7365
perf_fill_ns_link_info(struct perf_ns_link_info * ns_link_info,struct task_struct * task,const struct proc_ns_operations * ns_ops)7366 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info,
7367 struct task_struct *task,
7368 const struct proc_ns_operations *ns_ops)
7369 {
7370 struct path ns_path;
7371 struct inode *ns_inode;
7372 void *error;
7373
7374 error = ns_get_path(&ns_path, task, ns_ops);
7375 if (!error) {
7376 ns_inode = ns_path.dentry->d_inode;
7377 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev);
7378 ns_link_info->ino = ns_inode->i_ino;
7379 path_put(&ns_path);
7380 }
7381 }
7382
perf_event_namespaces(struct task_struct * task)7383 void perf_event_namespaces(struct task_struct *task)
7384 {
7385 struct perf_namespaces_event namespaces_event;
7386 struct perf_ns_link_info *ns_link_info;
7387
7388 if (!atomic_read(&nr_namespaces_events))
7389 return;
7390
7391 namespaces_event = (struct perf_namespaces_event){
7392 .task = task,
7393 .event_id = {
7394 .header = {
7395 .type = PERF_RECORD_NAMESPACES,
7396 .misc = 0,
7397 .size = sizeof(namespaces_event.event_id),
7398 },
7399 /* .pid */
7400 /* .tid */
7401 .nr_namespaces = NR_NAMESPACES,
7402 /* .link_info[NR_NAMESPACES] */
7403 },
7404 };
7405
7406 ns_link_info = namespaces_event.event_id.link_info;
7407
7408 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX],
7409 task, &mntns_operations);
7410
7411 #ifdef CONFIG_USER_NS
7412 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX],
7413 task, &userns_operations);
7414 #endif
7415 #ifdef CONFIG_NET_NS
7416 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX],
7417 task, &netns_operations);
7418 #endif
7419 #ifdef CONFIG_UTS_NS
7420 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX],
7421 task, &utsns_operations);
7422 #endif
7423 #ifdef CONFIG_IPC_NS
7424 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX],
7425 task, &ipcns_operations);
7426 #endif
7427 #ifdef CONFIG_PID_NS
7428 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX],
7429 task, &pidns_operations);
7430 #endif
7431 #ifdef CONFIG_CGROUPS
7432 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX],
7433 task, &cgroupns_operations);
7434 #endif
7435
7436 perf_iterate_sb(perf_event_namespaces_output,
7437 &namespaces_event,
7438 NULL);
7439 }
7440
7441 /*
7442 * mmap tracking
7443 */
7444
7445 struct perf_mmap_event {
7446 struct vm_area_struct *vma;
7447
7448 const char *file_name;
7449 int file_size;
7450 int maj, min;
7451 u64 ino;
7452 u64 ino_generation;
7453 u32 prot, flags;
7454
7455 struct {
7456 struct perf_event_header header;
7457
7458 u32 pid;
7459 u32 tid;
7460 u64 start;
7461 u64 len;
7462 u64 pgoff;
7463 } event_id;
7464 };
7465
perf_event_mmap_match(struct perf_event * event,void * data)7466 static int perf_event_mmap_match(struct perf_event *event,
7467 void *data)
7468 {
7469 struct perf_mmap_event *mmap_event = data;
7470 struct vm_area_struct *vma = mmap_event->vma;
7471 int executable = vma->vm_flags & VM_EXEC;
7472
7473 return (!executable && event->attr.mmap_data) ||
7474 (executable && (event->attr.mmap || event->attr.mmap2));
7475 }
7476
perf_event_mmap_output(struct perf_event * event,void * data)7477 static void perf_event_mmap_output(struct perf_event *event,
7478 void *data)
7479 {
7480 struct perf_mmap_event *mmap_event = data;
7481 struct perf_output_handle handle;
7482 struct perf_sample_data sample;
7483 int size = mmap_event->event_id.header.size;
7484 u32 type = mmap_event->event_id.header.type;
7485 int ret;
7486
7487 if (!perf_event_mmap_match(event, data))
7488 return;
7489
7490 if (event->attr.mmap2) {
7491 mmap_event->event_id.header.type = PERF_RECORD_MMAP2;
7492 mmap_event->event_id.header.size += sizeof(mmap_event->maj);
7493 mmap_event->event_id.header.size += sizeof(mmap_event->min);
7494 mmap_event->event_id.header.size += sizeof(mmap_event->ino);
7495 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation);
7496 mmap_event->event_id.header.size += sizeof(mmap_event->prot);
7497 mmap_event->event_id.header.size += sizeof(mmap_event->flags);
7498 }
7499
7500 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
7501 ret = perf_output_begin(&handle, event,
7502 mmap_event->event_id.header.size);
7503 if (ret)
7504 goto out;
7505
7506 mmap_event->event_id.pid = perf_event_pid(event, current);
7507 mmap_event->event_id.tid = perf_event_tid(event, current);
7508
7509 perf_output_put(&handle, mmap_event->event_id);
7510
7511 if (event->attr.mmap2) {
7512 perf_output_put(&handle, mmap_event->maj);
7513 perf_output_put(&handle, mmap_event->min);
7514 perf_output_put(&handle, mmap_event->ino);
7515 perf_output_put(&handle, mmap_event->ino_generation);
7516 perf_output_put(&handle, mmap_event->prot);
7517 perf_output_put(&handle, mmap_event->flags);
7518 }
7519
7520 __output_copy(&handle, mmap_event->file_name,
7521 mmap_event->file_size);
7522
7523 perf_event__output_id_sample(event, &handle, &sample);
7524
7525 perf_output_end(&handle);
7526 out:
7527 mmap_event->event_id.header.size = size;
7528 mmap_event->event_id.header.type = type;
7529 }
7530
perf_event_mmap_event(struct perf_mmap_event * mmap_event)7531 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
7532 {
7533 struct vm_area_struct *vma = mmap_event->vma;
7534 struct file *file = vma->vm_file;
7535 int maj = 0, min = 0;
7536 u64 ino = 0, gen = 0;
7537 u32 prot = 0, flags = 0;
7538 unsigned int size;
7539 char tmp[16];
7540 char *buf = NULL;
7541 char *name;
7542
7543 if (vma->vm_flags & VM_READ)
7544 prot |= PROT_READ;
7545 if (vma->vm_flags & VM_WRITE)
7546 prot |= PROT_WRITE;
7547 if (vma->vm_flags & VM_EXEC)
7548 prot |= PROT_EXEC;
7549
7550 if (vma->vm_flags & VM_MAYSHARE)
7551 flags = MAP_SHARED;
7552 else
7553 flags = MAP_PRIVATE;
7554
7555 if (vma->vm_flags & VM_DENYWRITE)
7556 flags |= MAP_DENYWRITE;
7557 if (vma->vm_flags & VM_MAYEXEC)
7558 flags |= MAP_EXECUTABLE;
7559 if (vma->vm_flags & VM_LOCKED)
7560 flags |= MAP_LOCKED;
7561 if (vma->vm_flags & VM_HUGETLB)
7562 flags |= MAP_HUGETLB;
7563
7564 if (file) {
7565 struct inode *inode;
7566 dev_t dev;
7567
7568 buf = kmalloc(PATH_MAX, GFP_KERNEL);
7569 if (!buf) {
7570 name = "//enomem";
7571 goto cpy_name;
7572 }
7573 /*
7574 * d_path() works from the end of the rb backwards, so we
7575 * need to add enough zero bytes after the string to handle
7576 * the 64bit alignment we do later.
7577 */
7578 name = file_path(file, buf, PATH_MAX - sizeof(u64));
7579 if (IS_ERR(name)) {
7580 name = "//toolong";
7581 goto cpy_name;
7582 }
7583 inode = file_inode(vma->vm_file);
7584 dev = inode->i_sb->s_dev;
7585 ino = inode->i_ino;
7586 gen = inode->i_generation;
7587 maj = MAJOR(dev);
7588 min = MINOR(dev);
7589
7590 goto got_name;
7591 } else {
7592 if (vma->vm_ops && vma->vm_ops->name) {
7593 name = (char *) vma->vm_ops->name(vma);
7594 if (name)
7595 goto cpy_name;
7596 }
7597
7598 name = (char *)arch_vma_name(vma);
7599 if (name)
7600 goto cpy_name;
7601
7602 if (vma->vm_start <= vma->vm_mm->start_brk &&
7603 vma->vm_end >= vma->vm_mm->brk) {
7604 name = "[heap]";
7605 goto cpy_name;
7606 }
7607 if (vma->vm_start <= vma->vm_mm->start_stack &&
7608 vma->vm_end >= vma->vm_mm->start_stack) {
7609 name = "[stack]";
7610 goto cpy_name;
7611 }
7612
7613 name = "//anon";
7614 goto cpy_name;
7615 }
7616
7617 cpy_name:
7618 strlcpy(tmp, name, sizeof(tmp));
7619 name = tmp;
7620 got_name:
7621 /*
7622 * Since our buffer works in 8 byte units we need to align our string
7623 * size to a multiple of 8. However, we must guarantee the tail end is
7624 * zero'd out to avoid leaking random bits to userspace.
7625 */
7626 size = strlen(name)+1;
7627 while (!IS_ALIGNED(size, sizeof(u64)))
7628 name[size++] = '\0';
7629
7630 mmap_event->file_name = name;
7631 mmap_event->file_size = size;
7632 mmap_event->maj = maj;
7633 mmap_event->min = min;
7634 mmap_event->ino = ino;
7635 mmap_event->ino_generation = gen;
7636 mmap_event->prot = prot;
7637 mmap_event->flags = flags;
7638
7639 if (!(vma->vm_flags & VM_EXEC))
7640 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA;
7641
7642 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
7643
7644 perf_iterate_sb(perf_event_mmap_output,
7645 mmap_event,
7646 NULL);
7647
7648 kfree(buf);
7649 }
7650
7651 /*
7652 * Check whether inode and address range match filter criteria.
7653 */
perf_addr_filter_match(struct perf_addr_filter * filter,struct file * file,unsigned long offset,unsigned long size)7654 static bool perf_addr_filter_match(struct perf_addr_filter *filter,
7655 struct file *file, unsigned long offset,
7656 unsigned long size)
7657 {
7658 /* d_inode(NULL) won't be equal to any mapped user-space file */
7659 if (!filter->path.dentry)
7660 return false;
7661
7662 if (d_inode(filter->path.dentry) != file_inode(file))
7663 return false;
7664
7665 if (filter->offset > offset + size)
7666 return false;
7667
7668 if (filter->offset + filter->size < offset)
7669 return false;
7670
7671 return true;
7672 }
7673
perf_addr_filter_vma_adjust(struct perf_addr_filter * filter,struct vm_area_struct * vma,struct perf_addr_filter_range * fr)7674 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter,
7675 struct vm_area_struct *vma,
7676 struct perf_addr_filter_range *fr)
7677 {
7678 unsigned long vma_size = vma->vm_end - vma->vm_start;
7679 unsigned long off = vma->vm_pgoff << PAGE_SHIFT;
7680 struct file *file = vma->vm_file;
7681
7682 if (!perf_addr_filter_match(filter, file, off, vma_size))
7683 return false;
7684
7685 if (filter->offset < off) {
7686 fr->start = vma->vm_start;
7687 fr->size = min(vma_size, filter->size - (off - filter->offset));
7688 } else {
7689 fr->start = vma->vm_start + filter->offset - off;
7690 fr->size = min(vma->vm_end - fr->start, filter->size);
7691 }
7692
7693 return true;
7694 }
7695
__perf_addr_filters_adjust(struct perf_event * event,void * data)7696 static void __perf_addr_filters_adjust(struct perf_event *event, void *data)
7697 {
7698 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
7699 struct vm_area_struct *vma = data;
7700 struct perf_addr_filter *filter;
7701 unsigned int restart = 0, count = 0;
7702 unsigned long flags;
7703
7704 if (!has_addr_filter(event))
7705 return;
7706
7707 if (!vma->vm_file)
7708 return;
7709
7710 raw_spin_lock_irqsave(&ifh->lock, flags);
7711 list_for_each_entry(filter, &ifh->list, entry) {
7712 if (perf_addr_filter_vma_adjust(filter, vma,
7713 &event->addr_filter_ranges[count]))
7714 restart++;
7715
7716 count++;
7717 }
7718
7719 if (restart)
7720 event->addr_filters_gen++;
7721 raw_spin_unlock_irqrestore(&ifh->lock, flags);
7722
7723 if (restart)
7724 perf_event_stop(event, 1);
7725 }
7726
7727 /*
7728 * Adjust all task's events' filters to the new vma
7729 */
perf_addr_filters_adjust(struct vm_area_struct * vma)7730 static void perf_addr_filters_adjust(struct vm_area_struct *vma)
7731 {
7732 struct perf_event_context *ctx;
7733 int ctxn;
7734
7735 /*
7736 * Data tracing isn't supported yet and as such there is no need
7737 * to keep track of anything that isn't related to executable code:
7738 */
7739 if (!(vma->vm_flags & VM_EXEC))
7740 return;
7741
7742 rcu_read_lock();
7743 for_each_task_context_nr(ctxn) {
7744 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
7745 if (!ctx)
7746 continue;
7747
7748 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true);
7749 }
7750 rcu_read_unlock();
7751 }
7752
perf_event_mmap(struct vm_area_struct * vma)7753 void perf_event_mmap(struct vm_area_struct *vma)
7754 {
7755 struct perf_mmap_event mmap_event;
7756
7757 if (!atomic_read(&nr_mmap_events))
7758 return;
7759
7760 mmap_event = (struct perf_mmap_event){
7761 .vma = vma,
7762 /* .file_name */
7763 /* .file_size */
7764 .event_id = {
7765 .header = {
7766 .type = PERF_RECORD_MMAP,
7767 .misc = PERF_RECORD_MISC_USER,
7768 /* .size */
7769 },
7770 /* .pid */
7771 /* .tid */
7772 .start = vma->vm_start,
7773 .len = vma->vm_end - vma->vm_start,
7774 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
7775 },
7776 /* .maj (attr_mmap2 only) */
7777 /* .min (attr_mmap2 only) */
7778 /* .ino (attr_mmap2 only) */
7779 /* .ino_generation (attr_mmap2 only) */
7780 /* .prot (attr_mmap2 only) */
7781 /* .flags (attr_mmap2 only) */
7782 };
7783
7784 perf_addr_filters_adjust(vma);
7785 perf_event_mmap_event(&mmap_event);
7786 }
7787
perf_event_aux_event(struct perf_event * event,unsigned long head,unsigned long size,u64 flags)7788 void perf_event_aux_event(struct perf_event *event, unsigned long head,
7789 unsigned long size, u64 flags)
7790 {
7791 struct perf_output_handle handle;
7792 struct perf_sample_data sample;
7793 struct perf_aux_event {
7794 struct perf_event_header header;
7795 u64 offset;
7796 u64 size;
7797 u64 flags;
7798 } rec = {
7799 .header = {
7800 .type = PERF_RECORD_AUX,
7801 .misc = 0,
7802 .size = sizeof(rec),
7803 },
7804 .offset = head,
7805 .size = size,
7806 .flags = flags,
7807 };
7808 int ret;
7809
7810 perf_event_header__init_id(&rec.header, &sample, event);
7811 ret = perf_output_begin(&handle, event, rec.header.size);
7812
7813 if (ret)
7814 return;
7815
7816 perf_output_put(&handle, rec);
7817 perf_event__output_id_sample(event, &handle, &sample);
7818
7819 perf_output_end(&handle);
7820 }
7821
7822 /*
7823 * Lost/dropped samples logging
7824 */
perf_log_lost_samples(struct perf_event * event,u64 lost)7825 void perf_log_lost_samples(struct perf_event *event, u64 lost)
7826 {
7827 struct perf_output_handle handle;
7828 struct perf_sample_data sample;
7829 int ret;
7830
7831 struct {
7832 struct perf_event_header header;
7833 u64 lost;
7834 } lost_samples_event = {
7835 .header = {
7836 .type = PERF_RECORD_LOST_SAMPLES,
7837 .misc = 0,
7838 .size = sizeof(lost_samples_event),
7839 },
7840 .lost = lost,
7841 };
7842
7843 perf_event_header__init_id(&lost_samples_event.header, &sample, event);
7844
7845 ret = perf_output_begin(&handle, event,
7846 lost_samples_event.header.size);
7847 if (ret)
7848 return;
7849
7850 perf_output_put(&handle, lost_samples_event);
7851 perf_event__output_id_sample(event, &handle, &sample);
7852 perf_output_end(&handle);
7853 }
7854
7855 /*
7856 * context_switch tracking
7857 */
7858
7859 struct perf_switch_event {
7860 struct task_struct *task;
7861 struct task_struct *next_prev;
7862
7863 struct {
7864 struct perf_event_header header;
7865 u32 next_prev_pid;
7866 u32 next_prev_tid;
7867 } event_id;
7868 };
7869
perf_event_switch_match(struct perf_event * event)7870 static int perf_event_switch_match(struct perf_event *event)
7871 {
7872 return event->attr.context_switch;
7873 }
7874
perf_event_switch_output(struct perf_event * event,void * data)7875 static void perf_event_switch_output(struct perf_event *event, void *data)
7876 {
7877 struct perf_switch_event *se = data;
7878 struct perf_output_handle handle;
7879 struct perf_sample_data sample;
7880 int ret;
7881
7882 if (!perf_event_switch_match(event))
7883 return;
7884
7885 /* Only CPU-wide events are allowed to see next/prev pid/tid */
7886 if (event->ctx->task) {
7887 se->event_id.header.type = PERF_RECORD_SWITCH;
7888 se->event_id.header.size = sizeof(se->event_id.header);
7889 } else {
7890 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE;
7891 se->event_id.header.size = sizeof(se->event_id);
7892 se->event_id.next_prev_pid =
7893 perf_event_pid(event, se->next_prev);
7894 se->event_id.next_prev_tid =
7895 perf_event_tid(event, se->next_prev);
7896 }
7897
7898 perf_event_header__init_id(&se->event_id.header, &sample, event);
7899
7900 ret = perf_output_begin(&handle, event, se->event_id.header.size);
7901 if (ret)
7902 return;
7903
7904 if (event->ctx->task)
7905 perf_output_put(&handle, se->event_id.header);
7906 else
7907 perf_output_put(&handle, se->event_id);
7908
7909 perf_event__output_id_sample(event, &handle, &sample);
7910
7911 perf_output_end(&handle);
7912 }
7913
perf_event_switch(struct task_struct * task,struct task_struct * next_prev,bool sched_in)7914 static void perf_event_switch(struct task_struct *task,
7915 struct task_struct *next_prev, bool sched_in)
7916 {
7917 struct perf_switch_event switch_event;
7918
7919 /* N.B. caller checks nr_switch_events != 0 */
7920
7921 switch_event = (struct perf_switch_event){
7922 .task = task,
7923 .next_prev = next_prev,
7924 .event_id = {
7925 .header = {
7926 /* .type */
7927 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT,
7928 /* .size */
7929 },
7930 /* .next_prev_pid */
7931 /* .next_prev_tid */
7932 },
7933 };
7934
7935 if (!sched_in && task->state == TASK_RUNNING)
7936 switch_event.event_id.header.misc |=
7937 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT;
7938
7939 perf_iterate_sb(perf_event_switch_output,
7940 &switch_event,
7941 NULL);
7942 }
7943
7944 /*
7945 * IRQ throttle logging
7946 */
7947
perf_log_throttle(struct perf_event * event,int enable)7948 static void perf_log_throttle(struct perf_event *event, int enable)
7949 {
7950 struct perf_output_handle handle;
7951 struct perf_sample_data sample;
7952 int ret;
7953
7954 struct {
7955 struct perf_event_header header;
7956 u64 time;
7957 u64 id;
7958 u64 stream_id;
7959 } throttle_event = {
7960 .header = {
7961 .type = PERF_RECORD_THROTTLE,
7962 .misc = 0,
7963 .size = sizeof(throttle_event),
7964 },
7965 .time = perf_event_clock(event),
7966 .id = primary_event_id(event),
7967 .stream_id = event->id,
7968 };
7969
7970 if (enable)
7971 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
7972
7973 perf_event_header__init_id(&throttle_event.header, &sample, event);
7974
7975 ret = perf_output_begin(&handle, event,
7976 throttle_event.header.size);
7977 if (ret)
7978 return;
7979
7980 perf_output_put(&handle, throttle_event);
7981 perf_event__output_id_sample(event, &handle, &sample);
7982 perf_output_end(&handle);
7983 }
7984
7985 /*
7986 * ksymbol register/unregister tracking
7987 */
7988
7989 struct perf_ksymbol_event {
7990 const char *name;
7991 int name_len;
7992 struct {
7993 struct perf_event_header header;
7994 u64 addr;
7995 u32 len;
7996 u16 ksym_type;
7997 u16 flags;
7998 } event_id;
7999 };
8000
perf_event_ksymbol_match(struct perf_event * event)8001 static int perf_event_ksymbol_match(struct perf_event *event)
8002 {
8003 return event->attr.ksymbol;
8004 }
8005
perf_event_ksymbol_output(struct perf_event * event,void * data)8006 static void perf_event_ksymbol_output(struct perf_event *event, void *data)
8007 {
8008 struct perf_ksymbol_event *ksymbol_event = data;
8009 struct perf_output_handle handle;
8010 struct perf_sample_data sample;
8011 int ret;
8012
8013 if (!perf_event_ksymbol_match(event))
8014 return;
8015
8016 perf_event_header__init_id(&ksymbol_event->event_id.header,
8017 &sample, event);
8018 ret = perf_output_begin(&handle, event,
8019 ksymbol_event->event_id.header.size);
8020 if (ret)
8021 return;
8022
8023 perf_output_put(&handle, ksymbol_event->event_id);
8024 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len);
8025 perf_event__output_id_sample(event, &handle, &sample);
8026
8027 perf_output_end(&handle);
8028 }
8029
perf_event_ksymbol(u16 ksym_type,u64 addr,u32 len,bool unregister,const char * sym)8030 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister,
8031 const char *sym)
8032 {
8033 struct perf_ksymbol_event ksymbol_event;
8034 char name[KSYM_NAME_LEN];
8035 u16 flags = 0;
8036 int name_len;
8037
8038 if (!atomic_read(&nr_ksymbol_events))
8039 return;
8040
8041 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX ||
8042 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN)
8043 goto err;
8044
8045 strlcpy(name, sym, KSYM_NAME_LEN);
8046 name_len = strlen(name) + 1;
8047 while (!IS_ALIGNED(name_len, sizeof(u64)))
8048 name[name_len++] = '\0';
8049 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64));
8050
8051 if (unregister)
8052 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER;
8053
8054 ksymbol_event = (struct perf_ksymbol_event){
8055 .name = name,
8056 .name_len = name_len,
8057 .event_id = {
8058 .header = {
8059 .type = PERF_RECORD_KSYMBOL,
8060 .size = sizeof(ksymbol_event.event_id) +
8061 name_len,
8062 },
8063 .addr = addr,
8064 .len = len,
8065 .ksym_type = ksym_type,
8066 .flags = flags,
8067 },
8068 };
8069
8070 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL);
8071 return;
8072 err:
8073 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type);
8074 }
8075
8076 /*
8077 * bpf program load/unload tracking
8078 */
8079
8080 struct perf_bpf_event {
8081 struct bpf_prog *prog;
8082 struct {
8083 struct perf_event_header header;
8084 u16 type;
8085 u16 flags;
8086 u32 id;
8087 u8 tag[BPF_TAG_SIZE];
8088 } event_id;
8089 };
8090
perf_event_bpf_match(struct perf_event * event)8091 static int perf_event_bpf_match(struct perf_event *event)
8092 {
8093 return event->attr.bpf_event;
8094 }
8095
perf_event_bpf_output(struct perf_event * event,void * data)8096 static void perf_event_bpf_output(struct perf_event *event, void *data)
8097 {
8098 struct perf_bpf_event *bpf_event = data;
8099 struct perf_output_handle handle;
8100 struct perf_sample_data sample;
8101 int ret;
8102
8103 if (!perf_event_bpf_match(event))
8104 return;
8105
8106 perf_event_header__init_id(&bpf_event->event_id.header,
8107 &sample, event);
8108 ret = perf_output_begin(&handle, event,
8109 bpf_event->event_id.header.size);
8110 if (ret)
8111 return;
8112
8113 perf_output_put(&handle, bpf_event->event_id);
8114 perf_event__output_id_sample(event, &handle, &sample);
8115
8116 perf_output_end(&handle);
8117 }
8118
perf_event_bpf_emit_ksymbols(struct bpf_prog * prog,enum perf_bpf_event_type type)8119 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog,
8120 enum perf_bpf_event_type type)
8121 {
8122 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD;
8123 char sym[KSYM_NAME_LEN];
8124 int i;
8125
8126 if (prog->aux->func_cnt == 0) {
8127 bpf_get_prog_name(prog, sym);
8128 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF,
8129 (u64)(unsigned long)prog->bpf_func,
8130 prog->jited_len, unregister, sym);
8131 } else {
8132 for (i = 0; i < prog->aux->func_cnt; i++) {
8133 struct bpf_prog *subprog = prog->aux->func[i];
8134
8135 bpf_get_prog_name(subprog, sym);
8136 perf_event_ksymbol(
8137 PERF_RECORD_KSYMBOL_TYPE_BPF,
8138 (u64)(unsigned long)subprog->bpf_func,
8139 subprog->jited_len, unregister, sym);
8140 }
8141 }
8142 }
8143
perf_event_bpf_event(struct bpf_prog * prog,enum perf_bpf_event_type type,u16 flags)8144 void perf_event_bpf_event(struct bpf_prog *prog,
8145 enum perf_bpf_event_type type,
8146 u16 flags)
8147 {
8148 struct perf_bpf_event bpf_event;
8149
8150 if (type <= PERF_BPF_EVENT_UNKNOWN ||
8151 type >= PERF_BPF_EVENT_MAX)
8152 return;
8153
8154 switch (type) {
8155 case PERF_BPF_EVENT_PROG_LOAD:
8156 case PERF_BPF_EVENT_PROG_UNLOAD:
8157 if (atomic_read(&nr_ksymbol_events))
8158 perf_event_bpf_emit_ksymbols(prog, type);
8159 break;
8160 default:
8161 break;
8162 }
8163
8164 if (!atomic_read(&nr_bpf_events))
8165 return;
8166
8167 bpf_event = (struct perf_bpf_event){
8168 .prog = prog,
8169 .event_id = {
8170 .header = {
8171 .type = PERF_RECORD_BPF_EVENT,
8172 .size = sizeof(bpf_event.event_id),
8173 },
8174 .type = type,
8175 .flags = flags,
8176 .id = prog->aux->id,
8177 },
8178 };
8179
8180 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64));
8181
8182 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE);
8183 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL);
8184 }
8185
perf_event_itrace_started(struct perf_event * event)8186 void perf_event_itrace_started(struct perf_event *event)
8187 {
8188 event->attach_state |= PERF_ATTACH_ITRACE;
8189 }
8190
perf_log_itrace_start(struct perf_event * event)8191 static void perf_log_itrace_start(struct perf_event *event)
8192 {
8193 struct perf_output_handle handle;
8194 struct perf_sample_data sample;
8195 struct perf_aux_event {
8196 struct perf_event_header header;
8197 u32 pid;
8198 u32 tid;
8199 } rec;
8200 int ret;
8201
8202 if (event->parent)
8203 event = event->parent;
8204
8205 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) ||
8206 event->attach_state & PERF_ATTACH_ITRACE)
8207 return;
8208
8209 rec.header.type = PERF_RECORD_ITRACE_START;
8210 rec.header.misc = 0;
8211 rec.header.size = sizeof(rec);
8212 rec.pid = perf_event_pid(event, current);
8213 rec.tid = perf_event_tid(event, current);
8214
8215 perf_event_header__init_id(&rec.header, &sample, event);
8216 ret = perf_output_begin(&handle, event, rec.header.size);
8217
8218 if (ret)
8219 return;
8220
8221 perf_output_put(&handle, rec);
8222 perf_event__output_id_sample(event, &handle, &sample);
8223
8224 perf_output_end(&handle);
8225 }
8226
8227 static int
__perf_event_account_interrupt(struct perf_event * event,int throttle)8228 __perf_event_account_interrupt(struct perf_event *event, int throttle)
8229 {
8230 struct hw_perf_event *hwc = &event->hw;
8231 int ret = 0;
8232 u64 seq;
8233
8234 seq = __this_cpu_read(perf_throttled_seq);
8235 if (seq != hwc->interrupts_seq) {
8236 hwc->interrupts_seq = seq;
8237 hwc->interrupts = 1;
8238 } else {
8239 hwc->interrupts++;
8240 if (unlikely(throttle &&
8241 hwc->interrupts > max_samples_per_tick)) {
8242 __this_cpu_inc(perf_throttled_count);
8243 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS);
8244 hwc->interrupts = MAX_INTERRUPTS;
8245 perf_log_throttle(event, 0);
8246 ret = 1;
8247 }
8248 }
8249
8250 if (event->attr.freq) {
8251 u64 now = perf_clock();
8252 s64 delta = now - hwc->freq_time_stamp;
8253
8254 hwc->freq_time_stamp = now;
8255
8256 if (delta > 0 && delta < 2*TICK_NSEC)
8257 perf_adjust_period(event, delta, hwc->last_period, true);
8258 }
8259
8260 return ret;
8261 }
8262
perf_event_account_interrupt(struct perf_event * event)8263 int perf_event_account_interrupt(struct perf_event *event)
8264 {
8265 return __perf_event_account_interrupt(event, 1);
8266 }
8267
8268 /*
8269 * Generic event overflow handling, sampling.
8270 */
8271
__perf_event_overflow(struct perf_event * event,int throttle,struct perf_sample_data * data,struct pt_regs * regs)8272 static int __perf_event_overflow(struct perf_event *event,
8273 int throttle, struct perf_sample_data *data,
8274 struct pt_regs *regs)
8275 {
8276 int events = atomic_read(&event->event_limit);
8277 int ret = 0;
8278
8279 /*
8280 * Non-sampling counters might still use the PMI to fold short
8281 * hardware counters, ignore those.
8282 */
8283 if (unlikely(!is_sampling_event(event)))
8284 return 0;
8285
8286 ret = __perf_event_account_interrupt(event, throttle);
8287
8288 /*
8289 * XXX event_limit might not quite work as expected on inherited
8290 * events
8291 */
8292
8293 event->pending_kill = POLL_IN;
8294 if (events && atomic_dec_and_test(&event->event_limit)) {
8295 ret = 1;
8296 event->pending_kill = POLL_HUP;
8297
8298 perf_event_disable_inatomic(event);
8299 }
8300
8301 READ_ONCE(event->overflow_handler)(event, data, regs);
8302
8303 if (*perf_event_fasync(event) && event->pending_kill) {
8304 event->pending_wakeup = 1;
8305 irq_work_queue(&event->pending);
8306 }
8307
8308 return ret;
8309 }
8310
perf_event_overflow(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8311 int perf_event_overflow(struct perf_event *event,
8312 struct perf_sample_data *data,
8313 struct pt_regs *regs)
8314 {
8315 return __perf_event_overflow(event, 1, data, regs);
8316 }
8317
8318 /*
8319 * Generic software event infrastructure
8320 */
8321
8322 struct swevent_htable {
8323 struct swevent_hlist *swevent_hlist;
8324 struct mutex hlist_mutex;
8325 int hlist_refcount;
8326
8327 /* Recursion avoidance in each contexts */
8328 int recursion[PERF_NR_CONTEXTS];
8329 };
8330
8331 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
8332
8333 /*
8334 * We directly increment event->count and keep a second value in
8335 * event->hw.period_left to count intervals. This period event
8336 * is kept in the range [-sample_period, 0] so that we can use the
8337 * sign as trigger.
8338 */
8339
perf_swevent_set_period(struct perf_event * event)8340 u64 perf_swevent_set_period(struct perf_event *event)
8341 {
8342 struct hw_perf_event *hwc = &event->hw;
8343 u64 period = hwc->last_period;
8344 u64 nr, offset;
8345 s64 old, val;
8346
8347 hwc->last_period = hwc->sample_period;
8348
8349 again:
8350 old = val = local64_read(&hwc->period_left);
8351 if (val < 0)
8352 return 0;
8353
8354 nr = div64_u64(period + val, period);
8355 offset = nr * period;
8356 val -= offset;
8357 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
8358 goto again;
8359
8360 return nr;
8361 }
8362
perf_swevent_overflow(struct perf_event * event,u64 overflow,struct perf_sample_data * data,struct pt_regs * regs)8363 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
8364 struct perf_sample_data *data,
8365 struct pt_regs *regs)
8366 {
8367 struct hw_perf_event *hwc = &event->hw;
8368 int throttle = 0;
8369
8370 if (!overflow)
8371 overflow = perf_swevent_set_period(event);
8372
8373 if (hwc->interrupts == MAX_INTERRUPTS)
8374 return;
8375
8376 for (; overflow; overflow--) {
8377 if (__perf_event_overflow(event, throttle,
8378 data, regs)) {
8379 /*
8380 * We inhibit the overflow from happening when
8381 * hwc->interrupts == MAX_INTERRUPTS.
8382 */
8383 break;
8384 }
8385 throttle = 1;
8386 }
8387 }
8388
perf_swevent_event(struct perf_event * event,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)8389 static void perf_swevent_event(struct perf_event *event, u64 nr,
8390 struct perf_sample_data *data,
8391 struct pt_regs *regs)
8392 {
8393 struct hw_perf_event *hwc = &event->hw;
8394
8395 local64_add(nr, &event->count);
8396
8397 if (!regs)
8398 return;
8399
8400 if (!is_sampling_event(event))
8401 return;
8402
8403 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) {
8404 data->period = nr;
8405 return perf_swevent_overflow(event, 1, data, regs);
8406 } else
8407 data->period = event->hw.last_period;
8408
8409 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
8410 return perf_swevent_overflow(event, 1, data, regs);
8411
8412 if (local64_add_negative(nr, &hwc->period_left))
8413 return;
8414
8415 perf_swevent_overflow(event, 0, data, regs);
8416 }
8417
perf_exclude_event(struct perf_event * event,struct pt_regs * regs)8418 static int perf_exclude_event(struct perf_event *event,
8419 struct pt_regs *regs)
8420 {
8421 if (event->hw.state & PERF_HES_STOPPED)
8422 return 1;
8423
8424 if (regs) {
8425 if (event->attr.exclude_user && user_mode(regs))
8426 return 1;
8427
8428 if (event->attr.exclude_kernel && !user_mode(regs))
8429 return 1;
8430 }
8431
8432 return 0;
8433 }
8434
perf_swevent_match(struct perf_event * event,enum perf_type_id type,u32 event_id,struct perf_sample_data * data,struct pt_regs * regs)8435 static int perf_swevent_match(struct perf_event *event,
8436 enum perf_type_id type,
8437 u32 event_id,
8438 struct perf_sample_data *data,
8439 struct pt_regs *regs)
8440 {
8441 if (event->attr.type != type)
8442 return 0;
8443
8444 if (event->attr.config != event_id)
8445 return 0;
8446
8447 if (perf_exclude_event(event, regs))
8448 return 0;
8449
8450 return 1;
8451 }
8452
swevent_hash(u64 type,u32 event_id)8453 static inline u64 swevent_hash(u64 type, u32 event_id)
8454 {
8455 u64 val = event_id | (type << 32);
8456
8457 return hash_64(val, SWEVENT_HLIST_BITS);
8458 }
8459
8460 static inline struct hlist_head *
__find_swevent_head(struct swevent_hlist * hlist,u64 type,u32 event_id)8461 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
8462 {
8463 u64 hash = swevent_hash(type, event_id);
8464
8465 return &hlist->heads[hash];
8466 }
8467
8468 /* For the read side: events when they trigger */
8469 static inline struct hlist_head *
find_swevent_head_rcu(struct swevent_htable * swhash,u64 type,u32 event_id)8470 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
8471 {
8472 struct swevent_hlist *hlist;
8473
8474 hlist = rcu_dereference(swhash->swevent_hlist);
8475 if (!hlist)
8476 return NULL;
8477
8478 return __find_swevent_head(hlist, type, event_id);
8479 }
8480
8481 /* For the event head insertion and removal in the hlist */
8482 static inline struct hlist_head *
find_swevent_head(struct swevent_htable * swhash,struct perf_event * event)8483 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
8484 {
8485 struct swevent_hlist *hlist;
8486 u32 event_id = event->attr.config;
8487 u64 type = event->attr.type;
8488
8489 /*
8490 * Event scheduling is always serialized against hlist allocation
8491 * and release. Which makes the protected version suitable here.
8492 * The context lock guarantees that.
8493 */
8494 hlist = rcu_dereference_protected(swhash->swevent_hlist,
8495 lockdep_is_held(&event->ctx->lock));
8496 if (!hlist)
8497 return NULL;
8498
8499 return __find_swevent_head(hlist, type, event_id);
8500 }
8501
do_perf_sw_event(enum perf_type_id type,u32 event_id,u64 nr,struct perf_sample_data * data,struct pt_regs * regs)8502 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
8503 u64 nr,
8504 struct perf_sample_data *data,
8505 struct pt_regs *regs)
8506 {
8507 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8508 struct perf_event *event;
8509 struct hlist_head *head;
8510
8511 rcu_read_lock();
8512 head = find_swevent_head_rcu(swhash, type, event_id);
8513 if (!head)
8514 goto end;
8515
8516 hlist_for_each_entry_rcu(event, head, hlist_entry) {
8517 if (perf_swevent_match(event, type, event_id, data, regs))
8518 perf_swevent_event(event, nr, data, regs);
8519 }
8520 end:
8521 rcu_read_unlock();
8522 }
8523
8524 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]);
8525
perf_swevent_get_recursion_context(void)8526 int perf_swevent_get_recursion_context(void)
8527 {
8528 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8529
8530 return get_recursion_context(swhash->recursion);
8531 }
8532 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
8533
perf_swevent_put_recursion_context(int rctx)8534 void perf_swevent_put_recursion_context(int rctx)
8535 {
8536 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8537
8538 put_recursion_context(swhash->recursion, rctx);
8539 }
8540
___perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)8541 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
8542 {
8543 struct perf_sample_data data;
8544
8545 if (WARN_ON_ONCE(!regs))
8546 return;
8547
8548 perf_sample_data_init(&data, addr, 0);
8549 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs);
8550 }
8551
__perf_sw_event(u32 event_id,u64 nr,struct pt_regs * regs,u64 addr)8552 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr)
8553 {
8554 int rctx;
8555
8556 preempt_disable_notrace();
8557 rctx = perf_swevent_get_recursion_context();
8558 if (unlikely(rctx < 0))
8559 goto fail;
8560
8561 ___perf_sw_event(event_id, nr, regs, addr);
8562
8563 perf_swevent_put_recursion_context(rctx);
8564 fail:
8565 preempt_enable_notrace();
8566 }
8567
perf_swevent_read(struct perf_event * event)8568 static void perf_swevent_read(struct perf_event *event)
8569 {
8570 }
8571
perf_swevent_add(struct perf_event * event,int flags)8572 static int perf_swevent_add(struct perf_event *event, int flags)
8573 {
8574 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable);
8575 struct hw_perf_event *hwc = &event->hw;
8576 struct hlist_head *head;
8577
8578 if (is_sampling_event(event)) {
8579 hwc->last_period = hwc->sample_period;
8580 perf_swevent_set_period(event);
8581 }
8582
8583 hwc->state = !(flags & PERF_EF_START);
8584
8585 head = find_swevent_head(swhash, event);
8586 if (WARN_ON_ONCE(!head))
8587 return -EINVAL;
8588
8589 hlist_add_head_rcu(&event->hlist_entry, head);
8590 perf_event_update_userpage(event);
8591
8592 return 0;
8593 }
8594
perf_swevent_del(struct perf_event * event,int flags)8595 static void perf_swevent_del(struct perf_event *event, int flags)
8596 {
8597 hlist_del_rcu(&event->hlist_entry);
8598 }
8599
perf_swevent_start(struct perf_event * event,int flags)8600 static void perf_swevent_start(struct perf_event *event, int flags)
8601 {
8602 event->hw.state = 0;
8603 }
8604
perf_swevent_stop(struct perf_event * event,int flags)8605 static void perf_swevent_stop(struct perf_event *event, int flags)
8606 {
8607 event->hw.state = PERF_HES_STOPPED;
8608 }
8609
8610 /* Deref the hlist from the update side */
8611 static inline struct swevent_hlist *
swevent_hlist_deref(struct swevent_htable * swhash)8612 swevent_hlist_deref(struct swevent_htable *swhash)
8613 {
8614 return rcu_dereference_protected(swhash->swevent_hlist,
8615 lockdep_is_held(&swhash->hlist_mutex));
8616 }
8617
swevent_hlist_release(struct swevent_htable * swhash)8618 static void swevent_hlist_release(struct swevent_htable *swhash)
8619 {
8620 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
8621
8622 if (!hlist)
8623 return;
8624
8625 RCU_INIT_POINTER(swhash->swevent_hlist, NULL);
8626 kfree_rcu(hlist, rcu_head);
8627 }
8628
swevent_hlist_put_cpu(int cpu)8629 static void swevent_hlist_put_cpu(int cpu)
8630 {
8631 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8632
8633 mutex_lock(&swhash->hlist_mutex);
8634
8635 if (!--swhash->hlist_refcount)
8636 swevent_hlist_release(swhash);
8637
8638 mutex_unlock(&swhash->hlist_mutex);
8639 }
8640
swevent_hlist_put(void)8641 static void swevent_hlist_put(void)
8642 {
8643 int cpu;
8644
8645 for_each_possible_cpu(cpu)
8646 swevent_hlist_put_cpu(cpu);
8647 }
8648
swevent_hlist_get_cpu(int cpu)8649 static int swevent_hlist_get_cpu(int cpu)
8650 {
8651 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
8652 int err = 0;
8653
8654 mutex_lock(&swhash->hlist_mutex);
8655 if (!swevent_hlist_deref(swhash) &&
8656 cpumask_test_cpu(cpu, perf_online_mask)) {
8657 struct swevent_hlist *hlist;
8658
8659 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
8660 if (!hlist) {
8661 err = -ENOMEM;
8662 goto exit;
8663 }
8664 rcu_assign_pointer(swhash->swevent_hlist, hlist);
8665 }
8666 swhash->hlist_refcount++;
8667 exit:
8668 mutex_unlock(&swhash->hlist_mutex);
8669
8670 return err;
8671 }
8672
swevent_hlist_get(void)8673 static int swevent_hlist_get(void)
8674 {
8675 int err, cpu, failed_cpu;
8676
8677 mutex_lock(&pmus_lock);
8678 for_each_possible_cpu(cpu) {
8679 err = swevent_hlist_get_cpu(cpu);
8680 if (err) {
8681 failed_cpu = cpu;
8682 goto fail;
8683 }
8684 }
8685 mutex_unlock(&pmus_lock);
8686 return 0;
8687 fail:
8688 for_each_possible_cpu(cpu) {
8689 if (cpu == failed_cpu)
8690 break;
8691 swevent_hlist_put_cpu(cpu);
8692 }
8693 mutex_unlock(&pmus_lock);
8694 return err;
8695 }
8696
8697 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX];
8698
sw_perf_event_destroy(struct perf_event * event)8699 static void sw_perf_event_destroy(struct perf_event *event)
8700 {
8701 u64 event_id = event->attr.config;
8702
8703 WARN_ON(event->parent);
8704
8705 static_key_slow_dec(&perf_swevent_enabled[event_id]);
8706 swevent_hlist_put();
8707 }
8708
perf_swevent_init(struct perf_event * event)8709 static int perf_swevent_init(struct perf_event *event)
8710 {
8711 u64 event_id = event->attr.config;
8712
8713 if (event->attr.type != PERF_TYPE_SOFTWARE)
8714 return -ENOENT;
8715
8716 /*
8717 * no branch sampling for software events
8718 */
8719 if (has_branch_stack(event))
8720 return -EOPNOTSUPP;
8721
8722 switch (event_id) {
8723 case PERF_COUNT_SW_CPU_CLOCK:
8724 case PERF_COUNT_SW_TASK_CLOCK:
8725 return -ENOENT;
8726
8727 default:
8728 break;
8729 }
8730
8731 if (event_id >= PERF_COUNT_SW_MAX)
8732 return -ENOENT;
8733
8734 if (!event->parent) {
8735 int err;
8736
8737 err = swevent_hlist_get();
8738 if (err)
8739 return err;
8740
8741 static_key_slow_inc(&perf_swevent_enabled[event_id]);
8742 event->destroy = sw_perf_event_destroy;
8743 }
8744
8745 return 0;
8746 }
8747
8748 static struct pmu perf_swevent = {
8749 .task_ctx_nr = perf_sw_context,
8750
8751 .capabilities = PERF_PMU_CAP_NO_NMI,
8752
8753 .event_init = perf_swevent_init,
8754 .add = perf_swevent_add,
8755 .del = perf_swevent_del,
8756 .start = perf_swevent_start,
8757 .stop = perf_swevent_stop,
8758 .read = perf_swevent_read,
8759 };
8760
8761 #ifdef CONFIG_EVENT_TRACING
8762
perf_tp_filter_match(struct perf_event * event,struct perf_sample_data * data)8763 static int perf_tp_filter_match(struct perf_event *event,
8764 struct perf_sample_data *data)
8765 {
8766 void *record = data->raw->frag.data;
8767
8768 /* only top level events have filters set */
8769 if (event->parent)
8770 event = event->parent;
8771
8772 if (likely(!event->filter) || filter_match_preds(event->filter, record))
8773 return 1;
8774 return 0;
8775 }
8776
perf_tp_event_match(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)8777 static int perf_tp_event_match(struct perf_event *event,
8778 struct perf_sample_data *data,
8779 struct pt_regs *regs)
8780 {
8781 if (event->hw.state & PERF_HES_STOPPED)
8782 return 0;
8783 /*
8784 * If exclude_kernel, only trace user-space tracepoints (uprobes)
8785 */
8786 if (event->attr.exclude_kernel && !user_mode(regs))
8787 return 0;
8788
8789 if (!perf_tp_filter_match(event, data))
8790 return 0;
8791
8792 return 1;
8793 }
8794
perf_trace_run_bpf_submit(void * raw_data,int size,int rctx,struct trace_event_call * call,u64 count,struct pt_regs * regs,struct hlist_head * head,struct task_struct * task)8795 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx,
8796 struct trace_event_call *call, u64 count,
8797 struct pt_regs *regs, struct hlist_head *head,
8798 struct task_struct *task)
8799 {
8800 if (bpf_prog_array_valid(call)) {
8801 *(struct pt_regs **)raw_data = regs;
8802 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) {
8803 perf_swevent_put_recursion_context(rctx);
8804 return;
8805 }
8806 }
8807 perf_tp_event(call->event.type, count, raw_data, size, regs, head,
8808 rctx, task);
8809 }
8810 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit);
8811
perf_tp_event(u16 event_type,u64 count,void * record,int entry_size,struct pt_regs * regs,struct hlist_head * head,int rctx,struct task_struct * task)8812 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size,
8813 struct pt_regs *regs, struct hlist_head *head, int rctx,
8814 struct task_struct *task)
8815 {
8816 struct perf_sample_data data;
8817 struct perf_event *event;
8818
8819 struct perf_raw_record raw = {
8820 .frag = {
8821 .size = entry_size,
8822 .data = record,
8823 },
8824 };
8825
8826 perf_sample_data_init(&data, 0, 0);
8827 data.raw = &raw;
8828
8829 perf_trace_buf_update(record, event_type);
8830
8831 hlist_for_each_entry_rcu(event, head, hlist_entry) {
8832 if (perf_tp_event_match(event, &data, regs))
8833 perf_swevent_event(event, count, &data, regs);
8834 }
8835
8836 /*
8837 * If we got specified a target task, also iterate its context and
8838 * deliver this event there too.
8839 */
8840 if (task && task != current) {
8841 struct perf_event_context *ctx;
8842 struct trace_entry *entry = record;
8843
8844 rcu_read_lock();
8845 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]);
8846 if (!ctx)
8847 goto unlock;
8848
8849 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
8850 if (event->cpu != smp_processor_id())
8851 continue;
8852 if (event->attr.type != PERF_TYPE_TRACEPOINT)
8853 continue;
8854 if (event->attr.config != entry->type)
8855 continue;
8856 if (perf_tp_event_match(event, &data, regs))
8857 perf_swevent_event(event, count, &data, regs);
8858 }
8859 unlock:
8860 rcu_read_unlock();
8861 }
8862
8863 perf_swevent_put_recursion_context(rctx);
8864 }
8865 EXPORT_SYMBOL_GPL(perf_tp_event);
8866
tp_perf_event_destroy(struct perf_event * event)8867 static void tp_perf_event_destroy(struct perf_event *event)
8868 {
8869 perf_trace_destroy(event);
8870 }
8871
perf_tp_event_init(struct perf_event * event)8872 static int perf_tp_event_init(struct perf_event *event)
8873 {
8874 int err;
8875
8876 if (event->attr.type != PERF_TYPE_TRACEPOINT)
8877 return -ENOENT;
8878
8879 /*
8880 * no branch sampling for tracepoint events
8881 */
8882 if (has_branch_stack(event))
8883 return -EOPNOTSUPP;
8884
8885 err = perf_trace_init(event);
8886 if (err)
8887 return err;
8888
8889 event->destroy = tp_perf_event_destroy;
8890
8891 return 0;
8892 }
8893
8894 static struct pmu perf_tracepoint = {
8895 .task_ctx_nr = perf_sw_context,
8896
8897 .event_init = perf_tp_event_init,
8898 .add = perf_trace_add,
8899 .del = perf_trace_del,
8900 .start = perf_swevent_start,
8901 .stop = perf_swevent_stop,
8902 .read = perf_swevent_read,
8903 };
8904
8905 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS)
8906 /*
8907 * Flags in config, used by dynamic PMU kprobe and uprobe
8908 * The flags should match following PMU_FORMAT_ATTR().
8909 *
8910 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe
8911 * if not set, create kprobe/uprobe
8912 *
8913 * The following values specify a reference counter (or semaphore in the
8914 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically
8915 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset.
8916 *
8917 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset
8918 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left
8919 */
8920 enum perf_probe_config {
8921 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */
8922 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32,
8923 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS,
8924 };
8925
8926 PMU_FORMAT_ATTR(retprobe, "config:0");
8927 #endif
8928
8929 #ifdef CONFIG_KPROBE_EVENTS
8930 static struct attribute *kprobe_attrs[] = {
8931 &format_attr_retprobe.attr,
8932 NULL,
8933 };
8934
8935 static struct attribute_group kprobe_format_group = {
8936 .name = "format",
8937 .attrs = kprobe_attrs,
8938 };
8939
8940 static const struct attribute_group *kprobe_attr_groups[] = {
8941 &kprobe_format_group,
8942 NULL,
8943 };
8944
8945 static int perf_kprobe_event_init(struct perf_event *event);
8946 static struct pmu perf_kprobe = {
8947 .task_ctx_nr = perf_sw_context,
8948 .event_init = perf_kprobe_event_init,
8949 .add = perf_trace_add,
8950 .del = perf_trace_del,
8951 .start = perf_swevent_start,
8952 .stop = perf_swevent_stop,
8953 .read = perf_swevent_read,
8954 .attr_groups = kprobe_attr_groups,
8955 };
8956
perf_kprobe_event_init(struct perf_event * event)8957 static int perf_kprobe_event_init(struct perf_event *event)
8958 {
8959 int err;
8960 bool is_retprobe;
8961
8962 if (event->attr.type != perf_kprobe.type)
8963 return -ENOENT;
8964
8965 if (!capable(CAP_SYS_ADMIN))
8966 return -EACCES;
8967
8968 /*
8969 * no branch sampling for probe events
8970 */
8971 if (has_branch_stack(event))
8972 return -EOPNOTSUPP;
8973
8974 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
8975 err = perf_kprobe_init(event, is_retprobe);
8976 if (err)
8977 return err;
8978
8979 event->destroy = perf_kprobe_destroy;
8980
8981 return 0;
8982 }
8983 #endif /* CONFIG_KPROBE_EVENTS */
8984
8985 #ifdef CONFIG_UPROBE_EVENTS
8986 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63");
8987
8988 static struct attribute *uprobe_attrs[] = {
8989 &format_attr_retprobe.attr,
8990 &format_attr_ref_ctr_offset.attr,
8991 NULL,
8992 };
8993
8994 static struct attribute_group uprobe_format_group = {
8995 .name = "format",
8996 .attrs = uprobe_attrs,
8997 };
8998
8999 static const struct attribute_group *uprobe_attr_groups[] = {
9000 &uprobe_format_group,
9001 NULL,
9002 };
9003
9004 static int perf_uprobe_event_init(struct perf_event *event);
9005 static struct pmu perf_uprobe = {
9006 .task_ctx_nr = perf_sw_context,
9007 .event_init = perf_uprobe_event_init,
9008 .add = perf_trace_add,
9009 .del = perf_trace_del,
9010 .start = perf_swevent_start,
9011 .stop = perf_swevent_stop,
9012 .read = perf_swevent_read,
9013 .attr_groups = uprobe_attr_groups,
9014 };
9015
perf_uprobe_event_init(struct perf_event * event)9016 static int perf_uprobe_event_init(struct perf_event *event)
9017 {
9018 int err;
9019 unsigned long ref_ctr_offset;
9020 bool is_retprobe;
9021
9022 if (event->attr.type != perf_uprobe.type)
9023 return -ENOENT;
9024
9025 if (!capable(CAP_SYS_ADMIN))
9026 return -EACCES;
9027
9028 /*
9029 * no branch sampling for probe events
9030 */
9031 if (has_branch_stack(event))
9032 return -EOPNOTSUPP;
9033
9034 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE;
9035 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT;
9036 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe);
9037 if (err)
9038 return err;
9039
9040 event->destroy = perf_uprobe_destroy;
9041
9042 return 0;
9043 }
9044 #endif /* CONFIG_UPROBE_EVENTS */
9045
perf_tp_register(void)9046 static inline void perf_tp_register(void)
9047 {
9048 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
9049 #ifdef CONFIG_KPROBE_EVENTS
9050 perf_pmu_register(&perf_kprobe, "kprobe", -1);
9051 #endif
9052 #ifdef CONFIG_UPROBE_EVENTS
9053 perf_pmu_register(&perf_uprobe, "uprobe", -1);
9054 #endif
9055 }
9056
perf_event_free_filter(struct perf_event * event)9057 static void perf_event_free_filter(struct perf_event *event)
9058 {
9059 ftrace_profile_free_filter(event);
9060 }
9061
9062 #ifdef CONFIG_BPF_SYSCALL
bpf_overflow_handler(struct perf_event * event,struct perf_sample_data * data,struct pt_regs * regs)9063 static void bpf_overflow_handler(struct perf_event *event,
9064 struct perf_sample_data *data,
9065 struct pt_regs *regs)
9066 {
9067 struct bpf_perf_event_data_kern ctx = {
9068 .data = data,
9069 .event = event,
9070 };
9071 int ret = 0;
9072
9073 ctx.regs = perf_arch_bpf_user_pt_regs(regs);
9074 preempt_disable();
9075 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1))
9076 goto out;
9077 rcu_read_lock();
9078 ret = BPF_PROG_RUN(event->prog, &ctx);
9079 rcu_read_unlock();
9080 out:
9081 __this_cpu_dec(bpf_prog_active);
9082 preempt_enable();
9083 if (!ret)
9084 return;
9085
9086 event->orig_overflow_handler(event, data, regs);
9087 }
9088
perf_event_set_bpf_handler(struct perf_event * event,u32 prog_fd)9089 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9090 {
9091 struct bpf_prog *prog;
9092
9093 if (event->overflow_handler_context)
9094 /* hw breakpoint or kernel counter */
9095 return -EINVAL;
9096
9097 if (event->prog)
9098 return -EEXIST;
9099
9100 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT);
9101 if (IS_ERR(prog))
9102 return PTR_ERR(prog);
9103
9104 event->prog = prog;
9105 event->orig_overflow_handler = READ_ONCE(event->overflow_handler);
9106 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler);
9107 return 0;
9108 }
9109
perf_event_free_bpf_handler(struct perf_event * event)9110 static void perf_event_free_bpf_handler(struct perf_event *event)
9111 {
9112 struct bpf_prog *prog = event->prog;
9113
9114 if (!prog)
9115 return;
9116
9117 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler);
9118 event->prog = NULL;
9119 bpf_prog_put(prog);
9120 }
9121 #else
perf_event_set_bpf_handler(struct perf_event * event,u32 prog_fd)9122 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd)
9123 {
9124 return -EOPNOTSUPP;
9125 }
perf_event_free_bpf_handler(struct perf_event * event)9126 static void perf_event_free_bpf_handler(struct perf_event *event)
9127 {
9128 }
9129 #endif
9130
9131 /*
9132 * returns true if the event is a tracepoint, or a kprobe/upprobe created
9133 * with perf_event_open()
9134 */
perf_event_is_tracing(struct perf_event * event)9135 static inline bool perf_event_is_tracing(struct perf_event *event)
9136 {
9137 if (event->pmu == &perf_tracepoint)
9138 return true;
9139 #ifdef CONFIG_KPROBE_EVENTS
9140 if (event->pmu == &perf_kprobe)
9141 return true;
9142 #endif
9143 #ifdef CONFIG_UPROBE_EVENTS
9144 if (event->pmu == &perf_uprobe)
9145 return true;
9146 #endif
9147 return false;
9148 }
9149
perf_event_set_bpf_prog(struct perf_event * event,u32 prog_fd)9150 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9151 {
9152 bool is_kprobe, is_tracepoint, is_syscall_tp;
9153 struct bpf_prog *prog;
9154 int ret;
9155
9156 if (!perf_event_is_tracing(event))
9157 return perf_event_set_bpf_handler(event, prog_fd);
9158
9159 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE;
9160 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT;
9161 is_syscall_tp = is_syscall_trace_event(event->tp_event);
9162 if (!is_kprobe && !is_tracepoint && !is_syscall_tp)
9163 /* bpf programs can only be attached to u/kprobe or tracepoint */
9164 return -EINVAL;
9165
9166 prog = bpf_prog_get(prog_fd);
9167 if (IS_ERR(prog))
9168 return PTR_ERR(prog);
9169
9170 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) ||
9171 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) ||
9172 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) {
9173 /* valid fd, but invalid bpf program type */
9174 bpf_prog_put(prog);
9175 return -EINVAL;
9176 }
9177
9178 /* Kprobe override only works for kprobes, not uprobes. */
9179 if (prog->kprobe_override &&
9180 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) {
9181 bpf_prog_put(prog);
9182 return -EINVAL;
9183 }
9184
9185 if (is_tracepoint || is_syscall_tp) {
9186 int off = trace_event_get_offsets(event->tp_event);
9187
9188 if (prog->aux->max_ctx_offset > off) {
9189 bpf_prog_put(prog);
9190 return -EACCES;
9191 }
9192 }
9193
9194 ret = perf_event_attach_bpf_prog(event, prog);
9195 if (ret)
9196 bpf_prog_put(prog);
9197 return ret;
9198 }
9199
perf_event_free_bpf_prog(struct perf_event * event)9200 static void perf_event_free_bpf_prog(struct perf_event *event)
9201 {
9202 if (!perf_event_is_tracing(event)) {
9203 perf_event_free_bpf_handler(event);
9204 return;
9205 }
9206 perf_event_detach_bpf_prog(event);
9207 }
9208
9209 #else
9210
perf_tp_register(void)9211 static inline void perf_tp_register(void)
9212 {
9213 }
9214
perf_event_free_filter(struct perf_event * event)9215 static void perf_event_free_filter(struct perf_event *event)
9216 {
9217 }
9218
perf_event_set_bpf_prog(struct perf_event * event,u32 prog_fd)9219 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd)
9220 {
9221 return -ENOENT;
9222 }
9223
perf_event_free_bpf_prog(struct perf_event * event)9224 static void perf_event_free_bpf_prog(struct perf_event *event)
9225 {
9226 }
9227 #endif /* CONFIG_EVENT_TRACING */
9228
9229 #ifdef CONFIG_HAVE_HW_BREAKPOINT
perf_bp_event(struct perf_event * bp,void * data)9230 void perf_bp_event(struct perf_event *bp, void *data)
9231 {
9232 struct perf_sample_data sample;
9233 struct pt_regs *regs = data;
9234
9235 perf_sample_data_init(&sample, bp->attr.bp_addr, 0);
9236
9237 if (!bp->hw.state && !perf_exclude_event(bp, regs))
9238 perf_swevent_event(bp, 1, &sample, regs);
9239 }
9240 #endif
9241
9242 /*
9243 * Allocate a new address filter
9244 */
9245 static struct perf_addr_filter *
perf_addr_filter_new(struct perf_event * event,struct list_head * filters)9246 perf_addr_filter_new(struct perf_event *event, struct list_head *filters)
9247 {
9248 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu);
9249 struct perf_addr_filter *filter;
9250
9251 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node);
9252 if (!filter)
9253 return NULL;
9254
9255 INIT_LIST_HEAD(&filter->entry);
9256 list_add_tail(&filter->entry, filters);
9257
9258 return filter;
9259 }
9260
free_filters_list(struct list_head * filters)9261 static void free_filters_list(struct list_head *filters)
9262 {
9263 struct perf_addr_filter *filter, *iter;
9264
9265 list_for_each_entry_safe(filter, iter, filters, entry) {
9266 path_put(&filter->path);
9267 list_del(&filter->entry);
9268 kfree(filter);
9269 }
9270 }
9271
9272 /*
9273 * Free existing address filters and optionally install new ones
9274 */
perf_addr_filters_splice(struct perf_event * event,struct list_head * head)9275 static void perf_addr_filters_splice(struct perf_event *event,
9276 struct list_head *head)
9277 {
9278 unsigned long flags;
9279 LIST_HEAD(list);
9280
9281 if (!has_addr_filter(event))
9282 return;
9283
9284 /* don't bother with children, they don't have their own filters */
9285 if (event->parent)
9286 return;
9287
9288 raw_spin_lock_irqsave(&event->addr_filters.lock, flags);
9289
9290 list_splice_init(&event->addr_filters.list, &list);
9291 if (head)
9292 list_splice(head, &event->addr_filters.list);
9293
9294 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags);
9295
9296 free_filters_list(&list);
9297 }
9298
9299 /*
9300 * Scan through mm's vmas and see if one of them matches the
9301 * @filter; if so, adjust filter's address range.
9302 * Called with mm::mmap_sem down for reading.
9303 */
perf_addr_filter_apply(struct perf_addr_filter * filter,struct mm_struct * mm,struct perf_addr_filter_range * fr)9304 static void perf_addr_filter_apply(struct perf_addr_filter *filter,
9305 struct mm_struct *mm,
9306 struct perf_addr_filter_range *fr)
9307 {
9308 struct vm_area_struct *vma;
9309
9310 for (vma = mm->mmap; vma; vma = vma->vm_next) {
9311 if (!vma->vm_file)
9312 continue;
9313
9314 if (perf_addr_filter_vma_adjust(filter, vma, fr))
9315 return;
9316 }
9317 }
9318
9319 /*
9320 * Update event's address range filters based on the
9321 * task's existing mappings, if any.
9322 */
perf_event_addr_filters_apply(struct perf_event * event)9323 static void perf_event_addr_filters_apply(struct perf_event *event)
9324 {
9325 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
9326 struct task_struct *task = READ_ONCE(event->ctx->task);
9327 struct perf_addr_filter *filter;
9328 struct mm_struct *mm = NULL;
9329 unsigned int count = 0;
9330 unsigned long flags;
9331
9332 /*
9333 * We may observe TASK_TOMBSTONE, which means that the event tear-down
9334 * will stop on the parent's child_mutex that our caller is also holding
9335 */
9336 if (task == TASK_TOMBSTONE)
9337 return;
9338
9339 if (ifh->nr_file_filters) {
9340 mm = get_task_mm(task);
9341 if (!mm)
9342 goto restart;
9343
9344 down_read(&mm->mmap_sem);
9345 }
9346
9347 raw_spin_lock_irqsave(&ifh->lock, flags);
9348 list_for_each_entry(filter, &ifh->list, entry) {
9349 if (filter->path.dentry) {
9350 /*
9351 * Adjust base offset if the filter is associated to a
9352 * binary that needs to be mapped:
9353 */
9354 event->addr_filter_ranges[count].start = 0;
9355 event->addr_filter_ranges[count].size = 0;
9356
9357 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]);
9358 } else {
9359 event->addr_filter_ranges[count].start = filter->offset;
9360 event->addr_filter_ranges[count].size = filter->size;
9361 }
9362
9363 count++;
9364 }
9365
9366 event->addr_filters_gen++;
9367 raw_spin_unlock_irqrestore(&ifh->lock, flags);
9368
9369 if (ifh->nr_file_filters) {
9370 up_read(&mm->mmap_sem);
9371
9372 mmput(mm);
9373 }
9374
9375 restart:
9376 perf_event_stop(event, 1);
9377 }
9378
9379 /*
9380 * Address range filtering: limiting the data to certain
9381 * instruction address ranges. Filters are ioctl()ed to us from
9382 * userspace as ascii strings.
9383 *
9384 * Filter string format:
9385 *
9386 * ACTION RANGE_SPEC
9387 * where ACTION is one of the
9388 * * "filter": limit the trace to this region
9389 * * "start": start tracing from this address
9390 * * "stop": stop tracing at this address/region;
9391 * RANGE_SPEC is
9392 * * for kernel addresses: <start address>[/<size>]
9393 * * for object files: <start address>[/<size>]@</path/to/object/file>
9394 *
9395 * if <size> is not specified or is zero, the range is treated as a single
9396 * address; not valid for ACTION=="filter".
9397 */
9398 enum {
9399 IF_ACT_NONE = -1,
9400 IF_ACT_FILTER,
9401 IF_ACT_START,
9402 IF_ACT_STOP,
9403 IF_SRC_FILE,
9404 IF_SRC_KERNEL,
9405 IF_SRC_FILEADDR,
9406 IF_SRC_KERNELADDR,
9407 };
9408
9409 enum {
9410 IF_STATE_ACTION = 0,
9411 IF_STATE_SOURCE,
9412 IF_STATE_END,
9413 };
9414
9415 static const match_table_t if_tokens = {
9416 { IF_ACT_FILTER, "filter" },
9417 { IF_ACT_START, "start" },
9418 { IF_ACT_STOP, "stop" },
9419 { IF_SRC_FILE, "%u/%u@%s" },
9420 { IF_SRC_KERNEL, "%u/%u" },
9421 { IF_SRC_FILEADDR, "%u@%s" },
9422 { IF_SRC_KERNELADDR, "%u" },
9423 { IF_ACT_NONE, NULL },
9424 };
9425
9426 /*
9427 * Address filter string parser
9428 */
9429 static int
perf_event_parse_addr_filter(struct perf_event * event,char * fstr,struct list_head * filters)9430 perf_event_parse_addr_filter(struct perf_event *event, char *fstr,
9431 struct list_head *filters)
9432 {
9433 struct perf_addr_filter *filter = NULL;
9434 char *start, *orig, *filename = NULL;
9435 substring_t args[MAX_OPT_ARGS];
9436 int state = IF_STATE_ACTION, token;
9437 unsigned int kernel = 0;
9438 int ret = -EINVAL;
9439
9440 orig = fstr = kstrdup(fstr, GFP_KERNEL);
9441 if (!fstr)
9442 return -ENOMEM;
9443
9444 while ((start = strsep(&fstr, " ,\n")) != NULL) {
9445 static const enum perf_addr_filter_action_t actions[] = {
9446 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER,
9447 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START,
9448 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP,
9449 };
9450 ret = -EINVAL;
9451
9452 if (!*start)
9453 continue;
9454
9455 /* filter definition begins */
9456 if (state == IF_STATE_ACTION) {
9457 filter = perf_addr_filter_new(event, filters);
9458 if (!filter)
9459 goto fail;
9460 }
9461
9462 token = match_token(start, if_tokens, args);
9463 switch (token) {
9464 case IF_ACT_FILTER:
9465 case IF_ACT_START:
9466 case IF_ACT_STOP:
9467 if (state != IF_STATE_ACTION)
9468 goto fail;
9469
9470 filter->action = actions[token];
9471 state = IF_STATE_SOURCE;
9472 break;
9473
9474 case IF_SRC_KERNELADDR:
9475 case IF_SRC_KERNEL:
9476 kernel = 1;
9477 /* fall through */
9478
9479 case IF_SRC_FILEADDR:
9480 case IF_SRC_FILE:
9481 if (state != IF_STATE_SOURCE)
9482 goto fail;
9483
9484 *args[0].to = 0;
9485 ret = kstrtoul(args[0].from, 0, &filter->offset);
9486 if (ret)
9487 goto fail;
9488
9489 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) {
9490 *args[1].to = 0;
9491 ret = kstrtoul(args[1].from, 0, &filter->size);
9492 if (ret)
9493 goto fail;
9494 }
9495
9496 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) {
9497 int fpos = token == IF_SRC_FILE ? 2 : 1;
9498
9499 kfree(filename);
9500 filename = match_strdup(&args[fpos]);
9501 if (!filename) {
9502 ret = -ENOMEM;
9503 goto fail;
9504 }
9505 }
9506
9507 state = IF_STATE_END;
9508 break;
9509
9510 default:
9511 goto fail;
9512 }
9513
9514 /*
9515 * Filter definition is fully parsed, validate and install it.
9516 * Make sure that it doesn't contradict itself or the event's
9517 * attribute.
9518 */
9519 if (state == IF_STATE_END) {
9520 ret = -EINVAL;
9521 if (kernel && event->attr.exclude_kernel)
9522 goto fail;
9523
9524 /*
9525 * ACTION "filter" must have a non-zero length region
9526 * specified.
9527 */
9528 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER &&
9529 !filter->size)
9530 goto fail;
9531
9532 if (!kernel) {
9533 if (!filename)
9534 goto fail;
9535
9536 /*
9537 * For now, we only support file-based filters
9538 * in per-task events; doing so for CPU-wide
9539 * events requires additional context switching
9540 * trickery, since same object code will be
9541 * mapped at different virtual addresses in
9542 * different processes.
9543 */
9544 ret = -EOPNOTSUPP;
9545 if (!event->ctx->task)
9546 goto fail;
9547
9548 /* look up the path and grab its inode */
9549 ret = kern_path(filename, LOOKUP_FOLLOW,
9550 &filter->path);
9551 if (ret)
9552 goto fail;
9553
9554 ret = -EINVAL;
9555 if (!filter->path.dentry ||
9556 !S_ISREG(d_inode(filter->path.dentry)
9557 ->i_mode))
9558 goto fail;
9559
9560 event->addr_filters.nr_file_filters++;
9561 }
9562
9563 /* ready to consume more filters */
9564 kfree(filename);
9565 filename = NULL;
9566 state = IF_STATE_ACTION;
9567 filter = NULL;
9568 kernel = 0;
9569 }
9570 }
9571
9572 if (state != IF_STATE_ACTION)
9573 goto fail;
9574
9575 kfree(filename);
9576 kfree(orig);
9577
9578 return 0;
9579
9580 fail:
9581 kfree(filename);
9582 free_filters_list(filters);
9583 kfree(orig);
9584
9585 return ret;
9586 }
9587
9588 static int
perf_event_set_addr_filter(struct perf_event * event,char * filter_str)9589 perf_event_set_addr_filter(struct perf_event *event, char *filter_str)
9590 {
9591 LIST_HEAD(filters);
9592 int ret;
9593
9594 /*
9595 * Since this is called in perf_ioctl() path, we're already holding
9596 * ctx::mutex.
9597 */
9598 lockdep_assert_held(&event->ctx->mutex);
9599
9600 if (WARN_ON_ONCE(event->parent))
9601 return -EINVAL;
9602
9603 ret = perf_event_parse_addr_filter(event, filter_str, &filters);
9604 if (ret)
9605 goto fail_clear_files;
9606
9607 ret = event->pmu->addr_filters_validate(&filters);
9608 if (ret)
9609 goto fail_free_filters;
9610
9611 /* remove existing filters, if any */
9612 perf_addr_filters_splice(event, &filters);
9613
9614 /* install new filters */
9615 perf_event_for_each_child(event, perf_event_addr_filters_apply);
9616
9617 return ret;
9618
9619 fail_free_filters:
9620 free_filters_list(&filters);
9621
9622 fail_clear_files:
9623 event->addr_filters.nr_file_filters = 0;
9624
9625 return ret;
9626 }
9627
perf_event_set_filter(struct perf_event * event,void __user * arg)9628 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
9629 {
9630 int ret = -EINVAL;
9631 char *filter_str;
9632
9633 filter_str = strndup_user(arg, PAGE_SIZE);
9634 if (IS_ERR(filter_str))
9635 return PTR_ERR(filter_str);
9636
9637 #ifdef CONFIG_EVENT_TRACING
9638 if (perf_event_is_tracing(event)) {
9639 struct perf_event_context *ctx = event->ctx;
9640
9641 /*
9642 * Beware, here be dragons!!
9643 *
9644 * the tracepoint muck will deadlock against ctx->mutex, but
9645 * the tracepoint stuff does not actually need it. So
9646 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we
9647 * already have a reference on ctx.
9648 *
9649 * This can result in event getting moved to a different ctx,
9650 * but that does not affect the tracepoint state.
9651 */
9652 mutex_unlock(&ctx->mutex);
9653 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
9654 mutex_lock(&ctx->mutex);
9655 } else
9656 #endif
9657 if (has_addr_filter(event))
9658 ret = perf_event_set_addr_filter(event, filter_str);
9659
9660 kfree(filter_str);
9661 return ret;
9662 }
9663
9664 /*
9665 * hrtimer based swevent callback
9666 */
9667
perf_swevent_hrtimer(struct hrtimer * hrtimer)9668 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
9669 {
9670 enum hrtimer_restart ret = HRTIMER_RESTART;
9671 struct perf_sample_data data;
9672 struct pt_regs *regs;
9673 struct perf_event *event;
9674 u64 period;
9675
9676 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
9677
9678 if (event->state != PERF_EVENT_STATE_ACTIVE)
9679 return HRTIMER_NORESTART;
9680
9681 event->pmu->read(event);
9682
9683 perf_sample_data_init(&data, 0, event->hw.last_period);
9684 regs = get_irq_regs();
9685
9686 if (regs && !perf_exclude_event(event, regs)) {
9687 if (!(event->attr.exclude_idle && is_idle_task(current)))
9688 if (__perf_event_overflow(event, 1, &data, regs))
9689 ret = HRTIMER_NORESTART;
9690 }
9691
9692 period = max_t(u64, 10000, event->hw.sample_period);
9693 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
9694
9695 return ret;
9696 }
9697
perf_swevent_start_hrtimer(struct perf_event * event)9698 static void perf_swevent_start_hrtimer(struct perf_event *event)
9699 {
9700 struct hw_perf_event *hwc = &event->hw;
9701 s64 period;
9702
9703 if (!is_sampling_event(event))
9704 return;
9705
9706 period = local64_read(&hwc->period_left);
9707 if (period) {
9708 if (period < 0)
9709 period = 10000;
9710
9711 local64_set(&hwc->period_left, 0);
9712 } else {
9713 period = max_t(u64, 10000, hwc->sample_period);
9714 }
9715 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period),
9716 HRTIMER_MODE_REL_PINNED_HARD);
9717 }
9718
perf_swevent_cancel_hrtimer(struct perf_event * event)9719 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
9720 {
9721 struct hw_perf_event *hwc = &event->hw;
9722
9723 if (is_sampling_event(event)) {
9724 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
9725 local64_set(&hwc->period_left, ktime_to_ns(remaining));
9726
9727 hrtimer_cancel(&hwc->hrtimer);
9728 }
9729 }
9730
perf_swevent_init_hrtimer(struct perf_event * event)9731 static void perf_swevent_init_hrtimer(struct perf_event *event)
9732 {
9733 struct hw_perf_event *hwc = &event->hw;
9734
9735 if (!is_sampling_event(event))
9736 return;
9737
9738 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
9739 hwc->hrtimer.function = perf_swevent_hrtimer;
9740
9741 /*
9742 * Since hrtimers have a fixed rate, we can do a static freq->period
9743 * mapping and avoid the whole period adjust feedback stuff.
9744 */
9745 if (event->attr.freq) {
9746 long freq = event->attr.sample_freq;
9747
9748 event->attr.sample_period = NSEC_PER_SEC / freq;
9749 hwc->sample_period = event->attr.sample_period;
9750 local64_set(&hwc->period_left, hwc->sample_period);
9751 hwc->last_period = hwc->sample_period;
9752 event->attr.freq = 0;
9753 }
9754 }
9755
9756 /*
9757 * Software event: cpu wall time clock
9758 */
9759
cpu_clock_event_update(struct perf_event * event)9760 static void cpu_clock_event_update(struct perf_event *event)
9761 {
9762 s64 prev;
9763 u64 now;
9764
9765 now = local_clock();
9766 prev = local64_xchg(&event->hw.prev_count, now);
9767 local64_add(now - prev, &event->count);
9768 }
9769
cpu_clock_event_start(struct perf_event * event,int flags)9770 static void cpu_clock_event_start(struct perf_event *event, int flags)
9771 {
9772 local64_set(&event->hw.prev_count, local_clock());
9773 perf_swevent_start_hrtimer(event);
9774 }
9775
cpu_clock_event_stop(struct perf_event * event,int flags)9776 static void cpu_clock_event_stop(struct perf_event *event, int flags)
9777 {
9778 perf_swevent_cancel_hrtimer(event);
9779 cpu_clock_event_update(event);
9780 }
9781
cpu_clock_event_add(struct perf_event * event,int flags)9782 static int cpu_clock_event_add(struct perf_event *event, int flags)
9783 {
9784 if (flags & PERF_EF_START)
9785 cpu_clock_event_start(event, flags);
9786 perf_event_update_userpage(event);
9787
9788 return 0;
9789 }
9790
cpu_clock_event_del(struct perf_event * event,int flags)9791 static void cpu_clock_event_del(struct perf_event *event, int flags)
9792 {
9793 cpu_clock_event_stop(event, flags);
9794 }
9795
cpu_clock_event_read(struct perf_event * event)9796 static void cpu_clock_event_read(struct perf_event *event)
9797 {
9798 cpu_clock_event_update(event);
9799 }
9800
cpu_clock_event_init(struct perf_event * event)9801 static int cpu_clock_event_init(struct perf_event *event)
9802 {
9803 if (event->attr.type != PERF_TYPE_SOFTWARE)
9804 return -ENOENT;
9805
9806 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
9807 return -ENOENT;
9808
9809 /*
9810 * no branch sampling for software events
9811 */
9812 if (has_branch_stack(event))
9813 return -EOPNOTSUPP;
9814
9815 perf_swevent_init_hrtimer(event);
9816
9817 return 0;
9818 }
9819
9820 static struct pmu perf_cpu_clock = {
9821 .task_ctx_nr = perf_sw_context,
9822
9823 .capabilities = PERF_PMU_CAP_NO_NMI,
9824
9825 .event_init = cpu_clock_event_init,
9826 .add = cpu_clock_event_add,
9827 .del = cpu_clock_event_del,
9828 .start = cpu_clock_event_start,
9829 .stop = cpu_clock_event_stop,
9830 .read = cpu_clock_event_read,
9831 };
9832
9833 /*
9834 * Software event: task time clock
9835 */
9836
task_clock_event_update(struct perf_event * event,u64 now)9837 static void task_clock_event_update(struct perf_event *event, u64 now)
9838 {
9839 u64 prev;
9840 s64 delta;
9841
9842 prev = local64_xchg(&event->hw.prev_count, now);
9843 delta = now - prev;
9844 local64_add(delta, &event->count);
9845 }
9846
task_clock_event_start(struct perf_event * event,int flags)9847 static void task_clock_event_start(struct perf_event *event, int flags)
9848 {
9849 local64_set(&event->hw.prev_count, event->ctx->time);
9850 perf_swevent_start_hrtimer(event);
9851 }
9852
task_clock_event_stop(struct perf_event * event,int flags)9853 static void task_clock_event_stop(struct perf_event *event, int flags)
9854 {
9855 perf_swevent_cancel_hrtimer(event);
9856 task_clock_event_update(event, event->ctx->time);
9857 }
9858
task_clock_event_add(struct perf_event * event,int flags)9859 static int task_clock_event_add(struct perf_event *event, int flags)
9860 {
9861 if (flags & PERF_EF_START)
9862 task_clock_event_start(event, flags);
9863 perf_event_update_userpage(event);
9864
9865 return 0;
9866 }
9867
task_clock_event_del(struct perf_event * event,int flags)9868 static void task_clock_event_del(struct perf_event *event, int flags)
9869 {
9870 task_clock_event_stop(event, PERF_EF_UPDATE);
9871 }
9872
task_clock_event_read(struct perf_event * event)9873 static void task_clock_event_read(struct perf_event *event)
9874 {
9875 u64 now = perf_clock();
9876 u64 delta = now - event->ctx->timestamp;
9877 u64 time = event->ctx->time + delta;
9878
9879 task_clock_event_update(event, time);
9880 }
9881
task_clock_event_init(struct perf_event * event)9882 static int task_clock_event_init(struct perf_event *event)
9883 {
9884 if (event->attr.type != PERF_TYPE_SOFTWARE)
9885 return -ENOENT;
9886
9887 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
9888 return -ENOENT;
9889
9890 /*
9891 * no branch sampling for software events
9892 */
9893 if (has_branch_stack(event))
9894 return -EOPNOTSUPP;
9895
9896 perf_swevent_init_hrtimer(event);
9897
9898 return 0;
9899 }
9900
9901 static struct pmu perf_task_clock = {
9902 .task_ctx_nr = perf_sw_context,
9903
9904 .capabilities = PERF_PMU_CAP_NO_NMI,
9905
9906 .event_init = task_clock_event_init,
9907 .add = task_clock_event_add,
9908 .del = task_clock_event_del,
9909 .start = task_clock_event_start,
9910 .stop = task_clock_event_stop,
9911 .read = task_clock_event_read,
9912 };
9913
perf_pmu_nop_void(struct pmu * pmu)9914 static void perf_pmu_nop_void(struct pmu *pmu)
9915 {
9916 }
9917
perf_pmu_nop_txn(struct pmu * pmu,unsigned int flags)9918 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags)
9919 {
9920 }
9921
perf_pmu_nop_int(struct pmu * pmu)9922 static int perf_pmu_nop_int(struct pmu *pmu)
9923 {
9924 return 0;
9925 }
9926
perf_event_nop_int(struct perf_event * event,u64 value)9927 static int perf_event_nop_int(struct perf_event *event, u64 value)
9928 {
9929 return 0;
9930 }
9931
9932 static DEFINE_PER_CPU(unsigned int, nop_txn_flags);
9933
perf_pmu_start_txn(struct pmu * pmu,unsigned int flags)9934 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags)
9935 {
9936 __this_cpu_write(nop_txn_flags, flags);
9937
9938 if (flags & ~PERF_PMU_TXN_ADD)
9939 return;
9940
9941 perf_pmu_disable(pmu);
9942 }
9943
perf_pmu_commit_txn(struct pmu * pmu)9944 static int perf_pmu_commit_txn(struct pmu *pmu)
9945 {
9946 unsigned int flags = __this_cpu_read(nop_txn_flags);
9947
9948 __this_cpu_write(nop_txn_flags, 0);
9949
9950 if (flags & ~PERF_PMU_TXN_ADD)
9951 return 0;
9952
9953 perf_pmu_enable(pmu);
9954 return 0;
9955 }
9956
perf_pmu_cancel_txn(struct pmu * pmu)9957 static void perf_pmu_cancel_txn(struct pmu *pmu)
9958 {
9959 unsigned int flags = __this_cpu_read(nop_txn_flags);
9960
9961 __this_cpu_write(nop_txn_flags, 0);
9962
9963 if (flags & ~PERF_PMU_TXN_ADD)
9964 return;
9965
9966 perf_pmu_enable(pmu);
9967 }
9968
perf_event_idx_default(struct perf_event * event)9969 static int perf_event_idx_default(struct perf_event *event)
9970 {
9971 return 0;
9972 }
9973
9974 /*
9975 * Ensures all contexts with the same task_ctx_nr have the same
9976 * pmu_cpu_context too.
9977 */
find_pmu_context(int ctxn)9978 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn)
9979 {
9980 struct pmu *pmu;
9981
9982 if (ctxn < 0)
9983 return NULL;
9984
9985 list_for_each_entry(pmu, &pmus, entry) {
9986 if (pmu->task_ctx_nr == ctxn)
9987 return pmu->pmu_cpu_context;
9988 }
9989
9990 return NULL;
9991 }
9992
free_pmu_context(struct pmu * pmu)9993 static void free_pmu_context(struct pmu *pmu)
9994 {
9995 /*
9996 * Static contexts such as perf_sw_context have a global lifetime
9997 * and may be shared between different PMUs. Avoid freeing them
9998 * when a single PMU is going away.
9999 */
10000 if (pmu->task_ctx_nr > perf_invalid_context)
10001 return;
10002
10003 free_percpu(pmu->pmu_cpu_context);
10004 }
10005
10006 /*
10007 * Let userspace know that this PMU supports address range filtering:
10008 */
nr_addr_filters_show(struct device * dev,struct device_attribute * attr,char * page)10009 static ssize_t nr_addr_filters_show(struct device *dev,
10010 struct device_attribute *attr,
10011 char *page)
10012 {
10013 struct pmu *pmu = dev_get_drvdata(dev);
10014
10015 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters);
10016 }
10017 DEVICE_ATTR_RO(nr_addr_filters);
10018
10019 static struct idr pmu_idr;
10020
10021 static ssize_t
type_show(struct device * dev,struct device_attribute * attr,char * page)10022 type_show(struct device *dev, struct device_attribute *attr, char *page)
10023 {
10024 struct pmu *pmu = dev_get_drvdata(dev);
10025
10026 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
10027 }
10028 static DEVICE_ATTR_RO(type);
10029
10030 static ssize_t
perf_event_mux_interval_ms_show(struct device * dev,struct device_attribute * attr,char * page)10031 perf_event_mux_interval_ms_show(struct device *dev,
10032 struct device_attribute *attr,
10033 char *page)
10034 {
10035 struct pmu *pmu = dev_get_drvdata(dev);
10036
10037 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms);
10038 }
10039
10040 static DEFINE_MUTEX(mux_interval_mutex);
10041
10042 static ssize_t
perf_event_mux_interval_ms_store(struct device * dev,struct device_attribute * attr,const char * buf,size_t count)10043 perf_event_mux_interval_ms_store(struct device *dev,
10044 struct device_attribute *attr,
10045 const char *buf, size_t count)
10046 {
10047 struct pmu *pmu = dev_get_drvdata(dev);
10048 int timer, cpu, ret;
10049
10050 ret = kstrtoint(buf, 0, &timer);
10051 if (ret)
10052 return ret;
10053
10054 if (timer < 1)
10055 return -EINVAL;
10056
10057 /* same value, noting to do */
10058 if (timer == pmu->hrtimer_interval_ms)
10059 return count;
10060
10061 mutex_lock(&mux_interval_mutex);
10062 pmu->hrtimer_interval_ms = timer;
10063
10064 /* update all cpuctx for this PMU */
10065 cpus_read_lock();
10066 for_each_online_cpu(cpu) {
10067 struct perf_cpu_context *cpuctx;
10068 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10069 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer);
10070
10071 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpuctx);
10072 }
10073 cpus_read_unlock();
10074 mutex_unlock(&mux_interval_mutex);
10075
10076 return count;
10077 }
10078 static DEVICE_ATTR_RW(perf_event_mux_interval_ms);
10079
10080 static struct attribute *pmu_dev_attrs[] = {
10081 &dev_attr_type.attr,
10082 &dev_attr_perf_event_mux_interval_ms.attr,
10083 &dev_attr_nr_addr_filters.attr,
10084 NULL,
10085 };
10086
pmu_dev_is_visible(struct kobject * kobj,struct attribute * a,int n)10087 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n)
10088 {
10089 struct device *dev = kobj_to_dev(kobj);
10090 struct pmu *pmu = dev_get_drvdata(dev);
10091
10092 if (n == 2 && !pmu->nr_addr_filters)
10093 return 0;
10094
10095 return a->mode;
10096 }
10097
10098 static struct attribute_group pmu_dev_attr_group = {
10099 .is_visible = pmu_dev_is_visible,
10100 .attrs = pmu_dev_attrs,
10101 };
10102
10103 static const struct attribute_group *pmu_dev_groups[] = {
10104 &pmu_dev_attr_group,
10105 NULL,
10106 };
10107
10108 static int pmu_bus_running;
10109 static struct bus_type pmu_bus = {
10110 .name = "event_source",
10111 .dev_groups = pmu_dev_groups,
10112 };
10113
pmu_dev_release(struct device * dev)10114 static void pmu_dev_release(struct device *dev)
10115 {
10116 kfree(dev);
10117 }
10118
pmu_dev_alloc(struct pmu * pmu)10119 static int pmu_dev_alloc(struct pmu *pmu)
10120 {
10121 int ret = -ENOMEM;
10122
10123 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
10124 if (!pmu->dev)
10125 goto out;
10126
10127 pmu->dev->groups = pmu->attr_groups;
10128 device_initialize(pmu->dev);
10129
10130 dev_set_drvdata(pmu->dev, pmu);
10131 pmu->dev->bus = &pmu_bus;
10132 pmu->dev->release = pmu_dev_release;
10133
10134 ret = dev_set_name(pmu->dev, "%s", pmu->name);
10135 if (ret)
10136 goto free_dev;
10137
10138 ret = device_add(pmu->dev);
10139 if (ret)
10140 goto free_dev;
10141
10142 if (pmu->attr_update) {
10143 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update);
10144 if (ret)
10145 goto del_dev;
10146 }
10147
10148 out:
10149 return ret;
10150
10151 del_dev:
10152 device_del(pmu->dev);
10153
10154 free_dev:
10155 put_device(pmu->dev);
10156 goto out;
10157 }
10158
10159 static struct lock_class_key cpuctx_mutex;
10160 static struct lock_class_key cpuctx_lock;
10161
perf_pmu_register(struct pmu * pmu,const char * name,int type)10162 int perf_pmu_register(struct pmu *pmu, const char *name, int type)
10163 {
10164 int cpu, ret;
10165
10166 mutex_lock(&pmus_lock);
10167 ret = -ENOMEM;
10168 pmu->pmu_disable_count = alloc_percpu(int);
10169 if (!pmu->pmu_disable_count)
10170 goto unlock;
10171
10172 pmu->type = -1;
10173 if (!name)
10174 goto skip_type;
10175 pmu->name = name;
10176
10177 if (type < 0) {
10178 type = idr_alloc(&pmu_idr, pmu, PERF_TYPE_MAX, 0, GFP_KERNEL);
10179 if (type < 0) {
10180 ret = type;
10181 goto free_pdc;
10182 }
10183 }
10184 pmu->type = type;
10185
10186 if (pmu_bus_running) {
10187 ret = pmu_dev_alloc(pmu);
10188 if (ret)
10189 goto free_idr;
10190 }
10191
10192 skip_type:
10193 if (pmu->task_ctx_nr == perf_hw_context) {
10194 static int hw_context_taken = 0;
10195
10196 /*
10197 * Other than systems with heterogeneous CPUs, it never makes
10198 * sense for two PMUs to share perf_hw_context. PMUs which are
10199 * uncore must use perf_invalid_context.
10200 */
10201 if (WARN_ON_ONCE(hw_context_taken &&
10202 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS)))
10203 pmu->task_ctx_nr = perf_invalid_context;
10204
10205 hw_context_taken = 1;
10206 }
10207
10208 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
10209 if (pmu->pmu_cpu_context)
10210 goto got_cpu_context;
10211
10212 ret = -ENOMEM;
10213 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
10214 if (!pmu->pmu_cpu_context)
10215 goto free_dev;
10216
10217 for_each_possible_cpu(cpu) {
10218 struct perf_cpu_context *cpuctx;
10219
10220 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
10221 __perf_event_init_context(&cpuctx->ctx);
10222 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
10223 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock);
10224 cpuctx->ctx.pmu = pmu;
10225 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask);
10226
10227 __perf_mux_hrtimer_init(cpuctx, cpu);
10228 }
10229
10230 got_cpu_context:
10231 if (!pmu->start_txn) {
10232 if (pmu->pmu_enable) {
10233 /*
10234 * If we have pmu_enable/pmu_disable calls, install
10235 * transaction stubs that use that to try and batch
10236 * hardware accesses.
10237 */
10238 pmu->start_txn = perf_pmu_start_txn;
10239 pmu->commit_txn = perf_pmu_commit_txn;
10240 pmu->cancel_txn = perf_pmu_cancel_txn;
10241 } else {
10242 pmu->start_txn = perf_pmu_nop_txn;
10243 pmu->commit_txn = perf_pmu_nop_int;
10244 pmu->cancel_txn = perf_pmu_nop_void;
10245 }
10246 }
10247
10248 if (!pmu->pmu_enable) {
10249 pmu->pmu_enable = perf_pmu_nop_void;
10250 pmu->pmu_disable = perf_pmu_nop_void;
10251 }
10252
10253 if (!pmu->check_period)
10254 pmu->check_period = perf_event_nop_int;
10255
10256 if (!pmu->event_idx)
10257 pmu->event_idx = perf_event_idx_default;
10258
10259 list_add_rcu(&pmu->entry, &pmus);
10260 atomic_set(&pmu->exclusive_cnt, 0);
10261 ret = 0;
10262 unlock:
10263 mutex_unlock(&pmus_lock);
10264
10265 return ret;
10266
10267 free_dev:
10268 device_del(pmu->dev);
10269 put_device(pmu->dev);
10270
10271 free_idr:
10272 if (pmu->type >= PERF_TYPE_MAX)
10273 idr_remove(&pmu_idr, pmu->type);
10274
10275 free_pdc:
10276 free_percpu(pmu->pmu_disable_count);
10277 goto unlock;
10278 }
10279 EXPORT_SYMBOL_GPL(perf_pmu_register);
10280
perf_pmu_unregister(struct pmu * pmu)10281 void perf_pmu_unregister(struct pmu *pmu)
10282 {
10283 mutex_lock(&pmus_lock);
10284 list_del_rcu(&pmu->entry);
10285
10286 /*
10287 * We dereference the pmu list under both SRCU and regular RCU, so
10288 * synchronize against both of those.
10289 */
10290 synchronize_srcu(&pmus_srcu);
10291 synchronize_rcu();
10292
10293 free_percpu(pmu->pmu_disable_count);
10294 if (pmu->type >= PERF_TYPE_MAX)
10295 idr_remove(&pmu_idr, pmu->type);
10296 if (pmu_bus_running) {
10297 if (pmu->nr_addr_filters)
10298 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters);
10299 device_del(pmu->dev);
10300 put_device(pmu->dev);
10301 }
10302 free_pmu_context(pmu);
10303 mutex_unlock(&pmus_lock);
10304 }
10305 EXPORT_SYMBOL_GPL(perf_pmu_unregister);
10306
has_extended_regs(struct perf_event * event)10307 static inline bool has_extended_regs(struct perf_event *event)
10308 {
10309 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) ||
10310 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK);
10311 }
10312
perf_try_init_event(struct pmu * pmu,struct perf_event * event)10313 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event)
10314 {
10315 struct perf_event_context *ctx = NULL;
10316 int ret;
10317
10318 if (!try_module_get(pmu->module))
10319 return -ENODEV;
10320
10321 /*
10322 * A number of pmu->event_init() methods iterate the sibling_list to,
10323 * for example, validate if the group fits on the PMU. Therefore,
10324 * if this is a sibling event, acquire the ctx->mutex to protect
10325 * the sibling_list.
10326 */
10327 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) {
10328 /*
10329 * This ctx->mutex can nest when we're called through
10330 * inheritance. See the perf_event_ctx_lock_nested() comment.
10331 */
10332 ctx = perf_event_ctx_lock_nested(event->group_leader,
10333 SINGLE_DEPTH_NESTING);
10334 BUG_ON(!ctx);
10335 }
10336
10337 event->pmu = pmu;
10338 ret = pmu->event_init(event);
10339
10340 if (ctx)
10341 perf_event_ctx_unlock(event->group_leader, ctx);
10342
10343 if (!ret) {
10344 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) &&
10345 has_extended_regs(event))
10346 ret = -EOPNOTSUPP;
10347
10348 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE &&
10349 event_has_any_exclude_flag(event))
10350 ret = -EINVAL;
10351
10352 if (ret && event->destroy)
10353 event->destroy(event);
10354 }
10355
10356 if (ret)
10357 module_put(pmu->module);
10358
10359 return ret;
10360 }
10361
perf_init_event(struct perf_event * event)10362 static struct pmu *perf_init_event(struct perf_event *event)
10363 {
10364 struct pmu *pmu;
10365 int idx;
10366 int ret;
10367
10368 idx = srcu_read_lock(&pmus_srcu);
10369
10370 /* Try parent's PMU first: */
10371 if (event->parent && event->parent->pmu) {
10372 pmu = event->parent->pmu;
10373 ret = perf_try_init_event(pmu, event);
10374 if (!ret)
10375 goto unlock;
10376 }
10377
10378 rcu_read_lock();
10379 pmu = idr_find(&pmu_idr, event->attr.type);
10380 rcu_read_unlock();
10381 if (pmu) {
10382 ret = perf_try_init_event(pmu, event);
10383 if (ret)
10384 pmu = ERR_PTR(ret);
10385 goto unlock;
10386 }
10387
10388 list_for_each_entry_rcu(pmu, &pmus, entry) {
10389 ret = perf_try_init_event(pmu, event);
10390 if (!ret)
10391 goto unlock;
10392
10393 if (ret != -ENOENT) {
10394 pmu = ERR_PTR(ret);
10395 goto unlock;
10396 }
10397 }
10398 pmu = ERR_PTR(-ENOENT);
10399 unlock:
10400 srcu_read_unlock(&pmus_srcu, idx);
10401
10402 return pmu;
10403 }
10404
attach_sb_event(struct perf_event * event)10405 static void attach_sb_event(struct perf_event *event)
10406 {
10407 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu);
10408
10409 raw_spin_lock(&pel->lock);
10410 list_add_rcu(&event->sb_list, &pel->list);
10411 raw_spin_unlock(&pel->lock);
10412 }
10413
10414 /*
10415 * We keep a list of all !task (and therefore per-cpu) events
10416 * that need to receive side-band records.
10417 *
10418 * This avoids having to scan all the various PMU per-cpu contexts
10419 * looking for them.
10420 */
account_pmu_sb_event(struct perf_event * event)10421 static void account_pmu_sb_event(struct perf_event *event)
10422 {
10423 if (is_sb_event(event))
10424 attach_sb_event(event);
10425 }
10426
account_event_cpu(struct perf_event * event,int cpu)10427 static void account_event_cpu(struct perf_event *event, int cpu)
10428 {
10429 if (event->parent)
10430 return;
10431
10432 if (is_cgroup_event(event))
10433 atomic_inc(&per_cpu(perf_cgroup_events, cpu));
10434 }
10435
10436 /* Freq events need the tick to stay alive (see perf_event_task_tick). */
account_freq_event_nohz(void)10437 static void account_freq_event_nohz(void)
10438 {
10439 #ifdef CONFIG_NO_HZ_FULL
10440 /* Lock so we don't race with concurrent unaccount */
10441 spin_lock(&nr_freq_lock);
10442 if (atomic_inc_return(&nr_freq_events) == 1)
10443 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS);
10444 spin_unlock(&nr_freq_lock);
10445 #endif
10446 }
10447
account_freq_event(void)10448 static void account_freq_event(void)
10449 {
10450 if (tick_nohz_full_enabled())
10451 account_freq_event_nohz();
10452 else
10453 atomic_inc(&nr_freq_events);
10454 }
10455
10456
account_event(struct perf_event * event)10457 static void account_event(struct perf_event *event)
10458 {
10459 bool inc = false;
10460
10461 if (event->parent)
10462 return;
10463
10464 if (event->attach_state & PERF_ATTACH_TASK)
10465 inc = true;
10466 if (event->attr.mmap || event->attr.mmap_data)
10467 atomic_inc(&nr_mmap_events);
10468 if (event->attr.comm)
10469 atomic_inc(&nr_comm_events);
10470 if (event->attr.namespaces)
10471 atomic_inc(&nr_namespaces_events);
10472 if (event->attr.task)
10473 atomic_inc(&nr_task_events);
10474 if (event->attr.freq)
10475 account_freq_event();
10476 if (event->attr.context_switch) {
10477 atomic_inc(&nr_switch_events);
10478 inc = true;
10479 }
10480 if (has_branch_stack(event))
10481 inc = true;
10482 if (is_cgroup_event(event))
10483 inc = true;
10484 if (event->attr.ksymbol)
10485 atomic_inc(&nr_ksymbol_events);
10486 if (event->attr.bpf_event)
10487 atomic_inc(&nr_bpf_events);
10488
10489 if (inc) {
10490 /*
10491 * We need the mutex here because static_branch_enable()
10492 * must complete *before* the perf_sched_count increment
10493 * becomes visible.
10494 */
10495 if (atomic_inc_not_zero(&perf_sched_count))
10496 goto enabled;
10497
10498 mutex_lock(&perf_sched_mutex);
10499 if (!atomic_read(&perf_sched_count)) {
10500 static_branch_enable(&perf_sched_events);
10501 /*
10502 * Guarantee that all CPUs observe they key change and
10503 * call the perf scheduling hooks before proceeding to
10504 * install events that need them.
10505 */
10506 synchronize_rcu();
10507 }
10508 /*
10509 * Now that we have waited for the sync_sched(), allow further
10510 * increments to by-pass the mutex.
10511 */
10512 atomic_inc(&perf_sched_count);
10513 mutex_unlock(&perf_sched_mutex);
10514 }
10515 enabled:
10516
10517 account_event_cpu(event, event->cpu);
10518
10519 account_pmu_sb_event(event);
10520 }
10521
10522 /*
10523 * Allocate and initialize an event structure
10524 */
10525 static struct perf_event *
perf_event_alloc(struct perf_event_attr * attr,int cpu,struct task_struct * task,struct perf_event * group_leader,struct perf_event * parent_event,perf_overflow_handler_t overflow_handler,void * context,int cgroup_fd)10526 perf_event_alloc(struct perf_event_attr *attr, int cpu,
10527 struct task_struct *task,
10528 struct perf_event *group_leader,
10529 struct perf_event *parent_event,
10530 perf_overflow_handler_t overflow_handler,
10531 void *context, int cgroup_fd)
10532 {
10533 struct pmu *pmu;
10534 struct perf_event *event;
10535 struct hw_perf_event *hwc;
10536 long err = -EINVAL;
10537
10538 if ((unsigned)cpu >= nr_cpu_ids) {
10539 if (!task || cpu != -1)
10540 return ERR_PTR(-EINVAL);
10541 }
10542
10543 event = kzalloc(sizeof(*event), GFP_KERNEL);
10544 if (!event)
10545 return ERR_PTR(-ENOMEM);
10546
10547 /*
10548 * Single events are their own group leaders, with an
10549 * empty sibling list:
10550 */
10551 if (!group_leader)
10552 group_leader = event;
10553
10554 mutex_init(&event->child_mutex);
10555 INIT_LIST_HEAD(&event->child_list);
10556
10557 INIT_LIST_HEAD(&event->event_entry);
10558 INIT_LIST_HEAD(&event->sibling_list);
10559 INIT_LIST_HEAD(&event->active_list);
10560 init_event_group(event);
10561 INIT_LIST_HEAD(&event->rb_entry);
10562 INIT_LIST_HEAD(&event->active_entry);
10563 INIT_LIST_HEAD(&event->addr_filters.list);
10564 INIT_HLIST_NODE(&event->hlist_entry);
10565
10566
10567 init_waitqueue_head(&event->waitq);
10568 event->pending_disable = -1;
10569 init_irq_work(&event->pending, perf_pending_event);
10570
10571 mutex_init(&event->mmap_mutex);
10572 raw_spin_lock_init(&event->addr_filters.lock);
10573
10574 atomic_long_set(&event->refcount, 1);
10575 event->cpu = cpu;
10576 event->attr = *attr;
10577 event->group_leader = group_leader;
10578 event->pmu = NULL;
10579 event->oncpu = -1;
10580
10581 event->parent = parent_event;
10582
10583 event->ns = get_pid_ns(task_active_pid_ns(current));
10584 event->id = atomic64_inc_return(&perf_event_id);
10585
10586 event->state = PERF_EVENT_STATE_INACTIVE;
10587
10588 if (task) {
10589 event->attach_state = PERF_ATTACH_TASK;
10590 /*
10591 * XXX pmu::event_init needs to know what task to account to
10592 * and we cannot use the ctx information because we need the
10593 * pmu before we get a ctx.
10594 */
10595 event->hw.target = get_task_struct(task);
10596 }
10597
10598 event->clock = &local_clock;
10599 if (parent_event)
10600 event->clock = parent_event->clock;
10601
10602 if (!overflow_handler && parent_event) {
10603 overflow_handler = parent_event->overflow_handler;
10604 context = parent_event->overflow_handler_context;
10605 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING)
10606 if (overflow_handler == bpf_overflow_handler) {
10607 struct bpf_prog *prog = bpf_prog_inc(parent_event->prog);
10608
10609 if (IS_ERR(prog)) {
10610 err = PTR_ERR(prog);
10611 goto err_ns;
10612 }
10613 event->prog = prog;
10614 event->orig_overflow_handler =
10615 parent_event->orig_overflow_handler;
10616 }
10617 #endif
10618 }
10619
10620 if (overflow_handler) {
10621 event->overflow_handler = overflow_handler;
10622 event->overflow_handler_context = context;
10623 } else if (is_write_backward(event)){
10624 event->overflow_handler = perf_event_output_backward;
10625 event->overflow_handler_context = NULL;
10626 } else {
10627 event->overflow_handler = perf_event_output_forward;
10628 event->overflow_handler_context = NULL;
10629 }
10630
10631 perf_event__state_init(event);
10632
10633 pmu = NULL;
10634
10635 hwc = &event->hw;
10636 hwc->sample_period = attr->sample_period;
10637 if (attr->freq && attr->sample_freq)
10638 hwc->sample_period = 1;
10639 hwc->last_period = hwc->sample_period;
10640
10641 local64_set(&hwc->period_left, hwc->sample_period);
10642
10643 /*
10644 * We currently do not support PERF_SAMPLE_READ on inherited events.
10645 * See perf_output_read().
10646 */
10647 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ))
10648 goto err_ns;
10649
10650 if (!has_branch_stack(event))
10651 event->attr.branch_sample_type = 0;
10652
10653 if (cgroup_fd != -1) {
10654 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader);
10655 if (err)
10656 goto err_ns;
10657 }
10658
10659 pmu = perf_init_event(event);
10660 if (IS_ERR(pmu)) {
10661 err = PTR_ERR(pmu);
10662 goto err_ns;
10663 }
10664
10665 /*
10666 * Disallow uncore-cgroup events, they don't make sense as the cgroup will
10667 * be different on other CPUs in the uncore mask.
10668 */
10669 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) {
10670 err = -EINVAL;
10671 goto err_pmu;
10672 }
10673
10674 if (event->attr.aux_output &&
10675 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) {
10676 err = -EOPNOTSUPP;
10677 goto err_pmu;
10678 }
10679
10680 err = exclusive_event_init(event);
10681 if (err)
10682 goto err_pmu;
10683
10684 if (has_addr_filter(event)) {
10685 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters,
10686 sizeof(struct perf_addr_filter_range),
10687 GFP_KERNEL);
10688 if (!event->addr_filter_ranges) {
10689 err = -ENOMEM;
10690 goto err_per_task;
10691 }
10692
10693 /*
10694 * Clone the parent's vma offsets: they are valid until exec()
10695 * even if the mm is not shared with the parent.
10696 */
10697 if (event->parent) {
10698 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event);
10699
10700 raw_spin_lock_irq(&ifh->lock);
10701 memcpy(event->addr_filter_ranges,
10702 event->parent->addr_filter_ranges,
10703 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range));
10704 raw_spin_unlock_irq(&ifh->lock);
10705 }
10706
10707 /* force hw sync on the address filters */
10708 event->addr_filters_gen = 1;
10709 }
10710
10711 if (!event->parent) {
10712 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
10713 err = get_callchain_buffers(attr->sample_max_stack);
10714 if (err)
10715 goto err_addr_filters;
10716 }
10717 }
10718
10719 err = security_perf_event_alloc(event);
10720 if (err)
10721 goto err_callchain_buffer;
10722
10723 /* symmetric to unaccount_event() in _free_event() */
10724 account_event(event);
10725
10726 return event;
10727
10728 err_callchain_buffer:
10729 if (!event->parent) {
10730 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
10731 put_callchain_buffers();
10732 }
10733 err_addr_filters:
10734 kfree(event->addr_filter_ranges);
10735
10736 err_per_task:
10737 exclusive_event_destroy(event);
10738
10739 err_pmu:
10740 if (event->destroy)
10741 event->destroy(event);
10742 module_put(pmu->module);
10743 err_ns:
10744 if (is_cgroup_event(event))
10745 perf_detach_cgroup(event);
10746 if (event->ns)
10747 put_pid_ns(event->ns);
10748 if (event->hw.target)
10749 put_task_struct(event->hw.target);
10750 kfree(event);
10751
10752 return ERR_PTR(err);
10753 }
10754
perf_copy_attr(struct perf_event_attr __user * uattr,struct perf_event_attr * attr)10755 static int perf_copy_attr(struct perf_event_attr __user *uattr,
10756 struct perf_event_attr *attr)
10757 {
10758 u32 size;
10759 int ret;
10760
10761 /* Zero the full structure, so that a short copy will be nice. */
10762 memset(attr, 0, sizeof(*attr));
10763
10764 ret = get_user(size, &uattr->size);
10765 if (ret)
10766 return ret;
10767
10768 /* ABI compatibility quirk: */
10769 if (!size)
10770 size = PERF_ATTR_SIZE_VER0;
10771 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE)
10772 goto err_size;
10773
10774 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
10775 if (ret) {
10776 if (ret == -E2BIG)
10777 goto err_size;
10778 return ret;
10779 }
10780
10781 attr->size = size;
10782
10783 if (attr->__reserved_1 || attr->__reserved_2)
10784 return -EINVAL;
10785
10786 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
10787 return -EINVAL;
10788
10789 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
10790 return -EINVAL;
10791
10792 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) {
10793 u64 mask = attr->branch_sample_type;
10794
10795 /* only using defined bits */
10796 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1))
10797 return -EINVAL;
10798
10799 /* at least one branch bit must be set */
10800 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL))
10801 return -EINVAL;
10802
10803 /* propagate priv level, when not set for branch */
10804 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) {
10805
10806 /* exclude_kernel checked on syscall entry */
10807 if (!attr->exclude_kernel)
10808 mask |= PERF_SAMPLE_BRANCH_KERNEL;
10809
10810 if (!attr->exclude_user)
10811 mask |= PERF_SAMPLE_BRANCH_USER;
10812
10813 if (!attr->exclude_hv)
10814 mask |= PERF_SAMPLE_BRANCH_HV;
10815 /*
10816 * adjust user setting (for HW filter setup)
10817 */
10818 attr->branch_sample_type = mask;
10819 }
10820 /* privileged levels capture (kernel, hv): check permissions */
10821 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) {
10822 ret = perf_allow_kernel(attr);
10823 if (ret)
10824 return ret;
10825 }
10826 }
10827
10828 if (attr->sample_type & PERF_SAMPLE_REGS_USER) {
10829 ret = perf_reg_validate(attr->sample_regs_user);
10830 if (ret)
10831 return ret;
10832 }
10833
10834 if (attr->sample_type & PERF_SAMPLE_STACK_USER) {
10835 if (!arch_perf_have_user_stack_dump())
10836 return -ENOSYS;
10837
10838 /*
10839 * We have __u32 type for the size, but so far
10840 * we can only use __u16 as maximum due to the
10841 * __u16 sample size limit.
10842 */
10843 if (attr->sample_stack_user >= USHRT_MAX)
10844 return -EINVAL;
10845 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64)))
10846 return -EINVAL;
10847 }
10848
10849 if (!attr->sample_max_stack)
10850 attr->sample_max_stack = sysctl_perf_event_max_stack;
10851
10852 if (attr->sample_type & PERF_SAMPLE_REGS_INTR)
10853 ret = perf_reg_validate(attr->sample_regs_intr);
10854 out:
10855 return ret;
10856
10857 err_size:
10858 put_user(sizeof(*attr), &uattr->size);
10859 ret = -E2BIG;
10860 goto out;
10861 }
10862
mutex_lock_double(struct mutex * a,struct mutex * b)10863 static void mutex_lock_double(struct mutex *a, struct mutex *b)
10864 {
10865 if (b < a)
10866 swap(a, b);
10867
10868 mutex_lock(a);
10869 mutex_lock_nested(b, SINGLE_DEPTH_NESTING);
10870 }
10871
10872 static int
perf_event_set_output(struct perf_event * event,struct perf_event * output_event)10873 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
10874 {
10875 struct ring_buffer *rb = NULL;
10876 int ret = -EINVAL;
10877
10878 if (!output_event) {
10879 mutex_lock(&event->mmap_mutex);
10880 goto set;
10881 }
10882
10883 /* don't allow circular references */
10884 if (event == output_event)
10885 goto out;
10886
10887 /*
10888 * Don't allow cross-cpu buffers
10889 */
10890 if (output_event->cpu != event->cpu)
10891 goto out;
10892
10893 /*
10894 * If its not a per-cpu rb, it must be the same task.
10895 */
10896 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target)
10897 goto out;
10898
10899 /*
10900 * Mixing clocks in the same buffer is trouble you don't need.
10901 */
10902 if (output_event->clock != event->clock)
10903 goto out;
10904
10905 /*
10906 * Either writing ring buffer from beginning or from end.
10907 * Mixing is not allowed.
10908 */
10909 if (is_write_backward(output_event) != is_write_backward(event))
10910 goto out;
10911
10912 /*
10913 * If both events generate aux data, they must be on the same PMU
10914 */
10915 if (has_aux(event) && has_aux(output_event) &&
10916 event->pmu != output_event->pmu)
10917 goto out;
10918
10919 /*
10920 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since
10921 * output_event is already on rb->event_list, and the list iteration
10922 * restarts after every removal, it is guaranteed this new event is
10923 * observed *OR* if output_event is already removed, it's guaranteed we
10924 * observe !rb->mmap_count.
10925 */
10926 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex);
10927 set:
10928 /* Can't redirect output if we've got an active mmap() */
10929 if (atomic_read(&event->mmap_count))
10930 goto unlock;
10931
10932 if (output_event) {
10933 /* get the rb we want to redirect to */
10934 rb = ring_buffer_get(output_event);
10935 if (!rb)
10936 goto unlock;
10937
10938 /* did we race against perf_mmap_close() */
10939 if (!atomic_read(&rb->mmap_count)) {
10940 ring_buffer_put(rb);
10941 goto unlock;
10942 }
10943 }
10944
10945 ring_buffer_attach(event, rb);
10946
10947 ret = 0;
10948 unlock:
10949 mutex_unlock(&event->mmap_mutex);
10950 if (output_event)
10951 mutex_unlock(&output_event->mmap_mutex);
10952
10953 out:
10954 return ret;
10955 }
10956
perf_event_set_clock(struct perf_event * event,clockid_t clk_id)10957 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id)
10958 {
10959 bool nmi_safe = false;
10960
10961 switch (clk_id) {
10962 case CLOCK_MONOTONIC:
10963 event->clock = &ktime_get_mono_fast_ns;
10964 nmi_safe = true;
10965 break;
10966
10967 case CLOCK_MONOTONIC_RAW:
10968 event->clock = &ktime_get_raw_fast_ns;
10969 nmi_safe = true;
10970 break;
10971
10972 case CLOCK_REALTIME:
10973 event->clock = &ktime_get_real_ns;
10974 break;
10975
10976 case CLOCK_BOOTTIME:
10977 event->clock = &ktime_get_boottime_ns;
10978 break;
10979
10980 case CLOCK_TAI:
10981 event->clock = &ktime_get_clocktai_ns;
10982 break;
10983
10984 default:
10985 return -EINVAL;
10986 }
10987
10988 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI))
10989 return -EINVAL;
10990
10991 return 0;
10992 }
10993
10994 /*
10995 * Variation on perf_event_ctx_lock_nested(), except we take two context
10996 * mutexes.
10997 */
10998 static struct perf_event_context *
__perf_event_ctx_lock_double(struct perf_event * group_leader,struct perf_event_context * ctx)10999 __perf_event_ctx_lock_double(struct perf_event *group_leader,
11000 struct perf_event_context *ctx)
11001 {
11002 struct perf_event_context *gctx;
11003
11004 again:
11005 rcu_read_lock();
11006 gctx = READ_ONCE(group_leader->ctx);
11007 if (!refcount_inc_not_zero(&gctx->refcount)) {
11008 rcu_read_unlock();
11009 goto again;
11010 }
11011 rcu_read_unlock();
11012
11013 mutex_lock_double(&gctx->mutex, &ctx->mutex);
11014
11015 if (group_leader->ctx != gctx) {
11016 mutex_unlock(&ctx->mutex);
11017 mutex_unlock(&gctx->mutex);
11018 put_ctx(gctx);
11019 goto again;
11020 }
11021
11022 return gctx;
11023 }
11024
11025 /**
11026 * sys_perf_event_open - open a performance event, associate it to a task/cpu
11027 *
11028 * @attr_uptr: event_id type attributes for monitoring/sampling
11029 * @pid: target pid
11030 * @cpu: target cpu
11031 * @group_fd: group leader event fd
11032 */
SYSCALL_DEFINE5(perf_event_open,struct perf_event_attr __user *,attr_uptr,pid_t,pid,int,cpu,int,group_fd,unsigned long,flags)11033 SYSCALL_DEFINE5(perf_event_open,
11034 struct perf_event_attr __user *, attr_uptr,
11035 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
11036 {
11037 struct perf_event *group_leader = NULL, *output_event = NULL;
11038 struct perf_event *event, *sibling;
11039 struct perf_event_attr attr;
11040 struct perf_event_context *ctx, *gctx;
11041 struct file *event_file = NULL;
11042 struct fd group = {NULL, 0};
11043 struct task_struct *task = NULL;
11044 struct pmu *pmu;
11045 int event_fd;
11046 int move_group = 0;
11047 int err;
11048 int f_flags = O_RDWR;
11049 int cgroup_fd = -1;
11050
11051 /* for future expandability... */
11052 if (flags & ~PERF_FLAG_ALL)
11053 return -EINVAL;
11054
11055 err = perf_copy_attr(attr_uptr, &attr);
11056 if (err)
11057 return err;
11058
11059 /* Do we allow access to perf_event_open(2) ? */
11060 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN);
11061 if (err)
11062 return err;
11063
11064 if (!attr.exclude_kernel) {
11065 err = perf_allow_kernel(&attr);
11066 if (err)
11067 return err;
11068 }
11069
11070 if (attr.namespaces) {
11071 if (!capable(CAP_SYS_ADMIN))
11072 return -EACCES;
11073 }
11074
11075 if (attr.freq) {
11076 if (attr.sample_freq > sysctl_perf_event_sample_rate)
11077 return -EINVAL;
11078 } else {
11079 if (attr.sample_period & (1ULL << 63))
11080 return -EINVAL;
11081 }
11082
11083 /* Only privileged users can get physical addresses */
11084 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) {
11085 err = perf_allow_kernel(&attr);
11086 if (err)
11087 return err;
11088 }
11089
11090 /* REGS_INTR can leak data, lockdown must prevent this */
11091 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) {
11092 err = security_locked_down(LOCKDOWN_PERF);
11093 if (err)
11094 return err;
11095 }
11096
11097 /*
11098 * In cgroup mode, the pid argument is used to pass the fd
11099 * opened to the cgroup directory in cgroupfs. The cpu argument
11100 * designates the cpu on which to monitor threads from that
11101 * cgroup.
11102 */
11103 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1))
11104 return -EINVAL;
11105
11106 if (flags & PERF_FLAG_FD_CLOEXEC)
11107 f_flags |= O_CLOEXEC;
11108
11109 event_fd = get_unused_fd_flags(f_flags);
11110 if (event_fd < 0)
11111 return event_fd;
11112
11113 if (group_fd != -1) {
11114 err = perf_fget_light(group_fd, &group);
11115 if (err)
11116 goto err_fd;
11117 group_leader = group.file->private_data;
11118 if (flags & PERF_FLAG_FD_OUTPUT)
11119 output_event = group_leader;
11120 if (flags & PERF_FLAG_FD_NO_GROUP)
11121 group_leader = NULL;
11122 }
11123
11124 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) {
11125 task = find_lively_task_by_vpid(pid);
11126 if (IS_ERR(task)) {
11127 err = PTR_ERR(task);
11128 goto err_group_fd;
11129 }
11130 }
11131
11132 if (task && group_leader &&
11133 group_leader->attr.inherit != attr.inherit) {
11134 err = -EINVAL;
11135 goto err_task;
11136 }
11137
11138 if (task) {
11139 err = mutex_lock_interruptible(&task->signal->cred_guard_mutex);
11140 if (err)
11141 goto err_task;
11142
11143 /*
11144 * Reuse ptrace permission checks for now.
11145 *
11146 * We must hold cred_guard_mutex across this and any potential
11147 * perf_install_in_context() call for this new event to
11148 * serialize against exec() altering our credentials (and the
11149 * perf_event_exit_task() that could imply).
11150 */
11151 err = -EACCES;
11152 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS))
11153 goto err_cred;
11154 }
11155
11156 if (flags & PERF_FLAG_PID_CGROUP)
11157 cgroup_fd = pid;
11158
11159 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL,
11160 NULL, NULL, cgroup_fd);
11161 if (IS_ERR(event)) {
11162 err = PTR_ERR(event);
11163 goto err_cred;
11164 }
11165
11166 if (is_sampling_event(event)) {
11167 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) {
11168 err = -EOPNOTSUPP;
11169 goto err_alloc;
11170 }
11171 }
11172
11173 /*
11174 * Special case software events and allow them to be part of
11175 * any hardware group.
11176 */
11177 pmu = event->pmu;
11178
11179 if (attr.use_clockid) {
11180 err = perf_event_set_clock(event, attr.clockid);
11181 if (err)
11182 goto err_alloc;
11183 }
11184
11185 if (pmu->task_ctx_nr == perf_sw_context)
11186 event->event_caps |= PERF_EV_CAP_SOFTWARE;
11187
11188 if (group_leader) {
11189 if (is_software_event(event) &&
11190 !in_software_context(group_leader)) {
11191 /*
11192 * If the event is a sw event, but the group_leader
11193 * is on hw context.
11194 *
11195 * Allow the addition of software events to hw
11196 * groups, this is safe because software events
11197 * never fail to schedule.
11198 */
11199 pmu = group_leader->ctx->pmu;
11200 } else if (!is_software_event(event) &&
11201 is_software_event(group_leader) &&
11202 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11203 /*
11204 * In case the group is a pure software group, and we
11205 * try to add a hardware event, move the whole group to
11206 * the hardware context.
11207 */
11208 move_group = 1;
11209 }
11210 }
11211
11212 /*
11213 * Get the target context (task or percpu):
11214 */
11215 ctx = find_get_context(pmu, task, event);
11216 if (IS_ERR(ctx)) {
11217 err = PTR_ERR(ctx);
11218 goto err_alloc;
11219 }
11220
11221 /*
11222 * Look up the group leader (we will attach this event to it):
11223 */
11224 if (group_leader) {
11225 err = -EINVAL;
11226
11227 /*
11228 * Do not allow a recursive hierarchy (this new sibling
11229 * becoming part of another group-sibling):
11230 */
11231 if (group_leader->group_leader != group_leader)
11232 goto err_context;
11233
11234 /* All events in a group should have the same clock */
11235 if (group_leader->clock != event->clock)
11236 goto err_context;
11237
11238 /*
11239 * Make sure we're both events for the same CPU;
11240 * grouping events for different CPUs is broken; since
11241 * you can never concurrently schedule them anyhow.
11242 */
11243 if (group_leader->cpu != event->cpu)
11244 goto err_context;
11245
11246 /*
11247 * Make sure we're both on the same task, or both
11248 * per-CPU events.
11249 */
11250 if (group_leader->ctx->task != ctx->task)
11251 goto err_context;
11252
11253 /*
11254 * Do not allow to attach to a group in a different task
11255 * or CPU context. If we're moving SW events, we'll fix
11256 * this up later, so allow that.
11257 *
11258 * Racy, not holding group_leader->ctx->mutex, see comment with
11259 * perf_event_ctx_lock().
11260 */
11261 if (!move_group && group_leader->ctx != ctx)
11262 goto err_context;
11263
11264 /*
11265 * Only a group leader can be exclusive or pinned
11266 */
11267 if (attr.exclusive || attr.pinned)
11268 goto err_context;
11269 }
11270
11271 if (output_event) {
11272 err = perf_event_set_output(event, output_event);
11273 if (err)
11274 goto err_context;
11275 }
11276
11277 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event,
11278 f_flags);
11279 if (IS_ERR(event_file)) {
11280 err = PTR_ERR(event_file);
11281 event_file = NULL;
11282 goto err_context;
11283 }
11284
11285 if (move_group) {
11286 gctx = __perf_event_ctx_lock_double(group_leader, ctx);
11287
11288 if (gctx->task == TASK_TOMBSTONE) {
11289 err = -ESRCH;
11290 goto err_locked;
11291 }
11292
11293 /*
11294 * Check if we raced against another sys_perf_event_open() call
11295 * moving the software group underneath us.
11296 */
11297 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) {
11298 /*
11299 * If someone moved the group out from under us, check
11300 * if this new event wound up on the same ctx, if so
11301 * its the regular !move_group case, otherwise fail.
11302 */
11303 if (gctx != ctx) {
11304 err = -EINVAL;
11305 goto err_locked;
11306 } else {
11307 perf_event_ctx_unlock(group_leader, gctx);
11308 move_group = 0;
11309 goto not_move_group;
11310 }
11311 }
11312
11313 /*
11314 * Failure to create exclusive events returns -EBUSY.
11315 */
11316 err = -EBUSY;
11317 if (!exclusive_event_installable(group_leader, ctx))
11318 goto err_locked;
11319
11320 for_each_sibling_event(sibling, group_leader) {
11321 if (!exclusive_event_installable(sibling, ctx))
11322 goto err_locked;
11323 }
11324 } else {
11325 mutex_lock(&ctx->mutex);
11326
11327 /*
11328 * Now that we hold ctx->lock, (re)validate group_leader->ctx == ctx,
11329 * see the group_leader && !move_group test earlier.
11330 */
11331 if (group_leader && group_leader->ctx != ctx) {
11332 err = -EINVAL;
11333 goto err_locked;
11334 }
11335 }
11336 not_move_group:
11337
11338 if (ctx->task == TASK_TOMBSTONE) {
11339 err = -ESRCH;
11340 goto err_locked;
11341 }
11342
11343 if (!perf_event_validate_size(event)) {
11344 err = -E2BIG;
11345 goto err_locked;
11346 }
11347
11348 if (!task) {
11349 /*
11350 * Check if the @cpu we're creating an event for is online.
11351 *
11352 * We use the perf_cpu_context::ctx::mutex to serialize against
11353 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11354 */
11355 struct perf_cpu_context *cpuctx =
11356 container_of(ctx, struct perf_cpu_context, ctx);
11357
11358 if (!cpuctx->online) {
11359 err = -ENODEV;
11360 goto err_locked;
11361 }
11362 }
11363
11364 if (event->attr.aux_output && !perf_get_aux_event(event, group_leader)) {
11365 err = -EINVAL;
11366 goto err_locked;
11367 }
11368
11369 /*
11370 * Must be under the same ctx::mutex as perf_install_in_context(),
11371 * because we need to serialize with concurrent event creation.
11372 */
11373 if (!exclusive_event_installable(event, ctx)) {
11374 err = -EBUSY;
11375 goto err_locked;
11376 }
11377
11378 WARN_ON_ONCE(ctx->parent_ctx);
11379
11380 /*
11381 * This is the point on no return; we cannot fail hereafter. This is
11382 * where we start modifying current state.
11383 */
11384
11385 if (move_group) {
11386 /*
11387 * See perf_event_ctx_lock() for comments on the details
11388 * of swizzling perf_event::ctx.
11389 */
11390 perf_remove_from_context(group_leader, 0);
11391 put_ctx(gctx);
11392
11393 for_each_sibling_event(sibling, group_leader) {
11394 perf_remove_from_context(sibling, 0);
11395 put_ctx(gctx);
11396 }
11397
11398 /*
11399 * Wait for everybody to stop referencing the events through
11400 * the old lists, before installing it on new lists.
11401 */
11402 synchronize_rcu();
11403
11404 /*
11405 * Install the group siblings before the group leader.
11406 *
11407 * Because a group leader will try and install the entire group
11408 * (through the sibling list, which is still in-tact), we can
11409 * end up with siblings installed in the wrong context.
11410 *
11411 * By installing siblings first we NO-OP because they're not
11412 * reachable through the group lists.
11413 */
11414 for_each_sibling_event(sibling, group_leader) {
11415 perf_event__state_init(sibling);
11416 perf_install_in_context(ctx, sibling, sibling->cpu);
11417 get_ctx(ctx);
11418 }
11419
11420 /*
11421 * Removing from the context ends up with disabled
11422 * event. What we want here is event in the initial
11423 * startup state, ready to be add into new context.
11424 */
11425 perf_event__state_init(group_leader);
11426 perf_install_in_context(ctx, group_leader, group_leader->cpu);
11427 get_ctx(ctx);
11428 }
11429
11430 /*
11431 * Precalculate sample_data sizes; do while holding ctx::mutex such
11432 * that we're serialized against further additions and before
11433 * perf_install_in_context() which is the point the event is active and
11434 * can use these values.
11435 */
11436 perf_event__header_size(event);
11437 perf_event__id_header_size(event);
11438
11439 event->owner = current;
11440
11441 perf_install_in_context(ctx, event, event->cpu);
11442 perf_unpin_context(ctx);
11443
11444 if (move_group)
11445 perf_event_ctx_unlock(group_leader, gctx);
11446 mutex_unlock(&ctx->mutex);
11447
11448 if (task) {
11449 mutex_unlock(&task->signal->cred_guard_mutex);
11450 put_task_struct(task);
11451 }
11452
11453 mutex_lock(¤t->perf_event_mutex);
11454 list_add_tail(&event->owner_entry, ¤t->perf_event_list);
11455 mutex_unlock(¤t->perf_event_mutex);
11456
11457 /*
11458 * Drop the reference on the group_event after placing the
11459 * new event on the sibling_list. This ensures destruction
11460 * of the group leader will find the pointer to itself in
11461 * perf_group_detach().
11462 */
11463 fdput(group);
11464 fd_install(event_fd, event_file);
11465 return event_fd;
11466
11467 err_locked:
11468 if (move_group)
11469 perf_event_ctx_unlock(group_leader, gctx);
11470 mutex_unlock(&ctx->mutex);
11471 /* err_file: */
11472 fput(event_file);
11473 err_context:
11474 perf_unpin_context(ctx);
11475 put_ctx(ctx);
11476 err_alloc:
11477 /*
11478 * If event_file is set, the fput() above will have called ->release()
11479 * and that will take care of freeing the event.
11480 */
11481 if (!event_file)
11482 free_event(event);
11483 err_cred:
11484 if (task)
11485 mutex_unlock(&task->signal->cred_guard_mutex);
11486 err_task:
11487 if (task)
11488 put_task_struct(task);
11489 err_group_fd:
11490 fdput(group);
11491 err_fd:
11492 put_unused_fd(event_fd);
11493 return err;
11494 }
11495
11496 /**
11497 * perf_event_create_kernel_counter
11498 *
11499 * @attr: attributes of the counter to create
11500 * @cpu: cpu in which the counter is bound
11501 * @task: task to profile (NULL for percpu)
11502 */
11503 struct perf_event *
perf_event_create_kernel_counter(struct perf_event_attr * attr,int cpu,struct task_struct * task,perf_overflow_handler_t overflow_handler,void * context)11504 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
11505 struct task_struct *task,
11506 perf_overflow_handler_t overflow_handler,
11507 void *context)
11508 {
11509 struct perf_event_context *ctx;
11510 struct perf_event *event;
11511 int err;
11512
11513 /*
11514 * Grouping is not supported for kernel events, neither is 'AUX',
11515 * make sure the caller's intentions are adjusted.
11516 */
11517 if (attr->aux_output)
11518 return ERR_PTR(-EINVAL);
11519
11520 event = perf_event_alloc(attr, cpu, task, NULL, NULL,
11521 overflow_handler, context, -1);
11522 if (IS_ERR(event)) {
11523 err = PTR_ERR(event);
11524 goto err;
11525 }
11526
11527 /* Mark owner so we could distinguish it from user events. */
11528 event->owner = TASK_TOMBSTONE;
11529
11530 /*
11531 * Get the target context (task or percpu):
11532 */
11533 ctx = find_get_context(event->pmu, task, event);
11534 if (IS_ERR(ctx)) {
11535 err = PTR_ERR(ctx);
11536 goto err_free;
11537 }
11538
11539 WARN_ON_ONCE(ctx->parent_ctx);
11540 mutex_lock(&ctx->mutex);
11541 if (ctx->task == TASK_TOMBSTONE) {
11542 err = -ESRCH;
11543 goto err_unlock;
11544 }
11545
11546 if (!task) {
11547 /*
11548 * Check if the @cpu we're creating an event for is online.
11549 *
11550 * We use the perf_cpu_context::ctx::mutex to serialize against
11551 * the hotplug notifiers. See perf_event_{init,exit}_cpu().
11552 */
11553 struct perf_cpu_context *cpuctx =
11554 container_of(ctx, struct perf_cpu_context, ctx);
11555 if (!cpuctx->online) {
11556 err = -ENODEV;
11557 goto err_unlock;
11558 }
11559 }
11560
11561 if (!exclusive_event_installable(event, ctx)) {
11562 err = -EBUSY;
11563 goto err_unlock;
11564 }
11565
11566 perf_install_in_context(ctx, event, event->cpu);
11567 perf_unpin_context(ctx);
11568 mutex_unlock(&ctx->mutex);
11569
11570 return event;
11571
11572 err_unlock:
11573 mutex_unlock(&ctx->mutex);
11574 perf_unpin_context(ctx);
11575 put_ctx(ctx);
11576 err_free:
11577 free_event(event);
11578 err:
11579 return ERR_PTR(err);
11580 }
11581 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
11582
perf_pmu_migrate_context(struct pmu * pmu,int src_cpu,int dst_cpu)11583 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu)
11584 {
11585 struct perf_event_context *src_ctx;
11586 struct perf_event_context *dst_ctx;
11587 struct perf_event *event, *tmp;
11588 LIST_HEAD(events);
11589
11590 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx;
11591 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx;
11592
11593 /*
11594 * See perf_event_ctx_lock() for comments on the details
11595 * of swizzling perf_event::ctx.
11596 */
11597 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex);
11598 list_for_each_entry_safe(event, tmp, &src_ctx->event_list,
11599 event_entry) {
11600 perf_remove_from_context(event, 0);
11601 unaccount_event_cpu(event, src_cpu);
11602 put_ctx(src_ctx);
11603 list_add(&event->migrate_entry, &events);
11604 }
11605
11606 /*
11607 * Wait for the events to quiesce before re-instating them.
11608 */
11609 synchronize_rcu();
11610
11611 /*
11612 * Re-instate events in 2 passes.
11613 *
11614 * Skip over group leaders and only install siblings on this first
11615 * pass, siblings will not get enabled without a leader, however a
11616 * leader will enable its siblings, even if those are still on the old
11617 * context.
11618 */
11619 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
11620 if (event->group_leader == event)
11621 continue;
11622
11623 list_del(&event->migrate_entry);
11624 if (event->state >= PERF_EVENT_STATE_OFF)
11625 event->state = PERF_EVENT_STATE_INACTIVE;
11626 account_event_cpu(event, dst_cpu);
11627 perf_install_in_context(dst_ctx, event, dst_cpu);
11628 get_ctx(dst_ctx);
11629 }
11630
11631 /*
11632 * Once all the siblings are setup properly, install the group leaders
11633 * to make it go.
11634 */
11635 list_for_each_entry_safe(event, tmp, &events, migrate_entry) {
11636 list_del(&event->migrate_entry);
11637 if (event->state >= PERF_EVENT_STATE_OFF)
11638 event->state = PERF_EVENT_STATE_INACTIVE;
11639 account_event_cpu(event, dst_cpu);
11640 perf_install_in_context(dst_ctx, event, dst_cpu);
11641 get_ctx(dst_ctx);
11642 }
11643 mutex_unlock(&dst_ctx->mutex);
11644 mutex_unlock(&src_ctx->mutex);
11645 }
11646 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context);
11647
sync_child_event(struct perf_event * child_event,struct task_struct * child)11648 static void sync_child_event(struct perf_event *child_event,
11649 struct task_struct *child)
11650 {
11651 struct perf_event *parent_event = child_event->parent;
11652 u64 child_val;
11653
11654 if (child_event->attr.inherit_stat)
11655 perf_event_read_event(child_event, child);
11656
11657 child_val = perf_event_count(child_event);
11658
11659 /*
11660 * Add back the child's count to the parent's count:
11661 */
11662 atomic64_add(child_val, &parent_event->child_count);
11663 atomic64_add(child_event->total_time_enabled,
11664 &parent_event->child_total_time_enabled);
11665 atomic64_add(child_event->total_time_running,
11666 &parent_event->child_total_time_running);
11667 }
11668
11669 static void
perf_event_exit_event(struct perf_event * child_event,struct perf_event_context * child_ctx,struct task_struct * child)11670 perf_event_exit_event(struct perf_event *child_event,
11671 struct perf_event_context *child_ctx,
11672 struct task_struct *child)
11673 {
11674 struct perf_event *parent_event = child_event->parent;
11675
11676 /*
11677 * Do not destroy the 'original' grouping; because of the context
11678 * switch optimization the original events could've ended up in a
11679 * random child task.
11680 *
11681 * If we were to destroy the original group, all group related
11682 * operations would cease to function properly after this random
11683 * child dies.
11684 *
11685 * Do destroy all inherited groups, we don't care about those
11686 * and being thorough is better.
11687 */
11688 raw_spin_lock_irq(&child_ctx->lock);
11689 WARN_ON_ONCE(child_ctx->is_active);
11690
11691 if (parent_event)
11692 perf_group_detach(child_event);
11693 list_del_event(child_event, child_ctx);
11694 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */
11695 raw_spin_unlock_irq(&child_ctx->lock);
11696
11697 /*
11698 * Parent events are governed by their filedesc, retain them.
11699 */
11700 if (!parent_event) {
11701 perf_event_wakeup(child_event);
11702 return;
11703 }
11704 /*
11705 * Child events can be cleaned up.
11706 */
11707
11708 sync_child_event(child_event, child);
11709
11710 /*
11711 * Remove this event from the parent's list
11712 */
11713 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
11714 mutex_lock(&parent_event->child_mutex);
11715 list_del_init(&child_event->child_list);
11716 mutex_unlock(&parent_event->child_mutex);
11717
11718 /*
11719 * Kick perf_poll() for is_event_hup().
11720 */
11721 perf_event_wakeup(parent_event);
11722 free_event(child_event);
11723 put_event(parent_event);
11724 }
11725
perf_event_exit_task_context(struct task_struct * child,int ctxn)11726 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
11727 {
11728 struct perf_event_context *child_ctx, *clone_ctx = NULL;
11729 struct perf_event *child_event, *next;
11730
11731 WARN_ON_ONCE(child != current);
11732
11733 child_ctx = perf_pin_task_context(child, ctxn);
11734 if (!child_ctx)
11735 return;
11736
11737 /*
11738 * In order to reduce the amount of tricky in ctx tear-down, we hold
11739 * ctx::mutex over the entire thing. This serializes against almost
11740 * everything that wants to access the ctx.
11741 *
11742 * The exception is sys_perf_event_open() /
11743 * perf_event_create_kernel_count() which does find_get_context()
11744 * without ctx::mutex (it cannot because of the move_group double mutex
11745 * lock thing). See the comments in perf_install_in_context().
11746 */
11747 mutex_lock(&child_ctx->mutex);
11748
11749 /*
11750 * In a single ctx::lock section, de-schedule the events and detach the
11751 * context from the task such that we cannot ever get it scheduled back
11752 * in.
11753 */
11754 raw_spin_lock_irq(&child_ctx->lock);
11755 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL);
11756
11757 /*
11758 * Now that the context is inactive, destroy the task <-> ctx relation
11759 * and mark the context dead.
11760 */
11761 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL);
11762 put_ctx(child_ctx); /* cannot be last */
11763 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE);
11764 put_task_struct(current); /* cannot be last */
11765
11766 clone_ctx = unclone_ctx(child_ctx);
11767 raw_spin_unlock_irq(&child_ctx->lock);
11768
11769 if (clone_ctx)
11770 put_ctx(clone_ctx);
11771
11772 /*
11773 * Report the task dead after unscheduling the events so that we
11774 * won't get any samples after PERF_RECORD_EXIT. We can however still
11775 * get a few PERF_RECORD_READ events.
11776 */
11777 perf_event_task(child, child_ctx, 0);
11778
11779 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry)
11780 perf_event_exit_event(child_event, child_ctx, child);
11781
11782 mutex_unlock(&child_ctx->mutex);
11783
11784 put_ctx(child_ctx);
11785 }
11786
11787 /*
11788 * When a child task exits, feed back event values to parent events.
11789 *
11790 * Can be called with cred_guard_mutex held when called from
11791 * install_exec_creds().
11792 */
perf_event_exit_task(struct task_struct * child)11793 void perf_event_exit_task(struct task_struct *child)
11794 {
11795 struct perf_event *event, *tmp;
11796 int ctxn;
11797
11798 mutex_lock(&child->perf_event_mutex);
11799 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
11800 owner_entry) {
11801 list_del_init(&event->owner_entry);
11802
11803 /*
11804 * Ensure the list deletion is visible before we clear
11805 * the owner, closes a race against perf_release() where
11806 * we need to serialize on the owner->perf_event_mutex.
11807 */
11808 smp_store_release(&event->owner, NULL);
11809 }
11810 mutex_unlock(&child->perf_event_mutex);
11811
11812 for_each_task_context_nr(ctxn)
11813 perf_event_exit_task_context(child, ctxn);
11814
11815 /*
11816 * The perf_event_exit_task_context calls perf_event_task
11817 * with child's task_ctx, which generates EXIT events for
11818 * child contexts and sets child->perf_event_ctxp[] to NULL.
11819 * At this point we need to send EXIT events to cpu contexts.
11820 */
11821 perf_event_task(child, NULL, 0);
11822 }
11823
perf_free_event(struct perf_event * event,struct perf_event_context * ctx)11824 static void perf_free_event(struct perf_event *event,
11825 struct perf_event_context *ctx)
11826 {
11827 struct perf_event *parent = event->parent;
11828
11829 if (WARN_ON_ONCE(!parent))
11830 return;
11831
11832 mutex_lock(&parent->child_mutex);
11833 list_del_init(&event->child_list);
11834 mutex_unlock(&parent->child_mutex);
11835
11836 put_event(parent);
11837
11838 raw_spin_lock_irq(&ctx->lock);
11839 perf_group_detach(event);
11840 list_del_event(event, ctx);
11841 raw_spin_unlock_irq(&ctx->lock);
11842 free_event(event);
11843 }
11844
11845 /*
11846 * Free a context as created by inheritance by perf_event_init_task() below,
11847 * used by fork() in case of fail.
11848 *
11849 * Even though the task has never lived, the context and events have been
11850 * exposed through the child_list, so we must take care tearing it all down.
11851 */
perf_event_free_task(struct task_struct * task)11852 void perf_event_free_task(struct task_struct *task)
11853 {
11854 struct perf_event_context *ctx;
11855 struct perf_event *event, *tmp;
11856 int ctxn;
11857
11858 for_each_task_context_nr(ctxn) {
11859 ctx = task->perf_event_ctxp[ctxn];
11860 if (!ctx)
11861 continue;
11862
11863 mutex_lock(&ctx->mutex);
11864 raw_spin_lock_irq(&ctx->lock);
11865 /*
11866 * Destroy the task <-> ctx relation and mark the context dead.
11867 *
11868 * This is important because even though the task hasn't been
11869 * exposed yet the context has been (through child_list).
11870 */
11871 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL);
11872 WRITE_ONCE(ctx->task, TASK_TOMBSTONE);
11873 put_task_struct(task); /* cannot be last */
11874 raw_spin_unlock_irq(&ctx->lock);
11875
11876 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry)
11877 perf_free_event(event, ctx);
11878
11879 mutex_unlock(&ctx->mutex);
11880
11881 /*
11882 * perf_event_release_kernel() could've stolen some of our
11883 * child events and still have them on its free_list. In that
11884 * case we must wait for these events to have been freed (in
11885 * particular all their references to this task must've been
11886 * dropped).
11887 *
11888 * Without this copy_process() will unconditionally free this
11889 * task (irrespective of its reference count) and
11890 * _free_event()'s put_task_struct(event->hw.target) will be a
11891 * use-after-free.
11892 *
11893 * Wait for all events to drop their context reference.
11894 */
11895 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1);
11896 put_ctx(ctx); /* must be last */
11897 }
11898 }
11899
perf_event_delayed_put(struct task_struct * task)11900 void perf_event_delayed_put(struct task_struct *task)
11901 {
11902 int ctxn;
11903
11904 for_each_task_context_nr(ctxn)
11905 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
11906 }
11907
perf_event_get(unsigned int fd)11908 struct file *perf_event_get(unsigned int fd)
11909 {
11910 struct file *file = fget(fd);
11911 if (!file)
11912 return ERR_PTR(-EBADF);
11913
11914 if (file->f_op != &perf_fops) {
11915 fput(file);
11916 return ERR_PTR(-EBADF);
11917 }
11918
11919 return file;
11920 }
11921
perf_get_event(struct file * file)11922 const struct perf_event *perf_get_event(struct file *file)
11923 {
11924 if (file->f_op != &perf_fops)
11925 return ERR_PTR(-EINVAL);
11926
11927 return file->private_data;
11928 }
11929
perf_event_attrs(struct perf_event * event)11930 const struct perf_event_attr *perf_event_attrs(struct perf_event *event)
11931 {
11932 if (!event)
11933 return ERR_PTR(-EINVAL);
11934
11935 return &event->attr;
11936 }
11937
11938 /*
11939 * Inherit an event from parent task to child task.
11940 *
11941 * Returns:
11942 * - valid pointer on success
11943 * - NULL for orphaned events
11944 * - IS_ERR() on error
11945 */
11946 static struct perf_event *
inherit_event(struct perf_event * parent_event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,struct perf_event * group_leader,struct perf_event_context * child_ctx)11947 inherit_event(struct perf_event *parent_event,
11948 struct task_struct *parent,
11949 struct perf_event_context *parent_ctx,
11950 struct task_struct *child,
11951 struct perf_event *group_leader,
11952 struct perf_event_context *child_ctx)
11953 {
11954 enum perf_event_state parent_state = parent_event->state;
11955 struct perf_event *child_event;
11956 unsigned long flags;
11957
11958 /*
11959 * Instead of creating recursive hierarchies of events,
11960 * we link inherited events back to the original parent,
11961 * which has a filp for sure, which we use as the reference
11962 * count:
11963 */
11964 if (parent_event->parent)
11965 parent_event = parent_event->parent;
11966
11967 child_event = perf_event_alloc(&parent_event->attr,
11968 parent_event->cpu,
11969 child,
11970 group_leader, parent_event,
11971 NULL, NULL, -1);
11972 if (IS_ERR(child_event))
11973 return child_event;
11974
11975
11976 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) &&
11977 !child_ctx->task_ctx_data) {
11978 struct pmu *pmu = child_event->pmu;
11979
11980 child_ctx->task_ctx_data = kzalloc(pmu->task_ctx_size,
11981 GFP_KERNEL);
11982 if (!child_ctx->task_ctx_data) {
11983 free_event(child_event);
11984 return ERR_PTR(-ENOMEM);
11985 }
11986 }
11987
11988 /*
11989 * is_orphaned_event() and list_add_tail(&parent_event->child_list)
11990 * must be under the same lock in order to serialize against
11991 * perf_event_release_kernel(), such that either we must observe
11992 * is_orphaned_event() or they will observe us on the child_list.
11993 */
11994 mutex_lock(&parent_event->child_mutex);
11995 if (is_orphaned_event(parent_event) ||
11996 !atomic_long_inc_not_zero(&parent_event->refcount)) {
11997 mutex_unlock(&parent_event->child_mutex);
11998 /* task_ctx_data is freed with child_ctx */
11999 free_event(child_event);
12000 return NULL;
12001 }
12002
12003 get_ctx(child_ctx);
12004
12005 /*
12006 * Make the child state follow the state of the parent event,
12007 * not its attr.disabled bit. We hold the parent's mutex,
12008 * so we won't race with perf_event_{en, dis}able_family.
12009 */
12010 if (parent_state >= PERF_EVENT_STATE_INACTIVE)
12011 child_event->state = PERF_EVENT_STATE_INACTIVE;
12012 else
12013 child_event->state = PERF_EVENT_STATE_OFF;
12014
12015 if (parent_event->attr.freq) {
12016 u64 sample_period = parent_event->hw.sample_period;
12017 struct hw_perf_event *hwc = &child_event->hw;
12018
12019 hwc->sample_period = sample_period;
12020 hwc->last_period = sample_period;
12021
12022 local64_set(&hwc->period_left, sample_period);
12023 }
12024
12025 child_event->ctx = child_ctx;
12026 child_event->overflow_handler = parent_event->overflow_handler;
12027 child_event->overflow_handler_context
12028 = parent_event->overflow_handler_context;
12029
12030 /*
12031 * Precalculate sample_data sizes
12032 */
12033 perf_event__header_size(child_event);
12034 perf_event__id_header_size(child_event);
12035
12036 /*
12037 * Link it up in the child's context:
12038 */
12039 raw_spin_lock_irqsave(&child_ctx->lock, flags);
12040 add_event_to_ctx(child_event, child_ctx);
12041 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
12042
12043 /*
12044 * Link this into the parent event's child list
12045 */
12046 list_add_tail(&child_event->child_list, &parent_event->child_list);
12047 mutex_unlock(&parent_event->child_mutex);
12048
12049 return child_event;
12050 }
12051
12052 /*
12053 * Inherits an event group.
12054 *
12055 * This will quietly suppress orphaned events; !inherit_event() is not an error.
12056 * This matches with perf_event_release_kernel() removing all child events.
12057 *
12058 * Returns:
12059 * - 0 on success
12060 * - <0 on error
12061 */
inherit_group(struct perf_event * parent_event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,struct perf_event_context * child_ctx)12062 static int inherit_group(struct perf_event *parent_event,
12063 struct task_struct *parent,
12064 struct perf_event_context *parent_ctx,
12065 struct task_struct *child,
12066 struct perf_event_context *child_ctx)
12067 {
12068 struct perf_event *leader;
12069 struct perf_event *sub;
12070 struct perf_event *child_ctr;
12071
12072 leader = inherit_event(parent_event, parent, parent_ctx,
12073 child, NULL, child_ctx);
12074 if (IS_ERR(leader))
12075 return PTR_ERR(leader);
12076 /*
12077 * @leader can be NULL here because of is_orphaned_event(). In this
12078 * case inherit_event() will create individual events, similar to what
12079 * perf_group_detach() would do anyway.
12080 */
12081 for_each_sibling_event(sub, parent_event) {
12082 child_ctr = inherit_event(sub, parent, parent_ctx,
12083 child, leader, child_ctx);
12084 if (IS_ERR(child_ctr))
12085 return PTR_ERR(child_ctr);
12086
12087 if (sub->aux_event == parent_event && child_ctr &&
12088 !perf_get_aux_event(child_ctr, leader))
12089 return -EINVAL;
12090 }
12091 leader->group_generation = parent_event->group_generation;
12092 return 0;
12093 }
12094
12095 /*
12096 * Creates the child task context and tries to inherit the event-group.
12097 *
12098 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave
12099 * inherited_all set when we 'fail' to inherit an orphaned event; this is
12100 * consistent with perf_event_release_kernel() removing all child events.
12101 *
12102 * Returns:
12103 * - 0 on success
12104 * - <0 on error
12105 */
12106 static int
inherit_task_group(struct perf_event * event,struct task_struct * parent,struct perf_event_context * parent_ctx,struct task_struct * child,int ctxn,int * inherited_all)12107 inherit_task_group(struct perf_event *event, struct task_struct *parent,
12108 struct perf_event_context *parent_ctx,
12109 struct task_struct *child, int ctxn,
12110 int *inherited_all)
12111 {
12112 int ret;
12113 struct perf_event_context *child_ctx;
12114
12115 if (!event->attr.inherit) {
12116 *inherited_all = 0;
12117 return 0;
12118 }
12119
12120 child_ctx = child->perf_event_ctxp[ctxn];
12121 if (!child_ctx) {
12122 /*
12123 * This is executed from the parent task context, so
12124 * inherit events that have been marked for cloning.
12125 * First allocate and initialize a context for the
12126 * child.
12127 */
12128 child_ctx = alloc_perf_context(parent_ctx->pmu, child);
12129 if (!child_ctx)
12130 return -ENOMEM;
12131
12132 child->perf_event_ctxp[ctxn] = child_ctx;
12133 }
12134
12135 ret = inherit_group(event, parent, parent_ctx,
12136 child, child_ctx);
12137
12138 if (ret)
12139 *inherited_all = 0;
12140
12141 return ret;
12142 }
12143
12144 /*
12145 * Initialize the perf_event context in task_struct
12146 */
perf_event_init_context(struct task_struct * child,int ctxn)12147 static int perf_event_init_context(struct task_struct *child, int ctxn)
12148 {
12149 struct perf_event_context *child_ctx, *parent_ctx;
12150 struct perf_event_context *cloned_ctx;
12151 struct perf_event *event;
12152 struct task_struct *parent = current;
12153 int inherited_all = 1;
12154 unsigned long flags;
12155 int ret = 0;
12156
12157 if (likely(!parent->perf_event_ctxp[ctxn]))
12158 return 0;
12159
12160 /*
12161 * If the parent's context is a clone, pin it so it won't get
12162 * swapped under us.
12163 */
12164 parent_ctx = perf_pin_task_context(parent, ctxn);
12165 if (!parent_ctx)
12166 return 0;
12167
12168 /*
12169 * No need to check if parent_ctx != NULL here; since we saw
12170 * it non-NULL earlier, the only reason for it to become NULL
12171 * is if we exit, and since we're currently in the middle of
12172 * a fork we can't be exiting at the same time.
12173 */
12174
12175 /*
12176 * Lock the parent list. No need to lock the child - not PID
12177 * hashed yet and not running, so nobody can access it.
12178 */
12179 mutex_lock(&parent_ctx->mutex);
12180
12181 /*
12182 * We dont have to disable NMIs - we are only looking at
12183 * the list, not manipulating it:
12184 */
12185 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) {
12186 ret = inherit_task_group(event, parent, parent_ctx,
12187 child, ctxn, &inherited_all);
12188 if (ret)
12189 goto out_unlock;
12190 }
12191
12192 /*
12193 * We can't hold ctx->lock when iterating the ->flexible_group list due
12194 * to allocations, but we need to prevent rotation because
12195 * rotate_ctx() will change the list from interrupt context.
12196 */
12197 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12198 parent_ctx->rotate_disable = 1;
12199 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12200
12201 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) {
12202 ret = inherit_task_group(event, parent, parent_ctx,
12203 child, ctxn, &inherited_all);
12204 if (ret)
12205 goto out_unlock;
12206 }
12207
12208 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
12209 parent_ctx->rotate_disable = 0;
12210
12211 child_ctx = child->perf_event_ctxp[ctxn];
12212
12213 if (child_ctx && inherited_all) {
12214 /*
12215 * Mark the child context as a clone of the parent
12216 * context, or of whatever the parent is a clone of.
12217 *
12218 * Note that if the parent is a clone, the holding of
12219 * parent_ctx->lock avoids it from being uncloned.
12220 */
12221 cloned_ctx = parent_ctx->parent_ctx;
12222 if (cloned_ctx) {
12223 child_ctx->parent_ctx = cloned_ctx;
12224 child_ctx->parent_gen = parent_ctx->parent_gen;
12225 } else {
12226 child_ctx->parent_ctx = parent_ctx;
12227 child_ctx->parent_gen = parent_ctx->generation;
12228 }
12229 get_ctx(child_ctx->parent_ctx);
12230 }
12231
12232 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
12233 out_unlock:
12234 mutex_unlock(&parent_ctx->mutex);
12235
12236 perf_unpin_context(parent_ctx);
12237 put_ctx(parent_ctx);
12238
12239 return ret;
12240 }
12241
12242 /*
12243 * Initialize the perf_event context in task_struct
12244 */
perf_event_init_task(struct task_struct * child)12245 int perf_event_init_task(struct task_struct *child)
12246 {
12247 int ctxn, ret;
12248
12249 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
12250 mutex_init(&child->perf_event_mutex);
12251 INIT_LIST_HEAD(&child->perf_event_list);
12252
12253 for_each_task_context_nr(ctxn) {
12254 ret = perf_event_init_context(child, ctxn);
12255 if (ret) {
12256 perf_event_free_task(child);
12257 return ret;
12258 }
12259 }
12260
12261 return 0;
12262 }
12263
perf_event_init_all_cpus(void)12264 static void __init perf_event_init_all_cpus(void)
12265 {
12266 struct swevent_htable *swhash;
12267 int cpu;
12268
12269 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL);
12270
12271 for_each_possible_cpu(cpu) {
12272 swhash = &per_cpu(swevent_htable, cpu);
12273 mutex_init(&swhash->hlist_mutex);
12274 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu));
12275
12276 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu));
12277 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu));
12278
12279 #ifdef CONFIG_CGROUP_PERF
12280 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu));
12281 #endif
12282 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu));
12283 }
12284 }
12285
perf_swevent_init_cpu(unsigned int cpu)12286 static void perf_swevent_init_cpu(unsigned int cpu)
12287 {
12288 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
12289
12290 mutex_lock(&swhash->hlist_mutex);
12291 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) {
12292 struct swevent_hlist *hlist;
12293
12294 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
12295 WARN_ON(!hlist);
12296 rcu_assign_pointer(swhash->swevent_hlist, hlist);
12297 }
12298 mutex_unlock(&swhash->hlist_mutex);
12299 }
12300
12301 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE
__perf_event_exit_context(void * __info)12302 static void __perf_event_exit_context(void *__info)
12303 {
12304 struct perf_event_context *ctx = __info;
12305 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
12306 struct perf_event *event;
12307
12308 raw_spin_lock(&ctx->lock);
12309 ctx_sched_out(ctx, cpuctx, EVENT_TIME);
12310 list_for_each_entry(event, &ctx->event_list, event_entry)
12311 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP);
12312 raw_spin_unlock(&ctx->lock);
12313 }
12314
perf_event_exit_cpu_context(int cpu)12315 static void perf_event_exit_cpu_context(int cpu)
12316 {
12317 struct perf_cpu_context *cpuctx;
12318 struct perf_event_context *ctx;
12319 struct pmu *pmu;
12320
12321 mutex_lock(&pmus_lock);
12322 list_for_each_entry(pmu, &pmus, entry) {
12323 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12324 ctx = &cpuctx->ctx;
12325
12326 mutex_lock(&ctx->mutex);
12327 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
12328 cpuctx->online = 0;
12329 mutex_unlock(&ctx->mutex);
12330 }
12331 cpumask_clear_cpu(cpu, perf_online_mask);
12332 mutex_unlock(&pmus_lock);
12333 }
12334 #else
12335
perf_event_exit_cpu_context(int cpu)12336 static void perf_event_exit_cpu_context(int cpu) { }
12337
12338 #endif
12339
perf_event_init_cpu(unsigned int cpu)12340 int perf_event_init_cpu(unsigned int cpu)
12341 {
12342 struct perf_cpu_context *cpuctx;
12343 struct perf_event_context *ctx;
12344 struct pmu *pmu;
12345
12346 perf_swevent_init_cpu(cpu);
12347
12348 mutex_lock(&pmus_lock);
12349 cpumask_set_cpu(cpu, perf_online_mask);
12350 list_for_each_entry(pmu, &pmus, entry) {
12351 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
12352 ctx = &cpuctx->ctx;
12353
12354 mutex_lock(&ctx->mutex);
12355 cpuctx->online = 1;
12356 mutex_unlock(&ctx->mutex);
12357 }
12358 mutex_unlock(&pmus_lock);
12359
12360 return 0;
12361 }
12362
perf_event_exit_cpu(unsigned int cpu)12363 int perf_event_exit_cpu(unsigned int cpu)
12364 {
12365 perf_event_exit_cpu_context(cpu);
12366 return 0;
12367 }
12368
12369 static int
perf_reboot(struct notifier_block * notifier,unsigned long val,void * v)12370 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
12371 {
12372 int cpu;
12373
12374 for_each_online_cpu(cpu)
12375 perf_event_exit_cpu(cpu);
12376
12377 return NOTIFY_OK;
12378 }
12379
12380 /*
12381 * Run the perf reboot notifier at the very last possible moment so that
12382 * the generic watchdog code runs as long as possible.
12383 */
12384 static struct notifier_block perf_reboot_notifier = {
12385 .notifier_call = perf_reboot,
12386 .priority = INT_MIN,
12387 };
12388
perf_event_init(void)12389 void __init perf_event_init(void)
12390 {
12391 int ret;
12392
12393 idr_init(&pmu_idr);
12394
12395 perf_event_init_all_cpus();
12396 init_srcu_struct(&pmus_srcu);
12397 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
12398 perf_pmu_register(&perf_cpu_clock, NULL, -1);
12399 perf_pmu_register(&perf_task_clock, NULL, -1);
12400 perf_tp_register();
12401 perf_event_init_cpu(smp_processor_id());
12402 register_reboot_notifier(&perf_reboot_notifier);
12403
12404 ret = init_hw_breakpoint();
12405 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
12406
12407 /*
12408 * Build time assertion that we keep the data_head at the intended
12409 * location. IOW, validation we got the __reserved[] size right.
12410 */
12411 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head))
12412 != 1024);
12413 }
12414
perf_event_sysfs_show(struct device * dev,struct device_attribute * attr,char * page)12415 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr,
12416 char *page)
12417 {
12418 struct perf_pmu_events_attr *pmu_attr =
12419 container_of(attr, struct perf_pmu_events_attr, attr);
12420
12421 if (pmu_attr->event_str)
12422 return sprintf(page, "%s\n", pmu_attr->event_str);
12423
12424 return 0;
12425 }
12426 EXPORT_SYMBOL_GPL(perf_event_sysfs_show);
12427
perf_event_sysfs_init(void)12428 static int __init perf_event_sysfs_init(void)
12429 {
12430 struct pmu *pmu;
12431 int ret;
12432
12433 mutex_lock(&pmus_lock);
12434
12435 ret = bus_register(&pmu_bus);
12436 if (ret)
12437 goto unlock;
12438
12439 list_for_each_entry(pmu, &pmus, entry) {
12440 if (!pmu->name || pmu->type < 0)
12441 continue;
12442
12443 ret = pmu_dev_alloc(pmu);
12444 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
12445 }
12446 pmu_bus_running = 1;
12447 ret = 0;
12448
12449 unlock:
12450 mutex_unlock(&pmus_lock);
12451
12452 return ret;
12453 }
12454 device_initcall(perf_event_sysfs_init);
12455
12456 #ifdef CONFIG_CGROUP_PERF
12457 static struct cgroup_subsys_state *
perf_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)12458 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
12459 {
12460 struct perf_cgroup *jc;
12461
12462 jc = kzalloc(sizeof(*jc), GFP_KERNEL);
12463 if (!jc)
12464 return ERR_PTR(-ENOMEM);
12465
12466 jc->info = alloc_percpu(struct perf_cgroup_info);
12467 if (!jc->info) {
12468 kfree(jc);
12469 return ERR_PTR(-ENOMEM);
12470 }
12471
12472 return &jc->css;
12473 }
12474
perf_cgroup_css_free(struct cgroup_subsys_state * css)12475 static void perf_cgroup_css_free(struct cgroup_subsys_state *css)
12476 {
12477 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css);
12478
12479 free_percpu(jc->info);
12480 kfree(jc);
12481 }
12482
__perf_cgroup_move(void * info)12483 static int __perf_cgroup_move(void *info)
12484 {
12485 struct task_struct *task = info;
12486 rcu_read_lock();
12487 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN);
12488 rcu_read_unlock();
12489 return 0;
12490 }
12491
perf_cgroup_attach(struct cgroup_taskset * tset)12492 static void perf_cgroup_attach(struct cgroup_taskset *tset)
12493 {
12494 struct task_struct *task;
12495 struct cgroup_subsys_state *css;
12496
12497 cgroup_taskset_for_each(task, css, tset)
12498 task_function_call(task, __perf_cgroup_move, task);
12499 }
12500
12501 struct cgroup_subsys perf_event_cgrp_subsys = {
12502 .css_alloc = perf_cgroup_css_alloc,
12503 .css_free = perf_cgroup_css_free,
12504 .attach = perf_cgroup_attach,
12505 /*
12506 * Implicitly enable on dfl hierarchy so that perf events can
12507 * always be filtered by cgroup2 path as long as perf_event
12508 * controller is not mounted on a legacy hierarchy.
12509 */
12510 .implicit_on_dfl = true,
12511 .threaded = true,
12512 };
12513 #endif /* CONFIG_CGROUP_PERF */
12514