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