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