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