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