Root/kernel/perf_event.c

1/*
2 * Performance events core code:
3 *
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>
8 *
9 * For licensing details see kernel-base/COPYING
10 */
11
12#include <linux/fs.h>
13#include <linux/mm.h>
14#include <linux/cpu.h>
15#include <linux/smp.h>
16#include <linux/file.h>
17#include <linux/poll.h>
18#include <linux/slab.h>
19#include <linux/hash.h>
20#include <linux/sysfs.h>
21#include <linux/dcache.h>
22#include <linux/percpu.h>
23#include <linux/ptrace.h>
24#include <linux/vmstat.h>
25#include <linux/vmalloc.h>
26#include <linux/hardirq.h>
27#include <linux/rculist.h>
28#include <linux/uaccess.h>
29#include <linux/syscalls.h>
30#include <linux/anon_inodes.h>
31#include <linux/kernel_stat.h>
32#include <linux/perf_event.h>
33#include <linux/ftrace_event.h>
34#include <linux/hw_breakpoint.h>
35
36#include <asm/irq_regs.h>
37
38/*
39 * Each CPU has a list of per CPU events:
40 */
41static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);
42
43int perf_max_events __read_mostly = 1;
44static int perf_reserved_percpu __read_mostly;
45static int perf_overcommit __read_mostly = 1;
46
47static atomic_t nr_events __read_mostly;
48static atomic_t nr_mmap_events __read_mostly;
49static atomic_t nr_comm_events __read_mostly;
50static atomic_t nr_task_events __read_mostly;
51
52/*
53 * perf event paranoia level:
54 * -1 - not paranoid at all
55 * 0 - disallow raw tracepoint access for unpriv
56 * 1 - disallow cpu events for unpriv
57 * 2 - disallow kernel profiling for unpriv
58 */
59int sysctl_perf_event_paranoid __read_mostly = 1;
60
61int sysctl_perf_event_mlock __read_mostly = 512; /* 'free' kb per user */
62
63/*
64 * max perf event sample rate
65 */
66int sysctl_perf_event_sample_rate __read_mostly = 100000;
67
68static atomic64_t perf_event_id;
69
70/*
71 * Lock for (sysadmin-configurable) event reservations:
72 */
73static DEFINE_SPINLOCK(perf_resource_lock);
74
75/*
76 * Architecture provided APIs - weak aliases:
77 */
78extern __weak const struct pmu *hw_perf_event_init(struct perf_event *event)
79{
80    return NULL;
81}
82
83void __weak hw_perf_disable(void) { barrier(); }
84void __weak hw_perf_enable(void) { barrier(); }
85
86void __weak perf_event_print_debug(void) { }
87
88static DEFINE_PER_CPU(int, perf_disable_count);
89
90void perf_disable(void)
91{
92    if (!__get_cpu_var(perf_disable_count)++)
93        hw_perf_disable();
94}
95
96void perf_enable(void)
97{
98    if (!--__get_cpu_var(perf_disable_count))
99        hw_perf_enable();
100}
101
102static void get_ctx(struct perf_event_context *ctx)
103{
104    WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
105}
106
107static void free_ctx(struct rcu_head *head)
108{
109    struct perf_event_context *ctx;
110
111    ctx = container_of(head, struct perf_event_context, rcu_head);
112    kfree(ctx);
113}
114
115static void put_ctx(struct perf_event_context *ctx)
116{
117    if (atomic_dec_and_test(&ctx->refcount)) {
118        if (ctx->parent_ctx)
119            put_ctx(ctx->parent_ctx);
120        if (ctx->task)
121            put_task_struct(ctx->task);
122        call_rcu(&ctx->rcu_head, free_ctx);
123    }
124}
125
126static void unclone_ctx(struct perf_event_context *ctx)
127{
128    if (ctx->parent_ctx) {
129        put_ctx(ctx->parent_ctx);
130        ctx->parent_ctx = NULL;
131    }
132}
133
134/*
135 * If we inherit events we want to return the parent event id
136 * to userspace.
137 */
138static u64 primary_event_id(struct perf_event *event)
139{
140    u64 id = event->id;
141
142    if (event->parent)
143        id = event->parent->id;
144
145    return id;
146}
147
148/*
149 * Get the perf_event_context for a task and lock it.
150 * This has to cope with with the fact that until it is locked,
151 * the context could get moved to another task.
152 */
153static struct perf_event_context *
154perf_lock_task_context(struct task_struct *task, unsigned long *flags)
155{
156    struct perf_event_context *ctx;
157
158    rcu_read_lock();
159 retry:
160    ctx = rcu_dereference(task->perf_event_ctxp);
161    if (ctx) {
162        /*
163         * If this context is a clone of another, it might
164         * get swapped for another underneath us by
165         * perf_event_task_sched_out, though the
166         * rcu_read_lock() protects us from any context
167         * getting freed. Lock the context and check if it
168         * got swapped before we could get the lock, and retry
169         * if so. If we locked the right context, then it
170         * can't get swapped on us any more.
171         */
172        raw_spin_lock_irqsave(&ctx->lock, *flags);
173        if (ctx != rcu_dereference(task->perf_event_ctxp)) {
174            raw_spin_unlock_irqrestore(&ctx->lock, *flags);
175            goto retry;
176        }
177
178        if (!atomic_inc_not_zero(&ctx->refcount)) {
179            raw_spin_unlock_irqrestore(&ctx->lock, *flags);
180            ctx = NULL;
181        }
182    }
183    rcu_read_unlock();
184    return ctx;
185}
186
187/*
188 * Get the context for a task and increment its pin_count so it
189 * can't get swapped to another task. This also increments its
190 * reference count so that the context can't get freed.
191 */
192static struct perf_event_context *perf_pin_task_context(struct task_struct *task)
193{
194    struct perf_event_context *ctx;
195    unsigned long flags;
196
197    ctx = perf_lock_task_context(task, &flags);
198    if (ctx) {
199        ++ctx->pin_count;
200        raw_spin_unlock_irqrestore(&ctx->lock, flags);
201    }
202    return ctx;
203}
204
205static void perf_unpin_context(struct perf_event_context *ctx)
206{
207    unsigned long flags;
208
209    raw_spin_lock_irqsave(&ctx->lock, flags);
210    --ctx->pin_count;
211    raw_spin_unlock_irqrestore(&ctx->lock, flags);
212    put_ctx(ctx);
213}
214
215static inline u64 perf_clock(void)
216{
217    return local_clock();
218}
219
220/*
221 * Update the record of the current time in a context.
222 */
223static void update_context_time(struct perf_event_context *ctx)
224{
225    u64 now = perf_clock();
226
227    ctx->time += now - ctx->timestamp;
228    ctx->timestamp = now;
229}
230
231/*
232 * Update the total_time_enabled and total_time_running fields for a event.
233 */
234static void update_event_times(struct perf_event *event)
235{
236    struct perf_event_context *ctx = event->ctx;
237    u64 run_end;
238
239    if (event->state < PERF_EVENT_STATE_INACTIVE ||
240        event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
241        return;
242
243    if (ctx->is_active)
244        run_end = ctx->time;
245    else
246        run_end = event->tstamp_stopped;
247
248    event->total_time_enabled = run_end - event->tstamp_enabled;
249
250    if (event->state == PERF_EVENT_STATE_INACTIVE)
251        run_end = event->tstamp_stopped;
252    else
253        run_end = ctx->time;
254
255    event->total_time_running = run_end - event->tstamp_running;
256}
257
258/*
259 * Update total_time_enabled and total_time_running for all events in a group.
260 */
261static void update_group_times(struct perf_event *leader)
262{
263    struct perf_event *event;
264
265    update_event_times(leader);
266    list_for_each_entry(event, &leader->sibling_list, group_entry)
267        update_event_times(event);
268}
269
270static struct list_head *
271ctx_group_list(struct perf_event *event, struct perf_event_context *ctx)
272{
273    if (event->attr.pinned)
274        return &ctx->pinned_groups;
275    else
276        return &ctx->flexible_groups;
277}
278
279/*
280 * Add a event from the lists for its context.
281 * Must be called with ctx->mutex and ctx->lock held.
282 */
283static void
284list_add_event(struct perf_event *event, struct perf_event_context *ctx)
285{
286    WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT);
287    event->attach_state |= PERF_ATTACH_CONTEXT;
288
289    /*
290     * If we're a stand alone event or group leader, we go to the context
291     * list, group events are kept attached to the group so that
292     * perf_group_detach can, at all times, locate all siblings.
293     */
294    if (event->group_leader == event) {
295        struct list_head *list;
296
297        if (is_software_event(event))
298            event->group_flags |= PERF_GROUP_SOFTWARE;
299
300        list = ctx_group_list(event, ctx);
301        list_add_tail(&event->group_entry, list);
302    }
303
304    list_add_rcu(&event->event_entry, &ctx->event_list);
305    ctx->nr_events++;
306    if (event->attr.inherit_stat)
307        ctx->nr_stat++;
308}
309
310static void perf_group_attach(struct perf_event *event)
311{
312    struct perf_event *group_leader = event->group_leader;
313
314    WARN_ON_ONCE(event->attach_state & PERF_ATTACH_GROUP);
315    event->attach_state |= PERF_ATTACH_GROUP;
316
317    if (group_leader == event)
318        return;
319
320    if (group_leader->group_flags & PERF_GROUP_SOFTWARE &&
321            !is_software_event(event))
322        group_leader->group_flags &= ~PERF_GROUP_SOFTWARE;
323
324    list_add_tail(&event->group_entry, &group_leader->sibling_list);
325    group_leader->nr_siblings++;
326}
327
328/*
329 * Remove a event from the lists for its context.
330 * Must be called with ctx->mutex and ctx->lock held.
331 */
332static void
333list_del_event(struct perf_event *event, struct perf_event_context *ctx)
334{
335    /*
336     * We can have double detach due to exit/hot-unplug + close.
337     */
338    if (!(event->attach_state & PERF_ATTACH_CONTEXT))
339        return;
340
341    event->attach_state &= ~PERF_ATTACH_CONTEXT;
342
343    ctx->nr_events--;
344    if (event->attr.inherit_stat)
345        ctx->nr_stat--;
346
347    list_del_rcu(&event->event_entry);
348
349    if (event->group_leader == event)
350        list_del_init(&event->group_entry);
351
352    update_group_times(event);
353
354    /*
355     * If event was in error state, then keep it
356     * that way, otherwise bogus counts will be
357     * returned on read(). The only way to get out
358     * of error state is by explicit re-enabling
359     * of the event
360     */
361    if (event->state > PERF_EVENT_STATE_OFF)
362        event->state = PERF_EVENT_STATE_OFF;
363}
364
365static void perf_group_detach(struct perf_event *event)
366{
367    struct perf_event *sibling, *tmp;
368    struct list_head *list = NULL;
369
370    /*
371     * We can have double detach due to exit/hot-unplug + close.
372     */
373    if (!(event->attach_state & PERF_ATTACH_GROUP))
374        return;
375
376    event->attach_state &= ~PERF_ATTACH_GROUP;
377
378    /*
379     * If this is a sibling, remove it from its group.
380     */
381    if (event->group_leader != event) {
382        list_del_init(&event->group_entry);
383        event->group_leader->nr_siblings--;
384        return;
385    }
386
387    if (!list_empty(&event->group_entry))
388        list = &event->group_entry;
389
390    /*
391     * If this was a group event with sibling events then
392     * upgrade the siblings to singleton events by adding them
393     * to whatever list we are on.
394     */
395    list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
396        if (list)
397            list_move_tail(&sibling->group_entry, list);
398        sibling->group_leader = sibling;
399
400        /* Inherit group flags from the previous leader */
401        sibling->group_flags = event->group_flags;
402    }
403}
404
405static inline int
406event_filter_match(struct perf_event *event)
407{
408    return event->cpu == -1 || event->cpu == smp_processor_id();
409}
410
411static void
412event_sched_out(struct perf_event *event,
413          struct perf_cpu_context *cpuctx,
414          struct perf_event_context *ctx)
415{
416    u64 delta;
417    /*
418     * An event which could not be activated because of
419     * filter mismatch still needs to have its timings
420     * maintained, otherwise bogus information is return
421     * via read() for time_enabled, time_running:
422     */
423    if (event->state == PERF_EVENT_STATE_INACTIVE
424        && !event_filter_match(event)) {
425        delta = ctx->time - event->tstamp_stopped;
426        event->tstamp_running += delta;
427        event->tstamp_stopped = ctx->time;
428    }
429
430    if (event->state != PERF_EVENT_STATE_ACTIVE)
431        return;
432
433    event->state = PERF_EVENT_STATE_INACTIVE;
434    if (event->pending_disable) {
435        event->pending_disable = 0;
436        event->state = PERF_EVENT_STATE_OFF;
437    }
438    event->tstamp_stopped = ctx->time;
439    event->pmu->disable(event);
440    event->oncpu = -1;
441
442    if (!is_software_event(event))
443        cpuctx->active_oncpu--;
444    ctx->nr_active--;
445    if (event->attr.exclusive || !cpuctx->active_oncpu)
446        cpuctx->exclusive = 0;
447}
448
449static void
450group_sched_out(struct perf_event *group_event,
451        struct perf_cpu_context *cpuctx,
452        struct perf_event_context *ctx)
453{
454    struct perf_event *event;
455    int state = group_event->state;
456
457    event_sched_out(group_event, cpuctx, ctx);
458
459    /*
460     * Schedule out siblings (if any):
461     */
462    list_for_each_entry(event, &group_event->sibling_list, group_entry)
463        event_sched_out(event, cpuctx, ctx);
464
465    if (state == PERF_EVENT_STATE_ACTIVE && group_event->attr.exclusive)
466        cpuctx->exclusive = 0;
467}
468
469/*
470 * Cross CPU call to remove a performance event
471 *
472 * We disable the event on the hardware level first. After that we
473 * remove it from the context list.
474 */
475static void __perf_event_remove_from_context(void *info)
476{
477    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
478    struct perf_event *event = info;
479    struct perf_event_context *ctx = event->ctx;
480
481    /*
482     * If this is a task context, we need to check whether it is
483     * the current task context of this cpu. If not it has been
484     * scheduled out before the smp call arrived.
485     */
486    if (ctx->task && cpuctx->task_ctx != ctx)
487        return;
488
489    raw_spin_lock(&ctx->lock);
490    /*
491     * Protect the list operation against NMI by disabling the
492     * events on a global level.
493     */
494    perf_disable();
495
496    event_sched_out(event, cpuctx, ctx);
497
498    list_del_event(event, ctx);
499
500    if (!ctx->task) {
501        /*
502         * Allow more per task events with respect to the
503         * reservation:
504         */
505        cpuctx->max_pertask =
506            min(perf_max_events - ctx->nr_events,
507                perf_max_events - perf_reserved_percpu);
508    }
509
510    perf_enable();
511    raw_spin_unlock(&ctx->lock);
512}
513
514
515/*
516 * Remove the event from a task's (or a CPU's) list of events.
517 *
518 * Must be called with ctx->mutex held.
519 *
520 * CPU events are removed with a smp call. For task events we only
521 * call when the task is on a CPU.
522 *
523 * If event->ctx is a cloned context, callers must make sure that
524 * every task struct that event->ctx->task could possibly point to
525 * remains valid. This is OK when called from perf_release since
526 * that only calls us on the top-level context, which can't be a clone.
527 * When called from perf_event_exit_task, it's OK because the
528 * context has been detached from its task.
529 */
530static void perf_event_remove_from_context(struct perf_event *event)
531{
532    struct perf_event_context *ctx = event->ctx;
533    struct task_struct *task = ctx->task;
534
535    if (!task) {
536        /*
537         * Per cpu events are removed via an smp call and
538         * the removal is always successful.
539         */
540        smp_call_function_single(event->cpu,
541                     __perf_event_remove_from_context,
542                     event, 1);
543        return;
544    }
545
546retry:
547    task_oncpu_function_call(task, __perf_event_remove_from_context,
548                 event);
549
550    raw_spin_lock_irq(&ctx->lock);
551    /*
552     * If the context is active we need to retry the smp call.
553     */
554    if (ctx->nr_active && !list_empty(&event->group_entry)) {
555        raw_spin_unlock_irq(&ctx->lock);
556        goto retry;
557    }
558
559    /*
560     * The lock prevents that this context is scheduled in so we
561     * can remove the event safely, if the call above did not
562     * succeed.
563     */
564    if (!list_empty(&event->group_entry))
565        list_del_event(event, ctx);
566    raw_spin_unlock_irq(&ctx->lock);
567}
568
569/*
570 * Cross CPU call to disable a performance event
571 */
572static void __perf_event_disable(void *info)
573{
574    struct perf_event *event = info;
575    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
576    struct perf_event_context *ctx = event->ctx;
577
578    /*
579     * If this is a per-task event, need to check whether this
580     * event's task is the current task on this cpu.
581     */
582    if (ctx->task && cpuctx->task_ctx != ctx)
583        return;
584
585    raw_spin_lock(&ctx->lock);
586
587    /*
588     * If the event is on, turn it off.
589     * If it is in error state, leave it in error state.
590     */
591    if (event->state >= PERF_EVENT_STATE_INACTIVE) {
592        update_context_time(ctx);
593        update_group_times(event);
594        if (event == event->group_leader)
595            group_sched_out(event, cpuctx, ctx);
596        else
597            event_sched_out(event, cpuctx, ctx);
598        event->state = PERF_EVENT_STATE_OFF;
599    }
600
601    raw_spin_unlock(&ctx->lock);
602}
603
604/*
605 * Disable a event.
606 *
607 * If event->ctx is a cloned context, callers must make sure that
608 * every task struct that event->ctx->task could possibly point to
609 * remains valid. This condition is satisifed when called through
610 * perf_event_for_each_child or perf_event_for_each because they
611 * hold the top-level event's child_mutex, so any descendant that
612 * goes to exit will block in sync_child_event.
613 * When called from perf_pending_event it's OK because event->ctx
614 * is the current context on this CPU and preemption is disabled,
615 * hence we can't get into perf_event_task_sched_out for this context.
616 */
617void perf_event_disable(struct perf_event *event)
618{
619    struct perf_event_context *ctx = event->ctx;
620    struct task_struct *task = ctx->task;
621
622    if (!task) {
623        /*
624         * Disable the event on the cpu that it's on
625         */
626        smp_call_function_single(event->cpu, __perf_event_disable,
627                     event, 1);
628        return;
629    }
630
631 retry:
632    task_oncpu_function_call(task, __perf_event_disable, event);
633
634    raw_spin_lock_irq(&ctx->lock);
635    /*
636     * If the event is still active, we need to retry the cross-call.
637     */
638    if (event->state == PERF_EVENT_STATE_ACTIVE) {
639        raw_spin_unlock_irq(&ctx->lock);
640        goto retry;
641    }
642
643    /*
644     * Since we have the lock this context can't be scheduled
645     * in, so we can change the state safely.
646     */
647    if (event->state == PERF_EVENT_STATE_INACTIVE) {
648        update_group_times(event);
649        event->state = PERF_EVENT_STATE_OFF;
650    }
651
652    raw_spin_unlock_irq(&ctx->lock);
653}
654
655static int
656event_sched_in(struct perf_event *event,
657         struct perf_cpu_context *cpuctx,
658         struct perf_event_context *ctx)
659{
660    if (event->state <= PERF_EVENT_STATE_OFF)
661        return 0;
662
663    event->state = PERF_EVENT_STATE_ACTIVE;
664    event->oncpu = smp_processor_id();
665    /*
666     * The new state must be visible before we turn it on in the hardware:
667     */
668    smp_wmb();
669
670    if (event->pmu->enable(event)) {
671        event->state = PERF_EVENT_STATE_INACTIVE;
672        event->oncpu = -1;
673        return -EAGAIN;
674    }
675
676    event->tstamp_running += ctx->time - event->tstamp_stopped;
677
678    if (!is_software_event(event))
679        cpuctx->active_oncpu++;
680    ctx->nr_active++;
681
682    if (event->attr.exclusive)
683        cpuctx->exclusive = 1;
684
685    return 0;
686}
687
688static int
689group_sched_in(struct perf_event *group_event,
690           struct perf_cpu_context *cpuctx,
691           struct perf_event_context *ctx)
692{
693    struct perf_event *event, *partial_group = NULL;
694    const struct pmu *pmu = group_event->pmu;
695    bool txn = false;
696
697    if (group_event->state == PERF_EVENT_STATE_OFF)
698        return 0;
699
700    /* Check if group transaction availabe */
701    if (pmu->start_txn)
702        txn = true;
703
704    if (txn)
705        pmu->start_txn(pmu);
706
707    if (event_sched_in(group_event, cpuctx, ctx)) {
708        if (txn)
709            pmu->cancel_txn(pmu);
710        return -EAGAIN;
711    }
712
713    /*
714     * Schedule in siblings as one group (if any):
715     */
716    list_for_each_entry(event, &group_event->sibling_list, group_entry) {
717        if (event_sched_in(event, cpuctx, ctx)) {
718            partial_group = event;
719            goto group_error;
720        }
721    }
722
723    if (!txn || !pmu->commit_txn(pmu))
724        return 0;
725
726group_error:
727    /*
728     * Groups can be scheduled in as one unit only, so undo any
729     * partial group before returning:
730     */
731    list_for_each_entry(event, &group_event->sibling_list, group_entry) {
732        if (event == partial_group)
733            break;
734        event_sched_out(event, cpuctx, ctx);
735    }
736    event_sched_out(group_event, cpuctx, ctx);
737
738    if (txn)
739        pmu->cancel_txn(pmu);
740
741    return -EAGAIN;
742}
743
744/*
745 * Work out whether we can put this event group on the CPU now.
746 */
747static int group_can_go_on(struct perf_event *event,
748               struct perf_cpu_context *cpuctx,
749               int can_add_hw)
750{
751    /*
752     * Groups consisting entirely of software events can always go on.
753     */
754    if (event->group_flags & PERF_GROUP_SOFTWARE)
755        return 1;
756    /*
757     * If an exclusive group is already on, no other hardware
758     * events can go on.
759     */
760    if (cpuctx->exclusive)
761        return 0;
762    /*
763     * If this group is exclusive and there are already
764     * events on the CPU, it can't go on.
765     */
766    if (event->attr.exclusive && cpuctx->active_oncpu)
767        return 0;
768    /*
769     * Otherwise, try to add it if all previous groups were able
770     * to go on.
771     */
772    return can_add_hw;
773}
774
775static void add_event_to_ctx(struct perf_event *event,
776                   struct perf_event_context *ctx)
777{
778    list_add_event(event, ctx);
779    perf_group_attach(event);
780    event->tstamp_enabled = ctx->time;
781    event->tstamp_running = ctx->time;
782    event->tstamp_stopped = ctx->time;
783}
784
785/*
786 * Cross CPU call to install and enable a performance event
787 *
788 * Must be called with ctx->mutex held
789 */
790static void __perf_install_in_context(void *info)
791{
792    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
793    struct perf_event *event = info;
794    struct perf_event_context *ctx = event->ctx;
795    struct perf_event *leader = event->group_leader;
796    int err;
797
798    /*
799     * If this is a task context, we need to check whether it is
800     * the current task context of this cpu. If not it has been
801     * scheduled out before the smp call arrived.
802     * Or possibly this is the right context but it isn't
803     * on this cpu because it had no events.
804     */
805    if (ctx->task && cpuctx->task_ctx != ctx) {
806        if (cpuctx->task_ctx || ctx->task != current)
807            return;
808        cpuctx->task_ctx = ctx;
809    }
810
811    raw_spin_lock(&ctx->lock);
812    ctx->is_active = 1;
813    update_context_time(ctx);
814
815    /*
816     * Protect the list operation against NMI by disabling the
817     * events on a global level. NOP for non NMI based events.
818     */
819    perf_disable();
820
821    add_event_to_ctx(event, ctx);
822
823    if (event->cpu != -1 && event->cpu != smp_processor_id())
824        goto unlock;
825
826    /*
827     * Don't put the event on if it is disabled or if
828     * it is in a group and the group isn't on.
829     */
830    if (event->state != PERF_EVENT_STATE_INACTIVE ||
831        (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE))
832        goto unlock;
833
834    /*
835     * An exclusive event can't go on if there are already active
836     * hardware events, and no hardware event can go on if there
837     * is already an exclusive event on.
838     */
839    if (!group_can_go_on(event, cpuctx, 1))
840        err = -EEXIST;
841    else
842        err = event_sched_in(event, cpuctx, ctx);
843
844    if (err) {
845        /*
846         * This event couldn't go on. If it is in a group
847         * then we have to pull the whole group off.
848         * If the event group is pinned then put it in error state.
849         */
850        if (leader != event)
851            group_sched_out(leader, cpuctx, ctx);
852        if (leader->attr.pinned) {
853            update_group_times(leader);
854            leader->state = PERF_EVENT_STATE_ERROR;
855        }
856    }
857
858    if (!err && !ctx->task && cpuctx->max_pertask)
859        cpuctx->max_pertask--;
860
861 unlock:
862    perf_enable();
863
864    raw_spin_unlock(&ctx->lock);
865}
866
867/*
868 * Attach a performance event to a context
869 *
870 * First we add the event to the list with the hardware enable bit
871 * in event->hw_config cleared.
872 *
873 * If the event is attached to a task which is on a CPU we use a smp
874 * call to enable it in the task context. The task might have been
875 * scheduled away, but we check this in the smp call again.
876 *
877 * Must be called with ctx->mutex held.
878 */
879static void
880perf_install_in_context(struct perf_event_context *ctx,
881            struct perf_event *event,
882            int cpu)
883{
884    struct task_struct *task = ctx->task;
885
886    if (!task) {
887        /*
888         * Per cpu events are installed via an smp call and
889         * the install is always successful.
890         */
891        smp_call_function_single(cpu, __perf_install_in_context,
892                     event, 1);
893        return;
894    }
895
896retry:
897    task_oncpu_function_call(task, __perf_install_in_context,
898                 event);
899
900    raw_spin_lock_irq(&ctx->lock);
901    /*
902     * we need to retry the smp call.
903     */
904    if (ctx->is_active && list_empty(&event->group_entry)) {
905        raw_spin_unlock_irq(&ctx->lock);
906        goto retry;
907    }
908
909    /*
910     * The lock prevents that this context is scheduled in so we
911     * can add the event safely, if it the call above did not
912     * succeed.
913     */
914    if (list_empty(&event->group_entry))
915        add_event_to_ctx(event, ctx);
916    raw_spin_unlock_irq(&ctx->lock);
917}
918
919/*
920 * Put a event into inactive state and update time fields.
921 * Enabling the leader of a group effectively enables all
922 * the group members that aren't explicitly disabled, so we
923 * have to update their ->tstamp_enabled also.
924 * Note: this works for group members as well as group leaders
925 * since the non-leader members' sibling_lists will be empty.
926 */
927static void __perf_event_mark_enabled(struct perf_event *event,
928                    struct perf_event_context *ctx)
929{
930    struct perf_event *sub;
931
932    event->state = PERF_EVENT_STATE_INACTIVE;
933    event->tstamp_enabled = ctx->time - event->total_time_enabled;
934    list_for_each_entry(sub, &event->sibling_list, group_entry)
935        if (sub->state >= PERF_EVENT_STATE_INACTIVE)
936            sub->tstamp_enabled =
937                ctx->time - sub->total_time_enabled;
938}
939
940/*
941 * Cross CPU call to enable a performance event
942 */
943static void __perf_event_enable(void *info)
944{
945    struct perf_event *event = info;
946    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
947    struct perf_event_context *ctx = event->ctx;
948    struct perf_event *leader = event->group_leader;
949    int err;
950
951    /*
952     * If this is a per-task event, need to check whether this
953     * event's task is the current task on this cpu.
954     */
955    if (ctx->task && cpuctx->task_ctx != ctx) {
956        if (cpuctx->task_ctx || ctx->task != current)
957            return;
958        cpuctx->task_ctx = ctx;
959    }
960
961    raw_spin_lock(&ctx->lock);
962    ctx->is_active = 1;
963    update_context_time(ctx);
964
965    if (event->state >= PERF_EVENT_STATE_INACTIVE)
966        goto unlock;
967    __perf_event_mark_enabled(event, ctx);
968
969    if (event->cpu != -1 && event->cpu != smp_processor_id())
970        goto unlock;
971
972    /*
973     * If the event is in a group and isn't the group leader,
974     * then don't put it on unless the group is on.
975     */
976    if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
977        goto unlock;
978
979    if (!group_can_go_on(event, cpuctx, 1)) {
980        err = -EEXIST;
981    } else {
982        perf_disable();
983        if (event == leader)
984            err = group_sched_in(event, cpuctx, ctx);
985        else
986            err = event_sched_in(event, cpuctx, ctx);
987        perf_enable();
988    }
989
990    if (err) {
991        /*
992         * If this event can't go on and it's part of a
993         * group, then the whole group has to come off.
994         */
995        if (leader != event)
996            group_sched_out(leader, cpuctx, ctx);
997        if (leader->attr.pinned) {
998            update_group_times(leader);
999            leader->state = PERF_EVENT_STATE_ERROR;
1000        }
1001    }
1002
1003 unlock:
1004    raw_spin_unlock(&ctx->lock);
1005}
1006
1007/*
1008 * Enable a event.
1009 *
1010 * If event->ctx is a cloned context, callers must make sure that
1011 * every task struct that event->ctx->task could possibly point to
1012 * remains valid. This condition is satisfied when called through
1013 * perf_event_for_each_child or perf_event_for_each as described
1014 * for perf_event_disable.
1015 */
1016void perf_event_enable(struct perf_event *event)
1017{
1018    struct perf_event_context *ctx = event->ctx;
1019    struct task_struct *task = ctx->task;
1020
1021    if (!task) {
1022        /*
1023         * Enable the event on the cpu that it's on
1024         */
1025        smp_call_function_single(event->cpu, __perf_event_enable,
1026                     event, 1);
1027        return;
1028    }
1029
1030    raw_spin_lock_irq(&ctx->lock);
1031    if (event->state >= PERF_EVENT_STATE_INACTIVE)
1032        goto out;
1033
1034    /*
1035     * If the event is in error state, clear that first.
1036     * That way, if we see the event in error state below, we
1037     * know that it has gone back into error state, as distinct
1038     * from the task having been scheduled away before the
1039     * cross-call arrived.
1040     */
1041    if (event->state == PERF_EVENT_STATE_ERROR)
1042        event->state = PERF_EVENT_STATE_OFF;
1043
1044 retry:
1045    raw_spin_unlock_irq(&ctx->lock);
1046    task_oncpu_function_call(task, __perf_event_enable, event);
1047
1048    raw_spin_lock_irq(&ctx->lock);
1049
1050    /*
1051     * If the context is active and the event is still off,
1052     * we need to retry the cross-call.
1053     */
1054    if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF)
1055        goto retry;
1056
1057    /*
1058     * Since we have the lock this context can't be scheduled
1059     * in, so we can change the state safely.
1060     */
1061    if (event->state == PERF_EVENT_STATE_OFF)
1062        __perf_event_mark_enabled(event, ctx);
1063
1064 out:
1065    raw_spin_unlock_irq(&ctx->lock);
1066}
1067
1068static int perf_event_refresh(struct perf_event *event, int refresh)
1069{
1070    /*
1071     * not supported on inherited events
1072     */
1073    if (event->attr.inherit)
1074        return -EINVAL;
1075
1076    atomic_add(refresh, &event->event_limit);
1077    perf_event_enable(event);
1078
1079    return 0;
1080}
1081
1082enum event_type_t {
1083    EVENT_FLEXIBLE = 0x1,
1084    EVENT_PINNED = 0x2,
1085    EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED,
1086};
1087
1088static void ctx_sched_out(struct perf_event_context *ctx,
1089              struct perf_cpu_context *cpuctx,
1090              enum event_type_t event_type)
1091{
1092    struct perf_event *event;
1093
1094    raw_spin_lock(&ctx->lock);
1095    ctx->is_active = 0;
1096    if (likely(!ctx->nr_events))
1097        goto out;
1098    update_context_time(ctx);
1099
1100    perf_disable();
1101    if (!ctx->nr_active)
1102        goto out_enable;
1103
1104    if (event_type & EVENT_PINNED)
1105        list_for_each_entry(event, &ctx->pinned_groups, group_entry)
1106            group_sched_out(event, cpuctx, ctx);
1107
1108    if (event_type & EVENT_FLEXIBLE)
1109        list_for_each_entry(event, &ctx->flexible_groups, group_entry)
1110            group_sched_out(event, cpuctx, ctx);
1111
1112 out_enable:
1113    perf_enable();
1114 out:
1115    raw_spin_unlock(&ctx->lock);
1116}
1117
1118/*
1119 * Test whether two contexts are equivalent, i.e. whether they
1120 * have both been cloned from the same version of the same context
1121 * and they both have the same number of enabled events.
1122 * If the number of enabled events is the same, then the set
1123 * of enabled events should be the same, because these are both
1124 * inherited contexts, therefore we can't access individual events
1125 * in them directly with an fd; we can only enable/disable all
1126 * events via prctl, or enable/disable all events in a family
1127 * via ioctl, which will have the same effect on both contexts.
1128 */
1129static int context_equiv(struct perf_event_context *ctx1,
1130             struct perf_event_context *ctx2)
1131{
1132    return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1133        && ctx1->parent_gen == ctx2->parent_gen
1134        && !ctx1->pin_count && !ctx2->pin_count;
1135}
1136
1137static void __perf_event_sync_stat(struct perf_event *event,
1138                     struct perf_event *next_event)
1139{
1140    u64 value;
1141
1142    if (!event->attr.inherit_stat)
1143        return;
1144
1145    /*
1146     * Update the event value, we cannot use perf_event_read()
1147     * because we're in the middle of a context switch and have IRQs
1148     * disabled, which upsets smp_call_function_single(), however
1149     * we know the event must be on the current CPU, therefore we
1150     * don't need to use it.
1151     */
1152    switch (event->state) {
1153    case PERF_EVENT_STATE_ACTIVE:
1154        event->pmu->read(event);
1155        /* fall-through */
1156
1157    case PERF_EVENT_STATE_INACTIVE:
1158        update_event_times(event);
1159        break;
1160
1161    default:
1162        break;
1163    }
1164
1165    /*
1166     * In order to keep per-task stats reliable we need to flip the event
1167     * values when we flip the contexts.
1168     */
1169    value = local64_read(&next_event->count);
1170    value = local64_xchg(&event->count, value);
1171    local64_set(&next_event->count, value);
1172
1173    swap(event->total_time_enabled, next_event->total_time_enabled);
1174    swap(event->total_time_running, next_event->total_time_running);
1175
1176    /*
1177     * Since we swizzled the values, update the user visible data too.
1178     */
1179    perf_event_update_userpage(event);
1180    perf_event_update_userpage(next_event);
1181}
1182
1183#define list_next_entry(pos, member) \
1184    list_entry(pos->member.next, typeof(*pos), member)
1185
1186static void perf_event_sync_stat(struct perf_event_context *ctx,
1187                   struct perf_event_context *next_ctx)
1188{
1189    struct perf_event *event, *next_event;
1190
1191    if (!ctx->nr_stat)
1192        return;
1193
1194    update_context_time(ctx);
1195
1196    event = list_first_entry(&ctx->event_list,
1197                   struct perf_event, event_entry);
1198
1199    next_event = list_first_entry(&next_ctx->event_list,
1200                    struct perf_event, event_entry);
1201
1202    while (&event->event_entry != &ctx->event_list &&
1203           &next_event->event_entry != &next_ctx->event_list) {
1204
1205        __perf_event_sync_stat(event, next_event);
1206
1207        event = list_next_entry(event, event_entry);
1208        next_event = list_next_entry(next_event, event_entry);
1209    }
1210}
1211
1212/*
1213 * Called from scheduler to remove the events of the current task,
1214 * with interrupts disabled.
1215 *
1216 * We stop each event and update the event value in event->count.
1217 *
1218 * This does not protect us against NMI, but disable()
1219 * sets the disabled bit in the control field of event _before_
1220 * accessing the event control register. If a NMI hits, then it will
1221 * not restart the event.
1222 */
1223void perf_event_task_sched_out(struct task_struct *task,
1224                 struct task_struct *next)
1225{
1226    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1227    struct perf_event_context *ctx = task->perf_event_ctxp;
1228    struct perf_event_context *next_ctx;
1229    struct perf_event_context *parent;
1230    int do_switch = 1;
1231
1232    perf_sw_event(PERF_COUNT_SW_CONTEXT_SWITCHES, 1, 1, NULL, 0);
1233
1234    if (likely(!ctx || !cpuctx->task_ctx))
1235        return;
1236
1237    rcu_read_lock();
1238    parent = rcu_dereference(ctx->parent_ctx);
1239    next_ctx = next->perf_event_ctxp;
1240    if (parent && next_ctx &&
1241        rcu_dereference(next_ctx->parent_ctx) == parent) {
1242        /*
1243         * Looks like the two contexts are clones, so we might be
1244         * able to optimize the context switch. We lock both
1245         * contexts and check that they are clones under the
1246         * lock (including re-checking that neither has been
1247         * uncloned in the meantime). It doesn't matter which
1248         * order we take the locks because no other cpu could
1249         * be trying to lock both of these tasks.
1250         */
1251        raw_spin_lock(&ctx->lock);
1252        raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
1253        if (context_equiv(ctx, next_ctx)) {
1254            /*
1255             * XXX do we need a memory barrier of sorts
1256             * wrt to rcu_dereference() of perf_event_ctxp
1257             */
1258            task->perf_event_ctxp = next_ctx;
1259            next->perf_event_ctxp = ctx;
1260            ctx->task = next;
1261            next_ctx->task = task;
1262            do_switch = 0;
1263
1264            perf_event_sync_stat(ctx, next_ctx);
1265        }
1266        raw_spin_unlock(&next_ctx->lock);
1267        raw_spin_unlock(&ctx->lock);
1268    }
1269    rcu_read_unlock();
1270
1271    if (do_switch) {
1272        ctx_sched_out(ctx, cpuctx, EVENT_ALL);
1273        cpuctx->task_ctx = NULL;
1274    }
1275}
1276
1277static void task_ctx_sched_out(struct perf_event_context *ctx,
1278                   enum event_type_t event_type)
1279{
1280    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1281
1282    if (!cpuctx->task_ctx)
1283        return;
1284
1285    if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
1286        return;
1287
1288    ctx_sched_out(ctx, cpuctx, event_type);
1289    cpuctx->task_ctx = NULL;
1290}
1291
1292/*
1293 * Called with IRQs disabled
1294 */
1295static void __perf_event_task_sched_out(struct perf_event_context *ctx)
1296{
1297    task_ctx_sched_out(ctx, EVENT_ALL);
1298}
1299
1300/*
1301 * Called with IRQs disabled
1302 */
1303static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx,
1304                  enum event_type_t event_type)
1305{
1306    ctx_sched_out(&cpuctx->ctx, cpuctx, event_type);
1307}
1308
1309static void
1310ctx_pinned_sched_in(struct perf_event_context *ctx,
1311            struct perf_cpu_context *cpuctx)
1312{
1313    struct perf_event *event;
1314
1315    list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
1316        if (event->state <= PERF_EVENT_STATE_OFF)
1317            continue;
1318        if (event->cpu != -1 && event->cpu != smp_processor_id())
1319            continue;
1320
1321        if (group_can_go_on(event, cpuctx, 1))
1322            group_sched_in(event, cpuctx, ctx);
1323
1324        /*
1325         * If this pinned group hasn't been scheduled,
1326         * put it in error state.
1327         */
1328        if (event->state == PERF_EVENT_STATE_INACTIVE) {
1329            update_group_times(event);
1330            event->state = PERF_EVENT_STATE_ERROR;
1331        }
1332    }
1333}
1334
1335static void
1336ctx_flexible_sched_in(struct perf_event_context *ctx,
1337              struct perf_cpu_context *cpuctx)
1338{
1339    struct perf_event *event;
1340    int can_add_hw = 1;
1341
1342    list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
1343        /* Ignore events in OFF or ERROR state */
1344        if (event->state <= PERF_EVENT_STATE_OFF)
1345            continue;
1346        /*
1347         * Listen to the 'cpu' scheduling filter constraint
1348         * of events:
1349         */
1350        if (event->cpu != -1 && event->cpu != smp_processor_id())
1351            continue;
1352
1353        if (group_can_go_on(event, cpuctx, can_add_hw))
1354            if (group_sched_in(event, cpuctx, ctx))
1355                can_add_hw = 0;
1356    }
1357}
1358
1359static void
1360ctx_sched_in(struct perf_event_context *ctx,
1361         struct perf_cpu_context *cpuctx,
1362         enum event_type_t event_type)
1363{
1364    raw_spin_lock(&ctx->lock);
1365    ctx->is_active = 1;
1366    if (likely(!ctx->nr_events))
1367        goto out;
1368
1369    ctx->timestamp = perf_clock();
1370
1371    perf_disable();
1372
1373    /*
1374     * First go through the list and put on any pinned groups
1375     * in order to give them the best chance of going on.
1376     */
1377    if (event_type & EVENT_PINNED)
1378        ctx_pinned_sched_in(ctx, cpuctx);
1379
1380    /* Then walk through the lower prio flexible groups */
1381    if (event_type & EVENT_FLEXIBLE)
1382        ctx_flexible_sched_in(ctx, cpuctx);
1383
1384    perf_enable();
1385 out:
1386    raw_spin_unlock(&ctx->lock);
1387}
1388
1389static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx,
1390                 enum event_type_t event_type)
1391{
1392    struct perf_event_context *ctx = &cpuctx->ctx;
1393
1394    ctx_sched_in(ctx, cpuctx, event_type);
1395}
1396
1397static void task_ctx_sched_in(struct task_struct *task,
1398                  enum event_type_t event_type)
1399{
1400    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1401    struct perf_event_context *ctx = task->perf_event_ctxp;
1402
1403    if (likely(!ctx))
1404        return;
1405    if (cpuctx->task_ctx == ctx)
1406        return;
1407    ctx_sched_in(ctx, cpuctx, event_type);
1408    cpuctx->task_ctx = ctx;
1409}
1410/*
1411 * Called from scheduler to add the events of the current task
1412 * with interrupts disabled.
1413 *
1414 * We restore the event value and then enable it.
1415 *
1416 * This does not protect us against NMI, but enable()
1417 * sets the enabled bit in the control field of event _before_
1418 * accessing the event control register. If a NMI hits, then it will
1419 * keep the event running.
1420 */
1421void perf_event_task_sched_in(struct task_struct *task)
1422{
1423    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1424    struct perf_event_context *ctx = task->perf_event_ctxp;
1425
1426    if (likely(!ctx))
1427        return;
1428
1429    if (cpuctx->task_ctx == ctx)
1430        return;
1431
1432    perf_disable();
1433
1434    /*
1435     * We want to keep the following priority order:
1436     * cpu pinned (that don't need to move), task pinned,
1437     * cpu flexible, task flexible.
1438     */
1439    cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
1440
1441    ctx_sched_in(ctx, cpuctx, EVENT_PINNED);
1442    cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
1443    ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE);
1444
1445    cpuctx->task_ctx = ctx;
1446
1447    perf_enable();
1448}
1449
1450#define MAX_INTERRUPTS (~0ULL)
1451
1452static void perf_log_throttle(struct perf_event *event, int enable);
1453
1454static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count)
1455{
1456    u64 frequency = event->attr.sample_freq;
1457    u64 sec = NSEC_PER_SEC;
1458    u64 divisor, dividend;
1459
1460    int count_fls, nsec_fls, frequency_fls, sec_fls;
1461
1462    count_fls = fls64(count);
1463    nsec_fls = fls64(nsec);
1464    frequency_fls = fls64(frequency);
1465    sec_fls = 30;
1466
1467    /*
1468     * We got @count in @nsec, with a target of sample_freq HZ
1469     * the target period becomes:
1470     *
1471     * @count * 10^9
1472     * period = -------------------
1473     * @nsec * sample_freq
1474     *
1475     */
1476
1477    /*
1478     * Reduce accuracy by one bit such that @a and @b converge
1479     * to a similar magnitude.
1480     */
1481#define REDUCE_FLS(a, b) \
1482do { \
1483    if (a##_fls > b##_fls) { \
1484        a >>= 1; \
1485        a##_fls--; \
1486    } else { \
1487        b >>= 1; \
1488        b##_fls--; \
1489    } \
1490} while (0)
1491
1492    /*
1493     * Reduce accuracy until either term fits in a u64, then proceed with
1494     * the other, so that finally we can do a u64/u64 division.
1495     */
1496    while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) {
1497        REDUCE_FLS(nsec, frequency);
1498        REDUCE_FLS(sec, count);
1499    }
1500
1501    if (count_fls + sec_fls > 64) {
1502        divisor = nsec * frequency;
1503
1504        while (count_fls + sec_fls > 64) {
1505            REDUCE_FLS(count, sec);
1506            divisor >>= 1;
1507        }
1508
1509        dividend = count * sec;
1510    } else {
1511        dividend = count * sec;
1512
1513        while (nsec_fls + frequency_fls > 64) {
1514            REDUCE_FLS(nsec, frequency);
1515            dividend >>= 1;
1516        }
1517
1518        divisor = nsec * frequency;
1519    }
1520
1521    if (!divisor)
1522        return dividend;
1523
1524    return div64_u64(dividend, divisor);
1525}
1526
1527static void perf_event_stop(struct perf_event *event)
1528{
1529    if (!event->pmu->stop)
1530        return event->pmu->disable(event);
1531
1532    return event->pmu->stop(event);
1533}
1534
1535static int perf_event_start(struct perf_event *event)
1536{
1537    if (!event->pmu->start)
1538        return event->pmu->enable(event);
1539
1540    return event->pmu->start(event);
1541}
1542
1543static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count)
1544{
1545    struct hw_perf_event *hwc = &event->hw;
1546    s64 period, sample_period;
1547    s64 delta;
1548
1549    period = perf_calculate_period(event, nsec, count);
1550
1551    delta = (s64)(period - hwc->sample_period);
1552    delta = (delta + 7) / 8; /* low pass filter */
1553
1554    sample_period = hwc->sample_period + delta;
1555
1556    if (!sample_period)
1557        sample_period = 1;
1558
1559    hwc->sample_period = sample_period;
1560
1561    if (local64_read(&hwc->period_left) > 8*sample_period) {
1562        perf_disable();
1563        perf_event_stop(event);
1564        local64_set(&hwc->period_left, 0);
1565        perf_event_start(event);
1566        perf_enable();
1567    }
1568}
1569
1570static void perf_ctx_adjust_freq(struct perf_event_context *ctx)
1571{
1572    struct perf_event *event;
1573    struct hw_perf_event *hwc;
1574    u64 interrupts, now;
1575    s64 delta;
1576
1577    raw_spin_lock(&ctx->lock);
1578    list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
1579        if (event->state != PERF_EVENT_STATE_ACTIVE)
1580            continue;
1581
1582        if (event->cpu != -1 && event->cpu != smp_processor_id())
1583            continue;
1584
1585        hwc = &event->hw;
1586
1587        interrupts = hwc->interrupts;
1588        hwc->interrupts = 0;
1589
1590        /*
1591         * unthrottle events on the tick
1592         */
1593        if (interrupts == MAX_INTERRUPTS) {
1594            perf_log_throttle(event, 1);
1595            perf_disable();
1596            event->pmu->unthrottle(event);
1597            perf_enable();
1598        }
1599
1600        if (!event->attr.freq || !event->attr.sample_freq)
1601            continue;
1602
1603        perf_disable();
1604        event->pmu->read(event);
1605        now = local64_read(&event->count);
1606        delta = now - hwc->freq_count_stamp;
1607        hwc->freq_count_stamp = now;
1608
1609        if (delta > 0)
1610            perf_adjust_period(event, TICK_NSEC, delta);
1611        perf_enable();
1612    }
1613    raw_spin_unlock(&ctx->lock);
1614}
1615
1616/*
1617 * Round-robin a context's events:
1618 */
1619static void rotate_ctx(struct perf_event_context *ctx)
1620{
1621    raw_spin_lock(&ctx->lock);
1622
1623    /* Rotate the first entry last of non-pinned groups */
1624    list_rotate_left(&ctx->flexible_groups);
1625
1626    raw_spin_unlock(&ctx->lock);
1627}
1628
1629void perf_event_task_tick(struct task_struct *curr)
1630{
1631    struct perf_cpu_context *cpuctx;
1632    struct perf_event_context *ctx;
1633    int rotate = 0;
1634
1635    if (!atomic_read(&nr_events))
1636        return;
1637
1638    cpuctx = &__get_cpu_var(perf_cpu_context);
1639    if (cpuctx->ctx.nr_events &&
1640        cpuctx->ctx.nr_events != cpuctx->ctx.nr_active)
1641        rotate = 1;
1642
1643    ctx = curr->perf_event_ctxp;
1644    if (ctx && ctx->nr_events && ctx->nr_events != ctx->nr_active)
1645        rotate = 1;
1646
1647    perf_ctx_adjust_freq(&cpuctx->ctx);
1648    if (ctx)
1649        perf_ctx_adjust_freq(ctx);
1650
1651    if (!rotate)
1652        return;
1653
1654    perf_disable();
1655    cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE);
1656    if (ctx)
1657        task_ctx_sched_out(ctx, EVENT_FLEXIBLE);
1658
1659    rotate_ctx(&cpuctx->ctx);
1660    if (ctx)
1661        rotate_ctx(ctx);
1662
1663    cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE);
1664    if (ctx)
1665        task_ctx_sched_in(curr, EVENT_FLEXIBLE);
1666    perf_enable();
1667}
1668
1669static int event_enable_on_exec(struct perf_event *event,
1670                struct perf_event_context *ctx)
1671{
1672    if (!event->attr.enable_on_exec)
1673        return 0;
1674
1675    event->attr.enable_on_exec = 0;
1676    if (event->state >= PERF_EVENT_STATE_INACTIVE)
1677        return 0;
1678
1679    __perf_event_mark_enabled(event, ctx);
1680
1681    return 1;
1682}
1683
1684/*
1685 * Enable all of a task's events that have been marked enable-on-exec.
1686 * This expects task == current.
1687 */
1688static void perf_event_enable_on_exec(struct task_struct *task)
1689{
1690    struct perf_event_context *ctx;
1691    struct perf_event *event;
1692    unsigned long flags;
1693    int enabled = 0;
1694    int ret;
1695
1696    local_irq_save(flags);
1697    ctx = task->perf_event_ctxp;
1698    if (!ctx || !ctx->nr_events)
1699        goto out;
1700
1701    __perf_event_task_sched_out(ctx);
1702
1703    raw_spin_lock(&ctx->lock);
1704
1705    list_for_each_entry(event, &ctx->pinned_groups, group_entry) {
1706        ret = event_enable_on_exec(event, ctx);
1707        if (ret)
1708            enabled = 1;
1709    }
1710
1711    list_for_each_entry(event, &ctx->flexible_groups, group_entry) {
1712        ret = event_enable_on_exec(event, ctx);
1713        if (ret)
1714            enabled = 1;
1715    }
1716
1717    /*
1718     * Unclone this context if we enabled any event.
1719     */
1720    if (enabled)
1721        unclone_ctx(ctx);
1722
1723    raw_spin_unlock(&ctx->lock);
1724
1725    perf_event_task_sched_in(task);
1726 out:
1727    local_irq_restore(flags);
1728}
1729
1730/*
1731 * Cross CPU call to read the hardware event
1732 */
1733static void __perf_event_read(void *info)
1734{
1735    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1736    struct perf_event *event = info;
1737    struct perf_event_context *ctx = event->ctx;
1738
1739    /*
1740     * If this is a task context, we need to check whether it is
1741     * the current task context of this cpu. If not it has been
1742     * scheduled out before the smp call arrived. In that case
1743     * event->count would have been updated to a recent sample
1744     * when the event was scheduled out.
1745     */
1746    if (ctx->task && cpuctx->task_ctx != ctx)
1747        return;
1748
1749    raw_spin_lock(&ctx->lock);
1750    update_context_time(ctx);
1751    update_event_times(event);
1752    raw_spin_unlock(&ctx->lock);
1753
1754    event->pmu->read(event);
1755}
1756
1757static inline u64 perf_event_count(struct perf_event *event)
1758{
1759    return local64_read(&event->count) + atomic64_read(&event->child_count);
1760}
1761
1762static u64 perf_event_read(struct perf_event *event)
1763{
1764    /*
1765     * If event is enabled and currently active on a CPU, update the
1766     * value in the event structure:
1767     */
1768    if (event->state == PERF_EVENT_STATE_ACTIVE) {
1769        smp_call_function_single(event->oncpu,
1770                     __perf_event_read, event, 1);
1771    } else if (event->state == PERF_EVENT_STATE_INACTIVE) {
1772        struct perf_event_context *ctx = event->ctx;
1773        unsigned long flags;
1774
1775        raw_spin_lock_irqsave(&ctx->lock, flags);
1776        update_context_time(ctx);
1777        update_event_times(event);
1778        raw_spin_unlock_irqrestore(&ctx->lock, flags);
1779    }
1780
1781    return perf_event_count(event);
1782}
1783
1784/*
1785 * Initialize the perf_event context in a task_struct:
1786 */
1787static void
1788__perf_event_init_context(struct perf_event_context *ctx,
1789                struct task_struct *task)
1790{
1791    raw_spin_lock_init(&ctx->lock);
1792    mutex_init(&ctx->mutex);
1793    INIT_LIST_HEAD(&ctx->pinned_groups);
1794    INIT_LIST_HEAD(&ctx->flexible_groups);
1795    INIT_LIST_HEAD(&ctx->event_list);
1796    atomic_set(&ctx->refcount, 1);
1797    ctx->task = task;
1798}
1799
1800static struct perf_event_context *find_get_context(pid_t pid, int cpu)
1801{
1802    struct perf_event_context *ctx;
1803    struct perf_cpu_context *cpuctx;
1804    struct task_struct *task;
1805    unsigned long flags;
1806    int err;
1807
1808    if (pid == -1 && cpu != -1) {
1809        /* Must be root to operate on a CPU event: */
1810        if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
1811            return ERR_PTR(-EACCES);
1812
1813        if (cpu < 0 || cpu >= nr_cpumask_bits)
1814            return ERR_PTR(-EINVAL);
1815
1816        /*
1817         * We could be clever and allow to attach a event to an
1818         * offline CPU and activate it when the CPU comes up, but
1819         * that's for later.
1820         */
1821        if (!cpu_online(cpu))
1822            return ERR_PTR(-ENODEV);
1823
1824        cpuctx = &per_cpu(perf_cpu_context, cpu);
1825        ctx = &cpuctx->ctx;
1826        get_ctx(ctx);
1827
1828        return ctx;
1829    }
1830
1831    rcu_read_lock();
1832    if (!pid)
1833        task = current;
1834    else
1835        task = find_task_by_vpid(pid);
1836    if (task)
1837        get_task_struct(task);
1838    rcu_read_unlock();
1839
1840    if (!task)
1841        return ERR_PTR(-ESRCH);
1842
1843    /*
1844     * Can't attach events to a dying task.
1845     */
1846    err = -ESRCH;
1847    if (task->flags & PF_EXITING)
1848        goto errout;
1849
1850    /* Reuse ptrace permission checks for now. */
1851    err = -EACCES;
1852    if (!ptrace_may_access(task, PTRACE_MODE_READ))
1853        goto errout;
1854
1855 retry:
1856    ctx = perf_lock_task_context(task, &flags);
1857    if (ctx) {
1858        unclone_ctx(ctx);
1859        raw_spin_unlock_irqrestore(&ctx->lock, flags);
1860    }
1861
1862    if (!ctx) {
1863        ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL);
1864        err = -ENOMEM;
1865        if (!ctx)
1866            goto errout;
1867        __perf_event_init_context(ctx, task);
1868        get_ctx(ctx);
1869        if (cmpxchg(&task->perf_event_ctxp, NULL, ctx)) {
1870            /*
1871             * We raced with some other task; use
1872             * the context they set.
1873             */
1874            kfree(ctx);
1875            goto retry;
1876        }
1877        get_task_struct(task);
1878    }
1879
1880    put_task_struct(task);
1881    return ctx;
1882
1883 errout:
1884    put_task_struct(task);
1885    return ERR_PTR(err);
1886}
1887
1888static void perf_event_free_filter(struct perf_event *event);
1889
1890static void free_event_rcu(struct rcu_head *head)
1891{
1892    struct perf_event *event;
1893
1894    event = container_of(head, struct perf_event, rcu_head);
1895    if (event->ns)
1896        put_pid_ns(event->ns);
1897    perf_event_free_filter(event);
1898    kfree(event);
1899}
1900
1901static void perf_pending_sync(struct perf_event *event);
1902static void perf_buffer_put(struct perf_buffer *buffer);
1903
1904static void free_event(struct perf_event *event)
1905{
1906    perf_pending_sync(event);
1907
1908    if (!event->parent) {
1909        atomic_dec(&nr_events);
1910        if (event->attr.mmap || event->attr.mmap_data)
1911            atomic_dec(&nr_mmap_events);
1912        if (event->attr.comm)
1913            atomic_dec(&nr_comm_events);
1914        if (event->attr.task)
1915            atomic_dec(&nr_task_events);
1916    }
1917
1918    if (event->buffer) {
1919        perf_buffer_put(event->buffer);
1920        event->buffer = NULL;
1921    }
1922
1923    if (event->destroy)
1924        event->destroy(event);
1925
1926    put_ctx(event->ctx);
1927    call_rcu(&event->rcu_head, free_event_rcu);
1928}
1929
1930int perf_event_release_kernel(struct perf_event *event)
1931{
1932    struct perf_event_context *ctx = event->ctx;
1933
1934    /*
1935     * Remove from the PMU, can't get re-enabled since we got
1936     * here because the last ref went.
1937     */
1938    perf_event_disable(event);
1939
1940    WARN_ON_ONCE(ctx->parent_ctx);
1941    /*
1942     * There are two ways this annotation is useful:
1943     *
1944     * 1) there is a lock recursion from perf_event_exit_task
1945     * see the comment there.
1946     *
1947     * 2) there is a lock-inversion with mmap_sem through
1948     * perf_event_read_group(), which takes faults while
1949     * holding ctx->mutex, however this is called after
1950     * the last filedesc died, so there is no possibility
1951     * to trigger the AB-BA case.
1952     */
1953    mutex_lock_nested(&ctx->mutex, SINGLE_DEPTH_NESTING);
1954    raw_spin_lock_irq(&ctx->lock);
1955    perf_group_detach(event);
1956    list_del_event(event, ctx);
1957    raw_spin_unlock_irq(&ctx->lock);
1958    mutex_unlock(&ctx->mutex);
1959
1960    mutex_lock(&event->owner->perf_event_mutex);
1961    list_del_init(&event->owner_entry);
1962    mutex_unlock(&event->owner->perf_event_mutex);
1963    put_task_struct(event->owner);
1964
1965    free_event(event);
1966
1967    return 0;
1968}
1969EXPORT_SYMBOL_GPL(perf_event_release_kernel);
1970
1971/*
1972 * Called when the last reference to the file is gone.
1973 */
1974static int perf_release(struct inode *inode, struct file *file)
1975{
1976    struct perf_event *event = file->private_data;
1977
1978    file->private_data = NULL;
1979
1980    return perf_event_release_kernel(event);
1981}
1982
1983static int perf_event_read_size(struct perf_event *event)
1984{
1985    int entry = sizeof(u64); /* value */
1986    int size = 0;
1987    int nr = 1;
1988
1989    if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1990        size += sizeof(u64);
1991
1992    if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1993        size += sizeof(u64);
1994
1995    if (event->attr.read_format & PERF_FORMAT_ID)
1996        entry += sizeof(u64);
1997
1998    if (event->attr.read_format & PERF_FORMAT_GROUP) {
1999        nr += event->group_leader->nr_siblings;
2000        size += sizeof(u64);
2001    }
2002
2003    size += entry * nr;
2004
2005    return size;
2006}
2007
2008u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running)
2009{
2010    struct perf_event *child;
2011    u64 total = 0;
2012
2013    *enabled = 0;
2014    *running = 0;
2015
2016    mutex_lock(&event->child_mutex);
2017    total += perf_event_read(event);
2018    *enabled += event->total_time_enabled +
2019            atomic64_read(&event->child_total_time_enabled);
2020    *running += event->total_time_running +
2021            atomic64_read(&event->child_total_time_running);
2022
2023    list_for_each_entry(child, &event->child_list, child_list) {
2024        total += perf_event_read(child);
2025        *enabled += child->total_time_enabled;
2026        *running += child->total_time_running;
2027    }
2028    mutex_unlock(&event->child_mutex);
2029
2030    return total;
2031}
2032EXPORT_SYMBOL_GPL(perf_event_read_value);
2033
2034static int perf_event_read_group(struct perf_event *event,
2035                   u64 read_format, char __user *buf)
2036{
2037    struct perf_event *leader = event->group_leader, *sub;
2038    int n = 0, size = 0, ret = -EFAULT;
2039    struct perf_event_context *ctx = leader->ctx;
2040    u64 values[5];
2041    u64 count, enabled, running;
2042
2043    mutex_lock(&ctx->mutex);
2044    count = perf_event_read_value(leader, &enabled, &running);
2045
2046    values[n++] = 1 + leader->nr_siblings;
2047    if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2048        values[n++] = enabled;
2049    if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2050        values[n++] = running;
2051    values[n++] = count;
2052    if (read_format & PERF_FORMAT_ID)
2053        values[n++] = primary_event_id(leader);
2054
2055    size = n * sizeof(u64);
2056
2057    if (copy_to_user(buf, values, size))
2058        goto unlock;
2059
2060    ret = size;
2061
2062    list_for_each_entry(sub, &leader->sibling_list, group_entry) {
2063        n = 0;
2064
2065        values[n++] = perf_event_read_value(sub, &enabled, &running);
2066        if (read_format & PERF_FORMAT_ID)
2067            values[n++] = primary_event_id(sub);
2068
2069        size = n * sizeof(u64);
2070
2071        if (copy_to_user(buf + ret, values, size)) {
2072            ret = -EFAULT;
2073            goto unlock;
2074        }
2075
2076        ret += size;
2077    }
2078unlock:
2079    mutex_unlock(&ctx->mutex);
2080
2081    return ret;
2082}
2083
2084static int perf_event_read_one(struct perf_event *event,
2085                 u64 read_format, char __user *buf)
2086{
2087    u64 enabled, running;
2088    u64 values[4];
2089    int n = 0;
2090
2091    values[n++] = perf_event_read_value(event, &enabled, &running);
2092    if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2093        values[n++] = enabled;
2094    if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2095        values[n++] = running;
2096    if (read_format & PERF_FORMAT_ID)
2097        values[n++] = primary_event_id(event);
2098
2099    if (copy_to_user(buf, values, n * sizeof(u64)))
2100        return -EFAULT;
2101
2102    return n * sizeof(u64);
2103}
2104
2105/*
2106 * Read the performance event - simple non blocking version for now
2107 */
2108static ssize_t
2109perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
2110{
2111    u64 read_format = event->attr.read_format;
2112    int ret;
2113
2114    /*
2115     * Return end-of-file for a read on a event that is in
2116     * error state (i.e. because it was pinned but it couldn't be
2117     * scheduled on to the CPU at some point).
2118     */
2119    if (event->state == PERF_EVENT_STATE_ERROR)
2120        return 0;
2121
2122    if (count < perf_event_read_size(event))
2123        return -ENOSPC;
2124
2125    WARN_ON_ONCE(event->ctx->parent_ctx);
2126    if (read_format & PERF_FORMAT_GROUP)
2127        ret = perf_event_read_group(event, read_format, buf);
2128    else
2129        ret = perf_event_read_one(event, read_format, buf);
2130
2131    return ret;
2132}
2133
2134static ssize_t
2135perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
2136{
2137    struct perf_event *event = file->private_data;
2138
2139    return perf_read_hw(event, buf, count);
2140}
2141
2142static unsigned int perf_poll(struct file *file, poll_table *wait)
2143{
2144    struct perf_event *event = file->private_data;
2145    struct perf_buffer *buffer;
2146    unsigned int events = POLL_HUP;
2147
2148    rcu_read_lock();
2149    buffer = rcu_dereference(event->buffer);
2150    if (buffer)
2151        events = atomic_xchg(&buffer->poll, 0);
2152    rcu_read_unlock();
2153
2154    poll_wait(file, &event->waitq, wait);
2155
2156    return events;
2157}
2158
2159static void perf_event_reset(struct perf_event *event)
2160{
2161    (void)perf_event_read(event);
2162    local64_set(&event->count, 0);
2163    perf_event_update_userpage(event);
2164}
2165
2166/*
2167 * Holding the top-level event's child_mutex means that any
2168 * descendant process that has inherited this event will block
2169 * in sync_child_event if it goes to exit, thus satisfying the
2170 * task existence requirements of perf_event_enable/disable.
2171 */
2172static void perf_event_for_each_child(struct perf_event *event,
2173                    void (*func)(struct perf_event *))
2174{
2175    struct perf_event *child;
2176
2177    WARN_ON_ONCE(event->ctx->parent_ctx);
2178    mutex_lock(&event->child_mutex);
2179    func(event);
2180    list_for_each_entry(child, &event->child_list, child_list)
2181        func(child);
2182    mutex_unlock(&event->child_mutex);
2183}
2184
2185static void perf_event_for_each(struct perf_event *event,
2186                  void (*func)(struct perf_event *))
2187{
2188    struct perf_event_context *ctx = event->ctx;
2189    struct perf_event *sibling;
2190
2191    WARN_ON_ONCE(ctx->parent_ctx);
2192    mutex_lock(&ctx->mutex);
2193    event = event->group_leader;
2194
2195    perf_event_for_each_child(event, func);
2196    func(event);
2197    list_for_each_entry(sibling, &event->sibling_list, group_entry)
2198        perf_event_for_each_child(event, func);
2199    mutex_unlock(&ctx->mutex);
2200}
2201
2202static int perf_event_period(struct perf_event *event, u64 __user *arg)
2203{
2204    struct perf_event_context *ctx = event->ctx;
2205    int ret = 0;
2206    u64 value;
2207
2208    if (!event->attr.sample_period)
2209        return -EINVAL;
2210
2211    if (copy_from_user(&value, arg, sizeof(value)))
2212        return -EFAULT;
2213
2214    if (!value)
2215        return -EINVAL;
2216
2217    raw_spin_lock_irq(&ctx->lock);
2218    if (event->attr.freq) {
2219        if (value > sysctl_perf_event_sample_rate) {
2220            ret = -EINVAL;
2221            goto unlock;
2222        }
2223
2224        event->attr.sample_freq = value;
2225    } else {
2226        event->attr.sample_period = value;
2227        event->hw.sample_period = value;
2228    }
2229unlock:
2230    raw_spin_unlock_irq(&ctx->lock);
2231
2232    return ret;
2233}
2234
2235static const struct file_operations perf_fops;
2236
2237static struct perf_event *perf_fget_light(int fd, int *fput_needed)
2238{
2239    struct file *file;
2240
2241    file = fget_light(fd, fput_needed);
2242    if (!file)
2243        return ERR_PTR(-EBADF);
2244
2245    if (file->f_op != &perf_fops) {
2246        fput_light(file, *fput_needed);
2247        *fput_needed = 0;
2248        return ERR_PTR(-EBADF);
2249    }
2250
2251    return file->private_data;
2252}
2253
2254static int perf_event_set_output(struct perf_event *event,
2255                 struct perf_event *output_event);
2256static int perf_event_set_filter(struct perf_event *event, void __user *arg);
2257
2258static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
2259{
2260    struct perf_event *event = file->private_data;
2261    void (*func)(struct perf_event *);
2262    u32 flags = arg;
2263
2264    switch (cmd) {
2265    case PERF_EVENT_IOC_ENABLE:
2266        func = perf_event_enable;
2267        break;
2268    case PERF_EVENT_IOC_DISABLE:
2269        func = perf_event_disable;
2270        break;
2271    case PERF_EVENT_IOC_RESET:
2272        func = perf_event_reset;
2273        break;
2274
2275    case PERF_EVENT_IOC_REFRESH:
2276        return perf_event_refresh(event, arg);
2277
2278    case PERF_EVENT_IOC_PERIOD:
2279        return perf_event_period(event, (u64 __user *)arg);
2280
2281    case PERF_EVENT_IOC_SET_OUTPUT:
2282    {
2283        struct perf_event *output_event = NULL;
2284        int fput_needed = 0;
2285        int ret;
2286
2287        if (arg != -1) {
2288            output_event = perf_fget_light(arg, &fput_needed);
2289            if (IS_ERR(output_event))
2290                return PTR_ERR(output_event);
2291        }
2292
2293        ret = perf_event_set_output(event, output_event);
2294        if (output_event)
2295            fput_light(output_event->filp, fput_needed);
2296
2297        return ret;
2298    }
2299
2300    case PERF_EVENT_IOC_SET_FILTER:
2301        return perf_event_set_filter(event, (void __user *)arg);
2302
2303    default:
2304        return -ENOTTY;
2305    }
2306
2307    if (flags & PERF_IOC_FLAG_GROUP)
2308        perf_event_for_each(event, func);
2309    else
2310        perf_event_for_each_child(event, func);
2311
2312    return 0;
2313}
2314
2315int perf_event_task_enable(void)
2316{
2317    struct perf_event *event;
2318
2319    mutex_lock(&current->perf_event_mutex);
2320    list_for_each_entry(event, &current->perf_event_list, owner_entry)
2321        perf_event_for_each_child(event, perf_event_enable);
2322    mutex_unlock(&current->perf_event_mutex);
2323
2324    return 0;
2325}
2326
2327int perf_event_task_disable(void)
2328{
2329    struct perf_event *event;
2330
2331    mutex_lock(&current->perf_event_mutex);
2332    list_for_each_entry(event, &current->perf_event_list, owner_entry)
2333        perf_event_for_each_child(event, perf_event_disable);
2334    mutex_unlock(&current->perf_event_mutex);
2335
2336    return 0;
2337}
2338
2339#ifndef PERF_EVENT_INDEX_OFFSET
2340# define PERF_EVENT_INDEX_OFFSET 0
2341#endif
2342
2343static int perf_event_index(struct perf_event *event)
2344{
2345    if (event->state != PERF_EVENT_STATE_ACTIVE)
2346        return 0;
2347
2348    return event->hw.idx + 1 - PERF_EVENT_INDEX_OFFSET;
2349}
2350
2351/*
2352 * Callers need to ensure there can be no nesting of this function, otherwise
2353 * the seqlock logic goes bad. We can not serialize this because the arch
2354 * code calls this from NMI context.
2355 */
2356void perf_event_update_userpage(struct perf_event *event)
2357{
2358    struct perf_event_mmap_page *userpg;
2359    struct perf_buffer *buffer;
2360
2361    rcu_read_lock();
2362    buffer = rcu_dereference(event->buffer);
2363    if (!buffer)
2364        goto unlock;
2365
2366    userpg = buffer->user_page;
2367
2368    /*
2369     * Disable preemption so as to not let the corresponding user-space
2370     * spin too long if we get preempted.
2371     */
2372    preempt_disable();
2373    ++userpg->lock;
2374    barrier();
2375    userpg->index = perf_event_index(event);
2376    userpg->offset = perf_event_count(event);
2377    if (event->state == PERF_EVENT_STATE_ACTIVE)
2378        userpg->offset -= local64_read(&event->hw.prev_count);
2379
2380    userpg->time_enabled = event->total_time_enabled +
2381            atomic64_read(&event->child_total_time_enabled);
2382
2383    userpg->time_running = event->total_time_running +
2384            atomic64_read(&event->child_total_time_running);
2385
2386    barrier();
2387    ++userpg->lock;
2388    preempt_enable();
2389unlock:
2390    rcu_read_unlock();
2391}
2392
2393static unsigned long perf_data_size(struct perf_buffer *buffer);
2394
2395static void
2396perf_buffer_init(struct perf_buffer *buffer, long watermark, int flags)
2397{
2398    long max_size = perf_data_size(buffer);
2399
2400    if (watermark)
2401        buffer->watermark = min(max_size, watermark);
2402
2403    if (!buffer->watermark)
2404        buffer->watermark = max_size / 2;
2405
2406    if (flags & PERF_BUFFER_WRITABLE)
2407        buffer->writable = 1;
2408
2409    atomic_set(&buffer->refcount, 1);
2410}
2411
2412#ifndef CONFIG_PERF_USE_VMALLOC
2413
2414/*
2415 * Back perf_mmap() with regular GFP_KERNEL-0 pages.
2416 */
2417
2418static struct page *
2419perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
2420{
2421    if (pgoff > buffer->nr_pages)
2422        return NULL;
2423
2424    if (pgoff == 0)
2425        return virt_to_page(buffer->user_page);
2426
2427    return virt_to_page(buffer->data_pages[pgoff - 1]);
2428}
2429
2430static void *perf_mmap_alloc_page(int cpu)
2431{
2432    struct page *page;
2433    int node;
2434
2435    node = (cpu == -1) ? cpu : cpu_to_node(cpu);
2436    page = alloc_pages_node(node, GFP_KERNEL | __GFP_ZERO, 0);
2437    if (!page)
2438        return NULL;
2439
2440    return page_address(page);
2441}
2442
2443static struct perf_buffer *
2444perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
2445{
2446    struct perf_buffer *buffer;
2447    unsigned long size;
2448    int i;
2449
2450    size = sizeof(struct perf_buffer);
2451    size += nr_pages * sizeof(void *);
2452
2453    buffer = kzalloc(size, GFP_KERNEL);
2454    if (!buffer)
2455        goto fail;
2456
2457    buffer->user_page = perf_mmap_alloc_page(cpu);
2458    if (!buffer->user_page)
2459        goto fail_user_page;
2460
2461    for (i = 0; i < nr_pages; i++) {
2462        buffer->data_pages[i] = perf_mmap_alloc_page(cpu);
2463        if (!buffer->data_pages[i])
2464            goto fail_data_pages;
2465    }
2466
2467    buffer->nr_pages = nr_pages;
2468
2469    perf_buffer_init(buffer, watermark, flags);
2470
2471    return buffer;
2472
2473fail_data_pages:
2474    for (i--; i >= 0; i--)
2475        free_page((unsigned long)buffer->data_pages[i]);
2476
2477    free_page((unsigned long)buffer->user_page);
2478
2479fail_user_page:
2480    kfree(buffer);
2481
2482fail:
2483    return NULL;
2484}
2485
2486static void perf_mmap_free_page(unsigned long addr)
2487{
2488    struct page *page = virt_to_page((void *)addr);
2489
2490    page->mapping = NULL;
2491    __free_page(page);
2492}
2493
2494static void perf_buffer_free(struct perf_buffer *buffer)
2495{
2496    int i;
2497
2498    perf_mmap_free_page((unsigned long)buffer->user_page);
2499    for (i = 0; i < buffer->nr_pages; i++)
2500        perf_mmap_free_page((unsigned long)buffer->data_pages[i]);
2501    kfree(buffer);
2502}
2503
2504static inline int page_order(struct perf_buffer *buffer)
2505{
2506    return 0;
2507}
2508
2509#else
2510
2511/*
2512 * Back perf_mmap() with vmalloc memory.
2513 *
2514 * Required for architectures that have d-cache aliasing issues.
2515 */
2516
2517static inline int page_order(struct perf_buffer *buffer)
2518{
2519    return buffer->page_order;
2520}
2521
2522static struct page *
2523perf_mmap_to_page(struct perf_buffer *buffer, unsigned long pgoff)
2524{
2525    if (pgoff > (1UL << page_order(buffer)))
2526        return NULL;
2527
2528    return vmalloc_to_page((void *)buffer->user_page + pgoff * PAGE_SIZE);
2529}
2530
2531static void perf_mmap_unmark_page(void *addr)
2532{
2533    struct page *page = vmalloc_to_page(addr);
2534
2535    page->mapping = NULL;
2536}
2537
2538static void perf_buffer_free_work(struct work_struct *work)
2539{
2540    struct perf_buffer *buffer;
2541    void *base;
2542    int i, nr;
2543
2544    buffer = container_of(work, struct perf_buffer, work);
2545    nr = 1 << page_order(buffer);
2546
2547    base = buffer->user_page;
2548    for (i = 0; i < nr + 1; i++)
2549        perf_mmap_unmark_page(base + (i * PAGE_SIZE));
2550
2551    vfree(base);
2552    kfree(buffer);
2553}
2554
2555static void perf_buffer_free(struct perf_buffer *buffer)
2556{
2557    schedule_work(&buffer->work);
2558}
2559
2560static struct perf_buffer *
2561perf_buffer_alloc(int nr_pages, long watermark, int cpu, int flags)
2562{
2563    struct perf_buffer *buffer;
2564    unsigned long size;
2565    void *all_buf;
2566
2567    size = sizeof(struct perf_buffer);
2568    size += sizeof(void *);
2569
2570    buffer = kzalloc(size, GFP_KERNEL);
2571    if (!buffer)
2572        goto fail;
2573
2574    INIT_WORK(&buffer->work, perf_buffer_free_work);
2575
2576    all_buf = vmalloc_user((nr_pages + 1) * PAGE_SIZE);
2577    if (!all_buf)
2578        goto fail_all_buf;
2579
2580    buffer->user_page = all_buf;
2581    buffer->data_pages[0] = all_buf + PAGE_SIZE;
2582    buffer->page_order = ilog2(nr_pages);
2583    buffer->nr_pages = 1;
2584
2585    perf_buffer_init(buffer, watermark, flags);
2586
2587    return buffer;
2588
2589fail_all_buf:
2590    kfree(buffer);
2591
2592fail:
2593    return NULL;
2594}
2595
2596#endif
2597
2598static unsigned long perf_data_size(struct perf_buffer *buffer)
2599{
2600    return buffer->nr_pages << (PAGE_SHIFT + page_order(buffer));
2601}
2602
2603static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
2604{
2605    struct perf_event *event = vma->vm_file->private_data;
2606    struct perf_buffer *buffer;
2607    int ret = VM_FAULT_SIGBUS;
2608
2609    if (vmf->flags & FAULT_FLAG_MKWRITE) {
2610        if (vmf->pgoff == 0)
2611            ret = 0;
2612        return ret;
2613    }
2614
2615    rcu_read_lock();
2616    buffer = rcu_dereference(event->buffer);
2617    if (!buffer)
2618        goto unlock;
2619
2620    if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE))
2621        goto unlock;
2622
2623    vmf->page = perf_mmap_to_page(buffer, vmf->pgoff);
2624    if (!vmf->page)
2625        goto unlock;
2626
2627    get_page(vmf->page);
2628    vmf->page->mapping = vma->vm_file->f_mapping;
2629    vmf->page->index = vmf->pgoff;
2630
2631    ret = 0;
2632unlock:
2633    rcu_read_unlock();
2634
2635    return ret;
2636}
2637
2638static void perf_buffer_free_rcu(struct rcu_head *rcu_head)
2639{
2640    struct perf_buffer *buffer;
2641
2642    buffer = container_of(rcu_head, struct perf_buffer, rcu_head);
2643    perf_buffer_free(buffer);
2644}
2645
2646static struct perf_buffer *perf_buffer_get(struct perf_event *event)
2647{
2648    struct perf_buffer *buffer;
2649
2650    rcu_read_lock();
2651    buffer = rcu_dereference(event->buffer);
2652    if (buffer) {
2653        if (!atomic_inc_not_zero(&buffer->refcount))
2654            buffer = NULL;
2655    }
2656    rcu_read_unlock();
2657
2658    return buffer;
2659}
2660
2661static void perf_buffer_put(struct perf_buffer *buffer)
2662{
2663    if (!atomic_dec_and_test(&buffer->refcount))
2664        return;
2665
2666    call_rcu(&buffer->rcu_head, perf_buffer_free_rcu);
2667}
2668
2669static void perf_mmap_open(struct vm_area_struct *vma)
2670{
2671    struct perf_event *event = vma->vm_file->private_data;
2672
2673    atomic_inc(&event->mmap_count);
2674}
2675
2676static void perf_mmap_close(struct vm_area_struct *vma)
2677{
2678    struct perf_event *event = vma->vm_file->private_data;
2679
2680    if (atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) {
2681        unsigned long size = perf_data_size(event->buffer);
2682        struct user_struct *user = event->mmap_user;
2683        struct perf_buffer *buffer = event->buffer;
2684
2685        atomic_long_sub((size >> PAGE_SHIFT) + 1, &user->locked_vm);
2686        vma->vm_mm->locked_vm -= event->mmap_locked;
2687        rcu_assign_pointer(event->buffer, NULL);
2688        mutex_unlock(&event->mmap_mutex);
2689
2690        perf_buffer_put(buffer);
2691        free_uid(user);
2692    }
2693}
2694
2695static const struct vm_operations_struct perf_mmap_vmops = {
2696    .open = perf_mmap_open,
2697    .close = perf_mmap_close,
2698    .fault = perf_mmap_fault,
2699    .page_mkwrite = perf_mmap_fault,
2700};
2701
2702static int perf_mmap(struct file *file, struct vm_area_struct *vma)
2703{
2704    struct perf_event *event = file->private_data;
2705    unsigned long user_locked, user_lock_limit;
2706    struct user_struct *user = current_user();
2707    unsigned long locked, lock_limit;
2708    struct perf_buffer *buffer;
2709    unsigned long vma_size;
2710    unsigned long nr_pages;
2711    long user_extra, extra;
2712    int ret = 0, flags = 0;
2713
2714    /*
2715     * Don't allow mmap() of inherited per-task counters. This would
2716     * create a performance issue due to all children writing to the
2717     * same buffer.
2718     */
2719    if (event->cpu == -1 && event->attr.inherit)
2720        return -EINVAL;
2721
2722    if (!(vma->vm_flags & VM_SHARED))
2723        return -EINVAL;
2724
2725    vma_size = vma->vm_end - vma->vm_start;
2726    nr_pages = (vma_size / PAGE_SIZE) - 1;
2727
2728    /*
2729     * If we have buffer pages ensure they're a power-of-two number, so we
2730     * can do bitmasks instead of modulo.
2731     */
2732    if (nr_pages != 0 && !is_power_of_2(nr_pages))
2733        return -EINVAL;
2734
2735    if (vma_size != PAGE_SIZE * (1 + nr_pages))
2736        return -EINVAL;
2737
2738    if (vma->vm_pgoff != 0)
2739        return -EINVAL;
2740
2741    WARN_ON_ONCE(event->ctx->parent_ctx);
2742    mutex_lock(&event->mmap_mutex);
2743    if (event->buffer) {
2744        if (event->buffer->nr_pages == nr_pages)
2745            atomic_inc(&event->buffer->refcount);
2746        else
2747            ret = -EINVAL;
2748        goto unlock;
2749    }
2750
2751    user_extra = nr_pages + 1;
2752    user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
2753
2754    /*
2755     * Increase the limit linearly with more CPUs:
2756     */
2757    user_lock_limit *= num_online_cpus();
2758
2759    user_locked = atomic_long_read(&user->locked_vm) + user_extra;
2760
2761    extra = 0;
2762    if (user_locked > user_lock_limit)
2763        extra = user_locked - user_lock_limit;
2764
2765    lock_limit = rlimit(RLIMIT_MEMLOCK);
2766    lock_limit >>= PAGE_SHIFT;
2767    locked = vma->vm_mm->locked_vm + extra;
2768
2769    if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
2770        !capable(CAP_IPC_LOCK)) {
2771        ret = -EPERM;
2772        goto unlock;
2773    }
2774
2775    WARN_ON(event->buffer);
2776
2777    if (vma->vm_flags & VM_WRITE)
2778        flags |= PERF_BUFFER_WRITABLE;
2779
2780    buffer = perf_buffer_alloc(nr_pages, event->attr.wakeup_watermark,
2781                   event->cpu, flags);
2782    if (!buffer) {
2783        ret = -ENOMEM;
2784        goto unlock;
2785    }
2786    rcu_assign_pointer(event->buffer, buffer);
2787
2788    atomic_long_add(user_extra, &user->locked_vm);
2789    event->mmap_locked = extra;
2790    event->mmap_user = get_current_user();
2791    vma->vm_mm->locked_vm += event->mmap_locked;
2792
2793unlock:
2794    if (!ret)
2795        atomic_inc(&event->mmap_count);
2796    mutex_unlock(&event->mmap_mutex);
2797
2798    vma->vm_flags |= VM_RESERVED;
2799    vma->vm_ops = &perf_mmap_vmops;
2800
2801    return ret;
2802}
2803
2804static int perf_fasync(int fd, struct file *filp, int on)
2805{
2806    struct inode *inode = filp->f_path.dentry->d_inode;
2807    struct perf_event *event = filp->private_data;
2808    int retval;
2809
2810    mutex_lock(&inode->i_mutex);
2811    retval = fasync_helper(fd, filp, on, &event->fasync);
2812    mutex_unlock(&inode->i_mutex);
2813
2814    if (retval < 0)
2815        return retval;
2816
2817    return 0;
2818}
2819
2820static const struct file_operations perf_fops = {
2821    .llseek = no_llseek,
2822    .release = perf_release,
2823    .read = perf_read,
2824    .poll = perf_poll,
2825    .unlocked_ioctl = perf_ioctl,
2826    .compat_ioctl = perf_ioctl,
2827    .mmap = perf_mmap,
2828    .fasync = perf_fasync,
2829};
2830
2831/*
2832 * Perf event wakeup
2833 *
2834 * If there's data, ensure we set the poll() state and publish everything
2835 * to user-space before waking everybody up.
2836 */
2837
2838void perf_event_wakeup(struct perf_event *event)
2839{
2840    wake_up_all(&event->waitq);
2841
2842    if (event->pending_kill) {
2843        kill_fasync(&event->fasync, SIGIO, event->pending_kill);
2844        event->pending_kill = 0;
2845    }
2846}
2847
2848/*
2849 * Pending wakeups
2850 *
2851 * Handle the case where we need to wakeup up from NMI (or rq->lock) context.
2852 *
2853 * The NMI bit means we cannot possibly take locks. Therefore, maintain a
2854 * single linked list and use cmpxchg() to add entries lockless.
2855 */
2856
2857static void perf_pending_event(struct perf_pending_entry *entry)
2858{
2859    struct perf_event *event = container_of(entry,
2860            struct perf_event, pending);
2861
2862    if (event->pending_disable) {
2863        event->pending_disable = 0;
2864        __perf_event_disable(event);
2865    }
2866
2867    if (event->pending_wakeup) {
2868        event->pending_wakeup = 0;
2869        perf_event_wakeup(event);
2870    }
2871}
2872
2873#define PENDING_TAIL ((struct perf_pending_entry *)-1UL)
2874
2875static DEFINE_PER_CPU(struct perf_pending_entry *, perf_pending_head) = {
2876    PENDING_TAIL,
2877};
2878
2879static void perf_pending_queue(struct perf_pending_entry *entry,
2880                   void (*func)(struct perf_pending_entry *))
2881{
2882    struct perf_pending_entry **head;
2883
2884    if (cmpxchg(&entry->next, NULL, PENDING_TAIL) != NULL)
2885        return;
2886
2887    entry->func = func;
2888
2889    head = &get_cpu_var(perf_pending_head);
2890
2891    do {
2892        entry->next = *head;
2893    } while (cmpxchg(head, entry->next, entry) != entry->next);
2894
2895    set_perf_event_pending();
2896
2897    put_cpu_var(perf_pending_head);
2898}
2899
2900static int __perf_pending_run(void)
2901{
2902    struct perf_pending_entry *list;
2903    int nr = 0;
2904
2905    list = xchg(&__get_cpu_var(perf_pending_head), PENDING_TAIL);
2906    while (list != PENDING_TAIL) {
2907        void (*func)(struct perf_pending_entry *);
2908        struct perf_pending_entry *entry = list;
2909
2910        list = list->next;
2911
2912        func = entry->func;
2913        entry->next = NULL;
2914        /*
2915         * Ensure we observe the unqueue before we issue the wakeup,
2916         * so that we won't be waiting forever.
2917         * -- see perf_not_pending().
2918         */
2919        smp_wmb();
2920
2921        func(entry);
2922        nr++;
2923    }
2924
2925    return nr;
2926}
2927
2928static inline int perf_not_pending(struct perf_event *event)
2929{
2930    /*
2931     * If we flush on whatever cpu we run, there is a chance we don't
2932     * need to wait.
2933     */
2934    get_cpu();
2935    __perf_pending_run();
2936    put_cpu();
2937
2938    /*
2939     * Ensure we see the proper queue state before going to sleep
2940     * so that we do not miss the wakeup. -- see perf_pending_handle()
2941     */
2942    smp_rmb();
2943    return event->pending.next == NULL;
2944}
2945
2946static void perf_pending_sync(struct perf_event *event)
2947{
2948    wait_event(event->waitq, perf_not_pending(event));
2949}
2950
2951void perf_event_do_pending(void)
2952{
2953    __perf_pending_run();
2954}
2955
2956/*
2957 * Callchain support -- arch specific
2958 */
2959
2960__weak struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2961{
2962    return NULL;
2963}
2964
2965
2966/*
2967 * We assume there is only KVM supporting the callbacks.
2968 * Later on, we might change it to a list if there is
2969 * another virtualization implementation supporting the callbacks.
2970 */
2971struct perf_guest_info_callbacks *perf_guest_cbs;
2972
2973int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
2974{
2975    perf_guest_cbs = cbs;
2976    return 0;
2977}
2978EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks);
2979
2980int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs)
2981{
2982    perf_guest_cbs = NULL;
2983    return 0;
2984}
2985EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks);
2986
2987/*
2988 * Output
2989 */
2990static bool perf_output_space(struct perf_buffer *buffer, unsigned long tail,
2991                  unsigned long offset, unsigned long head)
2992{
2993    unsigned long mask;
2994
2995    if (!buffer->writable)
2996        return true;
2997
2998    mask = perf_data_size(buffer) - 1;
2999
3000    offset = (offset - tail) & mask;
3001    head = (head - tail) & mask;
3002
3003    if ((int)(head - offset) < 0)
3004        return false;
3005
3006    return true;
3007}
3008
3009static void perf_output_wakeup(struct perf_output_handle *handle)
3010{
3011    atomic_set(&handle->buffer->poll, POLL_IN);
3012
3013    if (handle->nmi) {
3014        handle->event->pending_wakeup = 1;
3015        perf_pending_queue(&handle->event->pending,
3016                   perf_pending_event);
3017    } else
3018        perf_event_wakeup(handle->event);
3019}
3020
3021/*
3022 * We need to ensure a later event_id doesn't publish a head when a former
3023 * event isn't done writing. However since we need to deal with NMIs we
3024 * cannot fully serialize things.
3025 *
3026 * We only publish the head (and generate a wakeup) when the outer-most
3027 * event completes.
3028 */
3029static void perf_output_get_handle(struct perf_output_handle *handle)
3030{
3031    struct perf_buffer *buffer = handle->buffer;
3032
3033    preempt_disable();
3034    local_inc(&buffer->nest);
3035    handle->wakeup = local_read(&buffer->wakeup);
3036}
3037
3038static void perf_output_put_handle(struct perf_output_handle *handle)
3039{
3040    struct perf_buffer *buffer = handle->buffer;
3041    unsigned long head;
3042
3043again:
3044    head = local_read(&buffer->head);
3045
3046    /*
3047     * IRQ/NMI can happen here, which means we can miss a head update.
3048     */
3049
3050    if (!local_dec_and_test(&buffer->nest))
3051        goto out;
3052
3053    /*
3054     * Publish the known good head. Rely on the full barrier implied
3055     * by atomic_dec_and_test() order the buffer->head read and this
3056     * write.
3057     */
3058    buffer->user_page->data_head = head;
3059
3060    /*
3061     * Now check if we missed an update, rely on the (compiler)
3062     * barrier in atomic_dec_and_test() to re-read buffer->head.
3063     */
3064    if (unlikely(head != local_read(&buffer->head))) {
3065        local_inc(&buffer->nest);
3066        goto again;
3067    }
3068
3069    if (handle->wakeup != local_read(&buffer->wakeup))
3070        perf_output_wakeup(handle);
3071
3072 out:
3073    preempt_enable();
3074}
3075
3076__always_inline void perf_output_copy(struct perf_output_handle *handle,
3077              const void *buf, unsigned int len)
3078{
3079    do {
3080        unsigned long size = min_t(unsigned long, handle->size, len);
3081
3082        memcpy(handle->addr, buf, size);
3083
3084        len -= size;
3085        handle->addr += size;
3086        buf += size;
3087        handle->size -= size;
3088        if (!handle->size) {
3089            struct perf_buffer *buffer = handle->buffer;
3090
3091            handle->page++;
3092            handle->page &= buffer->nr_pages - 1;
3093            handle->addr = buffer->data_pages[handle->page];
3094            handle->size = PAGE_SIZE << page_order(buffer);
3095        }
3096    } while (len);
3097}
3098
3099int perf_output_begin(struct perf_output_handle *handle,
3100              struct perf_event *event, unsigned int size,
3101              int nmi, int sample)
3102{
3103    struct perf_buffer *buffer;
3104    unsigned long tail, offset, head;
3105    int have_lost;
3106    struct {
3107        struct perf_event_header header;
3108        u64 id;
3109        u64 lost;
3110    } lost_event;
3111
3112    rcu_read_lock();
3113    /*
3114     * For inherited events we send all the output towards the parent.
3115     */
3116    if (event->parent)
3117        event = event->parent;
3118
3119    buffer = rcu_dereference(event->buffer);
3120    if (!buffer)
3121        goto out;
3122
3123    handle->buffer = buffer;
3124    handle->event = event;
3125    handle->nmi = nmi;
3126    handle->sample = sample;
3127
3128    if (!buffer->nr_pages)
3129        goto out;
3130
3131    have_lost = local_read(&buffer->lost);
3132    if (have_lost)
3133        size += sizeof(lost_event);
3134
3135    perf_output_get_handle(handle);
3136
3137    do {
3138        /*
3139         * Userspace could choose to issue a mb() before updating the
3140         * tail pointer. So that all reads will be completed before the
3141         * write is issued.
3142         */
3143        tail = ACCESS_ONCE(buffer->user_page->data_tail);
3144        smp_rmb();
3145        offset = head = local_read(&buffer->head);
3146        head += size;
3147        if (unlikely(!perf_output_space(buffer, tail, offset, head)))
3148            goto fail;
3149    } while (local_cmpxchg(&buffer->head, offset, head) != offset);
3150
3151    if (head - local_read(&buffer->wakeup) > buffer->watermark)
3152        local_add(buffer->watermark, &buffer->wakeup);
3153
3154    handle->page = offset >> (PAGE_SHIFT + page_order(buffer));
3155    handle->page &= buffer->nr_pages - 1;
3156    handle->size = offset & ((PAGE_SIZE << page_order(buffer)) - 1);
3157    handle->addr = buffer->data_pages[handle->page];
3158    handle->addr += handle->size;
3159    handle->size = (PAGE_SIZE << page_order(buffer)) - handle->size;
3160
3161    if (have_lost) {
3162        lost_event.header.type = PERF_RECORD_LOST;
3163        lost_event.header.misc = 0;
3164        lost_event.header.size = sizeof(lost_event);
3165        lost_event.id = event->id;
3166        lost_event.lost = local_xchg(&buffer->lost, 0);
3167
3168        perf_output_put(handle, lost_event);
3169    }
3170
3171    return 0;
3172
3173fail:
3174    local_inc(&buffer->lost);
3175    perf_output_put_handle(handle);
3176out:
3177    rcu_read_unlock();
3178
3179    return -ENOSPC;
3180}
3181
3182void perf_output_end(struct perf_output_handle *handle)
3183{
3184    struct perf_event *event = handle->event;
3185    struct perf_buffer *buffer = handle->buffer;
3186
3187    int wakeup_events = event->attr.wakeup_events;
3188
3189    if (handle->sample && wakeup_events) {
3190        int events = local_inc_return(&buffer->events);
3191        if (events >= wakeup_events) {
3192            local_sub(wakeup_events, &buffer->events);
3193            local_inc(&buffer->wakeup);
3194        }
3195    }
3196
3197    perf_output_put_handle(handle);
3198    rcu_read_unlock();
3199}
3200
3201static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
3202{
3203    /*
3204     * only top level events have the pid namespace they were created in
3205     */
3206    if (event->parent)
3207        event = event->parent;
3208
3209    return task_tgid_nr_ns(p, event->ns);
3210}
3211
3212static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
3213{
3214    /*
3215     * only top level events have the pid namespace they were created in
3216     */
3217    if (event->parent)
3218        event = event->parent;
3219
3220    return task_pid_nr_ns(p, event->ns);
3221}
3222
3223static void perf_output_read_one(struct perf_output_handle *handle,
3224                 struct perf_event *event)
3225{
3226    u64 read_format = event->attr.read_format;
3227    u64 values[4];
3228    int n = 0;
3229
3230    values[n++] = perf_event_count(event);
3231    if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3232        values[n++] = event->total_time_enabled +
3233            atomic64_read(&event->child_total_time_enabled);
3234    }
3235    if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3236        values[n++] = event->total_time_running +
3237            atomic64_read(&event->child_total_time_running);
3238    }
3239    if (read_format & PERF_FORMAT_ID)
3240        values[n++] = primary_event_id(event);
3241
3242    perf_output_copy(handle, values, n * sizeof(u64));
3243}
3244
3245/*
3246 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
3247 */
3248static void perf_output_read_group(struct perf_output_handle *handle,
3249                struct perf_event *event)
3250{
3251    struct perf_event *leader = event->group_leader, *sub;
3252    u64 read_format = event->attr.read_format;
3253    u64 values[5];
3254    int n = 0;
3255
3256    values[n++] = 1 + leader->nr_siblings;
3257
3258    if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
3259        values[n++] = leader->total_time_enabled;
3260
3261    if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
3262        values[n++] = leader->total_time_running;
3263
3264    if (leader != event)
3265        leader->pmu->read(leader);
3266
3267    values[n++] = perf_event_count(leader);
3268    if (read_format & PERF_FORMAT_ID)
3269        values[n++] = primary_event_id(leader);
3270
3271    perf_output_copy(handle, values, n * sizeof(u64));
3272
3273    list_for_each_entry(sub, &leader->sibling_list, group_entry) {
3274        n = 0;
3275
3276        if (sub != event)
3277            sub->pmu->read(sub);
3278
3279        values[n++] = perf_event_count(sub);
3280        if (read_format & PERF_FORMAT_ID)
3281            values[n++] = primary_event_id(sub);
3282
3283        perf_output_copy(handle, values, n * sizeof(u64));
3284    }
3285}
3286
3287static void perf_output_read(struct perf_output_handle *handle,
3288                 struct perf_event *event)
3289{
3290    if (event->attr.read_format & PERF_FORMAT_GROUP)
3291        perf_output_read_group(handle, event);
3292    else
3293        perf_output_read_one(handle, event);
3294}
3295
3296void perf_output_sample(struct perf_output_handle *handle,
3297            struct perf_event_header *header,
3298            struct perf_sample_data *data,
3299            struct perf_event *event)
3300{
3301    u64 sample_type = data->type;
3302
3303    perf_output_put(handle, *header);
3304
3305    if (sample_type & PERF_SAMPLE_IP)
3306        perf_output_put(handle, data->ip);
3307
3308    if (sample_type & PERF_SAMPLE_TID)
3309        perf_output_put(handle, data->tid_entry);
3310
3311    if (sample_type & PERF_SAMPLE_TIME)
3312        perf_output_put(handle, data->time);
3313
3314    if (sample_type & PERF_SAMPLE_ADDR)
3315        perf_output_put(handle, data->addr);
3316
3317    if (sample_type & PERF_SAMPLE_ID)
3318        perf_output_put(handle, data->id);
3319
3320    if (sample_type & PERF_SAMPLE_STREAM_ID)
3321        perf_output_put(handle, data->stream_id);
3322
3323    if (sample_type & PERF_SAMPLE_CPU)
3324        perf_output_put(handle, data->cpu_entry);
3325
3326    if (sample_type & PERF_SAMPLE_PERIOD)
3327        perf_output_put(handle, data->period);
3328
3329    if (sample_type & PERF_SAMPLE_READ)
3330        perf_output_read(handle, event);
3331
3332    if (sample_type & PERF_SAMPLE_CALLCHAIN) {
3333        if (data->callchain) {
3334            int size = 1;
3335
3336            if (data->callchain)
3337                size += data->callchain->nr;
3338
3339            size *= sizeof(u64);
3340
3341            perf_output_copy(handle, data->callchain, size);
3342        } else {
3343            u64 nr = 0;
3344            perf_output_put(handle, nr);
3345        }
3346    }
3347
3348    if (sample_type & PERF_SAMPLE_RAW) {
3349        if (data->raw) {
3350            perf_output_put(handle, data->raw->size);
3351            perf_output_copy(handle, data->raw->data,
3352                     data->raw->size);
3353        } else {
3354            struct {
3355                u32 size;
3356                u32 data;
3357            } raw = {
3358                .size = sizeof(u32),
3359                .data = 0,
3360            };
3361            perf_output_put(handle, raw);
3362        }
3363    }
3364}
3365
3366void perf_prepare_sample(struct perf_event_header *header,
3367             struct perf_sample_data *data,
3368             struct perf_event *event,
3369             struct pt_regs *regs)
3370{
3371    u64 sample_type = event->attr.sample_type;
3372
3373    data->type = sample_type;
3374
3375    header->type = PERF_RECORD_SAMPLE;
3376    header->size = sizeof(*header);
3377
3378    header->misc = 0;
3379    header->misc |= perf_misc_flags(regs);
3380
3381    if (sample_type & PERF_SAMPLE_IP) {
3382        data->ip = perf_instruction_pointer(regs);
3383
3384        header->size += sizeof(data->ip);
3385    }
3386
3387    if (sample_type & PERF_SAMPLE_TID) {
3388        /* namespace issues */
3389        data->tid_entry.pid = perf_event_pid(event, current);
3390        data->tid_entry.tid = perf_event_tid(event, current);
3391
3392        header->size += sizeof(data->tid_entry);
3393    }
3394
3395    if (sample_type & PERF_SAMPLE_TIME) {
3396        data->time = perf_clock();
3397
3398        header->size += sizeof(data->time);
3399    }
3400
3401    if (sample_type & PERF_SAMPLE_ADDR)
3402        header->size += sizeof(data->addr);
3403
3404    if (sample_type & PERF_SAMPLE_ID) {
3405        data->id = primary_event_id(event);
3406
3407        header->size += sizeof(data->id);
3408    }
3409
3410    if (sample_type & PERF_SAMPLE_STREAM_ID) {
3411        data->stream_id = event->id;
3412
3413        header->size += sizeof(data->stream_id);
3414    }
3415
3416    if (sample_type & PERF_SAMPLE_CPU) {
3417        data->cpu_entry.cpu = raw_smp_processor_id();
3418        data->cpu_entry.reserved = 0;
3419
3420        header->size += sizeof(data->cpu_entry);
3421    }
3422
3423    if (sample_type & PERF_SAMPLE_PERIOD)
3424        header->size += sizeof(data->period);
3425
3426    if (sample_type & PERF_SAMPLE_READ)
3427        header->size += perf_event_read_size(event);
3428
3429    if (sample_type & PERF_SAMPLE_CALLCHAIN) {
3430        int size = 1;
3431
3432        data->callchain = perf_callchain(regs);
3433
3434        if (data->callchain)
3435            size += data->callchain->nr;
3436
3437        header->size += size * sizeof(u64);
3438    }
3439
3440    if (sample_type & PERF_SAMPLE_RAW) {
3441        int size = sizeof(u32);
3442
3443        if (data->raw)
3444            size += data->raw->size;
3445        else
3446            size += sizeof(u32);
3447
3448        WARN_ON_ONCE(size & (sizeof(u64)-1));
3449        header->size += size;
3450    }
3451}
3452
3453static void perf_event_output(struct perf_event *event, int nmi,
3454                struct perf_sample_data *data,
3455                struct pt_regs *regs)
3456{
3457    struct perf_output_handle handle;
3458    struct perf_event_header header;
3459
3460    perf_prepare_sample(&header, data, event, regs);
3461
3462    if (perf_output_begin(&handle, event, header.size, nmi, 1))
3463        return;
3464
3465    perf_output_sample(&handle, &header, data, event);
3466
3467    perf_output_end(&handle);
3468}
3469
3470/*
3471 * read event_id
3472 */
3473
3474struct perf_read_event {
3475    struct perf_event_header header;
3476
3477    u32 pid;
3478    u32 tid;
3479};
3480
3481static void
3482perf_event_read_event(struct perf_event *event,
3483            struct task_struct *task)
3484{
3485    struct perf_output_handle handle;
3486    struct perf_read_event read_event = {
3487        .header = {
3488            .type = PERF_RECORD_READ,
3489            .misc = 0,
3490            .size = sizeof(read_event) + perf_event_read_size(event),
3491        },
3492        .pid = perf_event_pid(event, task),
3493        .tid = perf_event_tid(event, task),
3494    };
3495    int ret;
3496
3497    ret = perf_output_begin(&handle, event, read_event.header.size, 0, 0);
3498    if (ret)
3499        return;
3500
3501    perf_output_put(&handle, read_event);
3502    perf_output_read(&handle, event);
3503
3504    perf_output_end(&handle);
3505}
3506
3507/*
3508 * task tracking -- fork/exit
3509 *
3510 * enabled by: attr.comm | attr.mmap | attr.mmap_data | attr.task
3511 */
3512
3513struct perf_task_event {
3514    struct task_struct *task;
3515    struct perf_event_context *task_ctx;
3516
3517    struct {
3518        struct perf_event_header header;
3519
3520        u32 pid;
3521        u32 ppid;
3522        u32 tid;
3523        u32 ptid;
3524        u64 time;
3525    } event_id;
3526};
3527
3528static void perf_event_task_output(struct perf_event *event,
3529                     struct perf_task_event *task_event)
3530{
3531    struct perf_output_handle handle;
3532    struct task_struct *task = task_event->task;
3533    int size, ret;
3534
3535    size = task_event->event_id.header.size;
3536    ret = perf_output_begin(&handle, event, size, 0, 0);
3537
3538    if (ret)
3539        return;
3540
3541    task_event->event_id.pid = perf_event_pid(event, task);
3542    task_event->event_id.ppid = perf_event_pid(event, current);
3543
3544    task_event->event_id.tid = perf_event_tid(event, task);
3545    task_event->event_id.ptid = perf_event_tid(event, current);
3546
3547    perf_output_put(&handle, task_event->event_id);
3548
3549    perf_output_end(&handle);
3550}
3551
3552static int perf_event_task_match(struct perf_event *event)
3553{
3554    if (event->state < PERF_EVENT_STATE_INACTIVE)
3555        return 0;
3556
3557    if (event->cpu != -1 && event->cpu != smp_processor_id())
3558        return 0;
3559
3560    if (event->attr.comm || event->attr.mmap ||
3561        event->attr.mmap_data || event->attr.task)
3562        return 1;
3563
3564    return 0;
3565}
3566
3567static void perf_event_task_ctx(struct perf_event_context *ctx,
3568                  struct perf_task_event *task_event)
3569{
3570    struct perf_event *event;
3571
3572    list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3573        if (perf_event_task_match(event))
3574            perf_event_task_output(event, task_event);
3575    }
3576}
3577
3578static void perf_event_task_event(struct perf_task_event *task_event)
3579{
3580    struct perf_cpu_context *cpuctx;
3581    struct perf_event_context *ctx = task_event->task_ctx;
3582
3583    rcu_read_lock();
3584    cpuctx = &get_cpu_var(perf_cpu_context);
3585    perf_event_task_ctx(&cpuctx->ctx, task_event);
3586    if (!ctx)
3587        ctx = rcu_dereference(current->perf_event_ctxp);
3588    if (ctx)
3589        perf_event_task_ctx(ctx, task_event);
3590    put_cpu_var(perf_cpu_context);
3591    rcu_read_unlock();
3592}
3593
3594static void perf_event_task(struct task_struct *task,
3595                  struct perf_event_context *task_ctx,
3596                  int new)
3597{
3598    struct perf_task_event task_event;
3599
3600    if (!atomic_read(&nr_comm_events) &&
3601        !atomic_read(&nr_mmap_events) &&
3602        !atomic_read(&nr_task_events))
3603        return;
3604
3605    task_event = (struct perf_task_event){
3606        .task = task,
3607        .task_ctx = task_ctx,
3608        .event_id = {
3609            .header = {
3610                .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
3611                .misc = 0,
3612                .size = sizeof(task_event.event_id),
3613            },
3614            /* .pid */
3615            /* .ppid */
3616            /* .tid */
3617            /* .ptid */
3618            .time = perf_clock(),
3619        },
3620    };
3621
3622    perf_event_task_event(&task_event);
3623}
3624
3625void perf_event_fork(struct task_struct *task)
3626{
3627    perf_event_task(task, NULL, 1);
3628}
3629
3630/*
3631 * comm tracking
3632 */
3633
3634struct perf_comm_event {
3635    struct task_struct *task;
3636    char *comm;
3637    int comm_size;
3638
3639    struct {
3640        struct perf_event_header header;
3641
3642        u32 pid;
3643        u32 tid;
3644    } event_id;
3645};
3646
3647static void perf_event_comm_output(struct perf_event *event,
3648                     struct perf_comm_event *comm_event)
3649{
3650    struct perf_output_handle handle;
3651    int size = comm_event->event_id.header.size;
3652    int ret = perf_output_begin(&handle, event, size, 0, 0);
3653
3654    if (ret)
3655        return;
3656
3657    comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
3658    comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
3659
3660    perf_output_put(&handle, comm_event->event_id);
3661    perf_output_copy(&handle, comm_event->comm,
3662                   comm_event->comm_size);
3663    perf_output_end(&handle);
3664}
3665
3666static int perf_event_comm_match(struct perf_event *event)
3667{
3668    if (event->state < PERF_EVENT_STATE_INACTIVE)
3669        return 0;
3670
3671    if (event->cpu != -1 && event->cpu != smp_processor_id())
3672        return 0;
3673
3674    if (event->attr.comm)
3675        return 1;
3676
3677    return 0;
3678}
3679
3680static void perf_event_comm_ctx(struct perf_event_context *ctx,
3681                  struct perf_comm_event *comm_event)
3682{
3683    struct perf_event *event;
3684
3685    list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3686        if (perf_event_comm_match(event))
3687            perf_event_comm_output(event, comm_event);
3688    }
3689}
3690
3691static void perf_event_comm_event(struct perf_comm_event *comm_event)
3692{
3693    struct perf_cpu_context *cpuctx;
3694    struct perf_event_context *ctx;
3695    unsigned int size;
3696    char comm[TASK_COMM_LEN];
3697
3698    memset(comm, 0, sizeof(comm));
3699    strlcpy(comm, comm_event->task->comm, sizeof(comm));
3700    size = ALIGN(strlen(comm)+1, sizeof(u64));
3701
3702    comm_event->comm = comm;
3703    comm_event->comm_size = size;
3704
3705    comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
3706
3707    rcu_read_lock();
3708    cpuctx = &get_cpu_var(perf_cpu_context);
3709    perf_event_comm_ctx(&cpuctx->ctx, comm_event);
3710    ctx = rcu_dereference(current->perf_event_ctxp);
3711    if (ctx)
3712        perf_event_comm_ctx(ctx, comm_event);
3713    put_cpu_var(perf_cpu_context);
3714    rcu_read_unlock();
3715}
3716
3717void perf_event_comm(struct task_struct *task)
3718{
3719    struct perf_comm_event comm_event;
3720
3721    if (task->perf_event_ctxp)
3722        perf_event_enable_on_exec(task);
3723
3724    if (!atomic_read(&nr_comm_events))
3725        return;
3726
3727    comm_event = (struct perf_comm_event){
3728        .task = task,
3729        /* .comm */
3730        /* .comm_size */
3731        .event_id = {
3732            .header = {
3733                .type = PERF_RECORD_COMM,
3734                .misc = 0,
3735                /* .size */
3736            },
3737            /* .pid */
3738            /* .tid */
3739        },
3740    };
3741
3742    perf_event_comm_event(&comm_event);
3743}
3744
3745/*
3746 * mmap tracking
3747 */
3748
3749struct perf_mmap_event {
3750    struct vm_area_struct *vma;
3751
3752    const char *file_name;
3753    int file_size;
3754
3755    struct {
3756        struct perf_event_header header;
3757
3758        u32 pid;
3759        u32 tid;
3760        u64 start;
3761        u64 len;
3762        u64 pgoff;
3763    } event_id;
3764};
3765
3766static void perf_event_mmap_output(struct perf_event *event,
3767                     struct perf_mmap_event *mmap_event)
3768{
3769    struct perf_output_handle handle;
3770    int size = mmap_event->event_id.header.size;
3771    int ret = perf_output_begin(&handle, event, size, 0, 0);
3772
3773    if (ret)
3774        return;
3775
3776    mmap_event->event_id.pid = perf_event_pid(event, current);
3777    mmap_event->event_id.tid = perf_event_tid(event, current);
3778
3779    perf_output_put(&handle, mmap_event->event_id);
3780    perf_output_copy(&handle, mmap_event->file_name,
3781                   mmap_event->file_size);
3782    perf_output_end(&handle);
3783}
3784
3785static int perf_event_mmap_match(struct perf_event *event,
3786                   struct perf_mmap_event *mmap_event,
3787                   int executable)
3788{
3789    if (event->state < PERF_EVENT_STATE_INACTIVE)
3790        return 0;
3791
3792    if (event->cpu != -1 && event->cpu != smp_processor_id())
3793        return 0;
3794
3795    if ((!executable && event->attr.mmap_data) ||
3796        (executable && event->attr.mmap))
3797        return 1;
3798
3799    return 0;
3800}
3801
3802static void perf_event_mmap_ctx(struct perf_event_context *ctx,
3803                  struct perf_mmap_event *mmap_event,
3804                  int executable)
3805{
3806    struct perf_event *event;
3807
3808    list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
3809        if (perf_event_mmap_match(event, mmap_event, executable))
3810            perf_event_mmap_output(event, mmap_event);
3811    }
3812}
3813
3814static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
3815{
3816    struct perf_cpu_context *cpuctx;
3817    struct perf_event_context *ctx;
3818    struct vm_area_struct *vma = mmap_event->vma;
3819    struct file *file = vma->vm_file;
3820    unsigned int size;
3821    char tmp[16];
3822    char *buf = NULL;
3823    const char *name;
3824
3825    memset(tmp, 0, sizeof(tmp));
3826
3827    if (file) {
3828        /*
3829         * d_path works from the end of the buffer backwards, so we
3830         * need to add enough zero bytes after the string to handle
3831         * the 64bit alignment we do later.
3832         */
3833        buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
3834        if (!buf) {
3835            name = strncpy(tmp, "//enomem", sizeof(tmp));
3836            goto got_name;
3837        }
3838        name = d_path(&file->f_path, buf, PATH_MAX);
3839        if (IS_ERR(name)) {
3840            name = strncpy(tmp, "//toolong", sizeof(tmp));
3841            goto got_name;
3842        }
3843    } else {
3844        if (arch_vma_name(mmap_event->vma)) {
3845            name = strncpy(tmp, arch_vma_name(mmap_event->vma),
3846                       sizeof(tmp));
3847            goto got_name;
3848        }
3849
3850        if (!vma->vm_mm) {
3851            name = strncpy(tmp, "[vdso]", sizeof(tmp));
3852            goto got_name;
3853        } else if (vma->vm_start <= vma->vm_mm->start_brk &&
3854                vma->vm_end >= vma->vm_mm->brk) {
3855            name = strncpy(tmp, "[heap]", sizeof(tmp));
3856            goto got_name;
3857        } else if (vma->vm_start <= vma->vm_mm->start_stack &&
3858                vma->vm_end >= vma->vm_mm->start_stack) {
3859            name = strncpy(tmp, "[stack]", sizeof(tmp));
3860            goto got_name;
3861        }
3862
3863        name = strncpy(tmp, "//anon", sizeof(tmp));
3864        goto got_name;
3865    }
3866
3867got_name:
3868    size = ALIGN(strlen(name)+1, sizeof(u64));
3869
3870    mmap_event->file_name = name;
3871    mmap_event->file_size = size;
3872
3873    mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
3874
3875    rcu_read_lock();
3876    cpuctx = &get_cpu_var(perf_cpu_context);
3877    perf_event_mmap_ctx(&cpuctx->ctx, mmap_event, vma->vm_flags & VM_EXEC);
3878    ctx = rcu_dereference(current->perf_event_ctxp);
3879    if (ctx)
3880        perf_event_mmap_ctx(ctx, mmap_event, vma->vm_flags & VM_EXEC);
3881    put_cpu_var(perf_cpu_context);
3882    rcu_read_unlock();
3883
3884    kfree(buf);
3885}
3886
3887void perf_event_mmap(struct vm_area_struct *vma)
3888{
3889    struct perf_mmap_event mmap_event;
3890
3891    if (!atomic_read(&nr_mmap_events))
3892        return;
3893
3894    mmap_event = (struct perf_mmap_event){
3895        .vma = vma,
3896        /* .file_name */
3897        /* .file_size */
3898        .event_id = {
3899            .header = {
3900                .type = PERF_RECORD_MMAP,
3901                .misc = PERF_RECORD_MISC_USER,
3902                /* .size */
3903            },
3904            /* .pid */
3905            /* .tid */
3906            .start = vma->vm_start,
3907            .len = vma->vm_end - vma->vm_start,
3908            .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT,
3909        },
3910    };
3911
3912    perf_event_mmap_event(&mmap_event);
3913}
3914
3915/*
3916 * IRQ throttle logging
3917 */
3918
3919static void perf_log_throttle(struct perf_event *event, int enable)
3920{
3921    struct perf_output_handle handle;
3922    int ret;
3923
3924    struct {
3925        struct perf_event_header header;
3926        u64 time;
3927        u64 id;
3928        u64 stream_id;
3929    } throttle_event = {
3930        .header = {
3931            .type = PERF_RECORD_THROTTLE,
3932            .misc = 0,
3933            .size = sizeof(throttle_event),
3934        },
3935        .time = perf_clock(),
3936        .id = primary_event_id(event),
3937        .stream_id = event->id,
3938    };
3939
3940    if (enable)
3941        throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
3942
3943    ret = perf_output_begin(&handle, event, sizeof(throttle_event), 1, 0);
3944    if (ret)
3945        return;
3946
3947    perf_output_put(&handle, throttle_event);
3948    perf_output_end(&handle);
3949}
3950
3951/*
3952 * Generic event overflow handling, sampling.
3953 */
3954
3955static int __perf_event_overflow(struct perf_event *event, int nmi,
3956                   int throttle, struct perf_sample_data *data,
3957                   struct pt_regs *regs)
3958{
3959    int events = atomic_read(&event->event_limit);
3960    struct hw_perf_event *hwc = &event->hw;
3961    int ret = 0;
3962
3963    throttle = (throttle && event->pmu->unthrottle != NULL);
3964
3965    if (!throttle) {
3966        hwc->interrupts++;
3967    } else {
3968        if (hwc->interrupts != MAX_INTERRUPTS) {
3969            hwc->interrupts++;
3970            if (HZ * hwc->interrupts >
3971                    (u64)sysctl_perf_event_sample_rate) {
3972                hwc->interrupts = MAX_INTERRUPTS;
3973                perf_log_throttle(event, 0);
3974                ret = 1;
3975            }
3976        } else {
3977            /*
3978             * Keep re-disabling events even though on the previous
3979             * pass we disabled it - just in case we raced with a
3980             * sched-in and the event got enabled again:
3981             */
3982            ret = 1;
3983        }
3984    }
3985
3986    if (event->attr.freq) {
3987        u64 now = perf_clock();
3988        s64 delta = now - hwc->freq_time_stamp;
3989
3990        hwc->freq_time_stamp = now;
3991
3992        if (delta > 0 && delta < 2*TICK_NSEC)
3993            perf_adjust_period(event, delta, hwc->last_period);
3994    }
3995
3996    /*
3997     * XXX event_limit might not quite work as expected on inherited
3998     * events
3999     */
4000
4001    event->pending_kill = POLL_IN;
4002    if (events && atomic_dec_and_test(&event->event_limit)) {
4003        ret = 1;
4004        event->pending_kill = POLL_HUP;
4005        if (nmi) {
4006            event->pending_disable = 1;
4007            perf_pending_queue(&event->pending,
4008                       perf_pending_event);
4009        } else
4010            perf_event_disable(event);
4011    }
4012
4013    if (event->overflow_handler)
4014        event->overflow_handler(event, nmi, data, regs);
4015    else
4016        perf_event_output(event, nmi, data, regs);
4017
4018    return ret;
4019}
4020
4021int perf_event_overflow(struct perf_event *event, int nmi,
4022              struct perf_sample_data *data,
4023              struct pt_regs *regs)
4024{
4025    return __perf_event_overflow(event, nmi, 1, data, regs);
4026}
4027
4028/*
4029 * Generic software event infrastructure
4030 */
4031
4032/*
4033 * We directly increment event->count and keep a second value in
4034 * event->hw.period_left to count intervals. This period event
4035 * is kept in the range [-sample_period, 0] so that we can use the
4036 * sign as trigger.
4037 */
4038
4039static u64 perf_swevent_set_period(struct perf_event *event)
4040{
4041    struct hw_perf_event *hwc = &event->hw;
4042    u64 period = hwc->last_period;
4043    u64 nr, offset;
4044    s64 old, val;
4045
4046    hwc->last_period = hwc->sample_period;
4047
4048again:
4049    old = val = local64_read(&hwc->period_left);
4050    if (val < 0)
4051        return 0;
4052
4053    nr = div64_u64(period + val, period);
4054    offset = nr * period;
4055    val -= offset;
4056    if (local64_cmpxchg(&hwc->period_left, old, val) != old)
4057        goto again;
4058
4059    return nr;
4060}
4061
4062static void perf_swevent_overflow(struct perf_event *event, u64 overflow,
4063                    int nmi, struct perf_sample_data *data,
4064                    struct pt_regs *regs)
4065{
4066    struct hw_perf_event *hwc = &event->hw;
4067    int throttle = 0;
4068
4069    data->period = event->hw.last_period;
4070    if (!overflow)
4071        overflow = perf_swevent_set_period(event);
4072
4073    if (hwc->interrupts == MAX_INTERRUPTS)
4074        return;
4075
4076    for (; overflow; overflow--) {
4077        if (__perf_event_overflow(event, nmi, throttle,
4078                        data, regs)) {
4079            /*
4080             * We inhibit the overflow from happening when
4081             * hwc->interrupts == MAX_INTERRUPTS.
4082             */
4083            break;
4084        }
4085        throttle = 1;
4086    }
4087}
4088
4089static void perf_swevent_add(struct perf_event *event, u64 nr,
4090                   int nmi, struct perf_sample_data *data,
4091                   struct pt_regs *regs)
4092{
4093    struct hw_perf_event *hwc = &event->hw;
4094
4095    local64_add(nr, &event->count);
4096
4097    if (!regs)
4098        return;
4099
4100    if (!hwc->sample_period)
4101        return;
4102
4103    if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq)
4104        return perf_swevent_overflow(event, 1, nmi, data, regs);
4105
4106    if (local64_add_negative(nr, &hwc->period_left))
4107        return;
4108
4109    perf_swevent_overflow(event, 0, nmi, data, regs);
4110}
4111
4112static int perf_exclude_event(struct perf_event *event,
4113                  struct pt_regs *regs)
4114{
4115    if (regs) {
4116        if (event->attr.exclude_user && user_mode(regs))
4117            return 1;
4118
4119        if (event->attr.exclude_kernel && !user_mode(regs))
4120            return 1;
4121    }
4122
4123    return 0;
4124}
4125
4126static int perf_swevent_match(struct perf_event *event,
4127                enum perf_type_id type,
4128                u32 event_id,
4129                struct perf_sample_data *data,
4130                struct pt_regs *regs)
4131{
4132    if (event->attr.type != type)
4133        return 0;
4134
4135    if (event->attr.config != event_id)
4136        return 0;
4137
4138    if (perf_exclude_event(event, regs))
4139        return 0;
4140
4141    return 1;
4142}
4143
4144static inline u64 swevent_hash(u64 type, u32 event_id)
4145{
4146    u64 val = event_id | (type << 32);
4147
4148    return hash_64(val, SWEVENT_HLIST_BITS);
4149}
4150
4151static inline struct hlist_head *
4152__find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id)
4153{
4154    u64 hash = swevent_hash(type, event_id);
4155
4156    return &hlist->heads[hash];
4157}
4158
4159/* For the read side: events when they trigger */
4160static inline struct hlist_head *
4161find_swevent_head_rcu(struct perf_cpu_context *ctx, u64 type, u32 event_id)
4162{
4163    struct swevent_hlist *hlist;
4164
4165    hlist = rcu_dereference(ctx->swevent_hlist);
4166    if (!hlist)
4167        return NULL;
4168
4169    return __find_swevent_head(hlist, type, event_id);
4170}
4171
4172/* For the event head insertion and removal in the hlist */
4173static inline struct hlist_head *
4174find_swevent_head(struct perf_cpu_context *ctx, struct perf_event *event)
4175{
4176    struct swevent_hlist *hlist;
4177    u32 event_id = event->attr.config;
4178    u64 type = event->attr.type;
4179
4180    /*
4181     * Event scheduling is always serialized against hlist allocation
4182     * and release. Which makes the protected version suitable here.
4183     * The context lock guarantees that.
4184     */
4185    hlist = rcu_dereference_protected(ctx->swevent_hlist,
4186                      lockdep_is_held(&event->ctx->lock));
4187    if (!hlist)
4188        return NULL;
4189
4190    return __find_swevent_head(hlist, type, event_id);
4191}
4192
4193static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
4194                    u64 nr, int nmi,
4195                    struct perf_sample_data *data,
4196                    struct pt_regs *regs)
4197{
4198    struct perf_cpu_context *cpuctx;
4199    struct perf_event *event;
4200    struct hlist_node *node;
4201    struct hlist_head *head;
4202
4203    cpuctx = &__get_cpu_var(perf_cpu_context);
4204
4205    rcu_read_lock();
4206
4207    head = find_swevent_head_rcu(cpuctx, type, event_id);
4208
4209    if (!head)
4210        goto end;
4211
4212    hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
4213        if (perf_swevent_match(event, type, event_id, data, regs))
4214            perf_swevent_add(event, nr, nmi, data, regs);
4215    }
4216end:
4217    rcu_read_unlock();
4218}
4219
4220int perf_swevent_get_recursion_context(void)
4221{
4222    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4223    int rctx;
4224
4225    if (in_nmi())
4226        rctx = 3;
4227    else if (in_irq())
4228        rctx = 2;
4229    else if (in_softirq())
4230        rctx = 1;
4231    else
4232        rctx = 0;
4233
4234    if (cpuctx->recursion[rctx])
4235        return -1;
4236
4237    cpuctx->recursion[rctx]++;
4238    barrier();
4239
4240    return rctx;
4241}
4242EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context);
4243
4244void inline perf_swevent_put_recursion_context(int rctx)
4245{
4246    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4247    barrier();
4248    cpuctx->recursion[rctx]--;
4249}
4250
4251void __perf_sw_event(u32 event_id, u64 nr, int nmi,
4252                struct pt_regs *regs, u64 addr)
4253{
4254    struct perf_sample_data data;
4255    int rctx;
4256
4257    preempt_disable_notrace();
4258    rctx = perf_swevent_get_recursion_context();
4259    if (rctx < 0)
4260        return;
4261
4262    perf_sample_data_init(&data, addr);
4263
4264    do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, nmi, &data, regs);
4265
4266    perf_swevent_put_recursion_context(rctx);
4267    preempt_enable_notrace();
4268}
4269
4270static void perf_swevent_read(struct perf_event *event)
4271{
4272}
4273
4274static int perf_swevent_enable(struct perf_event *event)
4275{
4276    struct hw_perf_event *hwc = &event->hw;
4277    struct perf_cpu_context *cpuctx;
4278    struct hlist_head *head;
4279
4280    cpuctx = &__get_cpu_var(perf_cpu_context);
4281
4282    if (hwc->sample_period) {
4283        hwc->last_period = hwc->sample_period;
4284        perf_swevent_set_period(event);
4285    }
4286
4287    head = find_swevent_head(cpuctx, event);
4288    if (WARN_ON_ONCE(!head))
4289        return -EINVAL;
4290
4291    hlist_add_head_rcu(&event->hlist_entry, head);
4292
4293    return 0;
4294}
4295
4296static void perf_swevent_disable(struct perf_event *event)
4297{
4298    hlist_del_rcu(&event->hlist_entry);
4299}
4300
4301static void perf_swevent_void(struct perf_event *event)
4302{
4303}
4304
4305static int perf_swevent_int(struct perf_event *event)
4306{
4307    return 0;
4308}
4309
4310static const struct pmu perf_ops_generic = {
4311    .enable = perf_swevent_enable,
4312    .disable = perf_swevent_disable,
4313    .start = perf_swevent_int,
4314    .stop = perf_swevent_void,
4315    .read = perf_swevent_read,
4316    .unthrottle = perf_swevent_void, /* hwc->interrupts already reset */
4317};
4318
4319/*
4320 * hrtimer based swevent callback
4321 */
4322
4323static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
4324{
4325    enum hrtimer_restart ret = HRTIMER_RESTART;
4326    struct perf_sample_data data;
4327    struct pt_regs *regs;
4328    struct perf_event *event;
4329    u64 period;
4330
4331    event = container_of(hrtimer, struct perf_event, hw.hrtimer);
4332    event->pmu->read(event);
4333
4334    perf_sample_data_init(&data, 0);
4335    data.period = event->hw.last_period;
4336    regs = get_irq_regs();
4337
4338    if (regs && !perf_exclude_event(event, regs)) {
4339        if (!(event->attr.exclude_idle && current->pid == 0))
4340            if (perf_event_overflow(event, 0, &data, regs))
4341                ret = HRTIMER_NORESTART;
4342    }
4343
4344    period = max_t(u64, 10000, event->hw.sample_period);
4345    hrtimer_forward_now(hrtimer, ns_to_ktime(period));
4346
4347    return ret;
4348}
4349
4350static void perf_swevent_start_hrtimer(struct perf_event *event)
4351{
4352    struct hw_perf_event *hwc = &event->hw;
4353
4354    hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
4355    hwc->hrtimer.function = perf_swevent_hrtimer;
4356    if (hwc->sample_period) {
4357        u64 period;
4358
4359        if (hwc->remaining) {
4360            if (hwc->remaining < 0)
4361                period = 10000;
4362            else
4363                period = hwc->remaining;
4364            hwc->remaining = 0;
4365        } else {
4366            period = max_t(u64, 10000, hwc->sample_period);
4367        }
4368        __hrtimer_start_range_ns(&hwc->hrtimer,
4369                ns_to_ktime(period), 0,
4370                HRTIMER_MODE_REL, 0);
4371    }
4372}
4373
4374static void perf_swevent_cancel_hrtimer(struct perf_event *event)
4375{
4376    struct hw_perf_event *hwc = &event->hw;
4377
4378    if (hwc->sample_period) {
4379        ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer);
4380        hwc->remaining = ktime_to_ns(remaining);
4381
4382        hrtimer_cancel(&hwc->hrtimer);
4383    }
4384}
4385
4386/*
4387 * Software event: cpu wall time clock
4388 */
4389
4390static void cpu_clock_perf_event_update(struct perf_event *event)
4391{
4392    int cpu = raw_smp_processor_id();
4393    s64 prev;
4394    u64 now;
4395
4396    now = cpu_clock(cpu);
4397    prev = local64_xchg(&event->hw.prev_count, now);
4398    local64_add(now - prev, &event->count);
4399}
4400
4401static int cpu_clock_perf_event_enable(struct perf_event *event)
4402{
4403    struct hw_perf_event *hwc = &event->hw;
4404    int cpu = raw_smp_processor_id();
4405
4406    local64_set(&hwc->prev_count, cpu_clock(cpu));
4407    perf_swevent_start_hrtimer(event);
4408
4409    return 0;
4410}
4411
4412static void cpu_clock_perf_event_disable(struct perf_event *event)
4413{
4414    perf_swevent_cancel_hrtimer(event);
4415    cpu_clock_perf_event_update(event);
4416}
4417
4418static void cpu_clock_perf_event_read(struct perf_event *event)
4419{
4420    cpu_clock_perf_event_update(event);
4421}
4422
4423static const struct pmu perf_ops_cpu_clock = {
4424    .enable = cpu_clock_perf_event_enable,
4425    .disable = cpu_clock_perf_event_disable,
4426    .read = cpu_clock_perf_event_read,
4427};
4428
4429/*
4430 * Software event: task time clock
4431 */
4432
4433static void task_clock_perf_event_update(struct perf_event *event, u64 now)
4434{
4435    u64 prev;
4436    s64 delta;
4437
4438    prev = local64_xchg(&event->hw.prev_count, now);
4439    delta = now - prev;
4440    local64_add(delta, &event->count);
4441}
4442
4443static int task_clock_perf_event_enable(struct perf_event *event)
4444{
4445    struct hw_perf_event *hwc = &event->hw;
4446    u64 now;
4447
4448    now = event->ctx->time;
4449
4450    local64_set(&hwc->prev_count, now);
4451
4452    perf_swevent_start_hrtimer(event);
4453
4454    return 0;
4455}
4456
4457static void task_clock_perf_event_disable(struct perf_event *event)
4458{
4459    perf_swevent_cancel_hrtimer(event);
4460    task_clock_perf_event_update(event, event->ctx->time);
4461
4462}
4463
4464static void task_clock_perf_event_read(struct perf_event *event)
4465{
4466    u64 time;
4467
4468    if (!in_nmi()) {
4469        update_context_time(event->ctx);
4470        time = event->ctx->time;
4471    } else {
4472        u64 now = perf_clock();
4473        u64 delta = now - event->ctx->timestamp;
4474        time = event->ctx->time + delta;
4475    }
4476
4477    task_clock_perf_event_update(event, time);
4478}
4479
4480static const struct pmu perf_ops_task_clock = {
4481    .enable = task_clock_perf_event_enable,
4482    .disable = task_clock_perf_event_disable,
4483    .read = task_clock_perf_event_read,
4484};
4485
4486/* Deref the hlist from the update side */
4487static inline struct swevent_hlist *
4488swevent_hlist_deref(struct perf_cpu_context *cpuctx)
4489{
4490    return rcu_dereference_protected(cpuctx->swevent_hlist,
4491                     lockdep_is_held(&cpuctx->hlist_mutex));
4492}
4493
4494static void swevent_hlist_release_rcu(struct rcu_head *rcu_head)
4495{
4496    struct swevent_hlist *hlist;
4497
4498    hlist = container_of(rcu_head, struct swevent_hlist, rcu_head);
4499    kfree(hlist);
4500}
4501
4502static void swevent_hlist_release(struct perf_cpu_context *cpuctx)
4503{
4504    struct swevent_hlist *hlist = swevent_hlist_deref(cpuctx);
4505
4506    if (!hlist)
4507        return;
4508
4509    rcu_assign_pointer(cpuctx->swevent_hlist, NULL);
4510    call_rcu(&hlist->rcu_head, swevent_hlist_release_rcu);
4511}
4512
4513static void swevent_hlist_put_cpu(struct perf_event *event, int cpu)
4514{
4515    struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4516
4517    mutex_lock(&cpuctx->hlist_mutex);
4518
4519    if (!--cpuctx->hlist_refcount)
4520        swevent_hlist_release(cpuctx);
4521
4522    mutex_unlock(&cpuctx->hlist_mutex);
4523}
4524
4525static void swevent_hlist_put(struct perf_event *event)
4526{
4527    int cpu;
4528
4529    if (event->cpu != -1) {
4530        swevent_hlist_put_cpu(event, event->cpu);
4531        return;
4532    }
4533
4534    for_each_possible_cpu(cpu)
4535        swevent_hlist_put_cpu(event, cpu);
4536}
4537
4538static int swevent_hlist_get_cpu(struct perf_event *event, int cpu)
4539{
4540    struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4541    int err = 0;
4542
4543    mutex_lock(&cpuctx->hlist_mutex);
4544
4545    if (!swevent_hlist_deref(cpuctx) && cpu_online(cpu)) {
4546        struct swevent_hlist *hlist;
4547
4548        hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
4549        if (!hlist) {
4550            err = -ENOMEM;
4551            goto exit;
4552        }
4553        rcu_assign_pointer(cpuctx->swevent_hlist, hlist);
4554    }
4555    cpuctx->hlist_refcount++;
4556 exit:
4557    mutex_unlock(&cpuctx->hlist_mutex);
4558
4559    return err;
4560}
4561
4562static int swevent_hlist_get(struct perf_event *event)
4563{
4564    int err;
4565    int cpu, failed_cpu;
4566
4567    if (event->cpu != -1)
4568        return swevent_hlist_get_cpu(event, event->cpu);
4569
4570    get_online_cpus();
4571    for_each_possible_cpu(cpu) {
4572        err = swevent_hlist_get_cpu(event, cpu);
4573        if (err) {
4574            failed_cpu = cpu;
4575            goto fail;
4576        }
4577    }
4578    put_online_cpus();
4579
4580    return 0;
4581 fail:
4582    for_each_possible_cpu(cpu) {
4583        if (cpu == failed_cpu)
4584            break;
4585        swevent_hlist_put_cpu(event, cpu);
4586    }
4587
4588    put_online_cpus();
4589    return err;
4590}
4591
4592#ifdef CONFIG_EVENT_TRACING
4593
4594static const struct pmu perf_ops_tracepoint = {
4595    .enable = perf_trace_enable,
4596    .disable = perf_trace_disable,
4597    .start = perf_swevent_int,
4598    .stop = perf_swevent_void,
4599    .read = perf_swevent_read,
4600    .unthrottle = perf_swevent_void,
4601};
4602
4603static int perf_tp_filter_match(struct perf_event *event,
4604                struct perf_sample_data *data)
4605{
4606    void *record = data->raw->data;
4607
4608    if (likely(!event->filter) || filter_match_preds(event->filter, record))
4609        return 1;
4610    return 0;
4611}
4612
4613static int perf_tp_event_match(struct perf_event *event,
4614                struct perf_sample_data *data,
4615                struct pt_regs *regs)
4616{
4617    /*
4618     * All tracepoints are from kernel-space.
4619     */
4620    if (event->attr.exclude_kernel)
4621        return 0;
4622
4623    if (!perf_tp_filter_match(event, data))
4624        return 0;
4625
4626    return 1;
4627}
4628
4629void perf_tp_event(u64 addr, u64 count, void *record, int entry_size,
4630           struct pt_regs *regs, struct hlist_head *head, int rctx)
4631{
4632    struct perf_sample_data data;
4633    struct perf_event *event;
4634    struct hlist_node *node;
4635
4636    struct perf_raw_record raw = {
4637        .size = entry_size,
4638        .data = record,
4639    };
4640
4641    perf_sample_data_init(&data, addr);
4642    data.raw = &raw;
4643
4644    hlist_for_each_entry_rcu(event, node, head, hlist_entry) {
4645        if (perf_tp_event_match(event, &data, regs))
4646            perf_swevent_add(event, count, 1, &data, regs);
4647    }
4648
4649    perf_swevent_put_recursion_context(rctx);
4650}
4651EXPORT_SYMBOL_GPL(perf_tp_event);
4652
4653static void tp_perf_event_destroy(struct perf_event *event)
4654{
4655    perf_trace_destroy(event);
4656}
4657
4658static const struct pmu *tp_perf_event_init(struct perf_event *event)
4659{
4660    int err;
4661
4662    /*
4663     * Raw tracepoint data is a severe data leak, only allow root to
4664     * have these.
4665     */
4666    if ((event->attr.sample_type & PERF_SAMPLE_RAW) &&
4667            perf_paranoid_tracepoint_raw() &&
4668            !capable(CAP_SYS_ADMIN))
4669        return ERR_PTR(-EPERM);
4670
4671    err = perf_trace_init(event);
4672    if (err)
4673        return NULL;
4674
4675    event->destroy = tp_perf_event_destroy;
4676
4677    return &perf_ops_tracepoint;
4678}
4679
4680static int perf_event_set_filter(struct perf_event *event, void __user *arg)
4681{
4682    char *filter_str;
4683    int ret;
4684
4685    if (event->attr.type != PERF_TYPE_TRACEPOINT)
4686        return -EINVAL;
4687
4688    filter_str = strndup_user(arg, PAGE_SIZE);
4689    if (IS_ERR(filter_str))
4690        return PTR_ERR(filter_str);
4691
4692    ret = ftrace_profile_set_filter(event, event->attr.config, filter_str);
4693
4694    kfree(filter_str);
4695    return ret;
4696}
4697
4698static void perf_event_free_filter(struct perf_event *event)
4699{
4700    ftrace_profile_free_filter(event);
4701}
4702
4703#else
4704
4705static const struct pmu *tp_perf_event_init(struct perf_event *event)
4706{
4707    return NULL;
4708}
4709
4710static int perf_event_set_filter(struct perf_event *event, void __user *arg)
4711{
4712    return -ENOENT;
4713}
4714
4715static void perf_event_free_filter(struct perf_event *event)
4716{
4717}
4718
4719#endif /* CONFIG_EVENT_TRACING */
4720
4721#ifdef CONFIG_HAVE_HW_BREAKPOINT
4722static void bp_perf_event_destroy(struct perf_event *event)
4723{
4724    release_bp_slot(event);
4725}
4726
4727static const struct pmu *bp_perf_event_init(struct perf_event *bp)
4728{
4729    int err;
4730
4731    err = register_perf_hw_breakpoint(bp);
4732    if (err)
4733        return ERR_PTR(err);
4734
4735    bp->destroy = bp_perf_event_destroy;
4736
4737    return &perf_ops_bp;
4738}
4739
4740void perf_bp_event(struct perf_event *bp, void *data)
4741{
4742    struct perf_sample_data sample;
4743    struct pt_regs *regs = data;
4744
4745    perf_sample_data_init(&sample, bp->attr.bp_addr);
4746
4747    if (!perf_exclude_event(bp, regs))
4748        perf_swevent_add(bp, 1, 1, &sample, regs);
4749}
4750#else
4751static const struct pmu *bp_perf_event_init(struct perf_event *bp)
4752{
4753    return NULL;
4754}
4755
4756void perf_bp_event(struct perf_event *bp, void *regs)
4757{
4758}
4759#endif
4760
4761atomic_t perf_swevent_enabled[PERF_COUNT_SW_MAX];
4762
4763static void sw_perf_event_destroy(struct perf_event *event)
4764{
4765    u64 event_id = event->attr.config;
4766
4767    WARN_ON(event->parent);
4768
4769    atomic_dec(&perf_swevent_enabled[event_id]);
4770    swevent_hlist_put(event);
4771}
4772
4773static const struct pmu *sw_perf_event_init(struct perf_event *event)
4774{
4775    const struct pmu *pmu = NULL;
4776    u64 event_id = event->attr.config;
4777
4778    /*
4779     * Software events (currently) can't in general distinguish
4780     * between user, kernel and hypervisor events.
4781     * However, context switches and cpu migrations are considered
4782     * to be kernel events, and page faults are never hypervisor
4783     * events.
4784     */
4785    switch (event_id) {
4786    case PERF_COUNT_SW_CPU_CLOCK:
4787        pmu = &perf_ops_cpu_clock;
4788
4789        break;
4790    case PERF_COUNT_SW_TASK_CLOCK:
4791        /*
4792         * If the user instantiates this as a per-cpu event,
4793         * use the cpu_clock event instead.
4794         */
4795        if (event->ctx->task)
4796            pmu = &perf_ops_task_clock;
4797        else
4798            pmu = &perf_ops_cpu_clock;
4799
4800        break;
4801    case PERF_COUNT_SW_PAGE_FAULTS:
4802    case PERF_COUNT_SW_PAGE_FAULTS_MIN:
4803    case PERF_COUNT_SW_PAGE_FAULTS_MAJ:
4804    case PERF_COUNT_SW_CONTEXT_SWITCHES:
4805    case PERF_COUNT_SW_CPU_MIGRATIONS:
4806    case PERF_COUNT_SW_ALIGNMENT_FAULTS:
4807    case PERF_COUNT_SW_EMULATION_FAULTS:
4808        if (!event->parent) {
4809            int err;
4810
4811            err = swevent_hlist_get(event);
4812            if (err)
4813                return ERR_PTR(err);
4814
4815            atomic_inc(&perf_swevent_enabled[event_id]);
4816            event->destroy = sw_perf_event_destroy;
4817        }
4818        pmu = &perf_ops_generic;
4819        break;
4820    }
4821
4822    return pmu;
4823}
4824
4825/*
4826 * Allocate and initialize a event structure
4827 */
4828static struct perf_event *
4829perf_event_alloc(struct perf_event_attr *attr,
4830           int cpu,
4831           struct perf_event_context *ctx,
4832           struct perf_event *group_leader,
4833           struct perf_event *parent_event,
4834           perf_overflow_handler_t overflow_handler,
4835           gfp_t gfpflags)
4836{
4837    const struct pmu *pmu;
4838    struct perf_event *event;
4839    struct hw_perf_event *hwc;
4840    long err;
4841
4842    event = kzalloc(sizeof(*event), gfpflags);
4843    if (!event)
4844        return ERR_PTR(-ENOMEM);
4845
4846    /*
4847     * Single events are their own group leaders, with an
4848     * empty sibling list:
4849     */
4850    if (!group_leader)
4851        group_leader = event;
4852
4853    mutex_init(&event->child_mutex);
4854    INIT_LIST_HEAD(&event->child_list);
4855
4856    INIT_LIST_HEAD(&event->group_entry);
4857    INIT_LIST_HEAD(&event->event_entry);
4858    INIT_LIST_HEAD(&event->sibling_list);
4859    init_waitqueue_head(&event->waitq);
4860
4861    mutex_init(&event->mmap_mutex);
4862
4863    event->cpu = cpu;
4864    event->attr = *attr;
4865    event->group_leader = group_leader;
4866    event->pmu = NULL;
4867    event->ctx = ctx;
4868    event->oncpu = -1;
4869
4870    event->parent = parent_event;
4871
4872    event->ns = get_pid_ns(current->nsproxy->pid_ns);
4873    event->id = atomic64_inc_return(&perf_event_id);
4874
4875    event->state = PERF_EVENT_STATE_INACTIVE;
4876
4877    if (!overflow_handler && parent_event)
4878        overflow_handler = parent_event->overflow_handler;
4879    
4880    event->overflow_handler = overflow_handler;
4881
4882    if (attr->disabled)
4883        event->state = PERF_EVENT_STATE_OFF;
4884
4885    pmu = NULL;
4886
4887    hwc = &event->hw;
4888    hwc->sample_period = attr->sample_period;
4889    if (attr->freq && attr->sample_freq)
4890        hwc->sample_period = 1;
4891    hwc->last_period = hwc->sample_period;
4892
4893    local64_set(&hwc->period_left, hwc->sample_period);
4894
4895    /*
4896     * we currently do not support PERF_FORMAT_GROUP on inherited events
4897     */
4898    if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
4899        goto done;
4900
4901    switch (attr->type) {
4902    case PERF_TYPE_RAW:
4903    case PERF_TYPE_HARDWARE:
4904    case PERF_TYPE_HW_CACHE:
4905        pmu = hw_perf_event_init(event);
4906        break;
4907
4908    case PERF_TYPE_SOFTWARE:
4909        pmu = sw_perf_event_init(event);
4910        break;
4911
4912    case PERF_TYPE_TRACEPOINT:
4913        pmu = tp_perf_event_init(event);
4914        break;
4915
4916    case PERF_TYPE_BREAKPOINT:
4917        pmu = bp_perf_event_init(event);
4918        break;
4919
4920
4921    default:
4922        break;
4923    }
4924done:
4925    err = 0;
4926    if (!pmu)
4927        err = -EINVAL;
4928    else if (IS_ERR(pmu))
4929        err = PTR_ERR(pmu);
4930
4931    if (err) {
4932        if (event->ns)
4933            put_pid_ns(event->ns);
4934        kfree(event);
4935        return ERR_PTR(err);
4936    }
4937
4938    event->pmu = pmu;
4939
4940    if (!event->parent) {
4941        atomic_inc(&nr_events);
4942        if (event->attr.mmap || event->attr.mmap_data)
4943            atomic_inc(&nr_mmap_events);
4944        if (event->attr.comm)
4945            atomic_inc(&nr_comm_events);
4946        if (event->attr.task)
4947            atomic_inc(&nr_task_events);
4948    }
4949
4950    return event;
4951}
4952
4953static int perf_copy_attr(struct perf_event_attr __user *uattr,
4954              struct perf_event_attr *attr)
4955{
4956    u32 size;
4957    int ret;
4958
4959    if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
4960        return -EFAULT;
4961
4962    /*
4963     * zero the full structure, so that a short copy will be nice.
4964     */
4965    memset(attr, 0, sizeof(*attr));
4966
4967    ret = get_user(size, &uattr->size);
4968    if (ret)
4969        return ret;
4970
4971    if (size > PAGE_SIZE) /* silly large */
4972        goto err_size;
4973
4974    if (!size) /* abi compat */
4975        size = PERF_ATTR_SIZE_VER0;
4976
4977    if (size < PERF_ATTR_SIZE_VER0)
4978        goto err_size;
4979
4980    /*
4981     * If we're handed a bigger struct than we know of,
4982     * ensure all the unknown bits are 0 - i.e. new
4983     * user-space does not rely on any kernel feature
4984     * extensions we dont know about yet.
4985     */
4986    if (size > sizeof(*attr)) {
4987        unsigned char __user *addr;
4988        unsigned char __user *end;
4989        unsigned char val;
4990
4991        addr = (void __user *)uattr + sizeof(*attr);
4992        end = (void __user *)uattr + size;
4993
4994        for (; addr < end; addr++) {
4995            ret = get_user(val, addr);
4996            if (ret)
4997                return ret;
4998            if (val)
4999                goto err_size;
5000        }
5001        size = sizeof(*attr);
5002    }
5003
5004    ret = copy_from_user(attr, uattr, size);
5005    if (ret)
5006        return -EFAULT;
5007
5008    /*
5009     * If the type exists, the corresponding creation will verify
5010     * the attr->config.
5011     */
5012    if (attr->type >= PERF_TYPE_MAX)
5013        return -EINVAL;
5014
5015    if (attr->__reserved_1)
5016        return -EINVAL;
5017
5018    if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
5019        return -EINVAL;
5020
5021    if (attr->read_format & ~(PERF_FORMAT_MAX-1))
5022        return -EINVAL;
5023
5024out:
5025    return ret;
5026
5027err_size:
5028    put_user(sizeof(*attr), &uattr->size);
5029    ret = -E2BIG;
5030    goto out;
5031}
5032
5033static int
5034perf_event_set_output(struct perf_event *event, struct perf_event *output_event)
5035{
5036    struct perf_buffer *buffer = NULL, *old_buffer = NULL;
5037    int ret = -EINVAL;
5038
5039    if (!output_event)
5040        goto set;
5041
5042    /* don't allow circular references */
5043    if (event == output_event)
5044        goto out;
5045
5046    /*
5047     * Don't allow cross-cpu buffers
5048     */
5049    if (output_event->cpu != event->cpu)
5050        goto out;
5051
5052    /*
5053     * If its not a per-cpu buffer, it must be the same task.
5054     */
5055    if (output_event->cpu == -1 && output_event->ctx != event->ctx)
5056        goto out;
5057
5058set:
5059    mutex_lock(&event->mmap_mutex);
5060    /* Can't redirect output if we've got an active mmap() */
5061    if (atomic_read(&event->mmap_count))
5062        goto unlock;
5063
5064    if (output_event) {
5065        /* get the buffer we want to redirect to */
5066        buffer = perf_buffer_get(output_event);
5067        if (!buffer)
5068            goto unlock;
5069    }
5070
5071    old_buffer = event->buffer;
5072    rcu_assign_pointer(event->buffer, buffer);
5073    ret = 0;
5074unlock:
5075    mutex_unlock(&event->mmap_mutex);
5076
5077    if (old_buffer)
5078        perf_buffer_put(old_buffer);
5079out:
5080    return ret;
5081}
5082
5083/**
5084 * sys_perf_event_open - open a performance event, associate it to a task/cpu
5085 *
5086 * @attr_uptr: event_id type attributes for monitoring/sampling
5087 * @pid: target pid
5088 * @cpu: target cpu
5089 * @group_fd: group leader event fd
5090 */
5091SYSCALL_DEFINE5(perf_event_open,
5092        struct perf_event_attr __user *, attr_uptr,
5093        pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
5094{
5095    struct perf_event *event, *group_leader = NULL, *output_event = NULL;
5096    struct perf_event_attr attr;
5097    struct perf_event_context *ctx;
5098    struct file *event_file = NULL;
5099    struct file *group_file = NULL;
5100    int event_fd;
5101    int fput_needed = 0;
5102    int err;
5103
5104    /* for future expandability... */
5105    if (flags & ~(PERF_FLAG_FD_NO_GROUP | PERF_FLAG_FD_OUTPUT))
5106        return -EINVAL;
5107
5108    err = perf_copy_attr(attr_uptr, &attr);
5109    if (err)
5110        return err;
5111
5112    if (!attr.exclude_kernel) {
5113        if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
5114            return -EACCES;
5115    }
5116
5117    if (attr.freq) {
5118        if (attr.sample_freq > sysctl_perf_event_sample_rate)
5119            return -EINVAL;
5120    }
5121
5122    event_fd = get_unused_fd_flags(O_RDWR);
5123    if (event_fd < 0)
5124        return event_fd;
5125
5126    /*
5127     * Get the target context (task or percpu):
5128     */
5129    ctx = find_get_context(pid, cpu);
5130    if (IS_ERR(ctx)) {
5131        err = PTR_ERR(ctx);
5132        goto err_fd;
5133    }
5134
5135    if (group_fd != -1) {
5136        group_leader = perf_fget_light(group_fd, &fput_needed);
5137        if (IS_ERR(group_leader)) {
5138            err = PTR_ERR(group_leader);
5139            goto err_put_context;
5140        }
5141        group_file = group_leader->filp;
5142        if (flags & PERF_FLAG_FD_OUTPUT)
5143            output_event = group_leader;
5144        if (flags & PERF_FLAG_FD_NO_GROUP)
5145            group_leader = NULL;
5146    }
5147
5148    /*
5149     * Look up the group leader (we will attach this event to it):
5150     */
5151    if (group_leader) {
5152        err = -EINVAL;
5153
5154        /*
5155         * Do not allow a recursive hierarchy (this new sibling
5156         * becoming part of another group-sibling):
5157         */
5158        if (group_leader->group_leader != group_leader)
5159            goto err_put_context;
5160        /*
5161         * Do not allow to attach to a group in a different
5162         * task or CPU context:
5163         */
5164        if (group_leader->ctx != ctx)
5165            goto err_put_context;
5166        /*
5167         * Only a group leader can be exclusive or pinned
5168         */
5169        if (attr.exclusive || attr.pinned)
5170            goto err_put_context;
5171    }
5172
5173    event = perf_event_alloc(&attr, cpu, ctx, group_leader,
5174                     NULL, NULL, GFP_KERNEL);
5175    if (IS_ERR(event)) {
5176        err = PTR_ERR(event);
5177        goto err_put_context;
5178    }
5179
5180    if (output_event) {
5181        err = perf_event_set_output(event, output_event);
5182        if (err)
5183            goto err_free_put_context;
5184    }
5185
5186    event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, O_RDWR);
5187    if (IS_ERR(event_file)) {
5188        err = PTR_ERR(event_file);
5189        goto err_free_put_context;
5190    }
5191
5192    event->filp = event_file;
5193    WARN_ON_ONCE(ctx->parent_ctx);
5194    mutex_lock(&ctx->mutex);
5195    perf_install_in_context(ctx, event, cpu);
5196    ++ctx->generation;
5197    mutex_unlock(&ctx->mutex);
5198
5199    event->owner = current;
5200    get_task_struct(current);
5201    mutex_lock(&current->perf_event_mutex);
5202    list_add_tail(&event->owner_entry, &current->perf_event_list);
5203    mutex_unlock(&current->perf_event_mutex);
5204
5205    /*
5206     * Drop the reference on the group_event after placing the
5207     * new event on the sibling_list. This ensures destruction
5208     * of the group leader will find the pointer to itself in
5209     * perf_group_detach().
5210     */
5211    fput_light(group_file, fput_needed);
5212    fd_install(event_fd, event_file);
5213    return event_fd;
5214
5215err_free_put_context:
5216    free_event(event);
5217err_put_context:
5218    fput_light(group_file, fput_needed);
5219    put_ctx(ctx);
5220err_fd:
5221    put_unused_fd(event_fd);
5222    return err;
5223}
5224
5225/**
5226 * perf_event_create_kernel_counter
5227 *
5228 * @attr: attributes of the counter to create
5229 * @cpu: cpu in which the counter is bound
5230 * @pid: task to profile
5231 */
5232struct perf_event *
5233perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu,
5234                 pid_t pid,
5235                 perf_overflow_handler_t overflow_handler)
5236{
5237    struct perf_event *event;
5238    struct perf_event_context *ctx;
5239    int err;
5240
5241    /*
5242     * Get the target context (task or percpu):
5243     */
5244
5245    ctx = find_get_context(pid, cpu);
5246    if (IS_ERR(ctx)) {
5247        err = PTR_ERR(ctx);
5248        goto err_exit;
5249    }
5250
5251    event = perf_event_alloc(attr, cpu, ctx, NULL,
5252                 NULL, overflow_handler, GFP_KERNEL);
5253    if (IS_ERR(event)) {
5254        err = PTR_ERR(event);
5255        goto err_put_context;
5256    }
5257
5258    event->filp = NULL;
5259    WARN_ON_ONCE(ctx->parent_ctx);
5260    mutex_lock(&ctx->mutex);
5261    perf_install_in_context(ctx, event, cpu);
5262    ++ctx->generation;
5263    mutex_unlock(&ctx->mutex);
5264
5265    event->owner = current;
5266    get_task_struct(current);
5267    mutex_lock(&current->perf_event_mutex);
5268    list_add_tail(&event->owner_entry, &current->perf_event_list);
5269    mutex_unlock(&current->perf_event_mutex);
5270
5271    return event;
5272
5273 err_put_context:
5274    put_ctx(ctx);
5275 err_exit:
5276    return ERR_PTR(err);
5277}
5278EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter);
5279
5280/*
5281 * inherit a event from parent task to child task:
5282 */
5283static struct perf_event *
5284inherit_event(struct perf_event *parent_event,
5285          struct task_struct *parent,
5286          struct perf_event_context *parent_ctx,
5287          struct task_struct *child,
5288          struct perf_event *group_leader,
5289          struct perf_event_context *child_ctx)
5290{
5291    struct perf_event *child_event;
5292
5293    /*
5294     * Instead of creating recursive hierarchies of events,
5295     * we link inherited events back to the original parent,
5296     * which has a filp for sure, which we use as the reference
5297     * count:
5298     */
5299    if (parent_event->parent)
5300        parent_event = parent_event->parent;
5301
5302    child_event = perf_event_alloc(&parent_event->attr,
5303                       parent_event->cpu, child_ctx,
5304                       group_leader, parent_event,
5305                       NULL, GFP_KERNEL);
5306    if (IS_ERR(child_event))
5307        return child_event;
5308    get_ctx(child_ctx);
5309
5310    /*
5311     * Make the child state follow the state of the parent event,
5312     * not its attr.disabled bit. We hold the parent's mutex,
5313     * so we won't race with perf_event_{en, dis}able_family.
5314     */
5315    if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
5316        child_event->state = PERF_EVENT_STATE_INACTIVE;
5317    else
5318        child_event->state = PERF_EVENT_STATE_OFF;
5319
5320    if (parent_event->attr.freq) {
5321        u64 sample_period = parent_event->hw.sample_period;
5322        struct hw_perf_event *hwc = &child_event->hw;
5323
5324        hwc->sample_period = sample_period;
5325        hwc->last_period = sample_period;
5326
5327        local64_set(&hwc->period_left, sample_period);
5328    }
5329
5330    child_event->overflow_handler = parent_event->overflow_handler;
5331
5332    /*
5333     * Link it up in the child's context:
5334     */
5335    add_event_to_ctx(child_event, child_ctx);
5336
5337    /*
5338     * Get a reference to the parent filp - we will fput it
5339     * when the child event exits. This is safe to do because
5340     * we are in the parent and we know that the filp still
5341     * exists and has a nonzero count:
5342     */
5343    atomic_long_inc(&parent_event->filp->f_count);
5344
5345    /*
5346     * Link this into the parent event's child list
5347     */
5348    WARN_ON_ONCE(parent_event->ctx->parent_ctx);
5349    mutex_lock(&parent_event->child_mutex);
5350    list_add_tail(&child_event->child_list, &parent_event->child_list);
5351    mutex_unlock(&parent_event->child_mutex);
5352
5353    return child_event;
5354}
5355
5356static int inherit_group(struct perf_event *parent_event,
5357          struct task_struct *parent,
5358          struct perf_event_context *parent_ctx,
5359          struct task_struct *child,
5360          struct perf_event_context *child_ctx)
5361{
5362    struct perf_event *leader;
5363    struct perf_event *sub;
5364    struct perf_event *child_ctr;
5365
5366    leader = inherit_event(parent_event, parent, parent_ctx,
5367                 child, NULL, child_ctx);
5368    if (IS_ERR(leader))
5369        return PTR_ERR(leader);
5370    list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
5371        child_ctr = inherit_event(sub, parent, parent_ctx,
5372                        child, leader, child_ctx);
5373        if (IS_ERR(child_ctr))
5374            return PTR_ERR(child_ctr);
5375    }
5376    return 0;
5377}
5378
5379static void sync_child_event(struct perf_event *child_event,
5380                   struct task_struct *child)
5381{
5382    struct perf_event *parent_event = child_event->parent;
5383    u64 child_val;
5384
5385    if (child_event->attr.inherit_stat)
5386        perf_event_read_event(child_event, child);
5387
5388    child_val = perf_event_count(child_event);
5389
5390    /*
5391     * Add back the child's count to the parent's count:
5392     */
5393    atomic64_add(child_val, &parent_event->child_count);
5394    atomic64_add(child_event->total_time_enabled,
5395             &parent_event->child_total_time_enabled);
5396    atomic64_add(child_event->total_time_running,
5397             &parent_event->child_total_time_running);
5398
5399    /*
5400     * Remove this event from the parent's list
5401     */
5402    WARN_ON_ONCE(parent_event->ctx->parent_ctx);
5403    mutex_lock(&parent_event->child_mutex);
5404    list_del_init(&child_event->child_list);
5405    mutex_unlock(&parent_event->child_mutex);
5406
5407    /*
5408     * Release the parent event, if this was the last
5409     * reference to it.
5410     */
5411    fput(parent_event->filp);
5412}
5413
5414static void
5415__perf_event_exit_task(struct perf_event *child_event,
5416             struct perf_event_context *child_ctx,
5417             struct task_struct *child)
5418{
5419    struct perf_event *parent_event;
5420
5421    perf_event_remove_from_context(child_event);
5422
5423    parent_event = child_event->parent;
5424    /*
5425     * It can happen that parent exits first, and has events
5426     * that are still around due to the child reference. These
5427     * events need to be zapped - but otherwise linger.
5428     */
5429    if (parent_event) {
5430        sync_child_event(child_event, child);
5431        free_event(child_event);
5432    }
5433}
5434
5435/*
5436 * When a child task exits, feed back event values to parent events.
5437 */
5438void perf_event_exit_task(struct task_struct *child)
5439{
5440    struct perf_event *child_event, *tmp;
5441    struct perf_event_context *child_ctx;
5442    unsigned long flags;
5443
5444    if (likely(!child->perf_event_ctxp)) {
5445        perf_event_task(child, NULL, 0);
5446        return;
5447    }
5448
5449    local_irq_save(flags);
5450    /*
5451     * We can't reschedule here because interrupts are disabled,
5452     * and either child is current or it is a task that can't be
5453     * scheduled, so we are now safe from rescheduling changing
5454     * our context.
5455     */
5456    child_ctx = child->perf_event_ctxp;
5457    __perf_event_task_sched_out(child_ctx);
5458
5459    /*
5460     * Take the context lock here so that if find_get_context is
5461     * reading child->perf_event_ctxp, we wait until it has
5462     * incremented the context's refcount before we do put_ctx below.
5463     */
5464    raw_spin_lock(&child_ctx->lock);
5465    child->perf_event_ctxp = NULL;
5466    /*
5467     * If this context is a clone; unclone it so it can't get
5468     * swapped to another process while we're removing all
5469     * the events from it.
5470     */
5471    unclone_ctx(child_ctx);
5472    update_context_time(child_ctx);
5473    raw_spin_unlock_irqrestore(&child_ctx->lock, flags);
5474
5475    /*
5476     * Report the task dead after unscheduling the events so that we
5477     * won't get any samples after PERF_RECORD_EXIT. We can however still
5478     * get a few PERF_RECORD_READ events.
5479     */
5480    perf_event_task(child, child_ctx, 0);
5481
5482    /*
5483     * We can recurse on the same lock type through:
5484     *
5485     * __perf_event_exit_task()
5486     * sync_child_event()
5487     * fput(parent_event->filp)
5488     * perf_release()
5489     * mutex_lock(&ctx->mutex)
5490     *
5491     * But since its the parent context it won't be the same instance.
5492     */
5493    mutex_lock(&child_ctx->mutex);
5494
5495again:
5496    list_for_each_entry_safe(child_event, tmp, &child_ctx->pinned_groups,
5497                 group_entry)
5498        __perf_event_exit_task(child_event, child_ctx, child);
5499
5500    list_for_each_entry_safe(child_event, tmp, &child_ctx->flexible_groups,
5501                 group_entry)
5502        __perf_event_exit_task(child_event, child_ctx, child);
5503
5504    /*
5505     * If the last event was a group event, it will have appended all
5506     * its siblings to the list, but we obtained 'tmp' before that which
5507     * will still point to the list head terminating the iteration.
5508     */
5509    if (!list_empty(&child_ctx->pinned_groups) ||
5510        !list_empty(&child_ctx->flexible_groups))
5511        goto again;
5512
5513    mutex_unlock(&child_ctx->mutex);
5514
5515    put_ctx(child_ctx);
5516}
5517
5518static void perf_free_event(struct perf_event *event,
5519                struct perf_event_context *ctx)
5520{
5521    struct perf_event *parent = event->parent;
5522
5523    if (WARN_ON_ONCE(!parent))
5524        return;
5525
5526    mutex_lock(&parent->child_mutex);
5527    list_del_init(&event->child_list);
5528    mutex_unlock(&parent->child_mutex);
5529
5530    fput(parent->filp);
5531
5532    perf_group_detach(event);
5533    list_del_event(event, ctx);
5534    free_event(event);
5535}
5536
5537/*
5538 * free an unexposed, unused context as created by inheritance by
5539 * init_task below, used by fork() in case of fail.
5540 */
5541void perf_event_free_task(struct task_struct *task)
5542{
5543    struct perf_event_context *ctx = task->perf_event_ctxp;
5544    struct perf_event *event, *tmp;
5545
5546    if (!ctx)
5547        return;
5548
5549    mutex_lock(&ctx->mutex);
5550again:
5551    list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
5552        perf_free_event(event, ctx);
5553
5554    list_for_each_entry_safe(event, tmp, &ctx->flexible_groups,
5555                 group_entry)
5556        perf_free_event(event, ctx);
5557
5558    if (!list_empty(&ctx->pinned_groups) ||
5559        !list_empty(&ctx->flexible_groups))
5560        goto again;
5561
5562    mutex_unlock(&ctx->mutex);
5563
5564    put_ctx(ctx);
5565}
5566
5567static int
5568inherit_task_group(struct perf_event *event, struct task_struct *parent,
5569           struct perf_event_context *parent_ctx,
5570           struct task_struct *child,
5571           int *inherited_all)
5572{
5573    int ret;
5574    struct perf_event_context *child_ctx = child->perf_event_ctxp;
5575
5576    if (!event->attr.inherit) {
5577        *inherited_all = 0;
5578        return 0;
5579    }
5580
5581    if (!child_ctx) {
5582        /*
5583         * This is executed from the parent task context, so
5584         * inherit events that have been marked for cloning.
5585         * First allocate and initialize a context for the
5586         * child.
5587         */
5588
5589        child_ctx = kzalloc(sizeof(struct perf_event_context),
5590                    GFP_KERNEL);
5591        if (!child_ctx)
5592            return -ENOMEM;
5593
5594        __perf_event_init_context(child_ctx, child);
5595        child->perf_event_ctxp = child_ctx;
5596        get_task_struct(child);
5597    }
5598
5599    ret = inherit_group(event, parent, parent_ctx,
5600                child, child_ctx);
5601
5602    if (ret)
5603        *inherited_all = 0;
5604
5605    return ret;
5606}
5607
5608
5609/*
5610 * Initialize the perf_event context in task_struct
5611 */
5612int perf_event_init_task(struct task_struct *child)
5613{
5614    struct perf_event_context *child_ctx, *parent_ctx;
5615    struct perf_event_context *cloned_ctx;
5616    struct perf_event *event;
5617    struct task_struct *parent = current;
5618    int inherited_all = 1;
5619    int ret = 0;
5620
5621    child->perf_event_ctxp = NULL;
5622
5623    mutex_init(&child->perf_event_mutex);
5624    INIT_LIST_HEAD(&child->perf_event_list);
5625
5626    if (likely(!parent->perf_event_ctxp))
5627        return 0;
5628
5629    /*
5630     * If the parent's context is a clone, pin it so it won't get
5631     * swapped under us.
5632     */
5633    parent_ctx = perf_pin_task_context(parent);
5634
5635    /*
5636     * No need to check if parent_ctx != NULL here; since we saw
5637     * it non-NULL earlier, the only reason for it to become NULL
5638     * is if we exit, and since we're currently in the middle of
5639     * a fork we can't be exiting at the same time.
5640     */
5641
5642    /*
5643     * Lock the parent list. No need to lock the child - not PID
5644     * hashed yet and not running, so nobody can access it.
5645     */
5646    mutex_lock(&parent_ctx->mutex);
5647
5648    /*
5649     * We dont have to disable NMIs - we are only looking at
5650     * the list, not manipulating it:
5651     */
5652    list_for_each_entry(event, &parent_ctx->pinned_groups, group_entry) {
5653        ret = inherit_task_group(event, parent, parent_ctx, child,
5654                     &inherited_all);
5655        if (ret)
5656            break;
5657    }
5658
5659    list_for_each_entry(event, &parent_ctx->flexible_groups, group_entry) {
5660        ret = inherit_task_group(event, parent, parent_ctx, child,
5661                     &inherited_all);
5662        if (ret)
5663            break;
5664    }
5665
5666    child_ctx = child->perf_event_ctxp;
5667
5668    if (child_ctx && inherited_all) {
5669        /*
5670         * Mark the child context as a clone of the parent
5671         * context, or of whatever the parent is a clone of.
5672         * Note that if the parent is a clone, it could get
5673         * uncloned at any point, but that doesn't matter
5674         * because the list of events and the generation
5675         * count can't have changed since we took the mutex.
5676         */
5677        cloned_ctx = rcu_dereference(parent_ctx->parent_ctx);
5678        if (cloned_ctx) {
5679            child_ctx->parent_ctx = cloned_ctx;
5680            child_ctx->parent_gen = parent_ctx->parent_gen;
5681        } else {
5682            child_ctx->parent_ctx = parent_ctx;
5683            child_ctx->parent_gen = parent_ctx->generation;
5684        }
5685        get_ctx(child_ctx->parent_ctx);
5686    }
5687
5688    mutex_unlock(&parent_ctx->mutex);
5689
5690    perf_unpin_context(parent_ctx);
5691
5692    return ret;
5693}
5694
5695static void __init perf_event_init_all_cpus(void)
5696{
5697    int cpu;
5698    struct perf_cpu_context *cpuctx;
5699
5700    for_each_possible_cpu(cpu) {
5701        cpuctx = &per_cpu(perf_cpu_context, cpu);
5702        mutex_init(&cpuctx->hlist_mutex);
5703        __perf_event_init_context(&cpuctx->ctx, NULL);
5704    }
5705}
5706
5707static void __cpuinit perf_event_init_cpu(int cpu)
5708{
5709    struct perf_cpu_context *cpuctx;
5710
5711    cpuctx = &per_cpu(perf_cpu_context, cpu);
5712
5713    spin_lock(&perf_resource_lock);
5714    cpuctx->max_pertask = perf_max_events - perf_reserved_percpu;
5715    spin_unlock(&perf_resource_lock);
5716
5717    mutex_lock(&cpuctx->hlist_mutex);
5718    if (cpuctx->hlist_refcount > 0) {
5719        struct swevent_hlist *hlist;
5720
5721        hlist = kzalloc(sizeof(*hlist), GFP_KERNEL);
5722        WARN_ON_ONCE(!hlist);
5723        rcu_assign_pointer(cpuctx->swevent_hlist, hlist);
5724    }
5725    mutex_unlock(&cpuctx->hlist_mutex);
5726}
5727
5728#ifdef CONFIG_HOTPLUG_CPU
5729static void __perf_event_exit_cpu(void *info)
5730{
5731    struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
5732    struct perf_event_context *ctx = &cpuctx->ctx;
5733    struct perf_event *event, *tmp;
5734
5735    list_for_each_entry_safe(event, tmp, &ctx->pinned_groups, group_entry)
5736        __perf_event_remove_from_context(event);
5737    list_for_each_entry_safe(event, tmp, &ctx->flexible_groups, group_entry)
5738        __perf_event_remove_from_context(event);
5739}
5740static void perf_event_exit_cpu(int cpu)
5741{
5742    struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
5743    struct perf_event_context *ctx = &cpuctx->ctx;
5744
5745    mutex_lock(&cpuctx->hlist_mutex);
5746    swevent_hlist_release(cpuctx);
5747    mutex_unlock(&cpuctx->hlist_mutex);
5748
5749    mutex_lock(&ctx->mutex);
5750    smp_call_function_single(cpu, __perf_event_exit_cpu, NULL, 1);
5751    mutex_unlock(&ctx->mutex);
5752}
5753#else
5754static inline void perf_event_exit_cpu(int cpu) { }
5755#endif
5756
5757static int __cpuinit
5758perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
5759{
5760    unsigned int cpu = (long)hcpu;
5761
5762    switch (action & ~CPU_TASKS_FROZEN) {
5763
5764    case CPU_UP_PREPARE:
5765    case CPU_DOWN_FAILED:
5766        perf_event_init_cpu(cpu);
5767        break;
5768
5769    case CPU_UP_CANCELED:
5770    case CPU_DOWN_PREPARE:
5771        perf_event_exit_cpu(cpu);
5772        break;
5773
5774    default:
5775        break;
5776    }
5777
5778    return NOTIFY_OK;
5779}
5780
5781/*
5782 * This has to have a higher priority than migration_notifier in sched.c.
5783 */
5784static struct notifier_block __cpuinitdata perf_cpu_nb = {
5785    .notifier_call = perf_cpu_notify,
5786    .priority = 20,
5787};
5788
5789void __init perf_event_init(void)
5790{
5791    perf_event_init_all_cpus();
5792    perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_UP_PREPARE,
5793            (void *)(long)smp_processor_id());
5794    perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_ONLINE,
5795            (void *)(long)smp_processor_id());
5796    register_cpu_notifier(&perf_cpu_nb);
5797}
5798
5799static ssize_t perf_show_reserve_percpu(struct sysdev_class *class,
5800                    struct sysdev_class_attribute *attr,
5801                    char *buf)
5802{
5803    return sprintf(buf, "%d\n", perf_reserved_percpu);
5804}
5805
5806static ssize_t
5807perf_set_reserve_percpu(struct sysdev_class *class,
5808            struct sysdev_class_attribute *attr,
5809            const char *buf,
5810            size_t count)
5811{
5812    struct perf_cpu_context *cpuctx;
5813    unsigned long val;
5814    int err, cpu, mpt;
5815
5816    err = strict_strtoul(buf, 10, &val);
5817    if (err)
5818        return err;
5819    if (val > perf_max_events)
5820        return -EINVAL;
5821
5822    spin_lock(&perf_resource_lock);
5823    perf_reserved_percpu = val;
5824    for_each_online_cpu(cpu) {
5825        cpuctx = &per_cpu(perf_cpu_context, cpu);
5826        raw_spin_lock_irq(&cpuctx->ctx.lock);
5827        mpt = min(perf_max_events - cpuctx->ctx.nr_events,
5828              perf_max_events - perf_reserved_percpu);
5829        cpuctx->max_pertask = mpt;
5830        raw_spin_unlock_irq(&cpuctx->ctx.lock);
5831    }
5832    spin_unlock(&perf_resource_lock);
5833
5834    return count;
5835}
5836
5837static ssize_t perf_show_overcommit(struct sysdev_class *class,
5838                    struct sysdev_class_attribute *attr,
5839                    char *buf)
5840{
5841    return sprintf(buf, "%d\n", perf_overcommit);
5842}
5843
5844static ssize_t
5845perf_set_overcommit(struct sysdev_class *class,
5846            struct sysdev_class_attribute *attr,
5847            const char *buf, size_t count)
5848{
5849    unsigned long val;
5850    int err;
5851
5852    err = strict_strtoul(buf, 10, &val);
5853    if (err)
5854        return err;
5855    if (val > 1)
5856        return -EINVAL;
5857
5858    spin_lock(&perf_resource_lock);
5859    perf_overcommit = val;
5860    spin_unlock(&perf_resource_lock);
5861
5862    return count;
5863}
5864
5865static SYSDEV_CLASS_ATTR(
5866                reserve_percpu,
5867                0644,
5868                perf_show_reserve_percpu,
5869                perf_set_reserve_percpu
5870            );
5871
5872static SYSDEV_CLASS_ATTR(
5873                overcommit,
5874                0644,
5875                perf_show_overcommit,
5876                perf_set_overcommit
5877            );
5878
5879static struct attribute *perfclass_attrs[] = {
5880    &attr_reserve_percpu.attr,
5881    &attr_overcommit.attr,
5882    NULL
5883};
5884
5885static struct attribute_group perfclass_attr_group = {
5886    .attrs = perfclass_attrs,
5887    .name = "perf_events",
5888};
5889
5890static int __init perf_event_sysfs_init(void)
5891{
5892    return sysfs_create_group(&cpu_sysdev_class.kset.kobj,
5893                  &perfclass_attr_group);
5894}
5895device_initcall(perf_event_sysfs_init);
5896

Archive Download this file



interactive