Merge branch 'linus' into perf/core
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / perf_event.c
bloba353a4d6d00dc312117eff3a853116719bfe4ea9
1 /*
2 * Performance events core code:
4 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
5 * Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
6 * Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
7 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
9 * For licensing details see kernel-base/COPYING
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/sysfs.h>
22 #include <linux/dcache.h>
23 #include <linux/percpu.h>
24 #include <linux/ptrace.h>
25 #include <linux/reboot.h>
26 #include <linux/vmstat.h>
27 #include <linux/device.h>
28 #include <linux/vmalloc.h>
29 #include <linux/hardirq.h>
30 #include <linux/rculist.h>
31 #include <linux/uaccess.h>
32 #include <linux/syscalls.h>
33 #include <linux/anon_inodes.h>
34 #include <linux/kernel_stat.h>
35 #include <linux/perf_event.h>
36 #include <linux/ftrace_event.h>
37 #include <linux/hw_breakpoint.h>
39 #include <asm/irq_regs.h>
41 struct remote_function_call {
42 struct task_struct *p;
43 int (*func)(void *info);
44 void *info;
45 int ret;
48 static void remote_function(void *data)
50 struct remote_function_call *tfc = data;
51 struct task_struct *p = tfc->p;
53 if (p) {
54 tfc->ret = -EAGAIN;
55 if (task_cpu(p) != smp_processor_id() || !task_curr(p))
56 return;
59 tfc->ret = tfc->func(tfc->info);
62 /**
63 * task_function_call - call a function on the cpu on which a task runs
64 * @p: the task to evaluate
65 * @func: the function to be called
66 * @info: the function call argument
68 * Calls the function @func when the task is currently running. This might
69 * be on the current CPU, which just calls the function directly
71 * returns: @func return value, or
72 * -ESRCH - when the process isn't running
73 * -EAGAIN - when the process moved away
75 static int
76 task_function_call(struct task_struct *p, int (*func) (void *info), void *info)
78 struct remote_function_call data = {
79 .p = p,
80 .func = func,
81 .info = info,
82 .ret = -ESRCH, /* No such (running) process */
85 if (task_curr(p))
86 smp_call_function_single(task_cpu(p), remote_function, &data, 1);
88 return data.ret;
91 /**
92 * cpu_function_call - call a function on the cpu
93 * @func: the function to be called
94 * @info: the function call argument
96 * Calls the function @func on the remote cpu.
98 * returns: @func return value or -ENXIO when the cpu is offline
100 static int cpu_function_call(int cpu, int (*func) (void *info), void *info)
102 struct remote_function_call data = {
103 .p = NULL,
104 .func = func,
105 .info = info,
106 .ret = -ENXIO, /* No such CPU */
109 smp_call_function_single(cpu, remote_function, &data, 1);
111 return data.ret;
114 enum event_type_t {
115 EVENT_FLEXIBLE = 0x1,
116 EVENT_PINNED = 0x2,
117 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
120 atomic_t perf_task_events __read_mostly;
121 static atomic_t nr_mmap_events __read_mostly;
122 static atomic_t nr_comm_events __read_mostly;
123 static atomic_t nr_task_events __read_mostly;
125 static LIST_HEAD(pmus);
126 static DEFINE_MUTEX(pmus_lock);
127 static struct srcu_struct pmus_srcu;
130 * perf event paranoia level:
131 * -1 - not paranoid at all
132 * 0 - disallow raw tracepoint access for unpriv
133 * 1 - disallow cpu events for unpriv
134 * 2 - disallow kernel profiling for unpriv
136 int sysctl_perf_event_paranoid __read_mostly = 1;
138 int sysctl_perf_event_mlock __read_mostly = 512; /* 'free' kb per user */
141 * max perf event sample rate
143 int sysctl_perf_event_sample_rate __read_mostly = 100000;
145 static atomic64_t perf_event_id;
147 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
148 enum event_type_t event_type);
150 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
151 enum event_type_t event_type);
153 void __weak perf_event_print_debug(void) { }
155 extern __weak const char *perf_pmu_name(void)
157 return "pmu";
160 static inline u64 perf_clock(void)
162 return local_clock();
165 void perf_pmu_disable(struct pmu *pmu)
167 int *count = this_cpu_ptr(pmu->pmu_disable_count);
168 if (!(*count)++)
169 pmu->pmu_disable(pmu);
172 void perf_pmu_enable(struct pmu *pmu)
174 int *count = this_cpu_ptr(pmu->pmu_disable_count);
175 if (!--(*count))
176 pmu->pmu_enable(pmu);
179 static DEFINE_PER_CPU(struct list_head, rotation_list);
182 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
183 * because they're strictly cpu affine and rotate_start is called with IRQs
184 * disabled, while rotate_context is called from IRQ context.
186 static void perf_pmu_rotate_start(struct pmu *pmu)
188 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
189 struct list_head *head = &__get_cpu_var(rotation_list);
191 WARN_ON(!irqs_disabled());
193 if (list_empty(&cpuctx->rotation_list))
194 list_add(&cpuctx->rotation_list, head);
197 static void get_ctx(struct perf_event_context *ctx)
199 WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
202 static void free_ctx(struct rcu_head *head)
204 struct perf_event_context *ctx;
206 ctx = container_of(head, struct perf_event_context, rcu_head);
207 kfree(ctx);
210 static void put_ctx(struct perf_event_context *ctx)
212 if (atomic_dec_and_test(&ctx->refcount)) {
213 if (ctx->parent_ctx)
214 put_ctx(ctx->parent_ctx);
215 if (ctx->task)
216 put_task_struct(ctx->task);
217 call_rcu(&ctx->rcu_head, free_ctx);
221 static void unclone_ctx(struct perf_event_context *ctx)
223 if (ctx->parent_ctx) {
224 put_ctx(ctx->parent_ctx);
225 ctx->parent_ctx = NULL;
229 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
232 * only top level events have the pid namespace they were created in
234 if (event->parent)
235 event = event->parent;
237 return task_tgid_nr_ns(p, event->ns);
240 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
243 * only top level events have the pid namespace they were created in
245 if (event->parent)
246 event = event->parent;
248 return task_pid_nr_ns(p, event->ns);
252 * If we inherit events we want to return the parent event id
253 * to userspace.
255 static u64 primary_event_id(struct perf_event *event)
257 u64 id = event->id;
259 if (event->parent)
260 id = event->parent->id;
262 return id;
266 * Get the perf_event_context for a task and lock it.
267 * This has to cope with with the fact that until it is locked,
268 * the context could get moved to another task.
270 static struct perf_event_context *
271 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags)
273 struct perf_event_context *ctx;
275 rcu_read_lock();
276 retry:
277 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]);
278 if (ctx) {
280 * If this context is a clone of another, it might
281 * get swapped for another underneath us by
282 * perf_event_task_sched_out, though the
283 * rcu_read_lock() protects us from any context
284 * getting freed. Lock the context and check if it
285 * got swapped before we could get the lock, and retry
286 * if so. If we locked the right context, then it
287 * can't get swapped on us any more.
289 raw_spin_lock_irqsave(&ctx->lock, *flags);
290 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) {
291 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
292 goto retry;
295 if (!atomic_inc_not_zero(&ctx->refcount)) {
296 raw_spin_unlock_irqrestore(&ctx->lock, *flags);
297 ctx = NULL;
300 rcu_read_unlock();
301 return ctx;
305 * Get the context for a task and increment its pin_count so it
306 * can't get swapped to another task. This also increments its
307 * reference count so that the context can't get freed.
309 static struct perf_event_context *
310 perf_pin_task_context(struct task_struct *task, int ctxn)
312 struct perf_event_context *ctx;
313 unsigned long flags;
315 ctx = perf_lock_task_context(task, ctxn, &flags);
316 if (ctx) {
317 ++ctx->pin_count;
318 raw_spin_unlock_irqrestore(&ctx->lock, flags);
320 return ctx;
323 static void perf_unpin_context(struct perf_event_context *ctx)
325 unsigned long flags;
327 raw_spin_lock_irqsave(&ctx->lock, flags);
328 --ctx->pin_count;
329 raw_spin_unlock_irqrestore(&ctx->lock, flags);
333 * Update the record of the current time in a context.
335 static void update_context_time(struct perf_event_context *ctx)
337 u64 now = perf_clock();
339 ctx->time += now - ctx->timestamp;
340 ctx->timestamp = now;
343 static u64 perf_event_time(struct perf_event *event)
345 struct perf_event_context *ctx = event->ctx;
346 return ctx ? ctx->time : 0;
350 * Update the total_time_enabled and total_time_running fields for a event.
352 static void update_event_times(struct perf_event *event)
354 struct perf_event_context *ctx = event->ctx;
355 u64 run_end;
357 if (event->state < PERF_EVENT_STATE_INACTIVE ||
358 event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
359 return;
361 if (ctx->is_active)
362 run_end = perf_event_time(event);
363 else
364 run_end = event->tstamp_stopped;
366 event->total_time_enabled = run_end - event->tstamp_enabled;
368 if (event->state == PERF_EVENT_STATE_INACTIVE)
369 run_end = event->tstamp_stopped;
370 else
371 run_end = perf_event_time(event);
373 event->total_time_running = run_end - event->tstamp_running;
377 * Update total_time_enabled and total_time_running for all events in a group.
379 static void update_group_times(struct perf_event *leader)
381 struct perf_event *event;
383 update_event_times(leader);
384 list_for_each_entry(event, &leader->sibling_list, group_entry)
385 update_event_times(event);
388 static struct list_head *
389 ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
391 if (event->attr.pinned)
392 return &ctx->pinned_groups;
393 else
394 return &ctx->flexible_groups;
398 * Add a event from the lists for its context.
399 * Must be called with ctx->mutex and ctx->lock held.
401 static void
402 list_add_event(struct perf_event *event, struct perf_event_context *ctx)
404 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
405 event->attach_state |= PERF_ATTACH_CONTEXT;
408 * If we're a stand alone event or group leader, we go to the context
409 * list, group events are kept attached to the group so that
410 * perf_group_detach can, at all times, locate all siblings.
412 if (event->group_leader == event) {
413 struct list_head *list;
415 if (is_software_event(event))
416 event->group_flags |= PERF_GROUP_SOFTWARE;
418 list = ctx_group_list(event, ctx);
419 list_add_tail(&event->group_entry, list);
422 list_add_rcu(&event->event_entry, &ctx->event_list);
423 if (!ctx->nr_events)
424 perf_pmu_rotate_start(ctx->pmu);
425 ctx->nr_events++;
426 if (event->attr.inherit_stat)
427 ctx->nr_stat++;
431 * Called at perf_event creation and when events are attached/detached from a
432 * group.
434 static void perf_event__read_size(struct perf_event *event)
436 int entry = sizeof(u64); /* value */
437 int size = 0;
438 int nr = 1;
440 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
441 size += sizeof(u64);
443 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
444 size += sizeof(u64);
446 if (event->attr.read_format & PERF_FORMAT_ID)
447 entry += sizeof(u64);
449 if (event->attr.read_format & PERF_FORMAT_GROUP) {
450 nr += event->group_leader->nr_siblings;
451 size += sizeof(u64);
454 size += entry * nr;
455 event->read_size = size;
458 static void perf_event__header_size(struct perf_event *event)
460 struct perf_sample_data *data;
461 u64 sample_type = event->attr.sample_type;
462 u16 size = 0;
464 perf_event__read_size(event);
466 if (sample_type & PERF_SAMPLE_IP)
467 size += sizeof(data->ip);
469 if (sample_type & PERF_SAMPLE_ADDR)
470 size += sizeof(data->addr);
472 if (sample_type & PERF_SAMPLE_PERIOD)
473 size += sizeof(data->period);
475 if (sample_type & PERF_SAMPLE_READ)
476 size += event->read_size;
478 event->header_size = size;
481 static void perf_event__id_header_size(struct perf_event *event)
483 struct perf_sample_data *data;
484 u64 sample_type = event->attr.sample_type;
485 u16 size = 0;
487 if (sample_type & PERF_SAMPLE_TID)
488 size += sizeof(data->tid_entry);
490 if (sample_type & PERF_SAMPLE_TIME)
491 size += sizeof(data->time);
493 if (sample_type & PERF_SAMPLE_ID)
494 size += sizeof(data->id);
496 if (sample_type & PERF_SAMPLE_STREAM_ID)
497 size += sizeof(data->stream_id);
499 if (sample_type & PERF_SAMPLE_CPU)
500 size += sizeof(data->cpu_entry);
502 event->id_header_size = size;
505 static void perf_group_attach(struct perf_event *event)
507 struct perf_event *group_leader = event->group_leader, *pos;
510 * We can have double attach due to group movement in perf_event_open.
512 if (event->attach_state & PERF_ATTACH_GROUP)
513 return;
515 event->attach_state |= PERF_ATTACH_GROUP;
517 if (group_leader == event)
518 return;
520 if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
521 !is_software_event(event))
522 group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
524 list_add_tail(&event->group_entry, &group_leader->sibling_list);
525 group_leader->nr_siblings++;
527 perf_event__header_size(group_leader);
529 list_for_each_entry(pos, &group_leader->sibling_list, group_entry)
530 perf_event__header_size(pos);
534 * Remove a event from the lists for its context.
535 * Must be called with ctx->mutex and ctx->lock held.
537 static void
538 list_del_event(struct perf_event *event, struct perf_event_context *ctx)
541 * We can have double detach due to exit/hot-unplug + close.
543 if (!(event->attach_state & PERF_ATTACH_CONTEXT))
544 return;
546 event->attach_state &= ~PERF_ATTACH_CONTEXT;
548 ctx->nr_events--;
549 if (event->attr.inherit_stat)
550 ctx->nr_stat--;
552 list_del_rcu(&event->event_entry);
554 if (event->group_leader == event)
555 list_del_init(&event->group_entry);
557 update_group_times(event);
560 * If event was in error state, then keep it
561 * that way, otherwise bogus counts will be
562 * returned on read(). The only way to get out
563 * of error state is by explicit re-enabling
564 * of the event
566 if (event->state > PERF_EVENT_STATE_OFF)
567 event->state = PERF_EVENT_STATE_OFF;
570 static void perf_group_detach(struct perf_event *event)
572 struct perf_event *sibling, *tmp;
573 struct list_head *list = NULL;
576 * We can have double detach due to exit/hot-unplug + close.
578 if (!(event->attach_state & PERF_ATTACH_GROUP))
579 return;
581 event->attach_state &= ~PERF_ATTACH_GROUP;
584 * If this is a sibling, remove it from its group.
586 if (event->group_leader != event) {
587 list_del_init(&event->group_entry);
588 event->group_leader->nr_siblings--;
589 goto out;
592 if (!list_empty(&event->group_entry))
593 list = &event->group_entry;
596 * If this was a group event with sibling events then
597 * upgrade the siblings to singleton events by adding them
598 * to whatever list we are on.
600 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
601 if (list)
602 list_move_tail(&sibling->group_entry, list);
603 sibling->group_leader = sibling;
605 /* Inherit group flags from the previous leader */
606 sibling->group_flags = event->group_flags;
609 out:
610 perf_event__header_size(event->group_leader);
612 list_for_each_entry(tmp, &event->group_leader->sibling_list, group_entry)
613 perf_event__header_size(tmp);
616 static inline int
617 event_filter_match(struct perf_event *event)
619 return event->cpu == -1 || event->cpu == smp_processor_id();
622 static void
623 event_sched_out(struct perf_event *event,
624 struct perf_cpu_context *cpuctx,
625 struct perf_event_context *ctx)
627 u64 tstamp = perf_event_time(event);
628 u64 delta;
630 * An event which could not be activated because of
631 * filter mismatch still needs to have its timings
632 * maintained, otherwise bogus information is return
633 * via read() for time_enabled, time_running:
635 if (event->state == PERF_EVENT_STATE_INACTIVE
636 && !event_filter_match(event)) {
637 delta = ctx->time - event->tstamp_stopped;
638 event->tstamp_running += delta;
639 event->tstamp_stopped = tstamp;
642 if (event->state != PERF_EVENT_STATE_ACTIVE)
643 return;
645 event->state = PERF_EVENT_STATE_INACTIVE;
646 if (event->pending_disable) {
647 event->pending_disable = 0;
648 event->state = PERF_EVENT_STATE_OFF;
650 event->tstamp_stopped = tstamp;
651 event->pmu->del(event, 0);
652 event->oncpu = -1;
654 if (!is_software_event(event))
655 cpuctx->active_oncpu--;
656 ctx->nr_active--;
657 if (event->attr.exclusive || !cpuctx->active_oncpu)
658 cpuctx->exclusive = 0;
661 static void
662 group_sched_out(struct perf_event *group_event,
663 struct perf_cpu_context *cpuctx,
664 struct perf_event_context *ctx)
666 struct perf_event *event;
667 int state = group_event->state;
669 event_sched_out(group_event, cpuctx, ctx);
672 * Schedule out siblings (if any):
674 list_for_each_entry(event, &group_event->sibling_list, group_entry)
675 event_sched_out(event, cpuctx, ctx);
677 if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
678 cpuctx->exclusive = 0;
681 static inline struct perf_cpu_context *
682 __get_cpu_context(struct perf_event_context *ctx)
684 return this_cpu_ptr(ctx->pmu->pmu_cpu_context);
688 * Cross CPU call to remove a performance event
690 * We disable the event on the hardware level first. After that we
691 * remove it from the context list.
693 static int __perf_remove_from_context(void *info)
695 struct perf_event *event = info;
696 struct perf_event_context *ctx = event->ctx;
697 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
699 raw_spin_lock(&ctx->lock);
700 event_sched_out(event, cpuctx, ctx);
701 list_del_event(event, ctx);
702 raw_spin_unlock(&ctx->lock);
704 return 0;
709 * Remove the event from a task's (or a CPU's) list of events.
711 * CPU events are removed with a smp call. For task events we only
712 * call when the task is on a CPU.
714 * If event->ctx is a cloned context, callers must make sure that
715 * every task struct that event->ctx->task could possibly point to
716 * remains valid. This is OK when called from perf_release since
717 * that only calls us on the top-level context, which can't be a clone.
718 * When called from perf_event_exit_task, it's OK because the
719 * context has been detached from its task.
721 static void perf_remove_from_context(struct perf_event *event)
723 struct perf_event_context *ctx = event->ctx;
724 struct task_struct *task = ctx->task;
726 lockdep_assert_held(&ctx->mutex);
728 if (!task) {
730 * Per cpu events are removed via an smp call and
731 * the removal is always successful.
733 cpu_function_call(event->cpu, __perf_remove_from_context, event);
734 return;
737 retry:
738 if (!task_function_call(task, __perf_remove_from_context, event))
739 return;
741 raw_spin_lock_irq(&ctx->lock);
743 * If we failed to find a running task, but find the context active now
744 * that we've acquired the ctx->lock, retry.
746 if (ctx->is_active) {
747 raw_spin_unlock_irq(&ctx->lock);
748 goto retry;
752 * Since the task isn't running, its safe to remove the event, us
753 * holding the ctx->lock ensures the task won't get scheduled in.
755 list_del_event(event, ctx);
756 raw_spin_unlock_irq(&ctx->lock);
760 * Cross CPU call to disable a performance event
762 static int __perf_event_disable(void *info)
764 struct perf_event *event = info;
765 struct perf_event_context *ctx = event->ctx;
766 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
769 * If this is a per-task event, need to check whether this
770 * event's task is the current task on this cpu.
772 * Can trigger due to concurrent perf_event_context_sched_out()
773 * flipping contexts around.
775 if (ctx->task && cpuctx->task_ctx != ctx)
776 return -EINVAL;
778 raw_spin_lock(&ctx->lock);
781 * If the event is on, turn it off.
782 * If it is in error state, leave it in error state.
784 if (event->state >= PERF_EVENT_STATE_INACTIVE) {
785 update_context_time(ctx);
786 update_group_times(event);
787 if (event == event->group_leader)
788 group_sched_out(event, cpuctx, ctx);
789 else
790 event_sched_out(event, cpuctx, ctx);
791 event->state = PERF_EVENT_STATE_OFF;
794 raw_spin_unlock(&ctx->lock);
796 return 0;
800 * Disable a event.
802 * If event->ctx is a cloned context, callers must make sure that
803 * every task struct that event->ctx->task could possibly point to
804 * remains valid. This condition is satisifed when called through
805 * perf_event_for_each_child or perf_event_for_each because they
806 * hold the top-level event's child_mutex, so any descendant that
807 * goes to exit will block in sync_child_event.
808 * When called from perf_pending_event it's OK because event->ctx
809 * is the current context on this CPU and preemption is disabled,
810 * hence we can't get into perf_event_task_sched_out for this context.
812 void perf_event_disable(struct perf_event *event)
814 struct perf_event_context *ctx = event->ctx;
815 struct task_struct *task = ctx->task;
817 if (!task) {
819 * Disable the event on the cpu that it's on
821 cpu_function_call(event->cpu, __perf_event_disable, event);
822 return;
825 retry:
826 if (!task_function_call(task, __perf_event_disable, event))
827 return;
829 raw_spin_lock_irq(&ctx->lock);
831 * If the event is still active, we need to retry the cross-call.
833 if (event->state == PERF_EVENT_STATE_ACTIVE) {
834 raw_spin_unlock_irq(&ctx->lock);
836 * Reload the task pointer, it might have been changed by
837 * a concurrent perf_event_context_sched_out().
839 task = ctx->task;
840 goto retry;
844 * Since we have the lock this context can't be scheduled
845 * in, so we can change the state safely.
847 if (event->state == PERF_EVENT_STATE_INACTIVE) {
848 update_group_times(event);
849 event->state = PERF_EVENT_STATE_OFF;
851 raw_spin_unlock_irq(&ctx->lock);
854 static int
855 event_sched_in(struct perf_event *event,
856 struct perf_cpu_context *cpuctx,
857 struct perf_event_context *ctx)
859 u64 tstamp = perf_event_time(event);
861 if (event->state <= PERF_EVENT_STATE_OFF)
862 return 0;
864 event->state = PERF_EVENT_STATE_ACTIVE;
865 event->oncpu = smp_processor_id();
867 * The new state must be visible before we turn it on in the hardware:
869 smp_wmb();
871 if (event->pmu->add(event, PERF_EF_START)) {
872 event->state = PERF_EVENT_STATE_INACTIVE;
873 event->oncpu = -1;
874 return -EAGAIN;
877 event->tstamp_running += tstamp - event->tstamp_stopped;
879 event->shadow_ctx_time = tstamp - ctx->timestamp;
881 if (!is_software_event(event))
882 cpuctx->active_oncpu++;
883 ctx->nr_active++;
885 if (event->attr.exclusive)
886 cpuctx->exclusive = 1;
888 return 0;
891 static int
892 group_sched_in(struct perf_event *group_event,
893 struct perf_cpu_context *cpuctx,
894 struct perf_event_context *ctx)
896 struct perf_event *event, *partial_group = NULL;
897 struct pmu *pmu = group_event->pmu;
898 u64 now = ctx->time;
899 bool simulate = false;
901 if (group_event->state == PERF_EVENT_STATE_OFF)
902 return 0;
904 pmu->start_txn(pmu);
906 if (event_sched_in(group_event, cpuctx, ctx)) {
907 pmu->cancel_txn(pmu);
908 return -EAGAIN;
912 * Schedule in siblings as one group (if any):
914 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
915 if (event_sched_in(event, cpuctx, ctx)) {
916 partial_group = event;
917 goto group_error;
921 if (!pmu->commit_txn(pmu))
922 return 0;
924 group_error:
926 * Groups can be scheduled in as one unit only, so undo any
927 * partial group before returning:
928 * The events up to the failed event are scheduled out normally,
929 * tstamp_stopped will be updated.
931 * The failed events and the remaining siblings need to have
932 * their timings updated as if they had gone thru event_sched_in()
933 * and event_sched_out(). This is required to get consistent timings
934 * across the group. This also takes care of the case where the group
935 * could never be scheduled by ensuring tstamp_stopped is set to mark
936 * the time the event was actually stopped, such that time delta
937 * calculation in update_event_times() is correct.
939 list_for_each_entry(event, &group_event->sibling_list, group_entry) {
940 if (event == partial_group)
941 simulate = true;
943 if (simulate) {
944 event->tstamp_running += now - event->tstamp_stopped;
945 event->tstamp_stopped = now;
946 } else {
947 event_sched_out(event, cpuctx, ctx);
950 event_sched_out(group_event, cpuctx, ctx);
952 pmu->cancel_txn(pmu);
954 return -EAGAIN;
958 * Work out whether we can put this event group on the CPU now.
960 static int group_can_go_on(struct perf_event *event,
961 struct perf_cpu_context *cpuctx,
962 int can_add_hw)
965 * Groups consisting entirely of software events can always go on.
967 if (event->group_flags & PERF_GROUP_SOFTWARE)
968 return 1;
970 * If an exclusive group is already on, no other hardware
971 * events can go on.
973 if (cpuctx->exclusive)
974 return 0;
976 * If this group is exclusive and there are already
977 * events on the CPU, it can't go on.
979 if (event->attr.exclusive && cpuctx->active_oncpu)
980 return 0;
982 * Otherwise, try to add it if all previous groups were able
983 * to go on.
985 return can_add_hw;
988 static void add_event_to_ctx(struct perf_event *event,
989 struct perf_event_context *ctx)
991 u64 tstamp = perf_event_time(event);
993 list_add_event(event, ctx);
994 perf_group_attach(event);
995 event->tstamp_enabled = tstamp;
996 event->tstamp_running = tstamp;
997 event->tstamp_stopped = tstamp;
1000 static void perf_event_context_sched_in(struct perf_event_context *ctx);
1003 * Cross CPU call to install and enable a performance event
1005 * Must be called with ctx->mutex held
1007 static int __perf_install_in_context(void *info)
1009 struct perf_event *event = info;
1010 struct perf_event_context *ctx = event->ctx;
1011 struct perf_event *leader = event->group_leader;
1012 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1013 int err;
1016 * In case we're installing a new context to an already running task,
1017 * could also happen before perf_event_task_sched_in() on architectures
1018 * which do context switches with IRQs enabled.
1020 if (ctx->task && !cpuctx->task_ctx)
1021 perf_event_context_sched_in(ctx);
1023 raw_spin_lock(&ctx->lock);
1024 ctx->is_active = 1;
1025 update_context_time(ctx);
1027 add_event_to_ctx(event, ctx);
1029 if (!event_filter_match(event))
1030 goto unlock;
1033 * Don't put the event on if it is disabled or if
1034 * it is in a group and the group isn't on.
1036 if (event->state != PERF_EVENT_STATE_INACTIVE ||
1037 (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE))
1038 goto unlock;
1041 * An exclusive event can't go on if there are already active
1042 * hardware events, and no hardware event can go on if there
1043 * is already an exclusive event on.
1045 if (!group_can_go_on(event, cpuctx, 1))
1046 err = -EEXIST;
1047 else
1048 err = event_sched_in(event, cpuctx, ctx);
1050 if (err) {
1052 * This event couldn't go on. If it is in a group
1053 * then we have to pull the whole group off.
1054 * If the event group is pinned then put it in error state.
1056 if (leader != event)
1057 group_sched_out(leader, cpuctx, ctx);
1058 if (leader->attr.pinned) {
1059 update_group_times(leader);
1060 leader->state = PERF_EVENT_STATE_ERROR;
1064 unlock:
1065 raw_spin_unlock(&ctx->lock);
1067 return 0;
1071 * Attach a performance event to a context
1073 * First we add the event to the list with the hardware enable bit
1074 * in event->hw_config cleared.
1076 * If the event is attached to a task which is on a CPU we use a smp
1077 * call to enable it in the task context. The task might have been
1078 * scheduled away, but we check this in the smp call again.
1080 static void
1081 perf_install_in_context(struct perf_event_context *ctx,
1082 struct perf_event *event,
1083 int cpu)
1085 struct task_struct *task = ctx->task;
1087 lockdep_assert_held(&ctx->mutex);
1089 event->ctx = ctx;
1091 if (!task) {
1093 * Per cpu events are installed via an smp call and
1094 * the install is always successful.
1096 cpu_function_call(cpu, __perf_install_in_context, event);
1097 return;
1100 retry:
1101 if (!task_function_call(task, __perf_install_in_context, event))
1102 return;
1104 raw_spin_lock_irq(&ctx->lock);
1106 * If we failed to find a running task, but find the context active now
1107 * that we've acquired the ctx->lock, retry.
1109 if (ctx->is_active) {
1110 raw_spin_unlock_irq(&ctx->lock);
1111 goto retry;
1115 * Since the task isn't running, its safe to add the event, us holding
1116 * the ctx->lock ensures the task won't get scheduled in.
1118 add_event_to_ctx(event, ctx);
1119 raw_spin_unlock_irq(&ctx->lock);
1123 * Put a event into inactive state and update time fields.
1124 * Enabling the leader of a group effectively enables all
1125 * the group members that aren't explicitly disabled, so we
1126 * have to update their ->tstamp_enabled also.
1127 * Note: this works for group members as well as group leaders
1128 * since the non-leader members' sibling_lists will be empty.
1130 static void __perf_event_mark_enabled(struct perf_event *event,
1131 struct perf_event_context *ctx)
1133 struct perf_event *sub;
1134 u64 tstamp = perf_event_time(event);
1136 event->state = PERF_EVENT_STATE_INACTIVE;
1137 event->tstamp_enabled = tstamp - event->total_time_enabled;
1138 list_for_each_entry(sub, &event->sibling_list, group_entry) {
1139 if (sub->state >= PERF_EVENT_STATE_INACTIVE)
1140 sub->tstamp_enabled = tstamp - sub->total_time_enabled;
1145 * Cross CPU call to enable a performance event
1147 static int __perf_event_enable(void *info)
1149 struct perf_event *event = info;
1150 struct perf_event_context *ctx = event->ctx;
1151 struct perf_event *leader = event->group_leader;
1152 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1153 int err;
1155 if (WARN_ON_ONCE(!ctx->is_active))
1156 return -EINVAL;
1158 raw_spin_lock(&ctx->lock);
1159 update_context_time(ctx);
1161 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1162 goto unlock;
1163 __perf_event_mark_enabled(event, ctx);
1165 if (!event_filter_match(event))
1166 goto unlock;
1169 * If the event is in a group and isn't the group leader,
1170 * then don't put it on unless the group is on.
1172 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
1173 goto unlock;
1175 if (!group_can_go_on(event, cpuctx, 1)) {
1176 err = -EEXIST;
1177 } else {
1178 if (event == leader)
1179 err = group_sched_in(event, cpuctx, ctx);
1180 else
1181 err = event_sched_in(event, cpuctx, ctx);
1184 if (err) {
1186 * If this event can't go on and it's part of a
1187 * group, then the whole group has to come off.
1189 if (leader != event)
1190 group_sched_out(leader, cpuctx, ctx);
1191 if (leader->attr.pinned) {
1192 update_group_times(leader);
1193 leader->state = PERF_EVENT_STATE_ERROR;
1197 unlock:
1198 raw_spin_unlock(&ctx->lock);
1200 return 0;
1204 * Enable a event.
1206 * If event->ctx is a cloned context, callers must make sure that
1207 * every task struct that event->ctx->task could possibly point to
1208 * remains valid. This condition is satisfied when called through
1209 * perf_event_for_each_child or perf_event_for_each as described
1210 * for perf_event_disable.
1212 void perf_event_enable(struct perf_event *event)
1214 struct perf_event_context *ctx = event->ctx;
1215 struct task_struct *task = ctx->task;
1217 if (!task) {
1219 * Enable the event on the cpu that it's on
1221 cpu_function_call(event->cpu, __perf_event_enable, event);
1222 return;
1225 raw_spin_lock_irq(&ctx->lock);
1226 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1227 goto out;
1230 * If the event is in error state, clear that first.
1231 * That way, if we see the event in error state below, we
1232 * know that it has gone back into error state, as distinct
1233 * from the task having been scheduled away before the
1234 * cross-call arrived.
1236 if (event->state == PERF_EVENT_STATE_ERROR)
1237 event->state = PERF_EVENT_STATE_OFF;
1239 retry:
1240 if (!ctx->is_active) {
1241 __perf_event_mark_enabled(event, ctx);
1242 goto out;
1245 raw_spin_unlock_irq(&ctx->lock);
1247 if (!task_function_call(task, __perf_event_enable, event))
1248 return;
1250 raw_spin_lock_irq(&ctx->lock);
1253 * If the context is active and the event is still off,
1254 * we need to retry the cross-call.
1256 if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF) {
1258 * task could have been flipped by a concurrent
1259 * perf_event_context_sched_out()
1261 task = ctx->task;
1262 goto retry;
1265 out:
1266 raw_spin_unlock_irq(&ctx->lock);
1269 static int perf_event_refresh(struct perf_event *event, int refresh)
1272 * not supported on inherited events
1274 if (event->attr.inherit || !is_sampling_event(event))
1275 return -EINVAL;
1277 atomic_add(refresh, &event->event_limit);
1278 perf_event_enable(event);
1280 return 0;
1283 static void ctx_sched_out(struct perf_event_context *ctx,
1284 struct perf_cpu_context *cpuctx,
1285 enum event_type_t event_type)
1287 struct perf_event *event;
1289 raw_spin_lock(&ctx->lock);
1290 perf_pmu_disable(ctx->pmu);
1291 ctx->is_active = 0;
1292 if (likely(!ctx->nr_events))
1293 goto out;
1294 update_context_time(ctx);
1296 if (!ctx->nr_active)
1297 goto out;
1299 if (event_type & EVENT_PINNED) {
1300 list_for_each_entry(event, &ctx->pinned_groups, group_entry)
1301 group_sched_out(event, cpuctx, ctx);
1304 if (event_type & EVENT_FLEXIBLE) {
1305 list_for_each_entry(event, &ctx->flexible_groups, group_entry)
1306 group_sched_out(event, cpuctx, ctx);
1308 out:
1309 perf_pmu_enable(ctx->pmu);
1310 raw_spin_unlock(&ctx->lock);
1314 * Test whether two contexts are equivalent, i.e. whether they
1315 * have both been cloned from the same version of the same context
1316 * and they both have the same number of enabled events.
1317 * If the number of enabled events is the same, then the set
1318 * of enabled events should be the same, because these are both
1319 * inherited contexts, therefore we can't access individual events
1320 * in them directly with an fd; we can only enable/disable all
1321 * events via prctl, or enable/disable all events in a family
1322 * via ioctl, which will have the same effect on both contexts.
1324 static int context_equiv(struct perf_event_context *ctx1,
1325 struct perf_event_context *ctx2)
1327 return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1328 && ctx1->parent_gen == ctx2->parent_gen
1329 && !ctx1->pin_count && !ctx2->pin_count;
1332 static void __perf_event_sync_stat(struct perf_event *event,
1333 struct perf_event *next_event)
1335 u64 value;
1337 if (!event->attr.inherit_stat)
1338 return;
1341 * Update the event value, we cannot use perf_event_read()
1342 * because we're in the middle of a context switch and have IRQs
1343 * disabled, which upsets smp_call_function_single(), however
1344 * we know the event must be on the current CPU, therefore we
1345 * don't need to use it.
1347 switch (event->state) {
1348 case PERF_EVENT_STATE_ACTIVE:
1349 event->pmu->read(event);
1350 /* fall-through */
1352 case PERF_EVENT_STATE_INACTIVE:
1353 update_event_times(event);
1354 break;
1356 default:
1357 break;
1361 * In order to keep per-task stats reliable we need to flip the event
1362 * values when we flip the contexts.
1364 value = local64_read(&next_event->count);
1365 value = local64_xchg(&event->count, value);
1366 local64_set(&next_event->count, value);
1368 swap(event->total_time_enabled, next_event->total_time_enabled);
1369 swap(event->total_time_running, next_event->total_time_running);
1372 * Since we swizzled the values, update the user visible data too.
1374 perf_event_update_userpage(event);
1375 perf_event_update_userpage(next_event);
1378 #define list_next_entry(pos, member) \
1379 list_entry(pos->member.next, typeof(*pos), member)
1381 static void perf_event_sync_stat(struct perf_event_context *ctx,
1382 struct perf_event_context *next_ctx)
1384 struct perf_event *event, *next_event;
1386 if (!ctx->nr_stat)
1387 return;
1389 update_context_time(ctx);
1391 event = list_first_entry(&ctx->event_list,
1392 struct perf_event, event_entry);
1394 next_event = list_first_entry(&next_ctx->event_list,
1395 struct perf_event, event_entry);
1397 while (&event->event_entry != &ctx->event_list &&
1398 &next_event->event_entry != &next_ctx->event_list) {
1400 __perf_event_sync_stat(event, next_event);
1402 event = list_next_entry(event, event_entry);
1403 next_event = list_next_entry(next_event, event_entry);
1407 static void perf_event_context_sched_out(struct task_struct *task, int ctxn,
1408 struct task_struct *next)
1410 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn];
1411 struct perf_event_context *next_ctx;
1412 struct perf_event_context *parent;
1413 struct perf_cpu_context *cpuctx;
1414 int do_switch = 1;
1416 if (likely(!ctx))
1417 return;
1419 cpuctx = __get_cpu_context(ctx);
1420 if (!cpuctx->task_ctx)
1421 return;
1423 rcu_read_lock();
1424 parent = rcu_dereference(ctx->parent_ctx);
1425 next_ctx = next->perf_event_ctxp[ctxn];
1426 if (parent && next_ctx &&
1427 rcu_dereference(next_ctx->parent_ctx) == parent) {
1429 * Looks like the two contexts are clones, so we might be
1430 * able to optimize the context switch. We lock both
1431 * contexts and check that they are clones under the
1432 * lock (including re-checking that neither has been
1433 * uncloned in the meantime). It doesn't matter which
1434 * order we take the locks because no other cpu could
1435 * be trying to lock both of these tasks.
1437 raw_spin_lock(&ctx->lock);
1438 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
1439 if (context_equiv(ctx, next_ctx)) {
1441 * XXX do we need a memory barrier of sorts
1442 * wrt to rcu_dereference() of perf_event_ctxp
1444 task->perf_event_ctxp[ctxn] = next_ctx;
1445 next->perf_event_ctxp[ctxn] = ctx;
1446 ctx->task = next;
1447 next_ctx->task = task;
1448 do_switch = 0;
1450 perf_event_sync_stat(ctx, next_ctx);
1452 raw_spin_unlock(&next_ctx->lock);
1453 raw_spin_unlock(&ctx->lock);
1455 rcu_read_unlock();
1457 if (do_switch) {
1458 ctx_sched_out(ctx, cpuctx, EVENT_ALL);
1459 cpuctx->task_ctx = NULL;
1463 #define for_each_task_context_nr(ctxn) \
1464 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++)
1467 * Called from scheduler to remove the events of the current task,
1468 * with interrupts disabled.
1470 * We stop each event and update the event value in event->count.
1472 * This does not protect us against NMI, but disable()
1473 * sets the disabled bit in the control field of event _before_
1474 * accessing the event control register. If a NMI hits, then it will
1475 * not restart the event.
1477 void __perf_event_task_sched_out(struct task_struct *task,
1478 struct task_struct *next)
1480 int ctxn;
1482 for_each_task_context_nr(ctxn)
1483 perf_event_context_sched_out(task, ctxn, next);
1486 static void task_ctx_sched_out(struct perf_event_context *ctx,
1487 enum event_type_t event_type)
1489 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1491 if (!cpuctx->task_ctx)
1492 return;
1494 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
1495 return;
1497 ctx_sched_out(ctx, cpuctx, event_type);
1498 cpuctx->task_ctx = NULL;
1502 * Called with IRQs disabled
1504 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
1505 enum event_type_t event_type)
1507 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
1510 static void
1511 ctx_pinned_sched_in(struct perf_event_context *ctx,
1512 struct perf_cpu_context *cpuctx)
1514 struct perf_event *event;
1516 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
1517 if (event->state <= PERF_EVENT_STATE_OFF)
1518 continue;
1519 if (!event_filter_match(event))
1520 continue;
1522 if (group_can_go_on(event, cpuctx, 1))
1523 group_sched_in(event, cpuctx, ctx);
1526 * If this pinned group hasn't been scheduled,
1527 * put it in error state.
1529 if (event->state == PERF_EVENT_STATE_INACTIVE) {
1530 update_group_times(event);
1531 event->state = PERF_EVENT_STATE_ERROR;
1536 static void
1537 ctx_flexible_sched_in(struct perf_event_context *ctx,
1538 struct perf_cpu_context *cpuctx)
1540 struct perf_event *event;
1541 int can_add_hw = 1;
1543 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
1544 /* Ignore events in OFF or ERROR state */
1545 if (event->state <= PERF_EVENT_STATE_OFF)
1546 continue;
1548 * Listen to the 'cpu' scheduling filter constraint
1549 * of events:
1551 if (!event_filter_match(event))
1552 continue;
1554 if (group_can_go_on(event, cpuctx, can_add_hw)) {
1555 if (group_sched_in(event, cpuctx, ctx))
1556 can_add_hw = 0;
1561 static void
1562 ctx_sched_in(struct perf_event_context *ctx,
1563 struct perf_cpu_context *cpuctx,
1564 enum event_type_t event_type)
1566 raw_spin_lock(&ctx->lock);
1567 ctx->is_active = 1;
1568 if (likely(!ctx->nr_events))
1569 goto out;
1571 ctx->timestamp = perf_clock();
1574 * First go through the list and put on any pinned groups
1575 * in order to give them the best chance of going on.
1577 if (event_type & EVENT_PINNED)
1578 ctx_pinned_sched_in(ctx, cpuctx);
1580 /* Then walk through the lower prio flexible groups */
1581 if (event_type & EVENT_FLEXIBLE)
1582 ctx_flexible_sched_in(ctx, cpuctx);
1584 out:
1585 raw_spin_unlock(&ctx->lock);
1588 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
1589 enum event_type_t event_type)
1591 struct perf_event_context *ctx = &cpuctx->ctx;
1593 ctx_sched_in(ctx, cpuctx, event_type);
1596 static void task_ctx_sched_in(struct perf_event_context *ctx,
1597 enum event_type_t event_type)
1599 struct perf_cpu_context *cpuctx;
1601 cpuctx = __get_cpu_context(ctx);
1602 if (cpuctx->task_ctx == ctx)
1603 return;
1605 ctx_sched_in(ctx, cpuctx, event_type);
1606 cpuctx->task_ctx = ctx;
1609 static void perf_event_context_sched_in(struct perf_event_context *ctx)
1611 struct perf_cpu_context *cpuctx;
1613 cpuctx = __get_cpu_context(ctx);
1614 if (cpuctx->task_ctx == ctx)
1615 return;
1617 perf_pmu_disable(ctx->pmu);
1619 * We want to keep the following priority order:
1620 * cpu pinned (that don't need to move), task pinned,
1621 * cpu flexible, task flexible.
1623 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
1625 ctx_sched_in(ctx, cpuctx, EVENT_PINNED);
1626 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
1627 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE);
1629 cpuctx->task_ctx = ctx;
1632 * Since these rotations are per-cpu, we need to ensure the
1633 * cpu-context we got scheduled on is actually rotating.
1635 perf_pmu_rotate_start(ctx->pmu);
1636 perf_pmu_enable(ctx->pmu);
1640 * Called from scheduler to add the events of the current task
1641 * with interrupts disabled.
1643 * We restore the event value and then enable it.
1645 * This does not protect us against NMI, but enable()
1646 * sets the enabled bit in the control field of event _before_
1647 * accessing the event control register. If a NMI hits, then it will
1648 * keep the event running.
1650 void __perf_event_task_sched_in(struct task_struct *task)
1652 struct perf_event_context *ctx;
1653 int ctxn;
1655 for_each_task_context_nr(ctxn) {
1656 ctx = task->perf_event_ctxp[ctxn];
1657 if (likely(!ctx))
1658 continue;
1660 perf_event_context_sched_in(ctx);
1664 #define MAX_INTERRUPTS (~0ULL)
1666 static void perf_log_throttle(struct perf_event *event, int enable);
1668 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
1670 u64 frequency = event->attr.sample_freq;
1671 u64 sec = NSEC_PER_SEC;
1672 u64 divisor, dividend;
1674 int count_fls, nsec_fls, frequency_fls, sec_fls;
1676 count_fls = fls64(count);
1677 nsec_fls = fls64(nsec);
1678 frequency_fls = fls64(frequency);
1679 sec_fls = 30;
1682 * We got @count in @nsec, with a target of sample_freq HZ
1683 * the target period becomes:
1685 * @count * 10^9
1686 * period = -------------------
1687 * @nsec * sample_freq
1692 * Reduce accuracy by one bit such that @a and @b converge
1693 * to a similar magnitude.
1695 #define REDUCE_FLS(a, b) \
1696 do { \
1697 if (a##_fls > b##_fls) { \
1698 a >>= 1; \
1699 a##_fls--; \
1700 } else { \
1701 b >>= 1; \
1702 b##_fls--; \
1704 } while (0)
1707 * Reduce accuracy until either term fits in a u64, then proceed with
1708 * the other, so that finally we can do a u64/u64 division.
1710 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
1711 REDUCE_FLS(nsec, frequency);
1712 REDUCE_FLS(sec, count);
1715 if (count_fls + sec_fls > 64) {
1716 divisor = nsec * frequency;
1718 while (count_fls + sec_fls > 64) {
1719 REDUCE_FLS(count, sec);
1720 divisor >>= 1;
1723 dividend = count * sec;
1724 } else {
1725 dividend = count * sec;
1727 while (nsec_fls + frequency_fls > 64) {
1728 REDUCE_FLS(nsec, frequency);
1729 dividend >>= 1;
1732 divisor = nsec * frequency;
1735 if (!divisor)
1736 return dividend;
1738 return div64_u64(dividend, divisor);
1741 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count)
1743 struct hw_perf_event *hwc = &event->hw;
1744 s64 period, sample_period;
1745 s64 delta;
1747 period = perf_calculate_period(event, nsec, count);
1749 delta = (s64)(period - hwc->sample_period);
1750 delta = (delta + 7) / 8; /* low pass filter */
1752 sample_period = hwc->sample_period + delta;
1754 if (!sample_period)
1755 sample_period = 1;
1757 hwc->sample_period = sample_period;
1759 if (local64_read(&hwc->period_left) > 8*sample_period) {
1760 event->pmu->stop(event, PERF_EF_UPDATE);
1761 local64_set(&hwc->period_left, 0);
1762 event->pmu->start(event, PERF_EF_RELOAD);
1766 static void perf_ctx_adjust_freq(struct perf_event_context *ctx, u64 period)
1768 struct perf_event *event;
1769 struct hw_perf_event *hwc;
1770 u64 interrupts, now;
1771 s64 delta;
1773 raw_spin_lock(&ctx->lock);
1774 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
1775 if (event->state != PERF_EVENT_STATE_ACTIVE)
1776 continue;
1778 if (!event_filter_match(event))
1779 continue;
1781 hwc = &event->hw;
1783 interrupts = hwc->interrupts;
1784 hwc->interrupts = 0;
1787 * unthrottle events on the tick
1789 if (interrupts == MAX_INTERRUPTS) {
1790 perf_log_throttle(event, 1);
1791 event->pmu->start(event, 0);
1794 if (!event->attr.freq || !event->attr.sample_freq)
1795 continue;
1797 event->pmu->read(event);
1798 now = local64_read(&event->count);
1799 delta = now - hwc->freq_count_stamp;
1800 hwc->freq_count_stamp = now;
1802 if (delta > 0)
1803 perf_adjust_period(event, period, delta);
1805 raw_spin_unlock(&ctx->lock);
1809 * Round-robin a context's events:
1811 static void rotate_ctx(struct perf_event_context *ctx)
1813 raw_spin_lock(&ctx->lock);
1816 * Rotate the first entry last of non-pinned groups. Rotation might be
1817 * disabled by the inheritance code.
1819 if (!ctx->rotate_disable)
1820 list_rotate_left(&ctx->flexible_groups);
1822 raw_spin_unlock(&ctx->lock);
1826 * perf_pmu_rotate_start() and perf_rotate_context() are fully serialized
1827 * because they're strictly cpu affine and rotate_start is called with IRQs
1828 * disabled, while rotate_context is called from IRQ context.
1830 static void perf_rotate_context(struct perf_cpu_context *cpuctx)
1832 u64 interval = (u64)cpuctx->jiffies_interval * TICK_NSEC;
1833 struct perf_event_context *ctx = NULL;
1834 int rotate = 0, remove = 1;
1836 if (cpuctx->ctx.nr_events) {
1837 remove = 0;
1838 if (cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
1839 rotate = 1;
1842 ctx = cpuctx->task_ctx;
1843 if (ctx && ctx->nr_events) {
1844 remove = 0;
1845 if (ctx->nr_events != ctx->nr_active)
1846 rotate = 1;
1849 perf_pmu_disable(cpuctx->ctx.pmu);
1850 perf_ctx_adjust_freq(&cpuctx->ctx, interval);
1851 if (ctx)
1852 perf_ctx_adjust_freq(ctx, interval);
1854 if (!rotate)
1855 goto done;
1857 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
1858 if (ctx)
1859 task_ctx_sched_out(ctx, EVENT_FLEXIBLE);
1861 rotate_ctx(&cpuctx->ctx);
1862 if (ctx)
1863 rotate_ctx(ctx);
1865 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
1866 if (ctx)
1867 task_ctx_sched_in(ctx, EVENT_FLEXIBLE);
1869 done:
1870 if (remove)
1871 list_del_init(&cpuctx->rotation_list);
1873 perf_pmu_enable(cpuctx->ctx.pmu);
1876 void perf_event_task_tick(void)
1878 struct list_head *head = &__get_cpu_var(rotation_list);
1879 struct perf_cpu_context *cpuctx, *tmp;
1881 WARN_ON(!irqs_disabled());
1883 list_for_each_entry_safe(cpuctx, tmp, head, rotation_list) {
1884 if (cpuctx->jiffies_interval == 1 ||
1885 !(jiffies % cpuctx->jiffies_interval))
1886 perf_rotate_context(cpuctx);
1890 static int event_enable_on_exec(struct perf_event *event,
1891 struct perf_event_context *ctx)
1893 if (!event->attr.enable_on_exec)
1894 return 0;
1896 event->attr.enable_on_exec = 0;
1897 if (event->state >= PERF_EVENT_STATE_INACTIVE)
1898 return 0;
1900 __perf_event_mark_enabled(event, ctx);
1902 return 1;
1906 * Enable all of a task's events that have been marked enable-on-exec.
1907 * This expects task == current.
1909 static void perf_event_enable_on_exec(struct perf_event_context *ctx)
1911 struct perf_event *event;
1912 unsigned long flags;
1913 int enabled = 0;
1914 int ret;
1916 local_irq_save(flags);
1917 if (!ctx || !ctx->nr_events)
1918 goto out;
1920 task_ctx_sched_out(ctx, EVENT_ALL);
1922 raw_spin_lock(&ctx->lock);
1924 list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
1925 ret = event_enable_on_exec(event, ctx);
1926 if (ret)
1927 enabled = 1;
1930 list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
1931 ret = event_enable_on_exec(event, ctx);
1932 if (ret)
1933 enabled = 1;
1937 * Unclone this context if we enabled any event.
1939 if (enabled)
1940 unclone_ctx(ctx);
1942 raw_spin_unlock(&ctx->lock);
1944 perf_event_context_sched_in(ctx);
1945 out:
1946 local_irq_restore(flags);
1950 * Cross CPU call to read the hardware event
1952 static void __perf_event_read(void *info)
1954 struct perf_event *event = info;
1955 struct perf_event_context *ctx = event->ctx;
1956 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx);
1959 * If this is a task context, we need to check whether it is
1960 * the current task context of this cpu. If not it has been
1961 * scheduled out before the smp call arrived. In that case
1962 * event->count would have been updated to a recent sample
1963 * when the event was scheduled out.
1965 if (ctx->task && cpuctx->task_ctx != ctx)
1966 return;
1968 raw_spin_lock(&ctx->lock);
1969 if (ctx->is_active)
1970 update_context_time(ctx);
1971 update_event_times(event);
1972 if (event->state == PERF_EVENT_STATE_ACTIVE)
1973 event->pmu->read(event);
1974 raw_spin_unlock(&ctx->lock);
1977 static inline u64 perf_event_count(struct perf_event *event)
1979 return local64_read(&event->count) + atomic64_read(&event->child_count);
1982 static u64 perf_event_read(struct perf_event *event)
1985 * If event is enabled and currently active on a CPU, update the
1986 * value in the event structure:
1988 if (event->state == PERF_EVENT_STATE_ACTIVE) {
1989 smp_call_function_single(event->oncpu,
1990 __perf_event_read, event, 1);
1991 } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
1992 struct perf_event_context *ctx = event->ctx;
1993 unsigned long flags;
1995 raw_spin_lock_irqsave(&ctx->lock, flags);
1997 * may read while context is not active
1998 * (e.g., thread is blocked), in that case
1999 * we cannot update context time
2001 if (ctx->is_active)
2002 update_context_time(ctx);
2003 update_event_times(event);
2004 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2007 return perf_event_count(event);
2011 * Callchain support
2014 struct callchain_cpus_entries {
2015 struct rcu_head rcu_head;
2016 struct perf_callchain_entry *cpu_entries[0];
2019 static DEFINE_PER_CPU(int, callchain_recursion[PERF_NR_CONTEXTS]);
2020 static atomic_t nr_callchain_events;
2021 static DEFINE_MUTEX(callchain_mutex);
2022 struct callchain_cpus_entries *callchain_cpus_entries;
2025 __weak void perf_callchain_kernel(struct perf_callchain_entry *entry,
2026 struct pt_regs *regs)
2030 __weak void perf_callchain_user(struct perf_callchain_entry *entry,
2031 struct pt_regs *regs)
2035 static void release_callchain_buffers_rcu(struct rcu_head *head)
2037 struct callchain_cpus_entries *entries;
2038 int cpu;
2040 entries = container_of(head, struct callchain_cpus_entries, rcu_head);
2042 for_each_possible_cpu(cpu)
2043 kfree(entries->cpu_entries[cpu]);
2045 kfree(entries);
2048 static void release_callchain_buffers(void)
2050 struct callchain_cpus_entries *entries;
2052 entries = callchain_cpus_entries;
2053 rcu_assign_pointer(callchain_cpus_entries, NULL);
2054 call_rcu(&entries->rcu_head, release_callchain_buffers_rcu);
2057 static int alloc_callchain_buffers(void)
2059 int cpu;
2060 int size;
2061 struct callchain_cpus_entries *entries;
2064 * We can't use the percpu allocation API for data that can be
2065 * accessed from NMI. Use a temporary manual per cpu allocation
2066 * until that gets sorted out.
2068 size = offsetof(struct callchain_cpus_entries, cpu_entries[nr_cpu_ids]);
2070 entries = kzalloc(size, GFP_KERNEL);
2071 if (!entries)
2072 return -ENOMEM;
2074 size = sizeof(struct perf_callchain_entry) * PERF_NR_CONTEXTS;
2076 for_each_possible_cpu(cpu) {
2077 entries->cpu_entries[cpu] = kmalloc_node(size, GFP_KERNEL,
2078 cpu_to_node(cpu));
2079 if (!entries->cpu_entries[cpu])
2080 goto fail;
2083 rcu_assign_pointer(callchain_cpus_entries, entries);
2085 return 0;
2087 fail:
2088 for_each_possible_cpu(cpu)
2089 kfree(entries->cpu_entries[cpu]);
2090 kfree(entries);
2092 return -ENOMEM;
2095 static int get_callchain_buffers(void)
2097 int err = 0;
2098 int count;
2100 mutex_lock(&callchain_mutex);
2102 count = atomic_inc_return(&nr_callchain_events);
2103 if (WARN_ON_ONCE(count < 1)) {
2104 err = -EINVAL;
2105 goto exit;
2108 if (count > 1) {
2109 /* If the allocation failed, give up */
2110 if (!callchain_cpus_entries)
2111 err = -ENOMEM;
2112 goto exit;
2115 err = alloc_callchain_buffers();
2116 if (err)
2117 release_callchain_buffers();
2118 exit:
2119 mutex_unlock(&callchain_mutex);
2121 return err;
2124 static void put_callchain_buffers(void)
2126 if (atomic_dec_and_mutex_lock(&nr_callchain_events, &callchain_mutex)) {
2127 release_callchain_buffers();
2128 mutex_unlock(&callchain_mutex);
2132 static int get_recursion_context(int *recursion)
2134 int rctx;
2136 if (in_nmi())
2137 rctx = 3;
2138 else if (in_irq())
2139 rctx = 2;
2140 else if (in_softirq())
2141 rctx = 1;
2142 else
2143 rctx = 0;
2145 if (recursion[rctx])
2146 return -1;
2148 recursion[rctx]++;
2149 barrier();
2151 return rctx;
2154 static inline void put_recursion_context(int *recursion, int rctx)
2156 barrier();
2157 recursion[rctx]--;
2160 static struct perf_callchain_entry *get_callchain_entry(int *rctx)
2162 int cpu;
2163 struct callchain_cpus_entries *entries;
2165 *rctx = get_recursion_context(__get_cpu_var(callchain_recursion));
2166 if (*rctx == -1)
2167 return NULL;
2169 entries = rcu_dereference(callchain_cpus_entries);
2170 if (!entries)
2171 return NULL;
2173 cpu = smp_processor_id();
2175 return &entries->cpu_entries[cpu][*rctx];
2178 static void
2179 put_callchain_entry(int rctx)
2181 put_recursion_context(__get_cpu_var(callchain_recursion), rctx);
2184 static struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2186 int rctx;
2187 struct perf_callchain_entry *entry;
2190 entry = get_callchain_entry(&rctx);
2191 if (rctx == -1)
2192 return NULL;
2194 if (!entry)
2195 goto exit_put;
2197 entry->nr = 0;
2199 if (!user_mode(regs)) {
2200 perf_callchain_store(entry, PERF_CONTEXT_KERNEL);
2201 perf_callchain_kernel(entry, regs);
2202 if (current->mm)
2203 regs = task_pt_regs(current);
2204 else
2205 regs = NULL;
2208 if (regs) {
2209 perf_callchain_store(entry, PERF_CONTEXT_USER);
2210 perf_callchain_user(entry, regs);
2213 exit_put:
2214 put_callchain_entry(rctx);
2216 return entry;
2220 * Initialize the perf_event context in a task_struct:
2222 static void __perf_event_init_context(struct perf_event_context *ctx)
2224 raw_spin_lock_init(&ctx->lock);
2225 mutex_init(&ctx->mutex);
2226 INIT_LIST_HEAD(&ctx->pinned_groups);
2227 INIT_LIST_HEAD(&ctx->flexible_groups);
2228 INIT_LIST_HEAD(&ctx->event_list);
2229 atomic_set(&ctx->refcount, 1);
2232 static struct perf_event_context *
2233 alloc_perf_context(struct pmu *pmu, struct task_struct *task)
2235 struct perf_event_context *ctx;
2237 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
2238 if (!ctx)
2239 return NULL;
2241 __perf_event_init_context(ctx);
2242 if (task) {
2243 ctx->task = task;
2244 get_task_struct(task);
2246 ctx->pmu = pmu;
2248 return ctx;
2251 static struct task_struct *
2252 find_lively_task_by_vpid(pid_t vpid)
2254 struct task_struct *task;
2255 int err;
2257 rcu_read_lock();
2258 if (!vpid)
2259 task = current;
2260 else
2261 task = find_task_by_vpid(vpid);
2262 if (task)
2263 get_task_struct(task);
2264 rcu_read_unlock();
2266 if (!task)
2267 return ERR_PTR(-ESRCH);
2269 /* Reuse ptrace permission checks for now. */
2270 err = -EACCES;
2271 if (!ptrace_may_access(task, PTRACE_MODE_READ))
2272 goto errout;
2274 return task;
2275 errout:
2276 put_task_struct(task);
2277 return ERR_PTR(err);
2282 * Returns a matching context with refcount and pincount.
2284 static struct perf_event_context *
2285 find_get_context(struct pmu *pmu, struct task_struct *task, int cpu)
2287 struct perf_event_context *ctx;
2288 struct perf_cpu_context *cpuctx;
2289 unsigned long flags;
2290 int ctxn, err;
2292 if (!task) {
2293 /* Must be root to operate on a CPU event: */
2294 if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
2295 return ERR_PTR(-EACCES);
2298 * We could be clever and allow to attach a event to an
2299 * offline CPU and activate it when the CPU comes up, but
2300 * that's for later.
2302 if (!cpu_online(cpu))
2303 return ERR_PTR(-ENODEV);
2305 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
2306 ctx = &cpuctx->ctx;
2307 get_ctx(ctx);
2308 ++ctx->pin_count;
2310 return ctx;
2313 err = -EINVAL;
2314 ctxn = pmu->task_ctx_nr;
2315 if (ctxn < 0)
2316 goto errout;
2318 retry:
2319 ctx = perf_lock_task_context(task, ctxn, &flags);
2320 if (ctx) {
2321 unclone_ctx(ctx);
2322 ++ctx->pin_count;
2323 raw_spin_unlock_irqrestore(&ctx->lock, flags);
2326 if (!ctx) {
2327 ctx = alloc_perf_context(pmu, task);
2328 err = -ENOMEM;
2329 if (!ctx)
2330 goto errout;
2332 get_ctx(ctx);
2334 err = 0;
2335 mutex_lock(&task->perf_event_mutex);
2337 * If it has already passed perf_event_exit_task().
2338 * we must see PF_EXITING, it takes this mutex too.
2340 if (task->flags & PF_EXITING)
2341 err = -ESRCH;
2342 else if (task->perf_event_ctxp[ctxn])
2343 err = -EAGAIN;
2344 else {
2345 ++ctx->pin_count;
2346 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx);
2348 mutex_unlock(&task->perf_event_mutex);
2350 if (unlikely(err)) {
2351 put_task_struct(task);
2352 kfree(ctx);
2354 if (err == -EAGAIN)
2355 goto retry;
2356 goto errout;
2360 return ctx;
2362 errout:
2363 return ERR_PTR(err);
2366 static void perf_event_free_filter(struct perf_event *event);
2368 static void free_event_rcu(struct rcu_head *head)
2370 struct perf_event *event;
2372 event = container_of(head, struct perf_event, rcu_head);
2373 if (event->ns)
2374 put_pid_ns(event->ns);
2375 perf_event_free_filter(event);
2376 kfree(event);
2379 static void perf_buffer_put(struct perf_buffer *buffer);
2381 static void free_event(struct perf_event *event)
2383 irq_work_sync(&event->pending);
2385 if (!event->parent) {
2386 if (event->attach_state & PERF_ATTACH_TASK)
2387 jump_label_dec(&perf_task_events);
2388 if (event->attr.mmap || event->attr.mmap_data)
2389 atomic_dec(&nr_mmap_events);
2390 if (event->attr.comm)
2391 atomic_dec(&nr_comm_events);
2392 if (event->attr.task)
2393 atomic_dec(&nr_task_events);
2394 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN)
2395 put_callchain_buffers();
2398 if (event->buffer) {
2399 perf_buffer_put(event->buffer);
2400 event->buffer = NULL;
2403 if (event->destroy)
2404 event->destroy(event);
2406 if (event->ctx)
2407 put_ctx(event->ctx);
2409 call_rcu(&event->rcu_head, free_event_rcu);
2412 int perf_event_release_kernel(struct perf_event *event)
2414 struct perf_event_context *ctx = event->ctx;
2417 * Remove from the PMU, can't get re-enabled since we got
2418 * here because the last ref went.
2420 perf_event_disable(event);
2422 WARN_ON_ONCE(ctx->parent_ctx);
2424 * There are two ways this annotation is useful:
2426 * 1) there is a lock recursion from perf_event_exit_task
2427 * see the comment there.
2429 * 2) there is a lock-inversion with mmap_sem through
2430 * perf_event_read_group(), which takes faults while
2431 * holding ctx->mutex, however this is called after
2432 * the last filedesc died, so there is no possibility
2433 * to trigger the AB-BA case.
2435 mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
2436 raw_spin_lock_irq(&ctx->lock);
2437 perf_group_detach(event);
2438 list_del_event(event, ctx);
2439 raw_spin_unlock_irq(&ctx->lock);
2440 mutex_unlock(&ctx->mutex);
2442 free_event(event);
2444 return 0;
2446 EXPORT_SYMBOL_GPL(perf_event_release_kernel);
2449 * Called when the last reference to the file is gone.
2451 static int perf_release(struct inode *inode, struct file *file)
2453 struct perf_event *event = file->private_data;
2454 struct task_struct *owner;
2456 file->private_data = NULL;
2458 rcu_read_lock();
2459 owner = ACCESS_ONCE(event->owner);
2461 * Matches the smp_wmb() in perf_event_exit_task(). If we observe
2462 * !owner it means the list deletion is complete and we can indeed
2463 * free this event, otherwise we need to serialize on
2464 * owner->perf_event_mutex.
2466 smp_read_barrier_depends();
2467 if (owner) {
2469 * Since delayed_put_task_struct() also drops the last
2470 * task reference we can safely take a new reference
2471 * while holding the rcu_read_lock().
2473 get_task_struct(owner);
2475 rcu_read_unlock();
2477 if (owner) {
2478 mutex_lock(&owner->perf_event_mutex);
2480 * We have to re-check the event->owner field, if it is cleared
2481 * we raced with perf_event_exit_task(), acquiring the mutex
2482 * ensured they're done, and we can proceed with freeing the
2483 * event.
2485 if (event->owner)
2486 list_del_init(&event->owner_entry);
2487 mutex_unlock(&owner->perf_event_mutex);
2488 put_task_struct(owner);
2491 return perf_event_release_kernel(event);
2494 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
2496 struct perf_event *child;
2497 u64 total = 0;
2499 *enabled = 0;
2500 *running = 0;
2502 mutex_lock(&event->child_mutex);
2503 total += perf_event_read(event);
2504 *enabled += event->total_time_enabled +
2505 atomic64_read(&event->child_total_time_enabled);
2506 *running += event->total_time_running +
2507 atomic64_read(&event->child_total_time_running);
2509 list_for_each_entry(child, &event->child_list, child_list) {
2510 total += perf_event_read(child);
2511 *enabled += child->total_time_enabled;
2512 *running += child->total_time_running;
2514 mutex_unlock(&event->child_mutex);
2516 return total;
2518 EXPORT_SYMBOL_GPL(perf_event_read_value);
2520 static int perf_event_read_group(struct perf_event *event,
2521 u64 read_format, char __user *buf)
2523 struct perf_event *leader = event->group_leader, *sub;
2524 int n = 0, size = 0, ret = -EFAULT;
2525 struct perf_event_context *ctx = leader->ctx;
2526 u64 values[5];
2527 u64 count, enabled, running;
2529 mutex_lock(&ctx->mutex);
2530 count = perf_event_read_value(leader, &enabled, &running);
2532 values[n++] = 1 + leader->nr_siblings;
2533 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2534 values[n++] = enabled;
2535 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2536 values[n++] = running;
2537 values[n++] = count;
2538 if (read_format & PERF_FORMAT_ID)
2539 values[n++] = primary_event_id(leader);
2541 size = n * sizeof(u64);
2543 if (copy_to_user(buf, values, size))
2544 goto unlock;
2546 ret = size;
2548 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
2549 n = 0;
2551 values[n++] = perf_event_read_value(sub, &enabled, &running);
2552 if (read_format & PERF_FORMAT_ID)
2553 values[n++] = primary_event_id(sub);
2555 size = n * sizeof(u64);
2557 if (copy_to_user(buf + ret, values, size)) {
2558 ret = -EFAULT;
2559 goto unlock;
2562 ret += size;
2564 unlock:
2565 mutex_unlock(&ctx->mutex);
2567 return ret;
2570 static int perf_event_read_one(struct perf_event *event,
2571 u64 read_format, char __user *buf)
2573 u64 enabled, running;
2574 u64 values[4];
2575 int n = 0;
2577 values[n++] = perf_event_read_value(event, &enabled, &running);
2578 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2579 values[n++] = enabled;
2580 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2581 values[n++] = running;
2582 if (read_format & PERF_FORMAT_ID)
2583 values[n++] = primary_event_id(event);
2585 if (copy_to_user(buf, values, n * sizeof(u64)))
2586 return -EFAULT;
2588 return n * sizeof(u64);
2592 * Read the performance event - simple non blocking version for now
2594 static ssize_t
2595 perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
2597 u64 read_format = event->attr.read_format;
2598 int ret;
2601 * Return end-of-file for a read on a event that is in
2602 * error state (i.e. because it was pinned but it couldn't be
2603 * scheduled on to the CPU at some point).
2605 if (event->state == PERF_EVENT_STATE_ERROR)
2606 return 0;
2608 if (count < event->read_size)
2609 return -ENOSPC;
2611 WARN_ON_ONCE(event->ctx->parent_ctx);
2612 if (read_format & PERF_FORMAT_GROUP)
2613 ret = perf_event_read_group(event, read_format, buf);
2614 else
2615 ret = perf_event_read_one(event, read_format, buf);
2617 return ret;
2620 static ssize_t
2621 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
2623 struct perf_event *event = file->private_data;
2625 return perf_read_hw(event, buf, count);
2628 static unsigned int perf_poll(struct file *file, poll_table *wait)
2630 struct perf_event *event = file->private_data;
2631 struct perf_buffer *buffer;
2632 unsigned int events = POLL_HUP;
2634 rcu_read_lock();
2635 buffer = rcu_dereference(event->buffer);
2636 if (buffer)
2637 events = atomic_xchg(&buffer->poll, 0);
2638 rcu_read_unlock();
2640 poll_wait(file, &event->waitq, wait);
2642 return events;
2645 static void perf_event_reset(struct perf_event *event)
2647 (void)perf_event_read(event);
2648 local64_set(&event->count, 0);
2649 perf_event_update_userpage(event);
2653 * Holding the top-level event's child_mutex means that any
2654 * descendant process that has inherited this event will block
2655 * in sync_child_event if it goes to exit, thus satisfying the
2656 * task existence requirements of perf_event_enable/disable.
2658 static void perf_event_for_each_child(struct perf_event *event,
2659 void (*func)(struct perf_event *))
2661 struct perf_event *child;
2663 WARN_ON_ONCE(event->ctx->parent_ctx);
2664 mutex_lock(&event->child_mutex);
2665 func(event);
2666 list_for_each_entry(child, &event->child_list, child_list)
2667 func(child);
2668 mutex_unlock(&event->child_mutex);
2671 static void perf_event_for_each(struct perf_event *event,
2672 void (*func)(struct perf_event *))
2674 struct perf_event_context *ctx = event->ctx;
2675 struct perf_event *sibling;
2677 WARN_ON_ONCE(ctx->parent_ctx);
2678 mutex_lock(&ctx->mutex);
2679 event = event->group_leader;
2681 perf_event_for_each_child(event, func);
2682 func(event);
2683 list_for_each_entry(sibling, &event->sibling_list, group_entry)
2684 perf_event_for_each_child(event, func);
2685 mutex_unlock(&ctx->mutex);
2688 static int perf_event_period(struct perf_event *event, u64 __user *arg)
2690 struct perf_event_context *ctx = event->ctx;
2691 int ret = 0;
2692 u64 value;
2694 if (!is_sampling_event(event))
2695 return -EINVAL;
2697 if (copy_from_user(&value, arg, sizeof(value)))
2698 return -EFAULT;
2700 if (!value)
2701 return -EINVAL;
2703 raw_spin_lock_irq(&ctx->lock);
2704 if (event->attr.freq) {
2705 if (value > sysctl_perf_event_sample_rate) {
2706 ret = -EINVAL;
2707 goto unlock;
2710 event->attr.sample_freq = value;
2711 } else {
2712 event->attr.sample_period = value;
2713 event->hw.sample_period = value;
2715 unlock:
2716 raw_spin_unlock_irq(&ctx->lock);
2718 return ret;
2721 static const struct file_operations perf_fops;
2723 static struct perf_event *perf_fget_light(int fd, int *fput_needed)
2725 struct file *file;
2727 file = fget_light(fd, fput_needed);
2728 if (!file)
2729 return ERR_PTR(-EBADF);
2731 if (file->f_op != &perf_fops) {
2732 fput_light(file, *fput_needed);
2733 *fput_needed = 0;
2734 return ERR_PTR(-EBADF);
2737 return file->private_data;
2740 static int perf_event_set_output(struct perf_event *event,
2741 struct perf_event *output_event);
2742 static int perf_event_set_filter(struct perf_event *event, void __user *arg);
2744 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2746 struct perf_event *event = file->private_data;
2747 void (*func)(struct perf_event *);
2748 u32 flags = arg;
2750 switch (cmd) {
2751 case PERF_EVENT_IOC_ENABLE:
2752 func = perf_event_enable;
2753 break;
2754 case PERF_EVENT_IOC_DISABLE:
2755 func = perf_event_disable;
2756 break;
2757 case PERF_EVENT_IOC_RESET:
2758 func = perf_event_reset;
2759 break;
2761 case PERF_EVENT_IOC_REFRESH:
2762 return perf_event_refresh(event, arg);
2764 case PERF_EVENT_IOC_PERIOD:
2765 return perf_event_period(event, (u64 __user *)arg);
2767 case PERF_EVENT_IOC_SET_OUTPUT:
2769 struct perf_event *output_event = NULL;
2770 int fput_needed = 0;
2771 int ret;
2773 if (arg != -1) {
2774 output_event = perf_fget_light(arg, &fput_needed);
2775 if (IS_ERR(output_event))
2776 return PTR_ERR(output_event);
2779 ret = perf_event_set_output(event, output_event);
2780 if (output_event)
2781 fput_light(output_event->filp, fput_needed);
2783 return ret;
2786 case PERF_EVENT_IOC_SET_FILTER:
2787 return perf_event_set_filter(event, (void __user *)arg);
2789 default:
2790 return -ENOTTY;
2793 if (flags & PERF_IOC_FLAG_GROUP)
2794 perf_event_for_each(event, func);
2795 else
2796 perf_event_for_each_child(event, func);
2798 return 0;
2801 int perf_event_task_enable(void)
2803 struct perf_event *event;
2805 mutex_lock(&current->perf_event_mutex);
2806 list_for_each_entry(event, &current->perf_event_list, owner_entry)
2807 perf_event_for_each_child(event, perf_event_enable);
2808 mutex_unlock(&current->perf_event_mutex);
2810 return 0;
2813 int perf_event_task_disable(void)
2815 struct perf_event *event;
2817 mutex_lock(&current->perf_event_mutex);
2818 list_for_each_entry(event, &current->perf_event_list, owner_entry)
2819 perf_event_for_each_child(event, perf_event_disable);
2820 mutex_unlock(&current->perf_event_mutex);
2822 return 0;
2825 #ifndef PERF_EVENT_INDEX_OFFSET
2826 # define PERF_EVENT_INDEX_OFFSET 0
2827 #endif
2829 static int perf_event_index(struct perf_event *event)
2831 if (event->hw.state & PERF_HES_STOPPED)
2832 return 0;
2834 if (event->state != PERF_EVENT_STATE_ACTIVE)
2835 return 0;
2837 return event->hw.idx + 1 - PERF_EVENT_INDEX_OFFSET;
2841 * Callers need to ensure there can be no nesting of this function, otherwise
2842 * the seqlock logic goes bad. We can not serialize this because the arch
2843 * code calls this from NMI context.
2845 void perf_event_update_userpage(struct perf_event *event)
2847 struct perf_event_mmap_page *userpg;
2848 struct perf_buffer *buffer;
2850 rcu_read_lock();
2851 buffer = rcu_dereference(event->buffer);
2852 if (!buffer)
2853 goto unlock;
2855 userpg = buffer->user_page;
2858 * Disable preemption so as to not let the corresponding user-space
2859 * spin too long if we get preempted.
2861 preempt_disable();
2862 ++userpg->lock;
2863 barrier();
2864 userpg->index = perf_event_index(event);
2865 userpg->offset = perf_event_count(event);
2866 if (event->state == PERF_EVENT_STATE_ACTIVE)
2867 userpg->offset -= local64_read(&event->hw.prev_count);
2869 userpg->time_enabled = event->total_time_enabled +
2870 atomic64_read(&event->child_total_time_enabled);
2872 userpg->time_running = event->total_time_running +
2873 atomic64_read(&event->child_total_time_running);
2875 barrier();
2876 ++userpg->lock;
2877 preempt_enable();
2878 unlock:
2879 rcu_read_unlock();
2882 static unsigned long perf_data_size(struct perf_buffer *buffer);
2884 static void
2885 perf_buffer_init(struct perf_buffer *buffer, long watermark, int flags)
2887 long max_size = perf_data_size(buffer);
2889 if (watermark)
2890 buffer->watermark = min(max_size, watermark);
2892 if (!buffer->watermark)
2893 buffer->watermark = max_size / 2;
2895 if (flags & PERF_BUFFER_WRITABLE)
2896 buffer->writable = 1;
2898 atomic_set(&buffer->refcount, 1);
2901 #ifndef CONFIG_PERF_USE_VMALLOC
2904 * Back perf_mmap() with regular GFP_KERNEL-0 pages.
2907 static struct page *
2908 perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
2910 if (pgoff > buffer->nr_pages)
2911 return NULL;
2913 if (pgoff == 0)
2914 return virt_to_page(buffer->user_page);
2916 return virt_to_page(buffer->data_pages[pgoff - 1]);
2919 static void *perf_mmap_alloc_page(int cpu)
2921 struct page *page;
2922 int node;
2924 node = (cpu == -1) ? cpu : cpu_to_node(cpu);
2925 page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
2926 if (!page)
2927 return NULL;
2929 return page_address(page);
2932 static struct perf_buffer *
2933 perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
2935 struct perf_buffer *buffer;
2936 unsigned long size;
2937 int i;
2939 size = sizeof(struct perf_buffer);
2940 size += nr_pages * sizeof(void *);
2942 buffer = kzalloc(size, GFP_KERNEL);
2943 if (!buffer)
2944 goto fail;
2946 buffer->user_page = perf_mmap_alloc_page(cpu);
2947 if (!buffer->user_page)
2948 goto fail_user_page;
2950 for (i = 0; i < nr_pages; i++) {
2951 buffer->data_pages[i] = perf_mmap_alloc_page(cpu);
2952 if (!buffer->data_pages[i])
2953 goto fail_data_pages;
2956 buffer->nr_pages = nr_pages;
2958 perf_buffer_init(buffer, watermark, flags);
2960 return buffer;
2962 fail_data_pages:
2963 for (i--; i >= 0; i--)
2964 free_page((unsigned long)buffer->data_pages[i]);
2966 free_page((unsigned long)buffer->user_page);
2968 fail_user_page:
2969 kfree(buffer);
2971 fail:
2972 return NULL;
2975 static void perf_mmap_free_page(unsigned long addr)
2977 struct page *page = virt_to_page((void *)addr);
2979 page->mapping = NULL;
2980 __free_page(page);
2983 static void perf_buffer_free(struct perf_buffer *buffer)
2985 int i;
2987 perf_mmap_free_page((unsigned long)buffer->user_page);
2988 for (i = 0; i < buffer->nr_pages; i++)
2989 perf_mmap_free_page((unsigned long)buffer->data_pages[i]);
2990 kfree(buffer);
2993 static inline int page_order(struct perf_buffer *buffer)
2995 return 0;
2998 #else
3001 * Back perf_mmap() with vmalloc memory.
3003 * Required for architectures that have d-cache aliasing issues.
3006 static inline int page_order(struct perf_buffer *buffer)
3008 return buffer->page_order;
3011 static struct page *
3012 perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
3014 if (pgoff > (1UL << page_order(buffer)))
3015 return NULL;
3017 return vmalloc_to_page((void *)buffer->user_page + pgoff * PAGE_SIZE);
3020 static void perf_mmap_unmark_page(void *addr)
3022 struct page *page = vmalloc_to_page(addr);
3024 page->mapping = NULL;
3027 static void perf_buffer_free_work(struct work_struct *work)
3029 struct perf_buffer *buffer;
3030 void *base;
3031 int i, nr;
3033 buffer = container_of(work, struct perf_buffer, work);
3034 nr = 1 << page_order(buffer);
3036 base = buffer->user_page;
3037 for (i = 0; i < nr + 1; i++)
3038 perf_mmap_unmark_page(base + (i * PAGE_SIZE));
3040 vfree(base);
3041 kfree(buffer);
3044 static void perf_buffer_free(struct perf_buffer *buffer)
3046 schedule_work(&buffer->work);
3049 static struct perf_buffer *
3050 perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
3052 struct perf_buffer *buffer;
3053 unsigned long size;
3054 void *all_buf;
3056 size = sizeof(struct perf_buffer);
3057 size += sizeof(void *);
3059 buffer = kzalloc(size, GFP_KERNEL);
3060 if (!buffer)
3061 goto fail;
3063 INIT_WORK(&buffer->work, perf_buffer_free_work);
3065 all_buf = vmalloc_user((nr_pages + 1) * PAGE_SIZE);
3066 if (!all_buf)
3067 goto fail_all_buf;
3069 buffer->user_page = all_buf;
3070 buffer->data_pages[0] = all_buf + PAGE_SIZE;
3071 buffer->page_order = ilog2(nr_pages);
3072 buffer->nr_pages = 1;
3074 perf_buffer_init(buffer, watermark, flags);
3076 return buffer;
3078 fail_all_buf:
3079 kfree(buffer);
3081 fail:
3082 return NULL;
3085 #endif
3087 static unsigned long perf_data_size(struct perf_buffer *buffer)
3089 return buffer->nr_pages << (PAGE_SHIFT + page_order(buffer));
3092 static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
3094 struct perf_event *event = vma->vm_file->private_data;
3095 struct perf_buffer *buffer;
3096 int ret = VM_FAULT_SIGBUS;
3098 if (vmf->flags & FAULT_FLAG_MKWRITE) {
3099 if (vmf->pgoff == 0)
3100 ret = 0;
3101 return ret;
3104 rcu_read_lock();
3105 buffer = rcu_dereference(event->buffer);
3106 if (!buffer)
3107 goto unlock;
3109 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
3110 goto unlock;
3112 vmf->page = perf_mmap_to_page(buffer, vmf->pgoff);
3113 if (!vmf->page)
3114 goto unlock;
3116 get_page(vmf->page);
3117 vmf->page->mapping = vma->vm_file->f_mapping;
3118 vmf->page->index = vmf->pgoff;
3120 ret = 0;
3121 unlock:
3122 rcu_read_unlock();
3124 return ret;
3127 static void perf_buffer_free_rcu(struct rcu_head *rcu_head)
3129 struct perf_buffer *buffer;
3131 buffer = container_of(rcu_head, struct perf_buffer, rcu_head);
3132 perf_buffer_free(buffer);
3135 static struct perf_buffer *perf_buffer_get(struct perf_event *event)
3137 struct perf_buffer *buffer;
3139 rcu_read_lock();
3140 buffer = rcu_dereference(event->buffer);
3141 if (buffer) {
3142 if (!atomic_inc_not_zero(&buffer->refcount))
3143 buffer = NULL;
3145 rcu_read_unlock();
3147 return buffer;
3150 static void perf_buffer_put(struct perf_buffer *buffer)
3152 if (!atomic_dec_and_test(&buffer->refcount))
3153 return;
3155 call_rcu(&buffer->rcu_head, perf_buffer_free_rcu);
3158 static void perf_mmap_open(struct vm_area_struct *vma)
3160 struct perf_event *event = vma->vm_file->private_data;
3162 atomic_inc(&event->mmap_count);
3165 static void perf_mmap_close(struct vm_area_struct *vma)
3167 struct perf_event *event = vma->vm_file->private_data;
3169 if (atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) {
3170 unsigned long size = perf_data_size(event->buffer);
3171 struct user_struct *user = event->mmap_user;
3172 struct perf_buffer *buffer = event->buffer;
3174 atomic_long_sub((size >> PAGE_SHIFT) + 1, &user->locked_vm);
3175 vma->vm_mm->locked_vm -= event->mmap_locked;
3176 rcu_assign_pointer(event->buffer, NULL);
3177 mutex_unlock(&event->mmap_mutex);
3179 perf_buffer_put(buffer);
3180 free_uid(user);
3184 static const struct vm_operations_struct perf_mmap_vmops = {
3185 .open = perf_mmap_open,
3186 .close = perf_mmap_close,
3187 .fault = perf_mmap_fault,
3188 .page_mkwrite = perf_mmap_fault,
3191 static int perf_mmap(struct file *file, struct vm_area_struct *vma)
3193 struct perf_event *event = file->private_data;
3194 unsigned long user_locked, user_lock_limit;
3195 struct user_struct *user = current_user();
3196 unsigned long locked, lock_limit;
3197 struct perf_buffer *buffer;
3198 unsigned long vma_size;
3199 unsigned long nr_pages;
3200 long user_extra, extra;
3201 int ret = 0, flags = 0;
3204 * Don't allow mmap() of inherited per-task counters. This would
3205 * create a performance issue due to all children writing to the
3206 * same buffer.
3208 if (event->cpu == -1 && event->attr.inherit)
3209 return -EINVAL;
3211 if (!(vma->vm_flags & VM_SHARED))
3212 return -EINVAL;
3214 vma_size = vma->vm_end - vma->vm_start;
3215 nr_pages = (vma_size / PAGE_SIZE) - 1;
3218 * If we have buffer pages ensure they're a power-of-two number, so we
3219 * can do bitmasks instead of modulo.
3221 if (nr_pages != 0 && !is_power_of_2(nr_pages))
3222 return -EINVAL;
3224 if (vma_size != PAGE_SIZE * (1 + nr_pages))
3225 return -EINVAL;
3227 if (vma->vm_pgoff != 0)
3228 return -EINVAL;
3230 WARN_ON_ONCE(event->ctx->parent_ctx);
3231 mutex_lock(&event->mmap_mutex);
3232 if (event->buffer) {
3233 if (event->buffer->nr_pages == nr_pages)
3234 atomic_inc(&event->buffer->refcount);
3235 else
3236 ret = -EINVAL;
3237 goto unlock;
3240 user_extra = nr_pages + 1;
3241 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
3244 * Increase the limit linearly with more CPUs:
3246 user_lock_limit *= num_online_cpus();
3248 user_locked = atomic_long_read(&user->locked_vm) + user_extra;
3250 extra = 0;
3251 if (user_locked > user_lock_limit)
3252 extra = user_locked - user_lock_limit;
3254 lock_limit = rlimit(RLIMIT_MEMLOCK);
3255 lock_limit >>= PAGE_SHIFT;
3256 locked = vma->vm_mm->locked_vm + extra;
3258 if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
3259 !capable(CAP_IPC_LOCK)) {
3260 ret = -EPERM;
3261 goto unlock;
3264 WARN_ON(event->buffer);
3266 if (vma->vm_flags & VM_WRITE)
3267 flags |= PERF_BUFFER_WRITABLE;
3269 buffer = perf_buffer_alloc(nr_pages, event->attr.wakeup_watermark,
3270 event->cpu, flags);
3271 if (!buffer) {
3272 ret = -ENOMEM;
3273 goto unlock;
3275 rcu_assign_pointer(event->buffer, buffer);
3277 atomic_long_add(user_extra, &user->locked_vm);
3278 event->mmap_locked = extra;
3279 event->mmap_user = get_current_user();
3280 vma->vm_mm->locked_vm += event->mmap_locked;
3282 unlock:
3283 if (!ret)
3284 atomic_inc(&event->mmap_count);
3285 mutex_unlock(&event->mmap_mutex);
3287 vma->vm_flags |= VM_RESERVED;
3288 vma->vm_ops = &perf_mmap_vmops;
3290 return ret;
3293 static int perf_fasync(int fd, struct file *filp, int on)
3295 struct inode *inode = filp->f_path.dentry->d_inode;
3296 struct perf_event *event = filp->private_data;
3297 int retval;
3299 mutex_lock(&inode->i_mutex);
3300 retval = fasync_helper(fd, filp, on, &event->fasync);
3301 mutex_unlock(&inode->i_mutex);
3303 if (retval < 0)
3304 return retval;
3306 return 0;
3309 static const struct file_operations perf_fops = {
3310 .llseek = no_llseek,
3311 .release = perf_release,
3312 .read = perf_read,
3313 .poll = perf_poll,
3314 .unlocked_ioctl = perf_ioctl,
3315 .compat_ioctl = perf_ioctl,
3316 .mmap = perf_mmap,
3317 .fasync = perf_fasync,
3321 * Perf event wakeup
3323 * If there's data, ensure we set the poll() state and publish everything
3324 * to user-space before waking everybody up.
3327 void perf_event_wakeup(struct perf_event *event)
3329 wake_up_all(&event->waitq);
3331 if (event->pending_kill) {
3332 kill_fasync(&event->fasync, SIGIO, event->pending_kill);
3333 event->pending_kill = 0;
3337 static void perf_pending_event(struct irq_work *entry)
3339 struct perf_event *event = container_of(entry,
3340 struct perf_event, pending);
3342 if (event->pending_disable) {
3343 event->pending_disable = 0;
3344 __perf_event_disable(event);
3347 if (event->pending_wakeup) {
3348 event->pending_wakeup = 0;
3349 perf_event_wakeup(event);
3354 * We assume there is only KVM supporting the callbacks.
3355 * Later on, we might change it to a list if there is
3356 * another virtualization implementation supporting the callbacks.
3358 struct perf_guest_info_callbacks *perf_guest_cbs;
3360 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3362 perf_guest_cbs = cbs;
3363 return 0;
3365 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
3367 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
3369 perf_guest_cbs = NULL;
3370 return 0;
3372 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
3375 * Output
3377 static bool perf_output_space(struct perf_buffer *buffer, unsigned long tail,
3378 unsigned long offset, unsigned long head)
3380 unsigned long mask;
3382 if (!buffer->writable)
3383 return true;
3385 mask = perf_data_size(buffer) - 1;
3387 offset = (offset - tail) & mask;
3388 head = (head - tail) & mask;
3390 if ((int)(head - offset) < 0)
3391 return false;
3393 return true;
3396 static void perf_output_wakeup(struct perf_output_handle *handle)
3398 atomic_set(&handle->buffer->poll, POLL_IN);
3400 if (handle->nmi) {
3401 handle->event->pending_wakeup = 1;
3402 irq_work_queue(&handle->event->pending);
3403 } else
3404 perf_event_wakeup(handle->event);
3408 * We need to ensure a later event_id doesn't publish a head when a former
3409 * event isn't done writing. However since we need to deal with NMIs we
3410 * cannot fully serialize things.
3412 * We only publish the head (and generate a wakeup) when the outer-most
3413 * event completes.
3415 static void perf_output_get_handle(struct perf_output_handle *handle)
3417 struct perf_buffer *buffer = handle->buffer;
3419 preempt_disable();
3420 local_inc(&buffer->nest);
3421 handle->wakeup = local_read(&buffer->wakeup);
3424 static void perf_output_put_handle(struct perf_output_handle *handle)
3426 struct perf_buffer *buffer = handle->buffer;
3427 unsigned long head;
3429 again:
3430 head = local_read(&buffer->head);
3433 * IRQ/NMI can happen here, which means we can miss a head update.
3436 if (!local_dec_and_test(&buffer->nest))
3437 goto out;
3440 * Publish the known good head. Rely on the full barrier implied
3441 * by atomic_dec_and_test() order the buffer->head read and this
3442 * write.
3444 buffer->user_page->data_head = head;
3447 * Now check if we missed an update, rely on the (compiler)
3448 * barrier in atomic_dec_and_test() to re-read buffer->head.
3450 if (unlikely(head != local_read(&buffer->head))) {
3451 local_inc(&buffer->nest);
3452 goto again;
3455 if (handle->wakeup != local_read(&buffer->wakeup))
3456 perf_output_wakeup(handle);
3458 out:
3459 preempt_enable();
3462 __always_inline void perf_output_copy(struct perf_output_handle *handle,
3463 const void *buf, unsigned int len)
3465 do {
3466 unsigned long size = min_t(unsigned long, handle->size, len);
3468 memcpy(handle->addr, buf, size);
3470 len -= size;
3471 handle->addr += size;
3472 buf += size;
3473 handle->size -= size;
3474 if (!handle->size) {
3475 struct perf_buffer *buffer = handle->buffer;
3477 handle->page++;
3478 handle->page &= buffer->nr_pages - 1;
3479 handle->addr = buffer->data_pages[handle->page];
3480 handle->size = PAGE_SIZE << page_order(buffer);
3482 } while (len);
3485 static void __perf_event_header__init_id(struct perf_event_header *header,
3486 struct perf_sample_data *data,
3487 struct perf_event *event)
3489 u64 sample_type = event->attr.sample_type;
3491 data->type = sample_type;
3492 header->size += event->id_header_size;
3494 if (sample_type & PERF_SAMPLE_TID) {
3495 /* namespace issues */
3496 data->tid_entry.pid = perf_event_pid(event, current);
3497 data->tid_entry.tid = perf_event_tid(event, current);
3500 if (sample_type & PERF_SAMPLE_TIME)
3501 data->time = perf_clock();
3503 if (sample_type & PERF_SAMPLE_ID)
3504 data->id = primary_event_id(event);
3506 if (sample_type & PERF_SAMPLE_STREAM_ID)
3507 data->stream_id = event->id;
3509 if (sample_type & PERF_SAMPLE_CPU) {
3510 data->cpu_entry.cpu = raw_smp_processor_id();
3511 data->cpu_entry.reserved = 0;
3515 static void perf_event_header__init_id(struct perf_event_header *header,
3516 struct perf_sample_data *data,
3517 struct perf_event *event)
3519 if (event->attr.sample_id_all)
3520 __perf_event_header__init_id(header, data, event);
3523 static void __perf_event__output_id_sample(struct perf_output_handle *handle,
3524 struct perf_sample_data *data)
3526 u64 sample_type = data->type;
3528 if (sample_type & PERF_SAMPLE_TID)
3529 perf_output_put(handle, data->tid_entry);
3531 if (sample_type & PERF_SAMPLE_TIME)
3532 perf_output_put(handle, data->time);
3534 if (sample_type & PERF_SAMPLE_ID)
3535 perf_output_put(handle, data->id);
3537 if (sample_type & PERF_SAMPLE_STREAM_ID)
3538 perf_output_put(handle, data->stream_id);
3540 if (sample_type & PERF_SAMPLE_CPU)
3541 perf_output_put(handle, data->cpu_entry);
3544 static void perf_event__output_id_sample(struct perf_event *event,
3545 struct perf_output_handle *handle,
3546 struct perf_sample_data *sample)
3548 if (event->attr.sample_id_all)
3549 __perf_event__output_id_sample(handle, sample);
3552 int perf_output_begin(struct perf_output_handle *handle,
3553 struct perf_event *event, unsigned int size,
3554 int nmi, int sample)
3556 struct perf_buffer *buffer;
3557 unsigned long tail, offset, head;
3558 int have_lost;
3559 struct perf_sample_data sample_data;
3560 struct {
3561 struct perf_event_header header;
3562 u64 id;
3563 u64 lost;
3564 } lost_event;
3566 rcu_read_lock();
3568 * For inherited events we send all the output towards the parent.
3570 if (event->parent)
3571 event = event->parent;
3573 buffer = rcu_dereference(event->buffer);
3574 if (!buffer)
3575 goto out;
3577 handle->buffer = buffer;
3578 handle->event = event;
3579 handle->nmi = nmi;
3580 handle->sample = sample;
3582 if (!buffer->nr_pages)
3583 goto out;
3585 have_lost = local_read(&buffer->lost);
3586 if (have_lost) {
3587 lost_event.header.size = sizeof(lost_event);
3588 perf_event_header__init_id(&lost_event.header, &sample_data,
3589 event);
3590 size += lost_event.header.size;
3593 perf_output_get_handle(handle);
3595 do {
3597 * Userspace could choose to issue a mb() before updating the
3598 * tail pointer. So that all reads will be completed before the
3599 * write is issued.
3601 tail = ACCESS_ONCE(buffer->user_page->data_tail);
3602 smp_rmb();
3603 offset = head = local_read(&buffer->head);
3604 head += size;
3605 if (unlikely(!perf_output_space(buffer, tail, offset, head)))
3606 goto fail;
3607 } while (local_cmpxchg(&buffer->head, offset, head) != offset);
3609 if (head - local_read(&buffer->wakeup) > buffer->watermark)
3610 local_add(buffer->watermark, &buffer->wakeup);
3612 handle->page = offset >> (PAGE_SHIFT + page_order(buffer));
3613 handle->page &= buffer->nr_pages - 1;
3614 handle->size = offset & ((PAGE_SIZE << page_order(buffer)) - 1);
3615 handle->addr = buffer->data_pages[handle->page];
3616 handle->addr += handle->size;
3617 handle->size = (PAGE_SIZE << page_order(buffer)) - handle->size;
3619 if (have_lost) {
3620 lost_event.header.type = PERF_RECORD_LOST;
3621 lost_event.header.misc = 0;
3622 lost_event.id = event->id;
3623 lost_event.lost = local_xchg(&buffer->lost, 0);
3625 perf_output_put(handle, lost_event);
3626 perf_event__output_id_sample(event, handle, &sample_data);
3629 return 0;
3631 fail:
3632 local_inc(&buffer->lost);
3633 perf_output_put_handle(handle);
3634 out:
3635 rcu_read_unlock();
3637 return -ENOSPC;
3640 void perf_output_end(struct perf_output_handle *handle)
3642 struct perf_event *event = handle->event;
3643 struct perf_buffer *buffer = handle->buffer;
3645 int wakeup_events = event->attr.wakeup_events;
3647 if (handle->sample && wakeup_events) {
3648 int events = local_inc_return(&buffer->events);
3649 if (events >= wakeup_events) {
3650 local_sub(wakeup_events, &buffer->events);
3651 local_inc(&buffer->wakeup);
3655 perf_output_put_handle(handle);
3656 rcu_read_unlock();
3659 static void perf_output_read_one(struct perf_output_handle *handle,
3660 struct perf_event *event,
3661 u64 enabled, u64 running)
3663 u64 read_format = event->attr.read_format;
3664 u64 values[4];
3665 int n = 0;
3667 values[n++] = perf_event_count(event);
3668 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3669 values[n++] = enabled +
3670 atomic64_read(&event->child_total_time_enabled);
3672 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3673 values[n++] = running +
3674 atomic64_read(&event->child_total_time_running);
3676 if (read_format & PERF_FORMAT_ID)
3677 values[n++] = primary_event_id(event);
3679 perf_output_copy(handle, values, n * sizeof(u64));
3683 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
3685 static void perf_output_read_group(struct perf_output_handle *handle,
3686 struct perf_event *event,
3687 u64 enabled, u64 running)
3689 struct perf_event *leader = event->group_leader, *sub;
3690 u64 read_format = event->attr.read_format;
3691 u64 values[5];
3692 int n = 0;
3694 values[n++] = 1 + leader->nr_siblings;
3696 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3697 values[n++] = enabled;
3699 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3700 values[n++] = running;
3702 if (leader != event)
3703 leader->pmu->read(leader);
3705 values[n++] = perf_event_count(leader);
3706 if (read_format & PERF_FORMAT_ID)
3707 values[n++] = primary_event_id(leader);
3709 perf_output_copy(handle, values, n * sizeof(u64));
3711 list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3712 n = 0;
3714 if (sub != event)
3715 sub->pmu->read(sub);
3717 values[n++] = perf_event_count(sub);
3718 if (read_format & PERF_FORMAT_ID)
3719 values[n++] = primary_event_id(sub);
3721 perf_output_copy(handle, values, n * sizeof(u64));
3725 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\
3726 PERF_FORMAT_TOTAL_TIME_RUNNING)
3728 static void perf_output_read(struct perf_output_handle *handle,
3729 struct perf_event *event)
3731 u64 enabled = 0, running = 0, now, ctx_time;
3732 u64 read_format = event->attr.read_format;
3735 * compute total_time_enabled, total_time_running
3736 * based on snapshot values taken when the event
3737 * was last scheduled in.
3739 * we cannot simply called update_context_time()
3740 * because of locking issue as we are called in
3741 * NMI context
3743 if (read_format & PERF_FORMAT_TOTAL_TIMES) {
3744 now = perf_clock();
3745 ctx_time = event->shadow_ctx_time + now;
3746 enabled = ctx_time - event->tstamp_enabled;
3747 running = ctx_time - event->tstamp_running;
3750 if (event->attr.read_format & PERF_FORMAT_GROUP)
3751 perf_output_read_group(handle, event, enabled, running);
3752 else
3753 perf_output_read_one(handle, event, enabled, running);
3756 void perf_output_sample(struct perf_output_handle *handle,
3757 struct perf_event_header *header,
3758 struct perf_sample_data *data,
3759 struct perf_event *event)
3761 u64 sample_type = data->type;
3763 perf_output_put(handle, *header);
3765 if (sample_type & PERF_SAMPLE_IP)
3766 perf_output_put(handle, data->ip);
3768 if (sample_type & PERF_SAMPLE_TID)
3769 perf_output_put(handle, data->tid_entry);
3771 if (sample_type & PERF_SAMPLE_TIME)
3772 perf_output_put(handle, data->time);
3774 if (sample_type & PERF_SAMPLE_ADDR)
3775 perf_output_put(handle, data->addr);
3777 if (sample_type & PERF_SAMPLE_ID)
3778 perf_output_put(handle, data->id);
3780 if (sample_type & PERF_SAMPLE_STREAM_ID)
3781 perf_output_put(handle, data->stream_id);
3783 if (sample_type & PERF_SAMPLE_CPU)
3784 perf_output_put(handle, data->cpu_entry);
3786 if (sample_type & PERF_SAMPLE_PERIOD)
3787 perf_output_put(handle, data->period);
3789 if (sample_type & PERF_SAMPLE_READ)
3790 perf_output_read(handle, event);
3792 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
3793 if (data->callchain) {
3794 int size = 1;
3796 if (data->callchain)
3797 size += data->callchain->nr;
3799 size *= sizeof(u64);
3801 perf_output_copy(handle, data->callchain, size);
3802 } else {
3803 u64 nr = 0;
3804 perf_output_put(handle, nr);
3808 if (sample_type & PERF_SAMPLE_RAW) {
3809 if (data->raw) {
3810 perf_output_put(handle, data->raw->size);
3811 perf_output_copy(handle, data->raw->data,
3812 data->raw->size);
3813 } else {
3814 struct {
3815 u32 size;
3816 u32 data;
3817 } raw = {
3818 .size = sizeof(u32),
3819 .data = 0,
3821 perf_output_put(handle, raw);
3826 void perf_prepare_sample(struct perf_event_header *header,
3827 struct perf_sample_data *data,
3828 struct perf_event *event,
3829 struct pt_regs *regs)
3831 u64 sample_type = event->attr.sample_type;
3833 header->type = PERF_RECORD_SAMPLE;
3834 header->size = sizeof(*header) + event->header_size;
3836 header->misc = 0;
3837 header->misc |= perf_misc_flags(regs);
3839 __perf_event_header__init_id(header, data, event);
3841 if (sample_type & PERF_SAMPLE_IP)
3842 data->ip = perf_instruction_pointer(regs);
3844 if (sample_type & PERF_SAMPLE_CALLCHAIN) {
3845 int size = 1;
3847 data->callchain = perf_callchain(regs);
3849 if (data->callchain)
3850 size += data->callchain->nr;
3852 header->size += size * sizeof(u64);
3855 if (sample_type & PERF_SAMPLE_RAW) {
3856 int size = sizeof(u32);
3858 if (data->raw)
3859 size += data->raw->size;
3860 else
3861 size += sizeof(u32);
3863 WARN_ON_ONCE(size & (sizeof(u64)-1));
3864 header->size += size;
3868 static void perf_event_output(struct perf_event *event, int nmi,
3869 struct perf_sample_data *data,
3870 struct pt_regs *regs)
3872 struct perf_output_handle handle;
3873 struct perf_event_header header;
3875 /* protect the callchain buffers */
3876 rcu_read_lock();
3878 perf_prepare_sample(&header, data, event, regs);
3880 if (perf_output_begin(&handle, event, header.size, nmi, 1))
3881 goto exit;
3883 perf_output_sample(&handle, &header, data, event);
3885 perf_output_end(&handle);
3887 exit:
3888 rcu_read_unlock();
3892 * read event_id
3895 struct perf_read_event {
3896 struct perf_event_header header;
3898 u32 pid;
3899 u32 tid;
3902 static void
3903 perf_event_read_event(struct perf_event *event,
3904 struct task_struct *task)
3906 struct perf_output_handle handle;
3907 struct perf_sample_data sample;
3908 struct perf_read_event read_event = {
3909 .header = {
3910 .type = PERF_RECORD_READ,
3911 .misc = 0,
3912 .size = sizeof(read_event) + event->read_size,
3914 .pid = perf_event_pid(event, task),
3915 .tid = perf_event_tid(event, task),
3917 int ret;
3919 perf_event_header__init_id(&read_event.header, &sample, event);
3920 ret = perf_output_begin(&handle, event, read_event.header.size, 0, 0);
3921 if (ret)
3922 return;
3924 perf_output_put(&handle, read_event);
3925 perf_output_read(&handle, event);
3926 perf_event__output_id_sample(event, &handle, &sample);
3928 perf_output_end(&handle);
3932 * task tracking -- fork/exit
3934 * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
3937 struct perf_task_event {
3938 struct task_struct *task;
3939 struct perf_event_context *task_ctx;
3941 struct {
3942 struct perf_event_header header;
3944 u32 pid;
3945 u32 ppid;
3946 u32 tid;
3947 u32 ptid;
3948 u64 time;
3949 } event_id;
3952 static void perf_event_task_output(struct perf_event *event,
3953 struct perf_task_event *task_event)
3955 struct perf_output_handle handle;
3956 struct perf_sample_data sample;
3957 struct task_struct *task = task_event->task;
3958 int ret, size = task_event->event_id.header.size;
3960 perf_event_header__init_id(&task_event->event_id.header, &sample, event);
3962 ret = perf_output_begin(&handle, event,
3963 task_event->event_id.header.size, 0, 0);
3964 if (ret)
3965 goto out;
3967 task_event->event_id.pid = perf_event_pid(event, task);
3968 task_event->event_id.ppid = perf_event_pid(event, current);
3970 task_event->event_id.tid = perf_event_tid(event, task);
3971 task_event->event_id.ptid = perf_event_tid(event, current);
3973 perf_output_put(&handle, task_event->event_id);
3975 perf_event__output_id_sample(event, &handle, &sample);
3977 perf_output_end(&handle);
3978 out:
3979 task_event->event_id.header.size = size;
3982 static int perf_event_task_match(struct perf_event *event)
3984 if (event->state < PERF_EVENT_STATE_INACTIVE)
3985 return 0;
3987 if (!event_filter_match(event))
3988 return 0;
3990 if (event->attr.comm || event->attr.mmap ||
3991 event->attr.mmap_data || event->attr.task)
3992 return 1;
3994 return 0;
3997 static void perf_event_task_ctx(struct perf_event_context *ctx,
3998 struct perf_task_event *task_event)
4000 struct perf_event *event;
4002 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4003 if (perf_event_task_match(event))
4004 perf_event_task_output(event, task_event);
4008 static void perf_event_task_event(struct perf_task_event *task_event)
4010 struct perf_cpu_context *cpuctx;
4011 struct perf_event_context *ctx;
4012 struct pmu *pmu;
4013 int ctxn;
4015 rcu_read_lock();
4016 list_for_each_entry_rcu(pmu, &pmus, entry) {
4017 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4018 if (cpuctx->active_pmu != pmu)
4019 goto next;
4020 perf_event_task_ctx(&cpuctx->ctx, task_event);
4022 ctx = task_event->task_ctx;
4023 if (!ctx) {
4024 ctxn = pmu->task_ctx_nr;
4025 if (ctxn < 0)
4026 goto next;
4027 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4029 if (ctx)
4030 perf_event_task_ctx(ctx, task_event);
4031 next:
4032 put_cpu_ptr(pmu->pmu_cpu_context);
4034 rcu_read_unlock();
4037 static void perf_event_task(struct task_struct *task,
4038 struct perf_event_context *task_ctx,
4039 int new)
4041 struct perf_task_event task_event;
4043 if (!atomic_read(&nr_comm_events) &&
4044 !atomic_read(&nr_mmap_events) &&
4045 !atomic_read(&nr_task_events))
4046 return;
4048 task_event = (struct perf_task_event){
4049 .task = task,
4050 .task_ctx = task_ctx,
4051 .event_id = {
4052 .header = {
4053 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
4054 .misc = 0,
4055 .size = sizeof(task_event.event_id),
4057 /* .pid */
4058 /* .ppid */
4059 /* .tid */
4060 /* .ptid */
4061 .time = perf_clock(),
4065 perf_event_task_event(&task_event);
4068 void perf_event_fork(struct task_struct *task)
4070 perf_event_task(task, NULL, 1);
4074 * comm tracking
4077 struct perf_comm_event {
4078 struct task_struct *task;
4079 char *comm;
4080 int comm_size;
4082 struct {
4083 struct perf_event_header header;
4085 u32 pid;
4086 u32 tid;
4087 } event_id;
4090 static void perf_event_comm_output(struct perf_event *event,
4091 struct perf_comm_event *comm_event)
4093 struct perf_output_handle handle;
4094 struct perf_sample_data sample;
4095 int size = comm_event->event_id.header.size;
4096 int ret;
4098 perf_event_header__init_id(&comm_event->event_id.header, &sample, event);
4099 ret = perf_output_begin(&handle, event,
4100 comm_event->event_id.header.size, 0, 0);
4102 if (ret)
4103 goto out;
4105 comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
4106 comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
4108 perf_output_put(&handle, comm_event->event_id);
4109 perf_output_copy(&handle, comm_event->comm,
4110 comm_event->comm_size);
4112 perf_event__output_id_sample(event, &handle, &sample);
4114 perf_output_end(&handle);
4115 out:
4116 comm_event->event_id.header.size = size;
4119 static int perf_event_comm_match(struct perf_event *event)
4121 if (event->state < PERF_EVENT_STATE_INACTIVE)
4122 return 0;
4124 if (!event_filter_match(event))
4125 return 0;
4127 if (event->attr.comm)
4128 return 1;
4130 return 0;
4133 static void perf_event_comm_ctx(struct perf_event_context *ctx,
4134 struct perf_comm_event *comm_event)
4136 struct perf_event *event;
4138 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4139 if (perf_event_comm_match(event))
4140 perf_event_comm_output(event, comm_event);
4144 static void perf_event_comm_event(struct perf_comm_event *comm_event)
4146 struct perf_cpu_context *cpuctx;
4147 struct perf_event_context *ctx;
4148 char comm[TASK_COMM_LEN];
4149 unsigned int size;
4150 struct pmu *pmu;
4151 int ctxn;
4153 memset(comm, 0, sizeof(comm));
4154 strlcpy(comm, comm_event->task->comm, sizeof(comm));
4155 size = ALIGN(strlen(comm)+1, sizeof(u64));
4157 comm_event->comm = comm;
4158 comm_event->comm_size = size;
4160 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
4161 rcu_read_lock();
4162 list_for_each_entry_rcu(pmu, &pmus, entry) {
4163 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4164 if (cpuctx->active_pmu != pmu)
4165 goto next;
4166 perf_event_comm_ctx(&cpuctx->ctx, comm_event);
4168 ctxn = pmu->task_ctx_nr;
4169 if (ctxn < 0)
4170 goto next;
4172 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4173 if (ctx)
4174 perf_event_comm_ctx(ctx, comm_event);
4175 next:
4176 put_cpu_ptr(pmu->pmu_cpu_context);
4178 rcu_read_unlock();
4181 void perf_event_comm(struct task_struct *task)
4183 struct perf_comm_event comm_event;
4184 struct perf_event_context *ctx;
4185 int ctxn;
4187 for_each_task_context_nr(ctxn) {
4188 ctx = task->perf_event_ctxp[ctxn];
4189 if (!ctx)
4190 continue;
4192 perf_event_enable_on_exec(ctx);
4195 if (!atomic_read(&nr_comm_events))
4196 return;
4198 comm_event = (struct perf_comm_event){
4199 .task = task,
4200 /* .comm */
4201 /* .comm_size */
4202 .event_id = {
4203 .header = {
4204 .type = PERF_RECORD_COMM,
4205 .misc = 0,
4206 /* .size */
4208 /* .pid */
4209 /* .tid */
4213 perf_event_comm_event(&comm_event);
4217 * mmap tracking
4220 struct perf_mmap_event {
4221 struct vm_area_struct *vma;
4223 const char *file_name;
4224 int file_size;
4226 struct {
4227 struct perf_event_header header;
4229 u32 pid;
4230 u32 tid;
4231 u64 start;
4232 u64 len;
4233 u64 pgoff;
4234 } event_id;
4237 static void perf_event_mmap_output(struct perf_event *event,
4238 struct perf_mmap_event *mmap_event)
4240 struct perf_output_handle handle;
4241 struct perf_sample_data sample;
4242 int size = mmap_event->event_id.header.size;
4243 int ret;
4245 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event);
4246 ret = perf_output_begin(&handle, event,
4247 mmap_event->event_id.header.size, 0, 0);
4248 if (ret)
4249 goto out;
4251 mmap_event->event_id.pid = perf_event_pid(event, current);
4252 mmap_event->event_id.tid = perf_event_tid(event, current);
4254 perf_output_put(&handle, mmap_event->event_id);
4255 perf_output_copy(&handle, mmap_event->file_name,
4256 mmap_event->file_size);
4258 perf_event__output_id_sample(event, &handle, &sample);
4260 perf_output_end(&handle);
4261 out:
4262 mmap_event->event_id.header.size = size;
4265 static int perf_event_mmap_match(struct perf_event *event,
4266 struct perf_mmap_event *mmap_event,
4267 int executable)
4269 if (event->state < PERF_EVENT_STATE_INACTIVE)
4270 return 0;
4272 if (!event_filter_match(event))
4273 return 0;
4275 if ((!executable && event->attr.mmap_data) ||
4276 (executable && event->attr.mmap))
4277 return 1;
4279 return 0;
4282 static void perf_event_mmap_ctx(struct perf_event_context *ctx,
4283 struct perf_mmap_event *mmap_event,
4284 int executable)
4286 struct perf_event *event;
4288 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
4289 if (perf_event_mmap_match(event, mmap_event, executable))
4290 perf_event_mmap_output(event, mmap_event);
4294 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
4296 struct perf_cpu_context *cpuctx;
4297 struct perf_event_context *ctx;
4298 struct vm_area_struct *vma = mmap_event->vma;
4299 struct file *file = vma->vm_file;
4300 unsigned int size;
4301 char tmp[16];
4302 char *buf = NULL;
4303 const char *name;
4304 struct pmu *pmu;
4305 int ctxn;
4307 memset(tmp, 0, sizeof(tmp));
4309 if (file) {
4311 * d_path works from the end of the buffer backwards, so we
4312 * need to add enough zero bytes after the string to handle
4313 * the 64bit alignment we do later.
4315 buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
4316 if (!buf) {
4317 name = strncpy(tmp, "//enomem", sizeof(tmp));
4318 goto got_name;
4320 name = d_path(&file->f_path, buf, PATH_MAX);
4321 if (IS_ERR(name)) {
4322 name = strncpy(tmp, "//toolong", sizeof(tmp));
4323 goto got_name;
4325 } else {
4326 if (arch_vma_name(mmap_event->vma)) {
4327 name = strncpy(tmp, arch_vma_name(mmap_event->vma),
4328 sizeof(tmp));
4329 goto got_name;
4332 if (!vma->vm_mm) {
4333 name = strncpy(tmp, "[vdso]", sizeof(tmp));
4334 goto got_name;
4335 } else if (vma->vm_start <= vma->vm_mm->start_brk &&
4336 vma->vm_end >= vma->vm_mm->brk) {
4337 name = strncpy(tmp, "[heap]", sizeof(tmp));
4338 goto got_name;
4339 } else if (vma->vm_start <= vma->vm_mm->start_stack &&
4340 vma->vm_end >= vma->vm_mm->start_stack) {
4341 name = strncpy(tmp, "[stack]", sizeof(tmp));
4342 goto got_name;
4345 name = strncpy(tmp, "//anon", sizeof(tmp));
4346 goto got_name;
4349 got_name:
4350 size = ALIGN(strlen(name)+1, sizeof(u64));
4352 mmap_event->file_name = name;
4353 mmap_event->file_size = size;
4355 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
4357 rcu_read_lock();
4358 list_for_each_entry_rcu(pmu, &pmus, entry) {
4359 cpuctx = get_cpu_ptr(pmu->pmu_cpu_context);
4360 if (cpuctx->active_pmu != pmu)
4361 goto next;
4362 perf_event_mmap_ctx(&cpuctx->ctx, mmap_event,
4363 vma->vm_flags & VM_EXEC);
4365 ctxn = pmu->task_ctx_nr;
4366 if (ctxn < 0)
4367 goto next;
4369 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]);
4370 if (ctx) {
4371 perf_event_mmap_ctx(ctx, mmap_event,
4372 vma->vm_flags & VM_EXEC);
4374 next:
4375 put_cpu_ptr(pmu->pmu_cpu_context);
4377 rcu_read_unlock();
4379 kfree(buf);
4382 void perf_event_mmap(struct vm_area_struct *vma)
4384 struct perf_mmap_event mmap_event;
4386 if (!atomic_read(&nr_mmap_events))
4387 return;
4389 mmap_event = (struct perf_mmap_event){
4390 .vma = vma,
4391 /* .file_name */
4392 /* .file_size */
4393 .event_id = {
4394 .header = {
4395 .type = PERF_RECORD_MMAP,
4396 .misc = PERF_RECORD_MISC_USER,
4397 /* .size */
4399 /* .pid */
4400 /* .tid */
4401 .start = vma->vm_start,
4402 .len = vma->vm_end - vma->vm_start,
4403 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
4407 perf_event_mmap_event(&mmap_event);
4411 * IRQ throttle logging
4414 static void perf_log_throttle(struct perf_event *event, int enable)
4416 struct perf_output_handle handle;
4417 struct perf_sample_data sample;
4418 int ret;
4420 struct {
4421 struct perf_event_header header;
4422 u64 time;
4423 u64 id;
4424 u64 stream_id;
4425 } throttle_event = {
4426 .header = {
4427 .type = PERF_RECORD_THROTTLE,
4428 .misc = 0,
4429 .size = sizeof(throttle_event),
4431 .time = perf_clock(),
4432 .id = primary_event_id(event),
4433 .stream_id = event->id,
4436 if (enable)
4437 throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
4439 perf_event_header__init_id(&throttle_event.header, &sample, event);
4441 ret = perf_output_begin(&handle, event,
4442 throttle_event.header.size, 1, 0);
4443 if (ret)
4444 return;
4446 perf_output_put(&handle, throttle_event);
4447 perf_event__output_id_sample(event, &handle, &sample);
4448 perf_output_end(&handle);
4452 * Generic event overflow handling, sampling.
4455 static int __perf_event_overflow(struct perf_event *event, int nmi,
4456 int throttle, struct perf_sample_data *data,
4457 struct pt_regs *regs)
4459 int events = atomic_read(&event->event_limit);
4460 struct hw_perf_event *hwc = &event->hw;
4461 int ret = 0;
4464 * Non-sampling counters might still use the PMI to fold short
4465 * hardware counters, ignore those.
4467 if (unlikely(!is_sampling_event(event)))
4468 return 0;
4470 if (!throttle) {
4471 hwc->interrupts++;
4472 } else {
4473 if (hwc->interrupts != MAX_INTERRUPTS) {
4474 hwc->interrupts++;
4475 if (HZ * hwc->interrupts >
4476 (u64)sysctl_perf_event_sample_rate) {
4477 hwc->interrupts = MAX_INTERRUPTS;
4478 perf_log_throttle(event, 0);
4479 ret = 1;
4481 } else {
4483 * Keep re-disabling events even though on the previous
4484 * pass we disabled it - just in case we raced with a
4485 * sched-in and the event got enabled again:
4487 ret = 1;
4491 if (event->attr.freq) {
4492 u64 now = perf_clock();
4493 s64 delta = now - hwc->freq_time_stamp;
4495 hwc->freq_time_stamp = now;
4497 if (delta > 0 && delta < 2*TICK_NSEC)
4498 perf_adjust_period(event, delta, hwc->last_period);
4502 * XXX event_limit might not quite work as expected on inherited
4503 * events
4506 event->pending_kill = POLL_IN;
4507 if (events && atomic_dec_and_test(&event->event_limit)) {
4508 ret = 1;
4509 event->pending_kill = POLL_HUP;
4510 if (nmi) {
4511 event->pending_disable = 1;
4512 irq_work_queue(&event->pending);
4513 } else
4514 perf_event_disable(event);
4517 if (event->overflow_handler)
4518 event->overflow_handler(event, nmi, data, regs);
4519 else
4520 perf_event_output(event, nmi, data, regs);
4522 return ret;
4525 int perf_event_overflow(struct perf_event *event, int nmi,
4526 struct perf_sample_data *data,
4527 struct pt_regs *regs)
4529 return __perf_event_overflow(event, nmi, 1, data, regs);
4533 * Generic software event infrastructure
4536 struct swevent_htable {
4537 struct swevent_hlist *swevent_hlist;
4538 struct mutex hlist_mutex;
4539 int hlist_refcount;
4541 /* Recursion avoidance in each contexts */
4542 int recursion[PERF_NR_CONTEXTS];
4545 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable);
4548 * We directly increment event->count and keep a second value in
4549 * event->hw.period_left to count intervals. This period event
4550 * is kept in the range [-sample_period, 0] so that we can use the
4551 * sign as trigger.
4554 static u64 perf_swevent_set_period(struct perf_event *event)
4556 struct hw_perf_event *hwc = &event->hw;
4557 u64 period = hwc->last_period;
4558 u64 nr, offset;
4559 s64 old, val;
4561 hwc->last_period = hwc->sample_period;
4563 again:
4564 old = val = local64_read(&hwc->period_left);
4565 if (val < 0)
4566 return 0;
4568 nr = div64_u64(period + val, period);
4569 offset = nr * period;
4570 val -= offset;
4571 if (local64_cmpxchg(&hwc->period_left, old, val) != old)
4572 goto again;
4574 return nr;
4577 static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
4578 int nmi, struct perf_sample_data *data,
4579 struct pt_regs *regs)
4581 struct hw_perf_event *hwc = &event->hw;
4582 int throttle = 0;
4584 data->period = event->hw.last_period;
4585 if (!overflow)
4586 overflow = perf_swevent_set_period(event);
4588 if (hwc->interrupts == MAX_INTERRUPTS)
4589 return;
4591 for (; overflow; overflow--) {
4592 if (__perf_event_overflow(event, nmi, throttle,
4593 data, regs)) {
4595 * We inhibit the overflow from happening when
4596 * hwc->interrupts == MAX_INTERRUPTS.
4598 break;
4600 throttle = 1;
4604 static void perf_swevent_event(struct perf_event *event, u64 nr,
4605 int nmi, struct perf_sample_data *data,
4606 struct pt_regs *regs)
4608 struct hw_perf_event *hwc = &event->hw;
4610 local64_add(nr, &event->count);
4612 if (!regs)
4613 return;
4615 if (!is_sampling_event(event))
4616 return;
4618 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
4619 return perf_swevent_overflow(event, 1, nmi, data, regs);
4621 if (local64_add_negative(nr, &hwc->period_left))
4622 return;
4624 perf_swevent_overflow(event, 0, nmi, data, regs);
4627 static int perf_exclude_event(struct perf_event *event,
4628 struct pt_regs *regs)
4630 if (event->hw.state & PERF_HES_STOPPED)
4631 return 0;
4633 if (regs) {
4634 if (event->attr.exclude_user && user_mode(regs))
4635 return 1;
4637 if (event->attr.exclude_kernel && !user_mode(regs))
4638 return 1;
4641 return 0;
4644 static int perf_swevent_match(struct perf_event *event,
4645 enum perf_type_id type,
4646 u32 event_id,
4647 struct perf_sample_data *data,
4648 struct pt_regs *regs)
4650 if (event->attr.type != type)
4651 return 0;
4653 if (event->attr.config != event_id)
4654 return 0;
4656 if (perf_exclude_event(event, regs))
4657 return 0;
4659 return 1;
4662 static inline u64 swevent_hash(u64 type, u32 event_id)
4664 u64 val = event_id | (type << 32);
4666 return hash_64(val, SWEVENT_HLIST_BITS);
4669 static inline struct hlist_head *
4670 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
4672 u64 hash = swevent_hash(type, event_id);
4674 return &hlist->heads[hash];
4677 /* For the read side: events when they trigger */
4678 static inline struct hlist_head *
4679 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id)
4681 struct swevent_hlist *hlist;
4683 hlist = rcu_dereference(swhash->swevent_hlist);
4684 if (!hlist)
4685 return NULL;
4687 return __find_swevent_head(hlist, type, event_id);
4690 /* For the event head insertion and removal in the hlist */
4691 static inline struct hlist_head *
4692 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event)
4694 struct swevent_hlist *hlist;
4695 u32 event_id = event->attr.config;
4696 u64 type = event->attr.type;
4699 * Event scheduling is always serialized against hlist allocation
4700 * and release. Which makes the protected version suitable here.
4701 * The context lock guarantees that.
4703 hlist = rcu_dereference_protected(swhash->swevent_hlist,
4704 lockdep_is_held(&event->ctx->lock));
4705 if (!hlist)
4706 return NULL;
4708 return __find_swevent_head(hlist, type, event_id);
4711 static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
4712 u64 nr, int nmi,
4713 struct perf_sample_data *data,
4714 struct pt_regs *regs)
4716 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
4717 struct perf_event *event;
4718 struct hlist_node *node;
4719 struct hlist_head *head;
4721 rcu_read_lock();
4722 head = find_swevent_head_rcu(swhash, type, event_id);
4723 if (!head)
4724 goto end;
4726 hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
4727 if (perf_swevent_match(event, type, event_id, data, regs))
4728 perf_swevent_event(event, nr, nmi, data, regs);
4730 end:
4731 rcu_read_unlock();
4734 int perf_swevent_get_recursion_context(void)
4736 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
4738 return get_recursion_context(swhash->recursion);
4740 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
4742 inline void perf_swevent_put_recursion_context(int rctx)
4744 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
4746 put_recursion_context(swhash->recursion, rctx);
4749 void __perf_sw_event(u32 event_id, u64 nr, int nmi,
4750 struct pt_regs *regs, u64 addr)
4752 struct perf_sample_data data;
4753 int rctx;
4755 preempt_disable_notrace();
4756 rctx = perf_swevent_get_recursion_context();
4757 if (rctx < 0)
4758 return;
4760 perf_sample_data_init(&data, addr);
4762 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, nmi, &data, regs);
4764 perf_swevent_put_recursion_context(rctx);
4765 preempt_enable_notrace();
4768 static void perf_swevent_read(struct perf_event *event)
4772 static int perf_swevent_add(struct perf_event *event, int flags)
4774 struct swevent_htable *swhash = &__get_cpu_var(swevent_htable);
4775 struct hw_perf_event *hwc = &event->hw;
4776 struct hlist_head *head;
4778 if (is_sampling_event(event)) {
4779 hwc->last_period = hwc->sample_period;
4780 perf_swevent_set_period(event);
4783 hwc->state = !(flags & PERF_EF_START);
4785 head = find_swevent_head(swhash, event);
4786 if (WARN_ON_ONCE(!head))
4787 return -EINVAL;
4789 hlist_add_head_rcu(&event->hlist_entry, head);
4791 return 0;
4794 static void perf_swevent_del(struct perf_event *event, int flags)
4796 hlist_del_rcu(&event->hlist_entry);
4799 static void perf_swevent_start(struct perf_event *event, int flags)
4801 event->hw.state = 0;
4804 static void perf_swevent_stop(struct perf_event *event, int flags)
4806 event->hw.state = PERF_HES_STOPPED;
4809 /* Deref the hlist from the update side */
4810 static inline struct swevent_hlist *
4811 swevent_hlist_deref(struct swevent_htable *swhash)
4813 return rcu_dereference_protected(swhash->swevent_hlist,
4814 lockdep_is_held(&swhash->hlist_mutex));
4817 static void swevent_hlist_release_rcu(struct rcu_head *rcu_head)
4819 struct swevent_hlist *hlist;
4821 hlist = container_of(rcu_head, struct swevent_hlist, rcu_head);
4822 kfree(hlist);
4825 static void swevent_hlist_release(struct swevent_htable *swhash)
4827 struct swevent_hlist *hlist = swevent_hlist_deref(swhash);
4829 if (!hlist)
4830 return;
4832 rcu_assign_pointer(swhash->swevent_hlist, NULL);
4833 call_rcu(&hlist->rcu_head, swevent_hlist_release_rcu);
4836 static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
4838 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
4840 mutex_lock(&swhash->hlist_mutex);
4842 if (!--swhash->hlist_refcount)
4843 swevent_hlist_release(swhash);
4845 mutex_unlock(&swhash->hlist_mutex);
4848 static void swevent_hlist_put(struct perf_event *event)
4850 int cpu;
4852 if (event->cpu != -1) {
4853 swevent_hlist_put_cpu(event, event->cpu);
4854 return;
4857 for_each_possible_cpu(cpu)
4858 swevent_hlist_put_cpu(event, cpu);
4861 static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
4863 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
4864 int err = 0;
4866 mutex_lock(&swhash->hlist_mutex);
4868 if (!swevent_hlist_deref(swhash) && cpu_online(cpu)) {
4869 struct swevent_hlist *hlist;
4871 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
4872 if (!hlist) {
4873 err = -ENOMEM;
4874 goto exit;
4876 rcu_assign_pointer(swhash->swevent_hlist, hlist);
4878 swhash->hlist_refcount++;
4879 exit:
4880 mutex_unlock(&swhash->hlist_mutex);
4882 return err;
4885 static int swevent_hlist_get(struct perf_event *event)
4887 int err;
4888 int cpu, failed_cpu;
4890 if (event->cpu != -1)
4891 return swevent_hlist_get_cpu(event, event->cpu);
4893 get_online_cpus();
4894 for_each_possible_cpu(cpu) {
4895 err = swevent_hlist_get_cpu(event, cpu);
4896 if (err) {
4897 failed_cpu = cpu;
4898 goto fail;
4901 put_online_cpus();
4903 return 0;
4904 fail:
4905 for_each_possible_cpu(cpu) {
4906 if (cpu == failed_cpu)
4907 break;
4908 swevent_hlist_put_cpu(event, cpu);
4911 put_online_cpus();
4912 return err;
4915 atomic_t perf_swevent_enabled[PERF_COUNT_SW_MAX];
4917 static void sw_perf_event_destroy(struct perf_event *event)
4919 u64 event_id = event->attr.config;
4921 WARN_ON(event->parent);
4923 jump_label_dec(&perf_swevent_enabled[event_id]);
4924 swevent_hlist_put(event);
4927 static int perf_swevent_init(struct perf_event *event)
4929 int event_id = event->attr.config;
4931 if (event->attr.type != PERF_TYPE_SOFTWARE)
4932 return -ENOENT;
4934 switch (event_id) {
4935 case PERF_COUNT_SW_CPU_CLOCK:
4936 case PERF_COUNT_SW_TASK_CLOCK:
4937 return -ENOENT;
4939 default:
4940 break;
4943 if (event_id >= PERF_COUNT_SW_MAX)
4944 return -ENOENT;
4946 if (!event->parent) {
4947 int err;
4949 err = swevent_hlist_get(event);
4950 if (err)
4951 return err;
4953 jump_label_inc(&perf_swevent_enabled[event_id]);
4954 event->destroy = sw_perf_event_destroy;
4957 return 0;
4960 static struct pmu perf_swevent = {
4961 .task_ctx_nr = perf_sw_context,
4963 .event_init = perf_swevent_init,
4964 .add = perf_swevent_add,
4965 .del = perf_swevent_del,
4966 .start = perf_swevent_start,
4967 .stop = perf_swevent_stop,
4968 .read = perf_swevent_read,
4971 #ifdef CONFIG_EVENT_TRACING
4973 static int perf_tp_filter_match(struct perf_event *event,
4974 struct perf_sample_data *data)
4976 void *record = data->raw->data;
4978 if (likely(!event->filter) || filter_match_preds(event->filter, record))
4979 return 1;
4980 return 0;
4983 static int perf_tp_event_match(struct perf_event *event,
4984 struct perf_sample_data *data,
4985 struct pt_regs *regs)
4988 * All tracepoints are from kernel-space.
4990 if (event->attr.exclude_kernel)
4991 return 0;
4993 if (!perf_tp_filter_match(event, data))
4994 return 0;
4996 return 1;
4999 void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
5000 struct pt_regs *regs, struct hlist_head *head, int rctx)
5002 struct perf_sample_data data;
5003 struct perf_event *event;
5004 struct hlist_node *node;
5006 struct perf_raw_record raw = {
5007 .size = entry_size,
5008 .data = record,
5011 perf_sample_data_init(&data, addr);
5012 data.raw = &raw;
5014 hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
5015 if (perf_tp_event_match(event, &data, regs))
5016 perf_swevent_event(event, count, 1, &data, regs);
5019 perf_swevent_put_recursion_context(rctx);
5021 EXPORT_SYMBOL_GPL(perf_tp_event);
5023 static void tp_perf_event_destroy(struct perf_event *event)
5025 perf_trace_destroy(event);
5028 static int perf_tp_event_init(struct perf_event *event)
5030 int err;
5032 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5033 return -ENOENT;
5035 err = perf_trace_init(event);
5036 if (err)
5037 return err;
5039 event->destroy = tp_perf_event_destroy;
5041 return 0;
5044 static struct pmu perf_tracepoint = {
5045 .task_ctx_nr = perf_sw_context,
5047 .event_init = perf_tp_event_init,
5048 .add = perf_trace_add,
5049 .del = perf_trace_del,
5050 .start = perf_swevent_start,
5051 .stop = perf_swevent_stop,
5052 .read = perf_swevent_read,
5055 static inline void perf_tp_register(void)
5057 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT);
5060 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5062 char *filter_str;
5063 int ret;
5065 if (event->attr.type != PERF_TYPE_TRACEPOINT)
5066 return -EINVAL;
5068 filter_str = strndup_user(arg, PAGE_SIZE);
5069 if (IS_ERR(filter_str))
5070 return PTR_ERR(filter_str);
5072 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
5074 kfree(filter_str);
5075 return ret;
5078 static void perf_event_free_filter(struct perf_event *event)
5080 ftrace_profile_free_filter(event);
5083 #else
5085 static inline void perf_tp_register(void)
5089 static int perf_event_set_filter(struct perf_event *event, void __user *arg)
5091 return -ENOENT;
5094 static void perf_event_free_filter(struct perf_event *event)
5098 #endif /* CONFIG_EVENT_TRACING */
5100 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5101 void perf_bp_event(struct perf_event *bp, void *data)
5103 struct perf_sample_data sample;
5104 struct pt_regs *regs = data;
5106 perf_sample_data_init(&sample, bp->attr.bp_addr);
5108 if (!bp->hw.state && !perf_exclude_event(bp, regs))
5109 perf_swevent_event(bp, 1, 1, &sample, regs);
5111 #endif
5114 * hrtimer based swevent callback
5117 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
5119 enum hrtimer_restart ret = HRTIMER_RESTART;
5120 struct perf_sample_data data;
5121 struct pt_regs *regs;
5122 struct perf_event *event;
5123 u64 period;
5125 event = container_of(hrtimer, struct perf_event, hw.hrtimer);
5126 event->pmu->read(event);
5128 perf_sample_data_init(&data, 0);
5129 data.period = event->hw.last_period;
5130 regs = get_irq_regs();
5132 if (regs && !perf_exclude_event(event, regs)) {
5133 if (!(event->attr.exclude_idle && current->pid == 0))
5134 if (perf_event_overflow(event, 0, &data, regs))
5135 ret = HRTIMER_NORESTART;
5138 period = max_t(u64, 10000, event->hw.sample_period);
5139 hrtimer_forward_now(hrtimer, ns_to_ktime(period));
5141 return ret;
5144 static void perf_swevent_start_hrtimer(struct perf_event *event)
5146 struct hw_perf_event *hwc = &event->hw;
5147 s64 period;
5149 if (!is_sampling_event(event))
5150 return;
5152 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
5153 hwc->hrtimer.function = perf_swevent_hrtimer;
5155 period = local64_read(&hwc->period_left);
5156 if (period) {
5157 if (period < 0)
5158 period = 10000;
5160 local64_set(&hwc->period_left, 0);
5161 } else {
5162 period = max_t(u64, 10000, hwc->sample_period);
5164 __hrtimer_start_range_ns(&hwc->hrtimer,
5165 ns_to_ktime(period), 0,
5166 HRTIMER_MODE_REL_PINNED, 0);
5169 static void perf_swevent_cancel_hrtimer(struct perf_event *event)
5171 struct hw_perf_event *hwc = &event->hw;
5173 if (is_sampling_event(event)) {
5174 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
5175 local64_set(&hwc->period_left, ktime_to_ns(remaining));
5177 hrtimer_cancel(&hwc->hrtimer);
5182 * Software event: cpu wall time clock
5185 static void cpu_clock_event_update(struct perf_event *event)
5187 s64 prev;
5188 u64 now;
5190 now = local_clock();
5191 prev = local64_xchg(&event->hw.prev_count, now);
5192 local64_add(now - prev, &event->count);
5195 static void cpu_clock_event_start(struct perf_event *event, int flags)
5197 local64_set(&event->hw.prev_count, local_clock());
5198 perf_swevent_start_hrtimer(event);
5201 static void cpu_clock_event_stop(struct perf_event *event, int flags)
5203 perf_swevent_cancel_hrtimer(event);
5204 cpu_clock_event_update(event);
5207 static int cpu_clock_event_add(struct perf_event *event, int flags)
5209 if (flags & PERF_EF_START)
5210 cpu_clock_event_start(event, flags);
5212 return 0;
5215 static void cpu_clock_event_del(struct perf_event *event, int flags)
5217 cpu_clock_event_stop(event, flags);
5220 static void cpu_clock_event_read(struct perf_event *event)
5222 cpu_clock_event_update(event);
5225 static int cpu_clock_event_init(struct perf_event *event)
5227 if (event->attr.type != PERF_TYPE_SOFTWARE)
5228 return -ENOENT;
5230 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK)
5231 return -ENOENT;
5233 return 0;
5236 static struct pmu perf_cpu_clock = {
5237 .task_ctx_nr = perf_sw_context,
5239 .event_init = cpu_clock_event_init,
5240 .add = cpu_clock_event_add,
5241 .del = cpu_clock_event_del,
5242 .start = cpu_clock_event_start,
5243 .stop = cpu_clock_event_stop,
5244 .read = cpu_clock_event_read,
5248 * Software event: task time clock
5251 static void task_clock_event_update(struct perf_event *event, u64 now)
5253 u64 prev;
5254 s64 delta;
5256 prev = local64_xchg(&event->hw.prev_count, now);
5257 delta = now - prev;
5258 local64_add(delta, &event->count);
5261 static void task_clock_event_start(struct perf_event *event, int flags)
5263 local64_set(&event->hw.prev_count, event->ctx->time);
5264 perf_swevent_start_hrtimer(event);
5267 static void task_clock_event_stop(struct perf_event *event, int flags)
5269 perf_swevent_cancel_hrtimer(event);
5270 task_clock_event_update(event, event->ctx->time);
5273 static int task_clock_event_add(struct perf_event *event, int flags)
5275 if (flags & PERF_EF_START)
5276 task_clock_event_start(event, flags);
5278 return 0;
5281 static void task_clock_event_del(struct perf_event *event, int flags)
5283 task_clock_event_stop(event, PERF_EF_UPDATE);
5286 static void task_clock_event_read(struct perf_event *event)
5288 u64 time;
5290 if (!in_nmi()) {
5291 update_context_time(event->ctx);
5292 time = event->ctx->time;
5293 } else {
5294 u64 now = perf_clock();
5295 u64 delta = now - event->ctx->timestamp;
5296 time = event->ctx->time + delta;
5299 task_clock_event_update(event, time);
5302 static int task_clock_event_init(struct perf_event *event)
5304 if (event->attr.type != PERF_TYPE_SOFTWARE)
5305 return -ENOENT;
5307 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK)
5308 return -ENOENT;
5310 return 0;
5313 static struct pmu perf_task_clock = {
5314 .task_ctx_nr = perf_sw_context,
5316 .event_init = task_clock_event_init,
5317 .add = task_clock_event_add,
5318 .del = task_clock_event_del,
5319 .start = task_clock_event_start,
5320 .stop = task_clock_event_stop,
5321 .read = task_clock_event_read,
5324 static void perf_pmu_nop_void(struct pmu *pmu)
5328 static int perf_pmu_nop_int(struct pmu *pmu)
5330 return 0;
5333 static void perf_pmu_start_txn(struct pmu *pmu)
5335 perf_pmu_disable(pmu);
5338 static int perf_pmu_commit_txn(struct pmu *pmu)
5340 perf_pmu_enable(pmu);
5341 return 0;
5344 static void perf_pmu_cancel_txn(struct pmu *pmu)
5346 perf_pmu_enable(pmu);
5350 * Ensures all contexts with the same task_ctx_nr have the same
5351 * pmu_cpu_context too.
5353 static void *find_pmu_context(int ctxn)
5355 struct pmu *pmu;
5357 if (ctxn < 0)
5358 return NULL;
5360 list_for_each_entry(pmu, &pmus, entry) {
5361 if (pmu->task_ctx_nr == ctxn)
5362 return pmu->pmu_cpu_context;
5365 return NULL;
5368 static void update_pmu_context(struct pmu *pmu, struct pmu *old_pmu)
5370 int cpu;
5372 for_each_possible_cpu(cpu) {
5373 struct perf_cpu_context *cpuctx;
5375 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
5377 if (cpuctx->active_pmu == old_pmu)
5378 cpuctx->active_pmu = pmu;
5382 static void free_pmu_context(struct pmu *pmu)
5384 struct pmu *i;
5386 mutex_lock(&pmus_lock);
5388 * Like a real lame refcount.
5390 list_for_each_entry(i, &pmus, entry) {
5391 if (i->pmu_cpu_context == pmu->pmu_cpu_context) {
5392 update_pmu_context(i, pmu);
5393 goto out;
5397 free_percpu(pmu->pmu_cpu_context);
5398 out:
5399 mutex_unlock(&pmus_lock);
5401 static struct idr pmu_idr;
5403 static ssize_t
5404 type_show(struct device *dev, struct device_attribute *attr, char *page)
5406 struct pmu *pmu = dev_get_drvdata(dev);
5408 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type);
5411 static struct device_attribute pmu_dev_attrs[] = {
5412 __ATTR_RO(type),
5413 __ATTR_NULL,
5416 static int pmu_bus_running;
5417 static struct bus_type pmu_bus = {
5418 .name = "event_source",
5419 .dev_attrs = pmu_dev_attrs,
5422 static void pmu_dev_release(struct device *dev)
5424 kfree(dev);
5427 static int pmu_dev_alloc(struct pmu *pmu)
5429 int ret = -ENOMEM;
5431 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL);
5432 if (!pmu->dev)
5433 goto out;
5435 device_initialize(pmu->dev);
5436 ret = dev_set_name(pmu->dev, "%s", pmu->name);
5437 if (ret)
5438 goto free_dev;
5440 dev_set_drvdata(pmu->dev, pmu);
5441 pmu->dev->bus = &pmu_bus;
5442 pmu->dev->release = pmu_dev_release;
5443 ret = device_add(pmu->dev);
5444 if (ret)
5445 goto free_dev;
5447 out:
5448 return ret;
5450 free_dev:
5451 put_device(pmu->dev);
5452 goto out;
5455 static struct lock_class_key cpuctx_mutex;
5457 int perf_pmu_register(struct pmu *pmu, char *name, int type)
5459 int cpu, ret;
5461 mutex_lock(&pmus_lock);
5462 ret = -ENOMEM;
5463 pmu->pmu_disable_count = alloc_percpu(int);
5464 if (!pmu->pmu_disable_count)
5465 goto unlock;
5467 pmu->type = -1;
5468 if (!name)
5469 goto skip_type;
5470 pmu->name = name;
5472 if (type < 0) {
5473 int err = idr_pre_get(&pmu_idr, GFP_KERNEL);
5474 if (!err)
5475 goto free_pdc;
5477 err = idr_get_new_above(&pmu_idr, pmu, PERF_TYPE_MAX, &type);
5478 if (err) {
5479 ret = err;
5480 goto free_pdc;
5483 pmu->type = type;
5485 if (pmu_bus_running) {
5486 ret = pmu_dev_alloc(pmu);
5487 if (ret)
5488 goto free_idr;
5491 skip_type:
5492 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr);
5493 if (pmu->pmu_cpu_context)
5494 goto got_cpu_context;
5496 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context);
5497 if (!pmu->pmu_cpu_context)
5498 goto free_dev;
5500 for_each_possible_cpu(cpu) {
5501 struct perf_cpu_context *cpuctx;
5503 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu);
5504 __perf_event_init_context(&cpuctx->ctx);
5505 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex);
5506 cpuctx->ctx.type = cpu_context;
5507 cpuctx->ctx.pmu = pmu;
5508 cpuctx->jiffies_interval = 1;
5509 INIT_LIST_HEAD(&cpuctx->rotation_list);
5510 cpuctx->active_pmu = pmu;
5513 got_cpu_context:
5514 if (!pmu->start_txn) {
5515 if (pmu->pmu_enable) {
5517 * If we have pmu_enable/pmu_disable calls, install
5518 * transaction stubs that use that to try and batch
5519 * hardware accesses.
5521 pmu->start_txn = perf_pmu_start_txn;
5522 pmu->commit_txn = perf_pmu_commit_txn;
5523 pmu->cancel_txn = perf_pmu_cancel_txn;
5524 } else {
5525 pmu->start_txn = perf_pmu_nop_void;
5526 pmu->commit_txn = perf_pmu_nop_int;
5527 pmu->cancel_txn = perf_pmu_nop_void;
5531 if (!pmu->pmu_enable) {
5532 pmu->pmu_enable = perf_pmu_nop_void;
5533 pmu->pmu_disable = perf_pmu_nop_void;
5536 list_add_rcu(&pmu->entry, &pmus);
5537 ret = 0;
5538 unlock:
5539 mutex_unlock(&pmus_lock);
5541 return ret;
5543 free_dev:
5544 device_del(pmu->dev);
5545 put_device(pmu->dev);
5547 free_idr:
5548 if (pmu->type >= PERF_TYPE_MAX)
5549 idr_remove(&pmu_idr, pmu->type);
5551 free_pdc:
5552 free_percpu(pmu->pmu_disable_count);
5553 goto unlock;
5556 void perf_pmu_unregister(struct pmu *pmu)
5558 mutex_lock(&pmus_lock);
5559 list_del_rcu(&pmu->entry);
5560 mutex_unlock(&pmus_lock);
5563 * We dereference the pmu list under both SRCU and regular RCU, so
5564 * synchronize against both of those.
5566 synchronize_srcu(&pmus_srcu);
5567 synchronize_rcu();
5569 free_percpu(pmu->pmu_disable_count);
5570 if (pmu->type >= PERF_TYPE_MAX)
5571 idr_remove(&pmu_idr, pmu->type);
5572 device_del(pmu->dev);
5573 put_device(pmu->dev);
5574 free_pmu_context(pmu);
5577 struct pmu *perf_init_event(struct perf_event *event)
5579 struct pmu *pmu = NULL;
5580 int idx;
5582 idx = srcu_read_lock(&pmus_srcu);
5584 rcu_read_lock();
5585 pmu = idr_find(&pmu_idr, event->attr.type);
5586 rcu_read_unlock();
5587 if (pmu)
5588 goto unlock;
5590 list_for_each_entry_rcu(pmu, &pmus, entry) {
5591 int ret = pmu->event_init(event);
5592 if (!ret)
5593 goto unlock;
5595 if (ret != -ENOENT) {
5596 pmu = ERR_PTR(ret);
5597 goto unlock;
5600 pmu = ERR_PTR(-ENOENT);
5601 unlock:
5602 srcu_read_unlock(&pmus_srcu, idx);
5604 return pmu;
5608 * Allocate and initialize a event structure
5610 static struct perf_event *
5611 perf_event_alloc(struct perf_event_attr *attr, int cpu,
5612 struct task_struct *task,
5613 struct perf_event *group_leader,
5614 struct perf_event *parent_event,
5615 perf_overflow_handler_t overflow_handler)
5617 struct pmu *pmu;
5618 struct perf_event *event;
5619 struct hw_perf_event *hwc;
5620 long err;
5622 if ((unsigned)cpu >= nr_cpu_ids) {
5623 if (!task || cpu != -1)
5624 return ERR_PTR(-EINVAL);
5627 event = kzalloc(sizeof(*event), GFP_KERNEL);
5628 if (!event)
5629 return ERR_PTR(-ENOMEM);
5632 * Single events are their own group leaders, with an
5633 * empty sibling list:
5635 if (!group_leader)
5636 group_leader = event;
5638 mutex_init(&event->child_mutex);
5639 INIT_LIST_HEAD(&event->child_list);
5641 INIT_LIST_HEAD(&event->group_entry);
5642 INIT_LIST_HEAD(&event->event_entry);
5643 INIT_LIST_HEAD(&event->sibling_list);
5644 init_waitqueue_head(&event->waitq);
5645 init_irq_work(&event->pending, perf_pending_event);
5647 mutex_init(&event->mmap_mutex);
5649 event->cpu = cpu;
5650 event->attr = *attr;
5651 event->group_leader = group_leader;
5652 event->pmu = NULL;
5653 event->oncpu = -1;
5655 event->parent = parent_event;
5657 event->ns = get_pid_ns(current->nsproxy->pid_ns);
5658 event->id = atomic64_inc_return(&perf_event_id);
5660 event->state = PERF_EVENT_STATE_INACTIVE;
5662 if (task) {
5663 event->attach_state = PERF_ATTACH_TASK;
5664 #ifdef CONFIG_HAVE_HW_BREAKPOINT
5666 * hw_breakpoint is a bit difficult here..
5668 if (attr->type == PERF_TYPE_BREAKPOINT)
5669 event->hw.bp_target = task;
5670 #endif
5673 if (!overflow_handler && parent_event)
5674 overflow_handler = parent_event->overflow_handler;
5676 event->overflow_handler = overflow_handler;
5678 if (attr->disabled)
5679 event->state = PERF_EVENT_STATE_OFF;
5681 pmu = NULL;
5683 hwc = &event->hw;
5684 hwc->sample_period = attr->sample_period;
5685 if (attr->freq && attr->sample_freq)
5686 hwc->sample_period = 1;
5687 hwc->last_period = hwc->sample_period;
5689 local64_set(&hwc->period_left, hwc->sample_period);
5692 * we currently do not support PERF_FORMAT_GROUP on inherited events
5694 if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
5695 goto done;
5697 pmu = perf_init_event(event);
5699 done:
5700 err = 0;
5701 if (!pmu)
5702 err = -EINVAL;
5703 else if (IS_ERR(pmu))
5704 err = PTR_ERR(pmu);
5706 if (err) {
5707 if (event->ns)
5708 put_pid_ns(event->ns);
5709 kfree(event);
5710 return ERR_PTR(err);
5713 event->pmu = pmu;
5715 if (!event->parent) {
5716 if (event->attach_state & PERF_ATTACH_TASK)
5717 jump_label_inc(&perf_task_events);
5718 if (event->attr.mmap || event->attr.mmap_data)
5719 atomic_inc(&nr_mmap_events);
5720 if (event->attr.comm)
5721 atomic_inc(&nr_comm_events);
5722 if (event->attr.task)
5723 atomic_inc(&nr_task_events);
5724 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) {
5725 err = get_callchain_buffers();
5726 if (err) {
5727 free_event(event);
5728 return ERR_PTR(err);
5733 return event;
5736 static int perf_copy_attr(struct perf_event_attr __user *uattr,
5737 struct perf_event_attr *attr)
5739 u32 size;
5740 int ret;
5742 if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
5743 return -EFAULT;
5746 * zero the full structure, so that a short copy will be nice.
5748 memset(attr, 0, sizeof(*attr));
5750 ret = get_user(size, &uattr->size);
5751 if (ret)
5752 return ret;
5754 if (size > PAGE_SIZE) /* silly large */
5755 goto err_size;
5757 if (!size) /* abi compat */
5758 size = PERF_ATTR_SIZE_VER0;
5760 if (size < PERF_ATTR_SIZE_VER0)
5761 goto err_size;
5764 * If we're handed a bigger struct than we know of,
5765 * ensure all the unknown bits are 0 - i.e. new
5766 * user-space does not rely on any kernel feature
5767 * extensions we dont know about yet.
5769 if (size > sizeof(*attr)) {
5770 unsigned char __user *addr;
5771 unsigned char __user *end;
5772 unsigned char val;
5774 addr = (void __user *)uattr + sizeof(*attr);
5775 end = (void __user *)uattr + size;
5777 for (; addr < end; addr++) {
5778 ret = get_user(val, addr);
5779 if (ret)
5780 return ret;
5781 if (val)
5782 goto err_size;
5784 size = sizeof(*attr);
5787 ret = copy_from_user(attr, uattr, size);
5788 if (ret)
5789 return -EFAULT;
5792 * If the type exists, the corresponding creation will verify
5793 * the attr->config.
5795 if (attr->type >= PERF_TYPE_MAX)
5796 return -EINVAL;
5798 if (attr->__reserved_1)
5799 return -EINVAL;
5801 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
5802 return -EINVAL;
5804 if (attr->read_format & ~(PERF_FORMAT_MAX-1))
5805 return -EINVAL;
5807 out:
5808 return ret;
5810 err_size:
5811 put_user(sizeof(*attr), &uattr->size);
5812 ret = -E2BIG;
5813 goto out;
5816 static int
5817 perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
5819 struct perf_buffer *buffer = NULL, *old_buffer = NULL;
5820 int ret = -EINVAL;
5822 if (!output_event)
5823 goto set;
5825 /* don't allow circular references */
5826 if (event == output_event)
5827 goto out;
5830 * Don't allow cross-cpu buffers
5832 if (output_event->cpu != event->cpu)
5833 goto out;
5836 * If its not a per-cpu buffer, it must be the same task.
5838 if (output_event->cpu == -1 && output_event->ctx != event->ctx)
5839 goto out;
5841 set:
5842 mutex_lock(&event->mmap_mutex);
5843 /* Can't redirect output if we've got an active mmap() */
5844 if (atomic_read(&event->mmap_count))
5845 goto unlock;
5847 if (output_event) {
5848 /* get the buffer we want to redirect to */
5849 buffer = perf_buffer_get(output_event);
5850 if (!buffer)
5851 goto unlock;
5854 old_buffer = event->buffer;
5855 rcu_assign_pointer(event->buffer, buffer);
5856 ret = 0;
5857 unlock:
5858 mutex_unlock(&event->mmap_mutex);
5860 if (old_buffer)
5861 perf_buffer_put(old_buffer);
5862 out:
5863 return ret;
5867 * sys_perf_event_open - open a performance event, associate it to a task/cpu
5869 * @attr_uptr: event_id type attributes for monitoring/sampling
5870 * @pid: target pid
5871 * @cpu: target cpu
5872 * @group_fd: group leader event fd
5874 SYSCALL_DEFINE5(perf_event_open,
5875 struct perf_event_attr __user *, attr_uptr,
5876 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
5878 struct perf_event *group_leader = NULL, *output_event = NULL;
5879 struct perf_event *event, *sibling;
5880 struct perf_event_attr attr;
5881 struct perf_event_context *ctx;
5882 struct file *event_file = NULL;
5883 struct file *group_file = NULL;
5884 struct task_struct *task = NULL;
5885 struct pmu *pmu;
5886 int event_fd;
5887 int move_group = 0;
5888 int fput_needed = 0;
5889 int err;
5891 /* for future expandability... */
5892 if (flags & ~(PERF_FLAG_FD_NO_GROUP | PERF_FLAG_FD_OUTPUT))
5893 return -EINVAL;
5895 err = perf_copy_attr(attr_uptr, &attr);
5896 if (err)
5897 return err;
5899 if (!attr.exclude_kernel) {
5900 if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
5901 return -EACCES;
5904 if (attr.freq) {
5905 if (attr.sample_freq > sysctl_perf_event_sample_rate)
5906 return -EINVAL;
5909 event_fd = get_unused_fd_flags(O_RDWR);
5910 if (event_fd < 0)
5911 return event_fd;
5913 if (group_fd != -1) {
5914 group_leader = perf_fget_light(group_fd, &fput_needed);
5915 if (IS_ERR(group_leader)) {
5916 err = PTR_ERR(group_leader);
5917 goto err_fd;
5919 group_file = group_leader->filp;
5920 if (flags & PERF_FLAG_FD_OUTPUT)
5921 output_event = group_leader;
5922 if (flags & PERF_FLAG_FD_NO_GROUP)
5923 group_leader = NULL;
5926 if (pid != -1) {
5927 task = find_lively_task_by_vpid(pid);
5928 if (IS_ERR(task)) {
5929 err = PTR_ERR(task);
5930 goto err_group_fd;
5934 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, NULL);
5935 if (IS_ERR(event)) {
5936 err = PTR_ERR(event);
5937 goto err_task;
5941 * Special case software events and allow them to be part of
5942 * any hardware group.
5944 pmu = event->pmu;
5946 if (group_leader &&
5947 (is_software_event(event) != is_software_event(group_leader))) {
5948 if (is_software_event(event)) {
5950 * If event and group_leader are not both a software
5951 * event, and event is, then group leader is not.
5953 * Allow the addition of software events to !software
5954 * groups, this is safe because software events never
5955 * fail to schedule.
5957 pmu = group_leader->pmu;
5958 } else if (is_software_event(group_leader) &&
5959 (group_leader->group_flags & PERF_GROUP_SOFTWARE)) {
5961 * In case the group is a pure software group, and we
5962 * try to add a hardware event, move the whole group to
5963 * the hardware context.
5965 move_group = 1;
5970 * Get the target context (task or percpu):
5972 ctx = find_get_context(pmu, task, cpu);
5973 if (IS_ERR(ctx)) {
5974 err = PTR_ERR(ctx);
5975 goto err_alloc;
5979 * Look up the group leader (we will attach this event to it):
5981 if (group_leader) {
5982 err = -EINVAL;
5985 * Do not allow a recursive hierarchy (this new sibling
5986 * becoming part of another group-sibling):
5988 if (group_leader->group_leader != group_leader)
5989 goto err_context;
5991 * Do not allow to attach to a group in a different
5992 * task or CPU context:
5994 if (move_group) {
5995 if (group_leader->ctx->type != ctx->type)
5996 goto err_context;
5997 } else {
5998 if (group_leader->ctx != ctx)
5999 goto err_context;
6003 * Only a group leader can be exclusive or pinned
6005 if (attr.exclusive || attr.pinned)
6006 goto err_context;
6009 if (output_event) {
6010 err = perf_event_set_output(event, output_event);
6011 if (err)
6012 goto err_context;
6015 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
6016 if (IS_ERR(event_file)) {
6017 err = PTR_ERR(event_file);
6018 goto err_context;
6021 if (move_group) {
6022 struct perf_event_context *gctx = group_leader->ctx;
6024 mutex_lock(&gctx->mutex);
6025 perf_remove_from_context(group_leader);
6026 list_for_each_entry(sibling, &group_leader->sibling_list,
6027 group_entry) {
6028 perf_remove_from_context(sibling);
6029 put_ctx(gctx);
6031 mutex_unlock(&gctx->mutex);
6032 put_ctx(gctx);
6035 event->filp = event_file;
6036 WARN_ON_ONCE(ctx->parent_ctx);
6037 mutex_lock(&ctx->mutex);
6039 if (move_group) {
6040 perf_install_in_context(ctx, group_leader, cpu);
6041 get_ctx(ctx);
6042 list_for_each_entry(sibling, &group_leader->sibling_list,
6043 group_entry) {
6044 perf_install_in_context(ctx, sibling, cpu);
6045 get_ctx(ctx);
6049 perf_install_in_context(ctx, event, cpu);
6050 ++ctx->generation;
6051 perf_unpin_context(ctx);
6052 mutex_unlock(&ctx->mutex);
6054 event->owner = current;
6056 mutex_lock(&current->perf_event_mutex);
6057 list_add_tail(&event->owner_entry, &current->perf_event_list);
6058 mutex_unlock(&current->perf_event_mutex);
6061 * Precalculate sample_data sizes
6063 perf_event__header_size(event);
6064 perf_event__id_header_size(event);
6067 * Drop the reference on the group_event after placing the
6068 * new event on the sibling_list. This ensures destruction
6069 * of the group leader will find the pointer to itself in
6070 * perf_group_detach().
6072 fput_light(group_file, fput_needed);
6073 fd_install(event_fd, event_file);
6074 return event_fd;
6076 err_context:
6077 perf_unpin_context(ctx);
6078 put_ctx(ctx);
6079 err_alloc:
6080 free_event(event);
6081 err_task:
6082 if (task)
6083 put_task_struct(task);
6084 err_group_fd:
6085 fput_light(group_file, fput_needed);
6086 err_fd:
6087 put_unused_fd(event_fd);
6088 return err;
6092 * perf_event_create_kernel_counter
6094 * @attr: attributes of the counter to create
6095 * @cpu: cpu in which the counter is bound
6096 * @task: task to profile (NULL for percpu)
6098 struct perf_event *
6099 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
6100 struct task_struct *task,
6101 perf_overflow_handler_t overflow_handler)
6103 struct perf_event_context *ctx;
6104 struct perf_event *event;
6105 int err;
6108 * Get the target context (task or percpu):
6111 event = perf_event_alloc(attr, cpu, task, NULL, NULL, overflow_handler);
6112 if (IS_ERR(event)) {
6113 err = PTR_ERR(event);
6114 goto err;
6117 ctx = find_get_context(event->pmu, task, cpu);
6118 if (IS_ERR(ctx)) {
6119 err = PTR_ERR(ctx);
6120 goto err_free;
6123 event->filp = NULL;
6124 WARN_ON_ONCE(ctx->parent_ctx);
6125 mutex_lock(&ctx->mutex);
6126 perf_install_in_context(ctx, event, cpu);
6127 ++ctx->generation;
6128 perf_unpin_context(ctx);
6129 mutex_unlock(&ctx->mutex);
6131 return event;
6133 err_free:
6134 free_event(event);
6135 err:
6136 return ERR_PTR(err);
6138 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
6140 static void sync_child_event(struct perf_event *child_event,
6141 struct task_struct *child)
6143 struct perf_event *parent_event = child_event->parent;
6144 u64 child_val;
6146 if (child_event->attr.inherit_stat)
6147 perf_event_read_event(child_event, child);
6149 child_val = perf_event_count(child_event);
6152 * Add back the child's count to the parent's count:
6154 atomic64_add(child_val, &parent_event->child_count);
6155 atomic64_add(child_event->total_time_enabled,
6156 &parent_event->child_total_time_enabled);
6157 atomic64_add(child_event->total_time_running,
6158 &parent_event->child_total_time_running);
6161 * Remove this event from the parent's list
6163 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
6164 mutex_lock(&parent_event->child_mutex);
6165 list_del_init(&child_event->child_list);
6166 mutex_unlock(&parent_event->child_mutex);
6169 * Release the parent event, if this was the last
6170 * reference to it.
6172 fput(parent_event->filp);
6175 static void
6176 __perf_event_exit_task(struct perf_event *child_event,
6177 struct perf_event_context *child_ctx,
6178 struct task_struct *child)
6180 struct perf_event *parent_event;
6182 perf_remove_from_context(child_event);
6184 parent_event = child_event->parent;
6186 * It can happen that parent exits first, and has events
6187 * that are still around due to the child reference. These
6188 * events need to be zapped - but otherwise linger.
6190 if (parent_event) {
6191 sync_child_event(child_event, child);
6192 free_event(child_event);
6196 static void perf_event_exit_task_context(struct task_struct *child, int ctxn)
6198 struct perf_event *child_event, *tmp;
6199 struct perf_event_context *child_ctx;
6200 unsigned long flags;
6202 if (likely(!child->perf_event_ctxp[ctxn])) {
6203 perf_event_task(child, NULL, 0);
6204 return;
6207 local_irq_save(flags);
6209 * We can't reschedule here because interrupts are disabled,
6210 * and either child is current or it is a task that can't be
6211 * scheduled, so we are now safe from rescheduling changing
6212 * our context.
6214 child_ctx = rcu_dereference_raw(child->perf_event_ctxp[ctxn]);
6215 task_ctx_sched_out(child_ctx, EVENT_ALL);
6218 * Take the context lock here so that if find_get_context is
6219 * reading child->perf_event_ctxp, we wait until it has
6220 * incremented the context's refcount before we do put_ctx below.
6222 raw_spin_lock(&child_ctx->lock);
6223 child->perf_event_ctxp[ctxn] = NULL;
6225 * If this context is a clone; unclone it so it can't get
6226 * swapped to another process while we're removing all
6227 * the events from it.
6229 unclone_ctx(child_ctx);
6230 update_context_time(child_ctx);
6231 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
6234 * Report the task dead after unscheduling the events so that we
6235 * won't get any samples after PERF_RECORD_EXIT. We can however still
6236 * get a few PERF_RECORD_READ events.
6238 perf_event_task(child, child_ctx, 0);
6241 * We can recurse on the same lock type through:
6243 * __perf_event_exit_task()
6244 * sync_child_event()
6245 * fput(parent_event->filp)
6246 * perf_release()
6247 * mutex_lock(&ctx->mutex)
6249 * But since its the parent context it won't be the same instance.
6251 mutex_lock(&child_ctx->mutex);
6253 again:
6254 list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
6255 group_entry)
6256 __perf_event_exit_task(child_event, child_ctx, child);
6258 list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
6259 group_entry)
6260 __perf_event_exit_task(child_event, child_ctx, child);
6263 * If the last event was a group event, it will have appended all
6264 * its siblings to the list, but we obtained 'tmp' before that which
6265 * will still point to the list head terminating the iteration.
6267 if (!list_empty(&child_ctx->pinned_groups) ||
6268 !list_empty(&child_ctx->flexible_groups))
6269 goto again;
6271 mutex_unlock(&child_ctx->mutex);
6273 put_ctx(child_ctx);
6277 * When a child task exits, feed back event values to parent events.
6279 void perf_event_exit_task(struct task_struct *child)
6281 struct perf_event *event, *tmp;
6282 int ctxn;
6284 mutex_lock(&child->perf_event_mutex);
6285 list_for_each_entry_safe(event, tmp, &child->perf_event_list,
6286 owner_entry) {
6287 list_del_init(&event->owner_entry);
6290 * Ensure the list deletion is visible before we clear
6291 * the owner, closes a race against perf_release() where
6292 * we need to serialize on the owner->perf_event_mutex.
6294 smp_wmb();
6295 event->owner = NULL;
6297 mutex_unlock(&child->perf_event_mutex);
6299 for_each_task_context_nr(ctxn)
6300 perf_event_exit_task_context(child, ctxn);
6303 static void perf_free_event(struct perf_event *event,
6304 struct perf_event_context *ctx)
6306 struct perf_event *parent = event->parent;
6308 if (WARN_ON_ONCE(!parent))
6309 return;
6311 mutex_lock(&parent->child_mutex);
6312 list_del_init(&event->child_list);
6313 mutex_unlock(&parent->child_mutex);
6315 fput(parent->filp);
6317 perf_group_detach(event);
6318 list_del_event(event, ctx);
6319 free_event(event);
6323 * free an unexposed, unused context as created by inheritance by
6324 * perf_event_init_task below, used by fork() in case of fail.
6326 void perf_event_free_task(struct task_struct *task)
6328 struct perf_event_context *ctx;
6329 struct perf_event *event, *tmp;
6330 int ctxn;
6332 for_each_task_context_nr(ctxn) {
6333 ctx = task->perf_event_ctxp[ctxn];
6334 if (!ctx)
6335 continue;
6337 mutex_lock(&ctx->mutex);
6338 again:
6339 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups,
6340 group_entry)
6341 perf_free_event(event, ctx);
6343 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
6344 group_entry)
6345 perf_free_event(event, ctx);
6347 if (!list_empty(&ctx->pinned_groups) ||
6348 !list_empty(&ctx->flexible_groups))
6349 goto again;
6351 mutex_unlock(&ctx->mutex);
6353 put_ctx(ctx);
6357 void perf_event_delayed_put(struct task_struct *task)
6359 int ctxn;
6361 for_each_task_context_nr(ctxn)
6362 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]);
6366 * inherit a event from parent task to child task:
6368 static struct perf_event *
6369 inherit_event(struct perf_event *parent_event,
6370 struct task_struct *parent,
6371 struct perf_event_context *parent_ctx,
6372 struct task_struct *child,
6373 struct perf_event *group_leader,
6374 struct perf_event_context *child_ctx)
6376 struct perf_event *child_event;
6377 unsigned long flags;
6380 * Instead of creating recursive hierarchies of events,
6381 * we link inherited events back to the original parent,
6382 * which has a filp for sure, which we use as the reference
6383 * count:
6385 if (parent_event->parent)
6386 parent_event = parent_event->parent;
6388 child_event = perf_event_alloc(&parent_event->attr,
6389 parent_event->cpu,
6390 child,
6391 group_leader, parent_event,
6392 NULL);
6393 if (IS_ERR(child_event))
6394 return child_event;
6395 get_ctx(child_ctx);
6398 * Make the child state follow the state of the parent event,
6399 * not its attr.disabled bit. We hold the parent's mutex,
6400 * so we won't race with perf_event_{en, dis}able_family.
6402 if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
6403 child_event->state = PERF_EVENT_STATE_INACTIVE;
6404 else
6405 child_event->state = PERF_EVENT_STATE_OFF;
6407 if (parent_event->attr.freq) {
6408 u64 sample_period = parent_event->hw.sample_period;
6409 struct hw_perf_event *hwc = &child_event->hw;
6411 hwc->sample_period = sample_period;
6412 hwc->last_period = sample_period;
6414 local64_set(&hwc->period_left, sample_period);
6417 child_event->ctx = child_ctx;
6418 child_event->overflow_handler = parent_event->overflow_handler;
6421 * Precalculate sample_data sizes
6423 perf_event__header_size(child_event);
6424 perf_event__id_header_size(child_event);
6427 * Link it up in the child's context:
6429 raw_spin_lock_irqsave(&child_ctx->lock, flags);
6430 add_event_to_ctx(child_event, child_ctx);
6431 raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
6434 * Get a reference to the parent filp - we will fput it
6435 * when the child event exits. This is safe to do because
6436 * we are in the parent and we know that the filp still
6437 * exists and has a nonzero count:
6439 atomic_long_inc(&parent_event->filp->f_count);
6442 * Link this into the parent event's child list
6444 WARN_ON_ONCE(parent_event->ctx->parent_ctx);
6445 mutex_lock(&parent_event->child_mutex);
6446 list_add_tail(&child_event->child_list, &parent_event->child_list);
6447 mutex_unlock(&parent_event->child_mutex);
6449 return child_event;
6452 static int inherit_group(struct perf_event *parent_event,
6453 struct task_struct *parent,
6454 struct perf_event_context *parent_ctx,
6455 struct task_struct *child,
6456 struct perf_event_context *child_ctx)
6458 struct perf_event *leader;
6459 struct perf_event *sub;
6460 struct perf_event *child_ctr;
6462 leader = inherit_event(parent_event, parent, parent_ctx,
6463 child, NULL, child_ctx);
6464 if (IS_ERR(leader))
6465 return PTR_ERR(leader);
6466 list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
6467 child_ctr = inherit_event(sub, parent, parent_ctx,
6468 child, leader, child_ctx);
6469 if (IS_ERR(child_ctr))
6470 return PTR_ERR(child_ctr);
6472 return 0;
6475 static int
6476 inherit_task_group(struct perf_event *event, struct task_struct *parent,
6477 struct perf_event_context *parent_ctx,
6478 struct task_struct *child, int ctxn,
6479 int *inherited_all)
6481 int ret;
6482 struct perf_event_context *child_ctx;
6484 if (!event->attr.inherit) {
6485 *inherited_all = 0;
6486 return 0;
6489 child_ctx = child->perf_event_ctxp[ctxn];
6490 if (!child_ctx) {
6492 * This is executed from the parent task context, so
6493 * inherit events that have been marked for cloning.
6494 * First allocate and initialize a context for the
6495 * child.
6498 child_ctx = alloc_perf_context(event->pmu, child);
6499 if (!child_ctx)
6500 return -ENOMEM;
6502 child->perf_event_ctxp[ctxn] = child_ctx;
6505 ret = inherit_group(event, parent, parent_ctx,
6506 child, child_ctx);
6508 if (ret)
6509 *inherited_all = 0;
6511 return ret;
6515 * Initialize the perf_event context in task_struct
6517 int perf_event_init_context(struct task_struct *child, int ctxn)
6519 struct perf_event_context *child_ctx, *parent_ctx;
6520 struct perf_event_context *cloned_ctx;
6521 struct perf_event *event;
6522 struct task_struct *parent = current;
6523 int inherited_all = 1;
6524 unsigned long flags;
6525 int ret = 0;
6527 if (likely(!parent->perf_event_ctxp[ctxn]))
6528 return 0;
6531 * If the parent's context is a clone, pin it so it won't get
6532 * swapped under us.
6534 parent_ctx = perf_pin_task_context(parent, ctxn);
6537 * No need to check if parent_ctx != NULL here; since we saw
6538 * it non-NULL earlier, the only reason for it to become NULL
6539 * is if we exit, and since we're currently in the middle of
6540 * a fork we can't be exiting at the same time.
6544 * Lock the parent list. No need to lock the child - not PID
6545 * hashed yet and not running, so nobody can access it.
6547 mutex_lock(&parent_ctx->mutex);
6550 * We dont have to disable NMIs - we are only looking at
6551 * the list, not manipulating it:
6553 list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
6554 ret = inherit_task_group(event, parent, parent_ctx,
6555 child, ctxn, &inherited_all);
6556 if (ret)
6557 break;
6561 * We can't hold ctx->lock when iterating the ->flexible_group list due
6562 * to allocations, but we need to prevent rotation because
6563 * rotate_ctx() will change the list from interrupt context.
6565 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
6566 parent_ctx->rotate_disable = 1;
6567 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
6569 list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
6570 ret = inherit_task_group(event, parent, parent_ctx,
6571 child, ctxn, &inherited_all);
6572 if (ret)
6573 break;
6576 raw_spin_lock_irqsave(&parent_ctx->lock, flags);
6577 parent_ctx->rotate_disable = 0;
6579 child_ctx = child->perf_event_ctxp[ctxn];
6581 if (child_ctx && inherited_all) {
6583 * Mark the child context as a clone of the parent
6584 * context, or of whatever the parent is a clone of.
6586 * Note that if the parent is a clone, the holding of
6587 * parent_ctx->lock avoids it from being uncloned.
6589 cloned_ctx = parent_ctx->parent_ctx;
6590 if (cloned_ctx) {
6591 child_ctx->parent_ctx = cloned_ctx;
6592 child_ctx->parent_gen = parent_ctx->parent_gen;
6593 } else {
6594 child_ctx->parent_ctx = parent_ctx;
6595 child_ctx->parent_gen = parent_ctx->generation;
6597 get_ctx(child_ctx->parent_ctx);
6600 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags);
6601 mutex_unlock(&parent_ctx->mutex);
6603 perf_unpin_context(parent_ctx);
6604 put_ctx(parent_ctx);
6606 return ret;
6610 * Initialize the perf_event context in task_struct
6612 int perf_event_init_task(struct task_struct *child)
6614 int ctxn, ret;
6616 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp));
6617 mutex_init(&child->perf_event_mutex);
6618 INIT_LIST_HEAD(&child->perf_event_list);
6620 for_each_task_context_nr(ctxn) {
6621 ret = perf_event_init_context(child, ctxn);
6622 if (ret)
6623 return ret;
6626 return 0;
6629 static void __init perf_event_init_all_cpus(void)
6631 struct swevent_htable *swhash;
6632 int cpu;
6634 for_each_possible_cpu(cpu) {
6635 swhash = &per_cpu(swevent_htable, cpu);
6636 mutex_init(&swhash->hlist_mutex);
6637 INIT_LIST_HEAD(&per_cpu(rotation_list, cpu));
6641 static void __cpuinit perf_event_init_cpu(int cpu)
6643 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6645 mutex_lock(&swhash->hlist_mutex);
6646 if (swhash->hlist_refcount > 0) {
6647 struct swevent_hlist *hlist;
6649 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu));
6650 WARN_ON(!hlist);
6651 rcu_assign_pointer(swhash->swevent_hlist, hlist);
6653 mutex_unlock(&swhash->hlist_mutex);
6656 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC
6657 static void perf_pmu_rotate_stop(struct pmu *pmu)
6659 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context);
6661 WARN_ON(!irqs_disabled());
6663 list_del_init(&cpuctx->rotation_list);
6666 static void __perf_event_exit_context(void *__info)
6668 struct perf_event_context *ctx = __info;
6669 struct perf_event *event, *tmp;
6671 perf_pmu_rotate_stop(ctx->pmu);
6673 list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
6674 __perf_remove_from_context(event);
6675 list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry)
6676 __perf_remove_from_context(event);
6679 static void perf_event_exit_cpu_context(int cpu)
6681 struct perf_event_context *ctx;
6682 struct pmu *pmu;
6683 int idx;
6685 idx = srcu_read_lock(&pmus_srcu);
6686 list_for_each_entry_rcu(pmu, &pmus, entry) {
6687 ctx = &per_cpu_ptr(pmu->pmu_cpu_context, cpu)->ctx;
6689 mutex_lock(&ctx->mutex);
6690 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1);
6691 mutex_unlock(&ctx->mutex);
6693 srcu_read_unlock(&pmus_srcu, idx);
6696 static void perf_event_exit_cpu(int cpu)
6698 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu);
6700 mutex_lock(&swhash->hlist_mutex);
6701 swevent_hlist_release(swhash);
6702 mutex_unlock(&swhash->hlist_mutex);
6704 perf_event_exit_cpu_context(cpu);
6706 #else
6707 static inline void perf_event_exit_cpu(int cpu) { }
6708 #endif
6710 static int
6711 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v)
6713 int cpu;
6715 for_each_online_cpu(cpu)
6716 perf_event_exit_cpu(cpu);
6718 return NOTIFY_OK;
6722 * Run the perf reboot notifier at the very last possible moment so that
6723 * the generic watchdog code runs as long as possible.
6725 static struct notifier_block perf_reboot_notifier = {
6726 .notifier_call = perf_reboot,
6727 .priority = INT_MIN,
6730 static int __cpuinit
6731 perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
6733 unsigned int cpu = (long)hcpu;
6735 switch (action & ~CPU_TASKS_FROZEN) {
6737 case CPU_UP_PREPARE:
6738 case CPU_DOWN_FAILED:
6739 perf_event_init_cpu(cpu);
6740 break;
6742 case CPU_UP_CANCELED:
6743 case CPU_DOWN_PREPARE:
6744 perf_event_exit_cpu(cpu);
6745 break;
6747 default:
6748 break;
6751 return NOTIFY_OK;
6754 void __init perf_event_init(void)
6756 int ret;
6758 idr_init(&pmu_idr);
6760 perf_event_init_all_cpus();
6761 init_srcu_struct(&pmus_srcu);
6762 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE);
6763 perf_pmu_register(&perf_cpu_clock, NULL, -1);
6764 perf_pmu_register(&perf_task_clock, NULL, -1);
6765 perf_tp_register();
6766 perf_cpu_notifier(perf_cpu_notify);
6767 register_reboot_notifier(&perf_reboot_notifier);
6769 ret = init_hw_breakpoint();
6770 WARN(ret, "hw_breakpoint initialization failed with: %d", ret);
6773 static int __init perf_event_sysfs_init(void)
6775 struct pmu *pmu;
6776 int ret;
6778 mutex_lock(&pmus_lock);
6780 ret = bus_register(&pmu_bus);
6781 if (ret)
6782 goto unlock;
6784 list_for_each_entry(pmu, &pmus, entry) {
6785 if (!pmu->name || pmu->type < 0)
6786 continue;
6788 ret = pmu_dev_alloc(pmu);
6789 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret);
6791 pmu_bus_running = 1;
6792 ret = 0;
6794 unlock:
6795 mutex_unlock(&pmus_lock);
6797 return ret;
6799 device_initcall(perf_event_sysfs_init);