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