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