perf_event.c 113.4 KB
Newer Older
T
Thomas Gleixner 已提交
1
/*
I
Ingo Molnar 已提交
2
 * Performance events core code:
T
Thomas Gleixner 已提交
3
 *
4 5 6
 *  Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de>
 *  Copyright (C) 2008-2009 Red Hat, Inc., Ingo Molnar
 *  Copyright (C) 2008-2009 Red Hat, Inc., Peter Zijlstra <pzijlstr@redhat.com>
7
 *  Copyright    2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com>
8
 *
I
Ingo Molnar 已提交
9
 * For licensing details see kernel-base/COPYING
T
Thomas Gleixner 已提交
10 11 12
 */

#include <linux/fs.h>
13
#include <linux/mm.h>
T
Thomas Gleixner 已提交
14 15
#include <linux/cpu.h>
#include <linux/smp.h>
16
#include <linux/file.h>
T
Thomas Gleixner 已提交
17 18
#include <linux/poll.h>
#include <linux/sysfs.h>
19
#include <linux/dcache.h>
T
Thomas Gleixner 已提交
20
#include <linux/percpu.h>
21
#include <linux/ptrace.h>
22 23 24
#include <linux/vmstat.h>
#include <linux/hardirq.h>
#include <linux/rculist.h>
T
Thomas Gleixner 已提交
25 26 27
#include <linux/uaccess.h>
#include <linux/syscalls.h>
#include <linux/anon_inodes.h>
I
Ingo Molnar 已提交
28
#include <linux/kernel_stat.h>
29
#include <linux/perf_event.h>
T
Thomas Gleixner 已提交
30

31 32
#include <asm/irq_regs.h>

T
Thomas Gleixner 已提交
33
/*
34
 * Each CPU has a list of per CPU events:
T
Thomas Gleixner 已提交
35 36 37
 */
DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context);

38
int perf_max_events __read_mostly = 1;
T
Thomas Gleixner 已提交
39 40 41
static int perf_reserved_percpu __read_mostly;
static int perf_overcommit __read_mostly = 1;

42 43 44 45
static atomic_t nr_events __read_mostly;
static atomic_t nr_mmap_events __read_mostly;
static atomic_t nr_comm_events __read_mostly;
static atomic_t nr_task_events __read_mostly;
46

47
/*
48
 * perf event paranoia level:
49 50
 *  -1 - not paranoid at all
 *   0 - disallow raw tracepoint access for unpriv
51
 *   1 - disallow cpu events for unpriv
52
 *   2 - disallow kernel profiling for unpriv
53
 */
54
int sysctl_perf_event_paranoid __read_mostly = 1;
55

56 57
static inline bool perf_paranoid_tracepoint_raw(void)
{
58
	return sysctl_perf_event_paranoid > -1;
59 60
}

61 62
static inline bool perf_paranoid_cpu(void)
{
63
	return sysctl_perf_event_paranoid > 0;
64 65 66 67
}

static inline bool perf_paranoid_kernel(void)
{
68
	return sysctl_perf_event_paranoid > 1;
69 70
}

71
int sysctl_perf_event_mlock __read_mostly = 512; /* 'free' kb per user */
72 73

/*
74
 * max perf event sample rate
75
 */
76
int sysctl_perf_event_sample_rate __read_mostly = 100000;
77

78
static atomic64_t perf_event_id;
79

T
Thomas Gleixner 已提交
80
/*
81
 * Lock for (sysadmin-configurable) event reservations:
T
Thomas Gleixner 已提交
82
 */
83
static DEFINE_SPINLOCK(perf_resource_lock);
T
Thomas Gleixner 已提交
84 85 86 87

/*
 * Architecture provided APIs - weak aliases:
 */
88
extern __weak const struct pmu *hw_perf_event_init(struct perf_event *event)
T
Thomas Gleixner 已提交
89
{
90
	return NULL;
T
Thomas Gleixner 已提交
91 92
}

93 94 95
void __weak hw_perf_disable(void)		{ barrier(); }
void __weak hw_perf_enable(void)		{ barrier(); }

96 97
void __weak hw_perf_event_setup(int cpu)	{ barrier(); }
void __weak hw_perf_event_setup_online(int cpu)	{ barrier(); }
98 99

int __weak
100
hw_perf_group_sched_in(struct perf_event *group_leader,
101
	       struct perf_cpu_context *cpuctx,
102
	       struct perf_event_context *ctx, int cpu)
103 104 105
{
	return 0;
}
T
Thomas Gleixner 已提交
106

107
void __weak perf_event_print_debug(void)	{ }
108

109
static DEFINE_PER_CPU(int, perf_disable_count);
110 111 112

void __perf_disable(void)
{
113
	__get_cpu_var(perf_disable_count)++;
114 115 116 117
}

bool __perf_enable(void)
{
118
	return !--__get_cpu_var(perf_disable_count);
119 120 121 122 123 124 125 126 127 128 129 130 131 132
}

void perf_disable(void)
{
	__perf_disable();
	hw_perf_disable();
}

void perf_enable(void)
{
	if (__perf_enable())
		hw_perf_enable();
}

133
static void get_ctx(struct perf_event_context *ctx)
134
{
135
	WARN_ON(!atomic_inc_not_zero(&ctx->refcount));
136 137
}

138 139
static void free_ctx(struct rcu_head *head)
{
140
	struct perf_event_context *ctx;
141

142
	ctx = container_of(head, struct perf_event_context, rcu_head);
143 144 145
	kfree(ctx);
}

146
static void put_ctx(struct perf_event_context *ctx)
147
{
148 149 150
	if (atomic_dec_and_test(&ctx->refcount)) {
		if (ctx->parent_ctx)
			put_ctx(ctx->parent_ctx);
151 152 153
		if (ctx->task)
			put_task_struct(ctx->task);
		call_rcu(&ctx->rcu_head, free_ctx);
154
	}
155 156
}

157
static void unclone_ctx(struct perf_event_context *ctx)
158 159 160 161 162 163 164
{
	if (ctx->parent_ctx) {
		put_ctx(ctx->parent_ctx);
		ctx->parent_ctx = NULL;
	}
}

165
/*
166
 * If we inherit events we want to return the parent event id
167 168
 * to userspace.
 */
169
static u64 primary_event_id(struct perf_event *event)
170
{
171
	u64 id = event->id;
172

173 174
	if (event->parent)
		id = event->parent->id;
175 176 177 178

	return id;
}

179
/*
180
 * Get the perf_event_context for a task and lock it.
181 182 183
 * This has to cope with with the fact that until it is locked,
 * the context could get moved to another task.
 */
184
static struct perf_event_context *
185
perf_lock_task_context(struct task_struct *task, unsigned long *flags)
186
{
187
	struct perf_event_context *ctx;
188 189 190

	rcu_read_lock();
 retry:
191
	ctx = rcu_dereference(task->perf_event_ctxp);
192 193 194 195
	if (ctx) {
		/*
		 * If this context is a clone of another, it might
		 * get swapped for another underneath us by
196
		 * perf_event_task_sched_out, though the
197 198 199 200 201 202 203
		 * rcu_read_lock() protects us from any context
		 * getting freed.  Lock the context and check if it
		 * got swapped before we could get the lock, and retry
		 * if so.  If we locked the right context, then it
		 * can't get swapped on us any more.
		 */
		spin_lock_irqsave(&ctx->lock, *flags);
204
		if (ctx != rcu_dereference(task->perf_event_ctxp)) {
205 206 207
			spin_unlock_irqrestore(&ctx->lock, *flags);
			goto retry;
		}
208 209 210 211 212

		if (!atomic_inc_not_zero(&ctx->refcount)) {
			spin_unlock_irqrestore(&ctx->lock, *flags);
			ctx = NULL;
		}
213 214 215 216 217 218 219 220 221 222
	}
	rcu_read_unlock();
	return ctx;
}

/*
 * Get the context for a task and increment its pin_count so it
 * can't get swapped to another task.  This also increments its
 * reference count so that the context can't get freed.
 */
223
static struct perf_event_context *perf_pin_task_context(struct task_struct *task)
224
{
225
	struct perf_event_context *ctx;
226 227 228 229 230 231 232 233 234 235
	unsigned long flags;

	ctx = perf_lock_task_context(task, &flags);
	if (ctx) {
		++ctx->pin_count;
		spin_unlock_irqrestore(&ctx->lock, flags);
	}
	return ctx;
}

236
static void perf_unpin_context(struct perf_event_context *ctx)
237 238 239 240 241 242 243 244 245
{
	unsigned long flags;

	spin_lock_irqsave(&ctx->lock, flags);
	--ctx->pin_count;
	spin_unlock_irqrestore(&ctx->lock, flags);
	put_ctx(ctx);
}

246
/*
247
 * Add a event from the lists for its context.
248 249
 * Must be called with ctx->mutex and ctx->lock held.
 */
250
static void
251
list_add_event(struct perf_event *event, struct perf_event_context *ctx)
252
{
253
	struct perf_event *group_leader = event->group_leader;
254 255

	/*
256 257
	 * Depending on whether it is a standalone or sibling event,
	 * add it straight to the context's event list, or to the group
258 259
	 * leader's sibling list:
	 */
260 261
	if (group_leader == event)
		list_add_tail(&event->group_entry, &ctx->group_list);
P
Peter Zijlstra 已提交
262
	else {
263
		list_add_tail(&event->group_entry, &group_leader->sibling_list);
P
Peter Zijlstra 已提交
264 265
		group_leader->nr_siblings++;
	}
P
Peter Zijlstra 已提交
266

267 268 269
	list_add_rcu(&event->event_entry, &ctx->event_list);
	ctx->nr_events++;
	if (event->attr.inherit_stat)
270
		ctx->nr_stat++;
271 272
}

273
/*
274
 * Remove a event from the lists for its context.
275
 * Must be called with ctx->mutex and ctx->lock held.
276
 */
277
static void
278
list_del_event(struct perf_event *event, struct perf_event_context *ctx)
279
{
280
	struct perf_event *sibling, *tmp;
281

282
	if (list_empty(&event->group_entry))
283
		return;
284 285
	ctx->nr_events--;
	if (event->attr.inherit_stat)
286
		ctx->nr_stat--;
287

288 289
	list_del_init(&event->group_entry);
	list_del_rcu(&event->event_entry);
290

291 292
	if (event->group_leader != event)
		event->group_leader->nr_siblings--;
P
Peter Zijlstra 已提交
293

294
	/*
295 296
	 * If this was a group event with sibling events then
	 * upgrade the siblings to singleton events by adding them
297 298
	 * to the context list directly:
	 */
299
	list_for_each_entry_safe(sibling, tmp, &event->sibling_list, group_entry) {
300

301
		list_move_tail(&sibling->group_entry, &ctx->group_list);
302 303 304 305
		sibling->group_leader = sibling;
	}
}

306
static void
307
event_sched_out(struct perf_event *event,
308
		  struct perf_cpu_context *cpuctx,
309
		  struct perf_event_context *ctx)
310
{
311
	if (event->state != PERF_EVENT_STATE_ACTIVE)
312 313
		return;

314 315 316 317
	event->state = PERF_EVENT_STATE_INACTIVE;
	if (event->pending_disable) {
		event->pending_disable = 0;
		event->state = PERF_EVENT_STATE_OFF;
318
	}
319 320 321
	event->tstamp_stopped = ctx->time;
	event->pmu->disable(event);
	event->oncpu = -1;
322

323
	if (!is_software_event(event))
324 325
		cpuctx->active_oncpu--;
	ctx->nr_active--;
326
	if (event->attr.exclusive || !cpuctx->active_oncpu)
327 328 329
		cpuctx->exclusive = 0;
}

330
static void
331
group_sched_out(struct perf_event *group_event,
332
		struct perf_cpu_context *cpuctx,
333
		struct perf_event_context *ctx)
334
{
335
	struct perf_event *event;
336

337
	if (group_event->state != PERF_EVENT_STATE_ACTIVE)
338 339
		return;

340
	event_sched_out(group_event, cpuctx, ctx);
341 342 343 344

	/*
	 * Schedule out siblings (if any):
	 */
345 346
	list_for_each_entry(event, &group_event->sibling_list, group_entry)
		event_sched_out(event, cpuctx, ctx);
347

348
	if (group_event->attr.exclusive)
349 350 351
		cpuctx->exclusive = 0;
}

T
Thomas Gleixner 已提交
352
/*
353
 * Cross CPU call to remove a performance event
T
Thomas Gleixner 已提交
354
 *
355
 * We disable the event on the hardware level first. After that we
T
Thomas Gleixner 已提交
356 357
 * remove it from the context list.
 */
358
static void __perf_event_remove_from_context(void *info)
T
Thomas Gleixner 已提交
359 360
{
	struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
361 362
	struct perf_event *event = info;
	struct perf_event_context *ctx = event->ctx;
T
Thomas Gleixner 已提交
363 364 365 366 367 368

	/*
	 * If this is a task context, we need to check whether it is
	 * the current task context of this cpu. If not it has been
	 * scheduled out before the smp call arrived.
	 */
369
	if (ctx->task && cpuctx->task_ctx != ctx)
T
Thomas Gleixner 已提交
370 371
		return;

372
	spin_lock(&ctx->lock);
373 374
	/*
	 * Protect the list operation against NMI by disabling the
375
	 * events on a global level.
376 377
	 */
	perf_disable();
T
Thomas Gleixner 已提交
378

379
	event_sched_out(event, cpuctx, ctx);
380

381
	list_del_event(event, ctx);
T
Thomas Gleixner 已提交
382 383 384

	if (!ctx->task) {
		/*
385
		 * Allow more per task events with respect to the
T
Thomas Gleixner 已提交
386 387 388
		 * reservation:
		 */
		cpuctx->max_pertask =
389 390
			min(perf_max_events - ctx->nr_events,
			    perf_max_events - perf_reserved_percpu);
T
Thomas Gleixner 已提交
391 392
	}

393
	perf_enable();
394
	spin_unlock(&ctx->lock);
T
Thomas Gleixner 已提交
395 396 397 398
}


/*
399
 * Remove the event from a task's (or a CPU's) list of events.
T
Thomas Gleixner 已提交
400
 *
401
 * Must be called with ctx->mutex held.
T
Thomas Gleixner 已提交
402
 *
403
 * CPU events are removed with a smp call. For task events we only
T
Thomas Gleixner 已提交
404
 * call when the task is on a CPU.
405
 *
406 407
 * If event->ctx is a cloned context, callers must make sure that
 * every task struct that event->ctx->task could possibly point to
408 409
 * remains valid.  This is OK when called from perf_release since
 * that only calls us on the top-level context, which can't be a clone.
410
 * When called from perf_event_exit_task, it's OK because the
411
 * context has been detached from its task.
T
Thomas Gleixner 已提交
412
 */
413
static void perf_event_remove_from_context(struct perf_event *event)
T
Thomas Gleixner 已提交
414
{
415
	struct perf_event_context *ctx = event->ctx;
T
Thomas Gleixner 已提交
416 417 418 419
	struct task_struct *task = ctx->task;

	if (!task) {
		/*
420
		 * Per cpu events are removed via an smp call and
T
Thomas Gleixner 已提交
421 422
		 * the removal is always sucessful.
		 */
423 424 425
		smp_call_function_single(event->cpu,
					 __perf_event_remove_from_context,
					 event, 1);
T
Thomas Gleixner 已提交
426 427 428 429
		return;
	}

retry:
430 431
	task_oncpu_function_call(task, __perf_event_remove_from_context,
				 event);
T
Thomas Gleixner 已提交
432 433 434 435 436

	spin_lock_irq(&ctx->lock);
	/*
	 * If the context is active we need to retry the smp call.
	 */
437
	if (ctx->nr_active && !list_empty(&event->group_entry)) {
T
Thomas Gleixner 已提交
438 439 440 441 442 443
		spin_unlock_irq(&ctx->lock);
		goto retry;
	}

	/*
	 * The lock prevents that this context is scheduled in so we
444
	 * can remove the event safely, if the call above did not
T
Thomas Gleixner 已提交
445 446
	 * succeed.
	 */
447 448
	if (!list_empty(&event->group_entry)) {
		list_del_event(event, ctx);
T
Thomas Gleixner 已提交
449 450 451 452
	}
	spin_unlock_irq(&ctx->lock);
}

453
static inline u64 perf_clock(void)
454
{
455
	return cpu_clock(smp_processor_id());
456 457 458 459 460
}

/*
 * Update the record of the current time in a context.
 */
461
static void update_context_time(struct perf_event_context *ctx)
462
{
463 464 465 466
	u64 now = perf_clock();

	ctx->time += now - ctx->timestamp;
	ctx->timestamp = now;
467 468 469
}

/*
470
 * Update the total_time_enabled and total_time_running fields for a event.
471
 */
472
static void update_event_times(struct perf_event *event)
473
{
474
	struct perf_event_context *ctx = event->ctx;
475 476
	u64 run_end;

477 478
	if (event->state < PERF_EVENT_STATE_INACTIVE ||
	    event->group_leader->state < PERF_EVENT_STATE_INACTIVE)
479 480
		return;

481
	event->total_time_enabled = ctx->time - event->tstamp_enabled;
482

483 484
	if (event->state == PERF_EVENT_STATE_INACTIVE)
		run_end = event->tstamp_stopped;
485 486 487
	else
		run_end = ctx->time;

488
	event->total_time_running = run_end - event->tstamp_running;
489 490 491
}

/*
492
 * Update total_time_enabled and total_time_running for all events in a group.
493
 */
494
static void update_group_times(struct perf_event *leader)
495
{
496
	struct perf_event *event;
497

498 499 500
	update_event_times(leader);
	list_for_each_entry(event, &leader->sibling_list, group_entry)
		update_event_times(event);
501 502
}

503
/*
504
 * Cross CPU call to disable a performance event
505
 */
506
static void __perf_event_disable(void *info)
507
{
508
	struct perf_event *event = info;
509
	struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
510
	struct perf_event_context *ctx = event->ctx;
511 512

	/*
513 514
	 * If this is a per-task event, need to check whether this
	 * event's task is the current task on this cpu.
515
	 */
516
	if (ctx->task && cpuctx->task_ctx != ctx)
517 518
		return;

519
	spin_lock(&ctx->lock);
520 521

	/*
522
	 * If the event is on, turn it off.
523 524
	 * If it is in error state, leave it in error state.
	 */
525
	if (event->state >= PERF_EVENT_STATE_INACTIVE) {
526
		update_context_time(ctx);
527 528 529
		update_group_times(event);
		if (event == event->group_leader)
			group_sched_out(event, cpuctx, ctx);
530
		else
531 532
			event_sched_out(event, cpuctx, ctx);
		event->state = PERF_EVENT_STATE_OFF;
533 534
	}

535
	spin_unlock(&ctx->lock);
536 537 538
}

/*
539
 * Disable a event.
540
 *
541 542
 * If event->ctx is a cloned context, callers must make sure that
 * every task struct that event->ctx->task could possibly point to
543
 * remains valid.  This condition is satisifed when called through
544 545 546 547
 * perf_event_for_each_child or perf_event_for_each because they
 * hold the top-level event's child_mutex, so any descendant that
 * goes to exit will block in sync_child_event.
 * When called from perf_pending_event it's OK because event->ctx
548
 * is the current context on this CPU and preemption is disabled,
549
 * hence we can't get into perf_event_task_sched_out for this context.
550
 */
551
static void perf_event_disable(struct perf_event *event)
552
{
553
	struct perf_event_context *ctx = event->ctx;
554 555 556 557
	struct task_struct *task = ctx->task;

	if (!task) {
		/*
558
		 * Disable the event on the cpu that it's on
559
		 */
560 561
		smp_call_function_single(event->cpu, __perf_event_disable,
					 event, 1);
562 563 564 565
		return;
	}

 retry:
566
	task_oncpu_function_call(task, __perf_event_disable, event);
567 568 569

	spin_lock_irq(&ctx->lock);
	/*
570
	 * If the event is still active, we need to retry the cross-call.
571
	 */
572
	if (event->state == PERF_EVENT_STATE_ACTIVE) {
573 574 575 576 577 578 579 580
		spin_unlock_irq(&ctx->lock);
		goto retry;
	}

	/*
	 * Since we have the lock this context can't be scheduled
	 * in, so we can change the state safely.
	 */
581 582 583
	if (event->state == PERF_EVENT_STATE_INACTIVE) {
		update_group_times(event);
		event->state = PERF_EVENT_STATE_OFF;
584
	}
585 586 587 588

	spin_unlock_irq(&ctx->lock);
}

589
static int
590
event_sched_in(struct perf_event *event,
591
		 struct perf_cpu_context *cpuctx,
592
		 struct perf_event_context *ctx,
593 594
		 int cpu)
{
595
	if (event->state <= PERF_EVENT_STATE_OFF)
596 597
		return 0;

598 599
	event->state = PERF_EVENT_STATE_ACTIVE;
	event->oncpu = cpu;	/* TODO: put 'cpu' into cpuctx->cpu */
600 601 602 603 604
	/*
	 * The new state must be visible before we turn it on in the hardware:
	 */
	smp_wmb();

605 606 607
	if (event->pmu->enable(event)) {
		event->state = PERF_EVENT_STATE_INACTIVE;
		event->oncpu = -1;
608 609 610
		return -EAGAIN;
	}

611
	event->tstamp_running += ctx->time - event->tstamp_stopped;
612

613
	if (!is_software_event(event))
614
		cpuctx->active_oncpu++;
615 616
	ctx->nr_active++;

617
	if (event->attr.exclusive)
618 619
		cpuctx->exclusive = 1;

620 621 622
	return 0;
}

623
static int
624
group_sched_in(struct perf_event *group_event,
625
	       struct perf_cpu_context *cpuctx,
626
	       struct perf_event_context *ctx,
627 628
	       int cpu)
{
629
	struct perf_event *event, *partial_group;
630 631
	int ret;

632
	if (group_event->state == PERF_EVENT_STATE_OFF)
633 634
		return 0;

635
	ret = hw_perf_group_sched_in(group_event, cpuctx, ctx, cpu);
636 637 638
	if (ret)
		return ret < 0 ? ret : 0;

639
	if (event_sched_in(group_event, cpuctx, ctx, cpu))
640 641 642 643 644
		return -EAGAIN;

	/*
	 * Schedule in siblings as one group (if any):
	 */
645 646 647
	list_for_each_entry(event, &group_event->sibling_list, group_entry) {
		if (event_sched_in(event, cpuctx, ctx, cpu)) {
			partial_group = event;
648 649 650 651 652 653 654 655 656 657 658
			goto group_error;
		}
	}

	return 0;

group_error:
	/*
	 * Groups can be scheduled in as one unit only, so undo any
	 * partial group before returning:
	 */
659 660
	list_for_each_entry(event, &group_event->sibling_list, group_entry) {
		if (event == partial_group)
661
			break;
662
		event_sched_out(event, cpuctx, ctx);
663
	}
664
	event_sched_out(group_event, cpuctx, ctx);
665 666 667 668

	return -EAGAIN;
}

669
/*
670 671
 * Return 1 for a group consisting entirely of software events,
 * 0 if the group contains any hardware events.
672
 */
673
static int is_software_only_group(struct perf_event *leader)
674
{
675
	struct perf_event *event;
676

677
	if (!is_software_event(leader))
678
		return 0;
P
Peter Zijlstra 已提交
679

680 681
	list_for_each_entry(event, &leader->sibling_list, group_entry)
		if (!is_software_event(event))
682
			return 0;
P
Peter Zijlstra 已提交
683

684 685 686 687
	return 1;
}

/*
688
 * Work out whether we can put this event group on the CPU now.
689
 */
690
static int group_can_go_on(struct perf_event *event,
691 692 693 694
			   struct perf_cpu_context *cpuctx,
			   int can_add_hw)
{
	/*
695
	 * Groups consisting entirely of software events can always go on.
696
	 */
697
	if (is_software_only_group(event))
698 699 700
		return 1;
	/*
	 * If an exclusive group is already on, no other hardware
701
	 * events can go on.
702 703 704 705 706
	 */
	if (cpuctx->exclusive)
		return 0;
	/*
	 * If this group is exclusive and there are already
707
	 * events on the CPU, it can't go on.
708
	 */
709
	if (event->attr.exclusive && cpuctx->active_oncpu)
710 711 712 713 714 715 716 717
		return 0;
	/*
	 * Otherwise, try to add it if all previous groups were able
	 * to go on.
	 */
	return can_add_hw;
}

718 719
static void add_event_to_ctx(struct perf_event *event,
			       struct perf_event_context *ctx)
720
{
721 722 723 724
	list_add_event(event, ctx);
	event->tstamp_enabled = ctx->time;
	event->tstamp_running = ctx->time;
	event->tstamp_stopped = ctx->time;
725 726
}

T
Thomas Gleixner 已提交
727
/*
728
 * Cross CPU call to install and enable a performance event
729 730
 *
 * Must be called with ctx->mutex held
T
Thomas Gleixner 已提交
731 732 733 734
 */
static void __perf_install_in_context(void *info)
{
	struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
735 736 737
	struct perf_event *event = info;
	struct perf_event_context *ctx = event->ctx;
	struct perf_event *leader = event->group_leader;
T
Thomas Gleixner 已提交
738
	int cpu = smp_processor_id();
739
	int err;
T
Thomas Gleixner 已提交
740 741 742 743 744

	/*
	 * If this is a task context, we need to check whether it is
	 * the current task context of this cpu. If not it has been
	 * scheduled out before the smp call arrived.
745
	 * Or possibly this is the right context but it isn't
746
	 * on this cpu because it had no events.
T
Thomas Gleixner 已提交
747
	 */
748
	if (ctx->task && cpuctx->task_ctx != ctx) {
749
		if (cpuctx->task_ctx || ctx->task != current)
750 751 752
			return;
		cpuctx->task_ctx = ctx;
	}
T
Thomas Gleixner 已提交
753

754
	spin_lock(&ctx->lock);
755
	ctx->is_active = 1;
756
	update_context_time(ctx);
T
Thomas Gleixner 已提交
757 758 759

	/*
	 * Protect the list operation against NMI by disabling the
760
	 * events on a global level. NOP for non NMI based events.
T
Thomas Gleixner 已提交
761
	 */
762
	perf_disable();
T
Thomas Gleixner 已提交
763

764
	add_event_to_ctx(event, ctx);
T
Thomas Gleixner 已提交
765

766
	/*
767
	 * Don't put the event on if it is disabled or if
768 769
	 * it is in a group and the group isn't on.
	 */
770 771
	if (event->state != PERF_EVENT_STATE_INACTIVE ||
	    (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE))
772 773
		goto unlock;

774
	/*
775 776 777
	 * An exclusive event can't go on if there are already active
	 * hardware events, and no hardware event can go on if there
	 * is already an exclusive event on.
778
	 */
779
	if (!group_can_go_on(event, cpuctx, 1))
780 781
		err = -EEXIST;
	else
782
		err = event_sched_in(event, cpuctx, ctx, cpu);
783

784 785
	if (err) {
		/*
786
		 * This event couldn't go on.  If it is in a group
787
		 * then we have to pull the whole group off.
788
		 * If the event group is pinned then put it in error state.
789
		 */
790
		if (leader != event)
791
			group_sched_out(leader, cpuctx, ctx);
792
		if (leader->attr.pinned) {
793
			update_group_times(leader);
794
			leader->state = PERF_EVENT_STATE_ERROR;
795
		}
796
	}
T
Thomas Gleixner 已提交
797

798
	if (!err && !ctx->task && cpuctx->max_pertask)
T
Thomas Gleixner 已提交
799 800
		cpuctx->max_pertask--;

801
 unlock:
802
	perf_enable();
803

804
	spin_unlock(&ctx->lock);
T
Thomas Gleixner 已提交
805 806 807
}

/*
808
 * Attach a performance event to a context
T
Thomas Gleixner 已提交
809
 *
810 811
 * First we add the event to the list with the hardware enable bit
 * in event->hw_config cleared.
T
Thomas Gleixner 已提交
812
 *
813
 * If the event is attached to a task which is on a CPU we use a smp
T
Thomas Gleixner 已提交
814 815
 * call to enable it in the task context. The task might have been
 * scheduled away, but we check this in the smp call again.
816 817
 *
 * Must be called with ctx->mutex held.
T
Thomas Gleixner 已提交
818 819
 */
static void
820 821
perf_install_in_context(struct perf_event_context *ctx,
			struct perf_event *event,
T
Thomas Gleixner 已提交
822 823 824 825 826 827
			int cpu)
{
	struct task_struct *task = ctx->task;

	if (!task) {
		/*
828
		 * Per cpu events are installed via an smp call and
T
Thomas Gleixner 已提交
829 830 831
		 * the install is always sucessful.
		 */
		smp_call_function_single(cpu, __perf_install_in_context,
832
					 event, 1);
T
Thomas Gleixner 已提交
833 834 835 836 837
		return;
	}

retry:
	task_oncpu_function_call(task, __perf_install_in_context,
838
				 event);
T
Thomas Gleixner 已提交
839 840 841 842 843

	spin_lock_irq(&ctx->lock);
	/*
	 * we need to retry the smp call.
	 */
844
	if (ctx->is_active && list_empty(&event->group_entry)) {
T
Thomas Gleixner 已提交
845 846 847 848 849 850
		spin_unlock_irq(&ctx->lock);
		goto retry;
	}

	/*
	 * The lock prevents that this context is scheduled in so we
851
	 * can add the event safely, if it the call above did not
T
Thomas Gleixner 已提交
852 853
	 * succeed.
	 */
854 855
	if (list_empty(&event->group_entry))
		add_event_to_ctx(event, ctx);
T
Thomas Gleixner 已提交
856 857 858
	spin_unlock_irq(&ctx->lock);
}

859
/*
860
 * Put a event into inactive state and update time fields.
861 862 863 864 865 866
 * Enabling the leader of a group effectively enables all
 * the group members that aren't explicitly disabled, so we
 * have to update their ->tstamp_enabled also.
 * Note: this works for group members as well as group leaders
 * since the non-leader members' sibling_lists will be empty.
 */
867 868
static void __perf_event_mark_enabled(struct perf_event *event,
					struct perf_event_context *ctx)
869
{
870
	struct perf_event *sub;
871

872 873 874 875
	event->state = PERF_EVENT_STATE_INACTIVE;
	event->tstamp_enabled = ctx->time - event->total_time_enabled;
	list_for_each_entry(sub, &event->sibling_list, group_entry)
		if (sub->state >= PERF_EVENT_STATE_INACTIVE)
876 877 878 879
			sub->tstamp_enabled =
				ctx->time - sub->total_time_enabled;
}

880
/*
881
 * Cross CPU call to enable a performance event
882
 */
883
static void __perf_event_enable(void *info)
884
{
885
	struct perf_event *event = info;
886
	struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
887 888
	struct perf_event_context *ctx = event->ctx;
	struct perf_event *leader = event->group_leader;
889
	int err;
890

891
	/*
892 893
	 * If this is a per-task event, need to check whether this
	 * event's task is the current task on this cpu.
894
	 */
895
	if (ctx->task && cpuctx->task_ctx != ctx) {
896
		if (cpuctx->task_ctx || ctx->task != current)
897 898 899
			return;
		cpuctx->task_ctx = ctx;
	}
900

901
	spin_lock(&ctx->lock);
902
	ctx->is_active = 1;
903
	update_context_time(ctx);
904

905
	if (event->state >= PERF_EVENT_STATE_INACTIVE)
906
		goto unlock;
907
	__perf_event_mark_enabled(event, ctx);
908 909

	/*
910
	 * If the event is in a group and isn't the group leader,
911
	 * then don't put it on unless the group is on.
912
	 */
913
	if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE)
914
		goto unlock;
915

916
	if (!group_can_go_on(event, cpuctx, 1)) {
917
		err = -EEXIST;
918
	} else {
919
		perf_disable();
920 921
		if (event == leader)
			err = group_sched_in(event, cpuctx, ctx,
922 923
					     smp_processor_id());
		else
924
			err = event_sched_in(event, cpuctx, ctx,
925
					       smp_processor_id());
926
		perf_enable();
927
	}
928 929 930

	if (err) {
		/*
931
		 * If this event can't go on and it's part of a
932 933
		 * group, then the whole group has to come off.
		 */
934
		if (leader != event)
935
			group_sched_out(leader, cpuctx, ctx);
936
		if (leader->attr.pinned) {
937
			update_group_times(leader);
938
			leader->state = PERF_EVENT_STATE_ERROR;
939
		}
940 941 942
	}

 unlock:
943
	spin_unlock(&ctx->lock);
944 945 946
}

/*
947
 * Enable a event.
948
 *
949 950
 * If event->ctx is a cloned context, callers must make sure that
 * every task struct that event->ctx->task could possibly point to
951
 * remains valid.  This condition is satisfied when called through
952 953
 * perf_event_for_each_child or perf_event_for_each as described
 * for perf_event_disable.
954
 */
955
static void perf_event_enable(struct perf_event *event)
956
{
957
	struct perf_event_context *ctx = event->ctx;
958 959 960 961
	struct task_struct *task = ctx->task;

	if (!task) {
		/*
962
		 * Enable the event on the cpu that it's on
963
		 */
964 965
		smp_call_function_single(event->cpu, __perf_event_enable,
					 event, 1);
966 967 968 969
		return;
	}

	spin_lock_irq(&ctx->lock);
970
	if (event->state >= PERF_EVENT_STATE_INACTIVE)
971 972 973
		goto out;

	/*
974 975
	 * If the event is in error state, clear that first.
	 * That way, if we see the event in error state below, we
976 977 978 979
	 * know that it has gone back into error state, as distinct
	 * from the task having been scheduled away before the
	 * cross-call arrived.
	 */
980 981
	if (event->state == PERF_EVENT_STATE_ERROR)
		event->state = PERF_EVENT_STATE_OFF;
982 983 984

 retry:
	spin_unlock_irq(&ctx->lock);
985
	task_oncpu_function_call(task, __perf_event_enable, event);
986 987 988 989

	spin_lock_irq(&ctx->lock);

	/*
990
	 * If the context is active and the event is still off,
991 992
	 * we need to retry the cross-call.
	 */
993
	if (ctx->is_active && event->state == PERF_EVENT_STATE_OFF)
994 995 996 997 998 999
		goto retry;

	/*
	 * Since we have the lock this context can't be scheduled
	 * in, so we can change the state safely.
	 */
1000 1001
	if (event->state == PERF_EVENT_STATE_OFF)
		__perf_event_mark_enabled(event, ctx);
1002

1003 1004 1005 1006
 out:
	spin_unlock_irq(&ctx->lock);
}

1007
static int perf_event_refresh(struct perf_event *event, int refresh)
1008
{
1009
	/*
1010
	 * not supported on inherited events
1011
	 */
1012
	if (event->attr.inherit)
1013 1014
		return -EINVAL;

1015 1016
	atomic_add(refresh, &event->event_limit);
	perf_event_enable(event);
1017 1018

	return 0;
1019 1020
}

1021
void __perf_event_sched_out(struct perf_event_context *ctx,
1022 1023
			      struct perf_cpu_context *cpuctx)
{
1024
	struct perf_event *event;
1025

1026 1027
	spin_lock(&ctx->lock);
	ctx->is_active = 0;
1028
	if (likely(!ctx->nr_events))
1029
		goto out;
1030
	update_context_time(ctx);
1031

1032
	perf_disable();
1033 1034 1035 1036
	if (ctx->nr_active)
		list_for_each_entry(event, &ctx->group_list, group_entry)
			group_sched_out(event, cpuctx, ctx);

1037
	perf_enable();
1038
 out:
1039 1040 1041
	spin_unlock(&ctx->lock);
}

1042 1043 1044
/*
 * Test whether two contexts are equivalent, i.e. whether they
 * have both been cloned from the same version of the same context
1045 1046 1047 1048
 * and they both have the same number of enabled events.
 * If the number of enabled events is the same, then the set
 * of enabled events should be the same, because these are both
 * inherited contexts, therefore we can't access individual events
1049
 * in them directly with an fd; we can only enable/disable all
1050
 * events via prctl, or enable/disable all events in a family
1051 1052
 * via ioctl, which will have the same effect on both contexts.
 */
1053 1054
static int context_equiv(struct perf_event_context *ctx1,
			 struct perf_event_context *ctx2)
1055 1056
{
	return ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx
1057
		&& ctx1->parent_gen == ctx2->parent_gen
1058
		&& !ctx1->pin_count && !ctx2->pin_count;
1059 1060
}

1061
static void __perf_event_read(void *event);
1062

1063 1064
static void __perf_event_sync_stat(struct perf_event *event,
				     struct perf_event *next_event)
1065 1066 1067
{
	u64 value;

1068
	if (!event->attr.inherit_stat)
1069 1070 1071
		return;

	/*
1072
	 * Update the event value, we cannot use perf_event_read()
1073 1074
	 * because we're in the middle of a context switch and have IRQs
	 * disabled, which upsets smp_call_function_single(), however
1075
	 * we know the event must be on the current CPU, therefore we
1076 1077
	 * don't need to use it.
	 */
1078 1079 1080
	switch (event->state) {
	case PERF_EVENT_STATE_ACTIVE:
		__perf_event_read(event);
1081 1082
		break;

1083 1084
	case PERF_EVENT_STATE_INACTIVE:
		update_event_times(event);
1085 1086 1087 1088 1089 1090 1091
		break;

	default:
		break;
	}

	/*
1092
	 * In order to keep per-task stats reliable we need to flip the event
1093 1094
	 * values when we flip the contexts.
	 */
1095 1096 1097
	value = atomic64_read(&next_event->count);
	value = atomic64_xchg(&event->count, value);
	atomic64_set(&next_event->count, value);
1098

1099 1100
	swap(event->total_time_enabled, next_event->total_time_enabled);
	swap(event->total_time_running, next_event->total_time_running);
1101

1102
	/*
1103
	 * Since we swizzled the values, update the user visible data too.
1104
	 */
1105 1106
	perf_event_update_userpage(event);
	perf_event_update_userpage(next_event);
1107 1108 1109 1110 1111
}

#define list_next_entry(pos, member) \
	list_entry(pos->member.next, typeof(*pos), member)

1112 1113
static void perf_event_sync_stat(struct perf_event_context *ctx,
				   struct perf_event_context *next_ctx)
1114
{
1115
	struct perf_event *event, *next_event;
1116 1117 1118 1119

	if (!ctx->nr_stat)
		return;

1120 1121
	event = list_first_entry(&ctx->event_list,
				   struct perf_event, event_entry);
1122

1123 1124
	next_event = list_first_entry(&next_ctx->event_list,
					struct perf_event, event_entry);
1125

1126 1127
	while (&event->event_entry != &ctx->event_list &&
	       &next_event->event_entry != &next_ctx->event_list) {
1128

1129
		__perf_event_sync_stat(event, next_event);
1130

1131 1132
		event = list_next_entry(event, event_entry);
		next_event = list_next_entry(next_event, event_entry);
1133 1134 1135
	}
}

T
Thomas Gleixner 已提交
1136
/*
1137
 * Called from scheduler to remove the events of the current task,
T
Thomas Gleixner 已提交
1138 1139
 * with interrupts disabled.
 *
1140
 * We stop each event and update the event value in event->count.
T
Thomas Gleixner 已提交
1141
 *
I
Ingo Molnar 已提交
1142
 * This does not protect us against NMI, but disable()
1143 1144 1145
 * sets the disabled bit in the control field of event _before_
 * accessing the event control register. If a NMI hits, then it will
 * not restart the event.
T
Thomas Gleixner 已提交
1146
 */
1147
void perf_event_task_sched_out(struct task_struct *task,
1148
				 struct task_struct *next, int cpu)
T
Thomas Gleixner 已提交
1149 1150
{
	struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
1151 1152 1153
	struct perf_event_context *ctx = task->perf_event_ctxp;
	struct perf_event_context *next_ctx;
	struct perf_event_context *parent;
1154
	struct pt_regs *regs;
1155
	int do_switch = 1;
T
Thomas Gleixner 已提交
1156

1157
	regs = task_pt_regs(task);
1158
	perf_sw_event(PERF_COUNT_SW_CONTEXT_SWITCHES, 1, 1, regs, 0);
1159

1160
	if (likely(!ctx || !cpuctx->task_ctx))
T
Thomas Gleixner 已提交
1161 1162
		return;

1163
	update_context_time(ctx);
1164 1165 1166

	rcu_read_lock();
	parent = rcu_dereference(ctx->parent_ctx);
1167
	next_ctx = next->perf_event_ctxp;
1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
	if (parent && next_ctx &&
	    rcu_dereference(next_ctx->parent_ctx) == parent) {
		/*
		 * Looks like the two contexts are clones, so we might be
		 * able to optimize the context switch.  We lock both
		 * contexts and check that they are clones under the
		 * lock (including re-checking that neither has been
		 * uncloned in the meantime).  It doesn't matter which
		 * order we take the locks because no other cpu could
		 * be trying to lock both of these tasks.
		 */
		spin_lock(&ctx->lock);
		spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING);
		if (context_equiv(ctx, next_ctx)) {
1182 1183
			/*
			 * XXX do we need a memory barrier of sorts
1184
			 * wrt to rcu_dereference() of perf_event_ctxp
1185
			 */
1186 1187
			task->perf_event_ctxp = next_ctx;
			next->perf_event_ctxp = ctx;
1188 1189 1190
			ctx->task = next;
			next_ctx->task = task;
			do_switch = 0;
1191

1192
			perf_event_sync_stat(ctx, next_ctx);
1193 1194 1195
		}
		spin_unlock(&next_ctx->lock);
		spin_unlock(&ctx->lock);
1196
	}
1197
	rcu_read_unlock();
1198

1199
	if (do_switch) {
1200
		__perf_event_sched_out(ctx, cpuctx);
1201 1202
		cpuctx->task_ctx = NULL;
	}
T
Thomas Gleixner 已提交
1203 1204
}

1205 1206 1207
/*
 * Called with IRQs disabled
 */
1208
static void __perf_event_task_sched_out(struct perf_event_context *ctx)
1209 1210 1211
{
	struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);

1212 1213
	if (!cpuctx->task_ctx)
		return;
1214 1215 1216 1217

	if (WARN_ON_ONCE(ctx != cpuctx->task_ctx))
		return;

1218
	__perf_event_sched_out(ctx, cpuctx);
1219 1220 1221
	cpuctx->task_ctx = NULL;
}

1222 1223 1224
/*
 * Called with IRQs disabled
 */
1225
static void perf_event_cpu_sched_out(struct perf_cpu_context *cpuctx)
1226
{
1227
	__perf_event_sched_out(&cpuctx->ctx, cpuctx);
1228 1229
}

1230
static void
1231
__perf_event_sched_in(struct perf_event_context *ctx,
1232
			struct perf_cpu_context *cpuctx, int cpu)
T
Thomas Gleixner 已提交
1233
{
1234
	struct perf_event *event;
1235
	int can_add_hw = 1;
T
Thomas Gleixner 已提交
1236

1237 1238
	spin_lock(&ctx->lock);
	ctx->is_active = 1;
1239
	if (likely(!ctx->nr_events))
1240
		goto out;
T
Thomas Gleixner 已提交
1241

1242
	ctx->timestamp = perf_clock();
1243

1244
	perf_disable();
1245 1246 1247 1248 1249

	/*
	 * First go through the list and put on any pinned groups
	 * in order to give them the best chance of going on.
	 */
1250 1251 1252
	list_for_each_entry(event, &ctx->group_list, group_entry) {
		if (event->state <= PERF_EVENT_STATE_OFF ||
		    !event->attr.pinned)
1253
			continue;
1254
		if (event->cpu != -1 && event->cpu != cpu)
1255 1256
			continue;

1257 1258
		if (group_can_go_on(event, cpuctx, 1))
			group_sched_in(event, cpuctx, ctx, cpu);
1259 1260 1261 1262 1263

		/*
		 * If this pinned group hasn't been scheduled,
		 * put it in error state.
		 */
1264 1265 1266
		if (event->state == PERF_EVENT_STATE_INACTIVE) {
			update_group_times(event);
			event->state = PERF_EVENT_STATE_ERROR;
1267
		}
1268 1269
	}

1270
	list_for_each_entry(event, &ctx->group_list, group_entry) {
1271
		/*
1272 1273
		 * Ignore events in OFF or ERROR state, and
		 * ignore pinned events since we did them already.
1274
		 */
1275 1276
		if (event->state <= PERF_EVENT_STATE_OFF ||
		    event->attr.pinned)
1277 1278
			continue;

1279 1280
		/*
		 * Listen to the 'cpu' scheduling filter constraint
1281
		 * of events:
1282
		 */
1283
		if (event->cpu != -1 && event->cpu != cpu)
T
Thomas Gleixner 已提交
1284 1285
			continue;

1286 1287
		if (group_can_go_on(event, cpuctx, can_add_hw))
			if (group_sched_in(event, cpuctx, ctx, cpu))
1288
				can_add_hw = 0;
T
Thomas Gleixner 已提交
1289
	}
1290
	perf_enable();
1291
 out:
T
Thomas Gleixner 已提交
1292
	spin_unlock(&ctx->lock);
1293 1294 1295
}

/*
1296
 * Called from scheduler to add the events of the current task
1297 1298
 * with interrupts disabled.
 *
1299
 * We restore the event value and then enable it.
1300 1301
 *
 * This does not protect us against NMI, but enable()
1302 1303 1304
 * sets the enabled bit in the control field of event _before_
 * accessing the event control register. If a NMI hits, then it will
 * keep the event running.
1305
 */
1306
void perf_event_task_sched_in(struct task_struct *task, int cpu)
1307 1308
{
	struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
1309
	struct perf_event_context *ctx = task->perf_event_ctxp;
1310

1311 1312
	if (likely(!ctx))
		return;
1313 1314
	if (cpuctx->task_ctx == ctx)
		return;
1315
	__perf_event_sched_in(ctx, cpuctx, cpu);
T
Thomas Gleixner 已提交
1316 1317 1318
	cpuctx->task_ctx = ctx;
}

1319
static void perf_event_cpu_sched_in(struct perf_cpu_context *cpuctx, int cpu)
1320
{
1321
	struct perf_event_context *ctx = &cpuctx->ctx;
1322

1323
	__perf_event_sched_in(ctx, cpuctx, cpu);
1324 1325
}

1326 1327
#define MAX_INTERRUPTS (~0ULL)

1328
static void perf_log_throttle(struct perf_event *event, int enable);
1329

1330
static void perf_adjust_period(struct perf_event *event, u64 events)
1331
{
1332
	struct hw_perf_event *hwc = &event->hw;
1333 1334 1335 1336
	u64 period, sample_period;
	s64 delta;

	events *= hwc->sample_period;
1337
	period = div64_u64(events, event->attr.sample_freq);
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349

	delta = (s64)(period - hwc->sample_period);
	delta = (delta + 7) / 8; /* low pass filter */

	sample_period = hwc->sample_period + delta;

	if (!sample_period)
		sample_period = 1;

	hwc->sample_period = sample_period;
}

1350
static void perf_ctx_adjust_freq(struct perf_event_context *ctx)
1351
{
1352 1353
	struct perf_event *event;
	struct hw_perf_event *hwc;
1354
	u64 interrupts, freq;
1355 1356

	spin_lock(&ctx->lock);
1357 1358
	list_for_each_entry(event, &ctx->group_list, group_entry) {
		if (event->state != PERF_EVENT_STATE_ACTIVE)
1359 1360
			continue;

1361
		hwc = &event->hw;
1362 1363 1364

		interrupts = hwc->interrupts;
		hwc->interrupts = 0;
1365

1366
		/*
1367
		 * unthrottle events on the tick
1368
		 */
1369
		if (interrupts == MAX_INTERRUPTS) {
1370 1371 1372
			perf_log_throttle(event, 1);
			event->pmu->unthrottle(event);
			interrupts = 2*sysctl_perf_event_sample_rate/HZ;
1373 1374
		}

1375
		if (!event->attr.freq || !event->attr.sample_freq)
1376 1377
			continue;

1378 1379 1380
		/*
		 * if the specified freq < HZ then we need to skip ticks
		 */
1381 1382
		if (event->attr.sample_freq < HZ) {
			freq = event->attr.sample_freq;
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395

			hwc->freq_count += freq;
			hwc->freq_interrupts += interrupts;

			if (hwc->freq_count < HZ)
				continue;

			interrupts = hwc->freq_interrupts;
			hwc->freq_interrupts = 0;
			hwc->freq_count -= HZ;
		} else
			freq = HZ;

1396
		perf_adjust_period(event, freq * interrupts);
1397

1398 1399 1400 1401 1402 1403 1404
		/*
		 * In order to avoid being stalled by an (accidental) huge
		 * sample period, force reset the sample period if we didn't
		 * get any events in this freq period.
		 */
		if (!interrupts) {
			perf_disable();
1405
			event->pmu->disable(event);
1406
			atomic64_set(&hwc->period_left, 0);
1407
			event->pmu->enable(event);
1408 1409
			perf_enable();
		}
1410 1411 1412 1413
	}
	spin_unlock(&ctx->lock);
}

1414
/*
1415
 * Round-robin a context's events:
1416
 */
1417
static void rotate_ctx(struct perf_event_context *ctx)
T
Thomas Gleixner 已提交
1418
{
1419
	struct perf_event *event;
T
Thomas Gleixner 已提交
1420

1421
	if (!ctx->nr_events)
T
Thomas Gleixner 已提交
1422 1423 1424 1425
		return;

	spin_lock(&ctx->lock);
	/*
1426
	 * Rotate the first entry last (works just fine for group events too):
T
Thomas Gleixner 已提交
1427
	 */
1428
	perf_disable();
1429 1430
	list_for_each_entry(event, &ctx->group_list, group_entry) {
		list_move_tail(&event->group_entry, &ctx->group_list);
T
Thomas Gleixner 已提交
1431 1432
		break;
	}
1433
	perf_enable();
T
Thomas Gleixner 已提交
1434 1435

	spin_unlock(&ctx->lock);
1436 1437
}

1438
void perf_event_task_tick(struct task_struct *curr, int cpu)
1439
{
1440
	struct perf_cpu_context *cpuctx;
1441
	struct perf_event_context *ctx;
1442

1443
	if (!atomic_read(&nr_events))
1444 1445 1446
		return;

	cpuctx = &per_cpu(perf_cpu_context, cpu);
1447
	ctx = curr->perf_event_ctxp;
1448

1449
	perf_ctx_adjust_freq(&cpuctx->ctx);
1450
	if (ctx)
1451
		perf_ctx_adjust_freq(ctx);
1452

1453
	perf_event_cpu_sched_out(cpuctx);
1454
	if (ctx)
1455
		__perf_event_task_sched_out(ctx);
T
Thomas Gleixner 已提交
1456

1457
	rotate_ctx(&cpuctx->ctx);
1458 1459
	if (ctx)
		rotate_ctx(ctx);
1460

1461
	perf_event_cpu_sched_in(cpuctx, cpu);
1462
	if (ctx)
1463
		perf_event_task_sched_in(curr, cpu);
T
Thomas Gleixner 已提交
1464 1465
}

1466
/*
1467
 * Enable all of a task's events that have been marked enable-on-exec.
1468 1469
 * This expects task == current.
 */
1470
static void perf_event_enable_on_exec(struct task_struct *task)
1471
{
1472 1473
	struct perf_event_context *ctx;
	struct perf_event *event;
1474 1475 1476 1477
	unsigned long flags;
	int enabled = 0;

	local_irq_save(flags);
1478 1479
	ctx = task->perf_event_ctxp;
	if (!ctx || !ctx->nr_events)
1480 1481
		goto out;

1482
	__perf_event_task_sched_out(ctx);
1483 1484 1485

	spin_lock(&ctx->lock);

1486 1487
	list_for_each_entry(event, &ctx->group_list, group_entry) {
		if (!event->attr.enable_on_exec)
1488
			continue;
1489 1490
		event->attr.enable_on_exec = 0;
		if (event->state >= PERF_EVENT_STATE_INACTIVE)
1491
			continue;
1492
		__perf_event_mark_enabled(event, ctx);
1493 1494 1495 1496
		enabled = 1;
	}

	/*
1497
	 * Unclone this context if we enabled any event.
1498
	 */
1499 1500
	if (enabled)
		unclone_ctx(ctx);
1501 1502 1503

	spin_unlock(&ctx->lock);

1504
	perf_event_task_sched_in(task, smp_processor_id());
1505 1506 1507 1508
 out:
	local_irq_restore(flags);
}

T
Thomas Gleixner 已提交
1509
/*
1510
 * Cross CPU call to read the hardware event
T
Thomas Gleixner 已提交
1511
 */
1512
static void __perf_event_read(void *info)
T
Thomas Gleixner 已提交
1513
{
1514
	struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
1515 1516
	struct perf_event *event = info;
	struct perf_event_context *ctx = event->ctx;
I
Ingo Molnar 已提交
1517
	unsigned long flags;
I
Ingo Molnar 已提交
1518

1519 1520 1521 1522
	/*
	 * If this is a task context, we need to check whether it is
	 * the current task context of this cpu.  If not it has been
	 * scheduled out before the smp call arrived.  In that case
1523 1524
	 * event->count would have been updated to a recent sample
	 * when the event was scheduled out.
1525 1526 1527 1528
	 */
	if (ctx->task && cpuctx->task_ctx != ctx)
		return;

1529
	local_irq_save(flags);
1530
	if (ctx->is_active)
1531
		update_context_time(ctx);
1532 1533
	event->pmu->read(event);
	update_event_times(event);
1534
	local_irq_restore(flags);
T
Thomas Gleixner 已提交
1535 1536
}

1537
static u64 perf_event_read(struct perf_event *event)
T
Thomas Gleixner 已提交
1538 1539
{
	/*
1540 1541
	 * If event is enabled and currently active on a CPU, update the
	 * value in the event structure:
T
Thomas Gleixner 已提交
1542
	 */
1543 1544 1545 1546 1547
	if (event->state == PERF_EVENT_STATE_ACTIVE) {
		smp_call_function_single(event->oncpu,
					 __perf_event_read, event, 1);
	} else if (event->state == PERF_EVENT_STATE_INACTIVE) {
		update_event_times(event);
T
Thomas Gleixner 已提交
1548 1549
	}

1550
	return atomic64_read(&event->count);
T
Thomas Gleixner 已提交
1551 1552
}

1553
/*
1554
 * Initialize the perf_event context in a task_struct:
1555 1556
 */
static void
1557
__perf_event_init_context(struct perf_event_context *ctx,
1558 1559 1560 1561 1562
			    struct task_struct *task)
{
	memset(ctx, 0, sizeof(*ctx));
	spin_lock_init(&ctx->lock);
	mutex_init(&ctx->mutex);
1563
	INIT_LIST_HEAD(&ctx->group_list);
1564 1565 1566 1567 1568
	INIT_LIST_HEAD(&ctx->event_list);
	atomic_set(&ctx->refcount, 1);
	ctx->task = task;
}

1569
static struct perf_event_context *find_get_context(pid_t pid, int cpu)
T
Thomas Gleixner 已提交
1570
{
1571
	struct perf_event_context *ctx;
1572
	struct perf_cpu_context *cpuctx;
T
Thomas Gleixner 已提交
1573
	struct task_struct *task;
1574
	unsigned long flags;
1575
	int err;
T
Thomas Gleixner 已提交
1576 1577

	/*
1578
	 * If cpu is not a wildcard then this is a percpu event:
T
Thomas Gleixner 已提交
1579 1580
	 */
	if (cpu != -1) {
1581
		/* Must be root to operate on a CPU event: */
1582
		if (perf_paranoid_cpu() && !capable(CAP_SYS_ADMIN))
T
Thomas Gleixner 已提交
1583 1584 1585 1586 1587 1588
			return ERR_PTR(-EACCES);

		if (cpu < 0 || cpu > num_possible_cpus())
			return ERR_PTR(-EINVAL);

		/*
1589
		 * We could be clever and allow to attach a event to an
T
Thomas Gleixner 已提交
1590 1591 1592 1593 1594 1595 1596 1597
		 * offline CPU and activate it when the CPU comes up, but
		 * that's for later.
		 */
		if (!cpu_isset(cpu, cpu_online_map))
			return ERR_PTR(-ENODEV);

		cpuctx = &per_cpu(perf_cpu_context, cpu);
		ctx = &cpuctx->ctx;
1598
		get_ctx(ctx);
T
Thomas Gleixner 已提交
1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614

		return ctx;
	}

	rcu_read_lock();
	if (!pid)
		task = current;
	else
		task = find_task_by_vpid(pid);
	if (task)
		get_task_struct(task);
	rcu_read_unlock();

	if (!task)
		return ERR_PTR(-ESRCH);

1615
	/*
1616
	 * Can't attach events to a dying task.
1617 1618 1619 1620 1621
	 */
	err = -ESRCH;
	if (task->flags & PF_EXITING)
		goto errout;

T
Thomas Gleixner 已提交
1622
	/* Reuse ptrace permission checks for now. */
1623 1624 1625 1626 1627
	err = -EACCES;
	if (!ptrace_may_access(task, PTRACE_MODE_READ))
		goto errout;

 retry:
1628
	ctx = perf_lock_task_context(task, &flags);
1629
	if (ctx) {
1630
		unclone_ctx(ctx);
1631
		spin_unlock_irqrestore(&ctx->lock, flags);
T
Thomas Gleixner 已提交
1632 1633
	}

1634
	if (!ctx) {
1635
		ctx = kmalloc(sizeof(struct perf_event_context), GFP_KERNEL);
1636 1637 1638
		err = -ENOMEM;
		if (!ctx)
			goto errout;
1639
		__perf_event_init_context(ctx, task);
1640
		get_ctx(ctx);
1641
		if (cmpxchg(&task->perf_event_ctxp, NULL, ctx)) {
1642 1643 1644 1645 1646
			/*
			 * We raced with some other task; use
			 * the context they set.
			 */
			kfree(ctx);
1647
			goto retry;
1648
		}
1649
		get_task_struct(task);
1650 1651
	}

1652
	put_task_struct(task);
T
Thomas Gleixner 已提交
1653
	return ctx;
1654 1655 1656 1657

 errout:
	put_task_struct(task);
	return ERR_PTR(err);
T
Thomas Gleixner 已提交
1658 1659
}

1660
static void free_event_rcu(struct rcu_head *head)
P
Peter Zijlstra 已提交
1661
{
1662
	struct perf_event *event;
P
Peter Zijlstra 已提交
1663

1664 1665 1666 1667
	event = container_of(head, struct perf_event, rcu_head);
	if (event->ns)
		put_pid_ns(event->ns);
	kfree(event);
P
Peter Zijlstra 已提交
1668 1669
}

1670
static void perf_pending_sync(struct perf_event *event);
1671

1672
static void free_event(struct perf_event *event)
1673
{
1674
	perf_pending_sync(event);
1675

1676 1677 1678 1679 1680 1681 1682 1683
	if (!event->parent) {
		atomic_dec(&nr_events);
		if (event->attr.mmap)
			atomic_dec(&nr_mmap_events);
		if (event->attr.comm)
			atomic_dec(&nr_comm_events);
		if (event->attr.task)
			atomic_dec(&nr_task_events);
1684
	}
1685

1686 1687 1688
	if (event->output) {
		fput(event->output->filp);
		event->output = NULL;
1689 1690
	}

1691 1692
	if (event->destroy)
		event->destroy(event);
1693

1694 1695
	put_ctx(event->ctx);
	call_rcu(&event->rcu_head, free_event_rcu);
1696 1697
}

T
Thomas Gleixner 已提交
1698 1699 1700 1701 1702
/*
 * Called when the last reference to the file is gone.
 */
static int perf_release(struct inode *inode, struct file *file)
{
1703 1704
	struct perf_event *event = file->private_data;
	struct perf_event_context *ctx = event->ctx;
T
Thomas Gleixner 已提交
1705 1706 1707

	file->private_data = NULL;

1708
	WARN_ON_ONCE(ctx->parent_ctx);
1709
	mutex_lock(&ctx->mutex);
1710
	perf_event_remove_from_context(event);
1711
	mutex_unlock(&ctx->mutex);
T
Thomas Gleixner 已提交
1712

1713 1714 1715 1716
	mutex_lock(&event->owner->perf_event_mutex);
	list_del_init(&event->owner_entry);
	mutex_unlock(&event->owner->perf_event_mutex);
	put_task_struct(event->owner);
1717

1718
	free_event(event);
T
Thomas Gleixner 已提交
1719 1720 1721 1722

	return 0;
}

1723
static int perf_event_read_size(struct perf_event *event)
1724 1725 1726 1727 1728
{
	int entry = sizeof(u64); /* value */
	int size = 0;
	int nr = 1;

1729
	if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1730 1731
		size += sizeof(u64);

1732
	if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1733 1734
		size += sizeof(u64);

1735
	if (event->attr.read_format & PERF_FORMAT_ID)
1736 1737
		entry += sizeof(u64);

1738 1739
	if (event->attr.read_format & PERF_FORMAT_GROUP) {
		nr += event->group_leader->nr_siblings;
1740 1741 1742 1743 1744 1745 1746 1747
		size += sizeof(u64);
	}

	size += entry * nr;

	return size;
}

1748
static u64 perf_event_read_value(struct perf_event *event)
1749
{
1750
	struct perf_event *child;
1751 1752
	u64 total = 0;

1753 1754 1755
	total += perf_event_read(event);
	list_for_each_entry(child, &event->child_list, child_list)
		total += perf_event_read(child);
1756 1757 1758 1759

	return total;
}

1760
static int perf_event_read_entry(struct perf_event *event,
1761 1762 1763 1764 1765
				   u64 read_format, char __user *buf)
{
	int n = 0, count = 0;
	u64 values[2];

1766
	values[n++] = perf_event_read_value(event);
1767
	if (read_format & PERF_FORMAT_ID)
1768
		values[n++] = primary_event_id(event);
1769 1770 1771 1772 1773 1774 1775 1776 1777

	count = n * sizeof(u64);

	if (copy_to_user(buf, values, count))
		return -EFAULT;

	return count;
}

1778
static int perf_event_read_group(struct perf_event *event,
1779 1780
				   u64 read_format, char __user *buf)
{
1781
	struct perf_event *leader = event->group_leader, *sub;
1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799
	int n = 0, size = 0, err = -EFAULT;
	u64 values[3];

	values[n++] = 1 + leader->nr_siblings;
	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
		values[n++] = leader->total_time_enabled +
			atomic64_read(&leader->child_total_time_enabled);
	}
	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
		values[n++] = leader->total_time_running +
			atomic64_read(&leader->child_total_time_running);
	}

	size = n * sizeof(u64);

	if (copy_to_user(buf, values, size))
		return -EFAULT;

1800
	err = perf_event_read_entry(leader, read_format, buf + size);
1801 1802 1803 1804 1805
	if (err < 0)
		return err;

	size += err;

1806
	list_for_each_entry(sub, &leader->sibling_list, group_entry) {
1807
		err = perf_event_read_entry(sub, read_format,
1808 1809 1810 1811 1812 1813 1814 1815 1816 1817
				buf + size);
		if (err < 0)
			return err;

		size += err;
	}

	return size;
}

1818
static int perf_event_read_one(struct perf_event *event,
1819 1820 1821 1822 1823
				 u64 read_format, char __user *buf)
{
	u64 values[4];
	int n = 0;

1824
	values[n++] = perf_event_read_value(event);
1825
	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1826 1827
		values[n++] = event->total_time_enabled +
			atomic64_read(&event->child_total_time_enabled);
1828 1829
	}
	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1830 1831
		values[n++] = event->total_time_running +
			atomic64_read(&event->child_total_time_running);
1832 1833
	}
	if (read_format & PERF_FORMAT_ID)
1834
		values[n++] = primary_event_id(event);
1835 1836 1837 1838 1839 1840 1841

	if (copy_to_user(buf, values, n * sizeof(u64)))
		return -EFAULT;

	return n * sizeof(u64);
}

T
Thomas Gleixner 已提交
1842
/*
1843
 * Read the performance event - simple non blocking version for now
T
Thomas Gleixner 已提交
1844 1845
 */
static ssize_t
1846
perf_read_hw(struct perf_event *event, char __user *buf, size_t count)
T
Thomas Gleixner 已提交
1847
{
1848
	u64 read_format = event->attr.read_format;
1849
	int ret;
T
Thomas Gleixner 已提交
1850

1851
	/*
1852
	 * Return end-of-file for a read on a event that is in
1853 1854 1855
	 * error state (i.e. because it was pinned but it couldn't be
	 * scheduled on to the CPU at some point).
	 */
1856
	if (event->state == PERF_EVENT_STATE_ERROR)
1857 1858
		return 0;

1859
	if (count < perf_event_read_size(event))
1860 1861
		return -ENOSPC;

1862 1863
	WARN_ON_ONCE(event->ctx->parent_ctx);
	mutex_lock(&event->child_mutex);
1864
	if (read_format & PERF_FORMAT_GROUP)
1865
		ret = perf_event_read_group(event, read_format, buf);
1866
	else
1867 1868
		ret = perf_event_read_one(event, read_format, buf);
	mutex_unlock(&event->child_mutex);
T
Thomas Gleixner 已提交
1869

1870
	return ret;
T
Thomas Gleixner 已提交
1871 1872 1873 1874 1875
}

static ssize_t
perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
1876
	struct perf_event *event = file->private_data;
T
Thomas Gleixner 已提交
1877

1878
	return perf_read_hw(event, buf, count);
T
Thomas Gleixner 已提交
1879 1880 1881 1882
}

static unsigned int perf_poll(struct file *file, poll_table *wait)
{
1883
	struct perf_event *event = file->private_data;
P
Peter Zijlstra 已提交
1884
	struct perf_mmap_data *data;
1885
	unsigned int events = POLL_HUP;
P
Peter Zijlstra 已提交
1886 1887

	rcu_read_lock();
1888
	data = rcu_dereference(event->data);
P
Peter Zijlstra 已提交
1889
	if (data)
1890
		events = atomic_xchg(&data->poll, 0);
P
Peter Zijlstra 已提交
1891
	rcu_read_unlock();
T
Thomas Gleixner 已提交
1892

1893
	poll_wait(file, &event->waitq, wait);
T
Thomas Gleixner 已提交
1894 1895 1896 1897

	return events;
}

1898
static void perf_event_reset(struct perf_event *event)
1899
{
1900 1901 1902
	(void)perf_event_read(event);
	atomic64_set(&event->count, 0);
	perf_event_update_userpage(event);
P
Peter Zijlstra 已提交
1903 1904
}

1905
/*
1906 1907 1908 1909
 * Holding the top-level event's child_mutex means that any
 * descendant process that has inherited this event will block
 * in sync_child_event if it goes to exit, thus satisfying the
 * task existence requirements of perf_event_enable/disable.
1910
 */
1911 1912
static void perf_event_for_each_child(struct perf_event *event,
					void (*func)(struct perf_event *))
P
Peter Zijlstra 已提交
1913
{
1914
	struct perf_event *child;
P
Peter Zijlstra 已提交
1915

1916 1917 1918 1919
	WARN_ON_ONCE(event->ctx->parent_ctx);
	mutex_lock(&event->child_mutex);
	func(event);
	list_for_each_entry(child, &event->child_list, child_list)
P
Peter Zijlstra 已提交
1920
		func(child);
1921
	mutex_unlock(&event->child_mutex);
P
Peter Zijlstra 已提交
1922 1923
}

1924 1925
static void perf_event_for_each(struct perf_event *event,
				  void (*func)(struct perf_event *))
P
Peter Zijlstra 已提交
1926
{
1927 1928
	struct perf_event_context *ctx = event->ctx;
	struct perf_event *sibling;
P
Peter Zijlstra 已提交
1929

1930 1931
	WARN_ON_ONCE(ctx->parent_ctx);
	mutex_lock(&ctx->mutex);
1932
	event = event->group_leader;
1933

1934 1935 1936 1937
	perf_event_for_each_child(event, func);
	func(event);
	list_for_each_entry(sibling, &event->sibling_list, group_entry)
		perf_event_for_each_child(event, func);
1938
	mutex_unlock(&ctx->mutex);
1939 1940
}

1941
static int perf_event_period(struct perf_event *event, u64 __user *arg)
1942
{
1943
	struct perf_event_context *ctx = event->ctx;
1944 1945 1946 1947
	unsigned long size;
	int ret = 0;
	u64 value;

1948
	if (!event->attr.sample_period)
1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
		return -EINVAL;

	size = copy_from_user(&value, arg, sizeof(value));
	if (size != sizeof(value))
		return -EFAULT;

	if (!value)
		return -EINVAL;

	spin_lock_irq(&ctx->lock);
1959 1960
	if (event->attr.freq) {
		if (value > sysctl_perf_event_sample_rate) {
1961 1962 1963 1964
			ret = -EINVAL;
			goto unlock;
		}

1965
		event->attr.sample_freq = value;
1966
	} else {
1967 1968
		event->attr.sample_period = value;
		event->hw.sample_period = value;
1969 1970 1971 1972 1973 1974 1975
	}
unlock:
	spin_unlock_irq(&ctx->lock);

	return ret;
}

1976
int perf_event_set_output(struct perf_event *event, int output_fd);
1977

1978 1979
static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
1980 1981
	struct perf_event *event = file->private_data;
	void (*func)(struct perf_event *);
P
Peter Zijlstra 已提交
1982
	u32 flags = arg;
1983 1984

	switch (cmd) {
1985 1986
	case PERF_EVENT_IOC_ENABLE:
		func = perf_event_enable;
1987
		break;
1988 1989
	case PERF_EVENT_IOC_DISABLE:
		func = perf_event_disable;
1990
		break;
1991 1992
	case PERF_EVENT_IOC_RESET:
		func = perf_event_reset;
1993
		break;
P
Peter Zijlstra 已提交
1994

1995 1996
	case PERF_EVENT_IOC_REFRESH:
		return perf_event_refresh(event, arg);
1997

1998 1999
	case PERF_EVENT_IOC_PERIOD:
		return perf_event_period(event, (u64 __user *)arg);
2000

2001 2002
	case PERF_EVENT_IOC_SET_OUTPUT:
		return perf_event_set_output(event, arg);
2003

2004
	default:
P
Peter Zijlstra 已提交
2005
		return -ENOTTY;
2006
	}
P
Peter Zijlstra 已提交
2007 2008

	if (flags & PERF_IOC_FLAG_GROUP)
2009
		perf_event_for_each(event, func);
P
Peter Zijlstra 已提交
2010
	else
2011
		perf_event_for_each_child(event, func);
P
Peter Zijlstra 已提交
2012 2013

	return 0;
2014 2015
}

2016
int perf_event_task_enable(void)
2017
{
2018
	struct perf_event *event;
2019

2020 2021 2022 2023
	mutex_lock(&current->perf_event_mutex);
	list_for_each_entry(event, &current->perf_event_list, owner_entry)
		perf_event_for_each_child(event, perf_event_enable);
	mutex_unlock(&current->perf_event_mutex);
2024 2025 2026 2027

	return 0;
}

2028
int perf_event_task_disable(void)
2029
{
2030
	struct perf_event *event;
2031

2032 2033 2034 2035
	mutex_lock(&current->perf_event_mutex);
	list_for_each_entry(event, &current->perf_event_list, owner_entry)
		perf_event_for_each_child(event, perf_event_disable);
	mutex_unlock(&current->perf_event_mutex);
2036 2037 2038 2039

	return 0;
}

2040 2041
#ifndef PERF_EVENT_INDEX_OFFSET
# define PERF_EVENT_INDEX_OFFSET 0
I
Ingo Molnar 已提交
2042 2043
#endif

2044
static int perf_event_index(struct perf_event *event)
2045
{
2046
	if (event->state != PERF_EVENT_STATE_ACTIVE)
2047 2048
		return 0;

2049
	return event->hw.idx + 1 - PERF_EVENT_INDEX_OFFSET;
2050 2051
}

2052 2053 2054 2055 2056
/*
 * Callers need to ensure there can be no nesting of this function, otherwise
 * the seqlock logic goes bad. We can not serialize this because the arch
 * code calls this from NMI context.
 */
2057
void perf_event_update_userpage(struct perf_event *event)
2058
{
2059
	struct perf_event_mmap_page *userpg;
2060
	struct perf_mmap_data *data;
2061 2062

	rcu_read_lock();
2063
	data = rcu_dereference(event->data);
2064 2065 2066 2067
	if (!data)
		goto unlock;

	userpg = data->user_page;
2068

2069 2070 2071 2072 2073
	/*
	 * Disable preemption so as to not let the corresponding user-space
	 * spin too long if we get preempted.
	 */
	preempt_disable();
2074
	++userpg->lock;
2075
	barrier();
2076 2077 2078 2079
	userpg->index = perf_event_index(event);
	userpg->offset = atomic64_read(&event->count);
	if (event->state == PERF_EVENT_STATE_ACTIVE)
		userpg->offset -= atomic64_read(&event->hw.prev_count);
2080

2081 2082
	userpg->time_enabled = event->total_time_enabled +
			atomic64_read(&event->child_total_time_enabled);
2083

2084 2085
	userpg->time_running = event->total_time_running +
			atomic64_read(&event->child_total_time_running);
2086

2087
	barrier();
2088
	++userpg->lock;
2089
	preempt_enable();
2090
unlock:
2091
	rcu_read_unlock();
2092 2093 2094 2095
}

static int perf_mmap_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
2096
	struct perf_event *event = vma->vm_file->private_data;
2097 2098 2099
	struct perf_mmap_data *data;
	int ret = VM_FAULT_SIGBUS;

2100 2101 2102 2103 2104 2105
	if (vmf->flags & FAULT_FLAG_MKWRITE) {
		if (vmf->pgoff == 0)
			ret = 0;
		return ret;
	}

2106
	rcu_read_lock();
2107
	data = rcu_dereference(event->data);
2108 2109 2110 2111 2112 2113 2114
	if (!data)
		goto unlock;

	if (vmf->pgoff == 0) {
		vmf->page = virt_to_page(data->user_page);
	} else {
		int nr = vmf->pgoff - 1;
2115

2116 2117
		if ((unsigned)nr > data->nr_pages)
			goto unlock;
2118

2119 2120 2121
		if (vmf->flags & FAULT_FLAG_WRITE)
			goto unlock;

2122 2123
		vmf->page = virt_to_page(data->data_pages[nr]);
	}
2124

2125
	get_page(vmf->page);
2126 2127 2128
	vmf->page->mapping = vma->vm_file->f_mapping;
	vmf->page->index   = vmf->pgoff;

2129 2130 2131 2132 2133 2134 2135
	ret = 0;
unlock:
	rcu_read_unlock();

	return ret;
}

2136
static int perf_mmap_data_alloc(struct perf_event *event, int nr_pages)
2137 2138 2139 2140 2141
{
	struct perf_mmap_data *data;
	unsigned long size;
	int i;

2142
	WARN_ON(atomic_read(&event->mmap_count));
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161

	size = sizeof(struct perf_mmap_data);
	size += nr_pages * sizeof(void *);

	data = kzalloc(size, GFP_KERNEL);
	if (!data)
		goto fail;

	data->user_page = (void *)get_zeroed_page(GFP_KERNEL);
	if (!data->user_page)
		goto fail_user_page;

	for (i = 0; i < nr_pages; i++) {
		data->data_pages[i] = (void *)get_zeroed_page(GFP_KERNEL);
		if (!data->data_pages[i])
			goto fail_data_pages;
	}

	data->nr_pages = nr_pages;
2162
	atomic_set(&data->lock, -1);
2163

2164
	if (event->attr.watermark) {
2165
		data->watermark = min_t(long, PAGE_SIZE * nr_pages,
2166
				      event->attr.wakeup_watermark);
2167 2168 2169 2170
	}
	if (!data->watermark)
		data->watermark = max(PAGE_SIZE, PAGE_SIZE * nr_pages / 4);

2171
	rcu_assign_pointer(event->data, data);
2172

2173
	return 0;
2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187

fail_data_pages:
	for (i--; i >= 0; i--)
		free_page((unsigned long)data->data_pages[i]);

	free_page((unsigned long)data->user_page);

fail_user_page:
	kfree(data);

fail:
	return -ENOMEM;
}

2188 2189
static void perf_mmap_free_page(unsigned long addr)
{
K
Kevin Cernekee 已提交
2190
	struct page *page = virt_to_page((void *)addr);
2191 2192 2193 2194 2195

	page->mapping = NULL;
	__free_page(page);
}

2196 2197
static void __perf_mmap_data_free(struct rcu_head *rcu_head)
{
2198
	struct perf_mmap_data *data;
2199 2200
	int i;

2201 2202
	data = container_of(rcu_head, struct perf_mmap_data, rcu_head);

2203
	perf_mmap_free_page((unsigned long)data->user_page);
2204
	for (i = 0; i < data->nr_pages; i++)
2205 2206
		perf_mmap_free_page((unsigned long)data->data_pages[i]);

2207 2208 2209
	kfree(data);
}

2210
static void perf_mmap_data_free(struct perf_event *event)
2211
{
2212
	struct perf_mmap_data *data = event->data;
2213

2214
	WARN_ON(atomic_read(&event->mmap_count));
2215

2216
	rcu_assign_pointer(event->data, NULL);
2217 2218 2219 2220 2221
	call_rcu(&data->rcu_head, __perf_mmap_data_free);
}

static void perf_mmap_open(struct vm_area_struct *vma)
{
2222
	struct perf_event *event = vma->vm_file->private_data;
2223

2224
	atomic_inc(&event->mmap_count);
2225 2226 2227 2228
}

static void perf_mmap_close(struct vm_area_struct *vma)
{
2229
	struct perf_event *event = vma->vm_file->private_data;
2230

2231 2232
	WARN_ON_ONCE(event->ctx->parent_ctx);
	if (atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) {
2233 2234
		struct user_struct *user = current_user();

2235 2236 2237 2238
		atomic_long_sub(event->data->nr_pages + 1, &user->locked_vm);
		vma->vm_mm->locked_vm -= event->data->nr_locked;
		perf_mmap_data_free(event);
		mutex_unlock(&event->mmap_mutex);
2239
	}
2240 2241
}

2242
static const struct vm_operations_struct perf_mmap_vmops = {
2243 2244 2245 2246
	.open		= perf_mmap_open,
	.close		= perf_mmap_close,
	.fault		= perf_mmap_fault,
	.page_mkwrite	= perf_mmap_fault,
2247 2248 2249 2250
};

static int perf_mmap(struct file *file, struct vm_area_struct *vma)
{
2251
	struct perf_event *event = file->private_data;
2252
	unsigned long user_locked, user_lock_limit;
2253
	struct user_struct *user = current_user();
2254
	unsigned long locked, lock_limit;
2255 2256
	unsigned long vma_size;
	unsigned long nr_pages;
2257
	long user_extra, extra;
2258
	int ret = 0;
2259

2260
	if (!(vma->vm_flags & VM_SHARED))
2261
		return -EINVAL;
2262 2263 2264 2265

	vma_size = vma->vm_end - vma->vm_start;
	nr_pages = (vma_size / PAGE_SIZE) - 1;

2266 2267 2268 2269 2270
	/*
	 * If we have data pages ensure they're a power-of-two number, so we
	 * can do bitmasks instead of modulo.
	 */
	if (nr_pages != 0 && !is_power_of_2(nr_pages))
2271 2272
		return -EINVAL;

2273
	if (vma_size != PAGE_SIZE * (1 + nr_pages))
2274 2275
		return -EINVAL;

2276 2277
	if (vma->vm_pgoff != 0)
		return -EINVAL;
2278

2279 2280 2281
	WARN_ON_ONCE(event->ctx->parent_ctx);
	mutex_lock(&event->mmap_mutex);
	if (event->output) {
2282 2283 2284 2285
		ret = -EINVAL;
		goto unlock;
	}

2286 2287
	if (atomic_inc_not_zero(&event->mmap_count)) {
		if (nr_pages != event->data->nr_pages)
2288 2289 2290 2291
			ret = -EINVAL;
		goto unlock;
	}

2292
	user_extra = nr_pages + 1;
2293
	user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10);
I
Ingo Molnar 已提交
2294 2295 2296 2297 2298 2299

	/*
	 * Increase the limit linearly with more CPUs:
	 */
	user_lock_limit *= num_online_cpus();

2300
	user_locked = atomic_long_read(&user->locked_vm) + user_extra;
2301

2302 2303 2304
	extra = 0;
	if (user_locked > user_lock_limit)
		extra = user_locked - user_lock_limit;
2305 2306 2307

	lock_limit = current->signal->rlim[RLIMIT_MEMLOCK].rlim_cur;
	lock_limit >>= PAGE_SHIFT;
2308
	locked = vma->vm_mm->locked_vm + extra;
2309

2310 2311
	if ((locked > lock_limit) && perf_paranoid_tracepoint_raw() &&
		!capable(CAP_IPC_LOCK)) {
2312 2313 2314
		ret = -EPERM;
		goto unlock;
	}
2315

2316 2317
	WARN_ON(event->data);
	ret = perf_mmap_data_alloc(event, nr_pages);
2318 2319 2320
	if (ret)
		goto unlock;

2321
	atomic_set(&event->mmap_count, 1);
2322
	atomic_long_add(user_extra, &user->locked_vm);
2323
	vma->vm_mm->locked_vm += extra;
2324
	event->data->nr_locked = extra;
2325
	if (vma->vm_flags & VM_WRITE)
2326
		event->data->writable = 1;
2327

2328
unlock:
2329
	mutex_unlock(&event->mmap_mutex);
2330 2331 2332

	vma->vm_flags |= VM_RESERVED;
	vma->vm_ops = &perf_mmap_vmops;
2333 2334

	return ret;
2335 2336
}

P
Peter Zijlstra 已提交
2337 2338 2339
static int perf_fasync(int fd, struct file *filp, int on)
{
	struct inode *inode = filp->f_path.dentry->d_inode;
2340
	struct perf_event *event = filp->private_data;
P
Peter Zijlstra 已提交
2341 2342 2343
	int retval;

	mutex_lock(&inode->i_mutex);
2344
	retval = fasync_helper(fd, filp, on, &event->fasync);
P
Peter Zijlstra 已提交
2345 2346 2347 2348 2349 2350 2351 2352
	mutex_unlock(&inode->i_mutex);

	if (retval < 0)
		return retval;

	return 0;
}

T
Thomas Gleixner 已提交
2353 2354 2355 2356
static const struct file_operations perf_fops = {
	.release		= perf_release,
	.read			= perf_read,
	.poll			= perf_poll,
2357 2358
	.unlocked_ioctl		= perf_ioctl,
	.compat_ioctl		= perf_ioctl,
2359
	.mmap			= perf_mmap,
P
Peter Zijlstra 已提交
2360
	.fasync			= perf_fasync,
T
Thomas Gleixner 已提交
2361 2362
};

2363
/*
2364
 * Perf event wakeup
2365 2366 2367 2368 2369
 *
 * If there's data, ensure we set the poll() state and publish everything
 * to user-space before waking everybody up.
 */

2370
void perf_event_wakeup(struct perf_event *event)
2371
{
2372
	wake_up_all(&event->waitq);
2373

2374 2375 2376
	if (event->pending_kill) {
		kill_fasync(&event->fasync, SIGIO, event->pending_kill);
		event->pending_kill = 0;
2377
	}
2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388
}

/*
 * Pending wakeups
 *
 * Handle the case where we need to wakeup up from NMI (or rq->lock) context.
 *
 * The NMI bit means we cannot possibly take locks. Therefore, maintain a
 * single linked list and use cmpxchg() to add entries lockless.
 */

2389
static void perf_pending_event(struct perf_pending_entry *entry)
2390
{
2391 2392
	struct perf_event *event = container_of(entry,
			struct perf_event, pending);
2393

2394 2395 2396
	if (event->pending_disable) {
		event->pending_disable = 0;
		__perf_event_disable(event);
2397 2398
	}

2399 2400 2401
	if (event->pending_wakeup) {
		event->pending_wakeup = 0;
		perf_event_wakeup(event);
2402 2403 2404
	}
}

2405
#define PENDING_TAIL ((struct perf_pending_entry *)-1UL)
2406

2407
static DEFINE_PER_CPU(struct perf_pending_entry *, perf_pending_head) = {
2408 2409 2410
	PENDING_TAIL,
};

2411 2412
static void perf_pending_queue(struct perf_pending_entry *entry,
			       void (*func)(struct perf_pending_entry *))
2413
{
2414
	struct perf_pending_entry **head;
2415

2416
	if (cmpxchg(&entry->next, NULL, PENDING_TAIL) != NULL)
2417 2418
		return;

2419 2420 2421
	entry->func = func;

	head = &get_cpu_var(perf_pending_head);
2422 2423

	do {
2424 2425
		entry->next = *head;
	} while (cmpxchg(head, entry->next, entry) != entry->next);
2426

2427
	set_perf_event_pending();
2428

2429
	put_cpu_var(perf_pending_head);
2430 2431 2432 2433
}

static int __perf_pending_run(void)
{
2434
	struct perf_pending_entry *list;
2435 2436
	int nr = 0;

2437
	list = xchg(&__get_cpu_var(perf_pending_head), PENDING_TAIL);
2438
	while (list != PENDING_TAIL) {
2439 2440
		void (*func)(struct perf_pending_entry *);
		struct perf_pending_entry *entry = list;
2441 2442 2443

		list = list->next;

2444 2445
		func = entry->func;
		entry->next = NULL;
2446 2447 2448 2449 2450 2451 2452
		/*
		 * Ensure we observe the unqueue before we issue the wakeup,
		 * so that we won't be waiting forever.
		 * -- see perf_not_pending().
		 */
		smp_wmb();

2453
		func(entry);
2454 2455 2456 2457 2458 2459
		nr++;
	}

	return nr;
}

2460
static inline int perf_not_pending(struct perf_event *event)
2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474
{
	/*
	 * If we flush on whatever cpu we run, there is a chance we don't
	 * need to wait.
	 */
	get_cpu();
	__perf_pending_run();
	put_cpu();

	/*
	 * Ensure we see the proper queue state before going to sleep
	 * so that we do not miss the wakeup. -- see perf_pending_handle()
	 */
	smp_rmb();
2475
	return event->pending.next == NULL;
2476 2477
}

2478
static void perf_pending_sync(struct perf_event *event)
2479
{
2480
	wait_event(event->waitq, perf_not_pending(event));
2481 2482
}

2483
void perf_event_do_pending(void)
2484 2485 2486 2487
{
	__perf_pending_run();
}

2488 2489 2490 2491
/*
 * Callchain support -- arch specific
 */

2492
__weak struct perf_callchain_entry *perf_callchain(struct pt_regs *regs)
2493 2494 2495 2496
{
	return NULL;
}

2497 2498 2499
/*
 * Output
 */
2500 2501
static bool perf_output_space(struct perf_mmap_data *data, unsigned long tail,
			      unsigned long offset, unsigned long head)
2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518
{
	unsigned long mask;

	if (!data->writable)
		return true;

	mask = (data->nr_pages << PAGE_SHIFT) - 1;

	offset = (offset - tail) & mask;
	head   = (head   - tail) & mask;

	if ((int)(head - offset) < 0)
		return false;

	return true;
}

2519
static void perf_output_wakeup(struct perf_output_handle *handle)
2520
{
2521 2522
	atomic_set(&handle->data->poll, POLL_IN);

2523
	if (handle->nmi) {
2524 2525 2526
		handle->event->pending_wakeup = 1;
		perf_pending_queue(&handle->event->pending,
				   perf_pending_event);
2527
	} else
2528
		perf_event_wakeup(handle->event);
2529 2530
}

2531 2532 2533
/*
 * Curious locking construct.
 *
2534 2535
 * We need to ensure a later event_id doesn't publish a head when a former
 * event_id isn't done writing. However since we need to deal with NMIs we
2536 2537 2538 2539 2540 2541
 * cannot fully serialize things.
 *
 * What we do is serialize between CPUs so we only have to deal with NMI
 * nesting on a single CPU.
 *
 * We only publish the head (and generate a wakeup) when the outer-most
2542
 * event_id completes.
2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
 */
static void perf_output_lock(struct perf_output_handle *handle)
{
	struct perf_mmap_data *data = handle->data;
	int cpu;

	handle->locked = 0;

	local_irq_save(handle->flags);
	cpu = smp_processor_id();

	if (in_nmi() && atomic_read(&data->lock) == cpu)
		return;

2557
	while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2558 2559 2560 2561 2562 2563 2564 2565
		cpu_relax();

	handle->locked = 1;
}

static void perf_output_unlock(struct perf_output_handle *handle)
{
	struct perf_mmap_data *data = handle->data;
2566 2567
	unsigned long head;
	int cpu;
2568

2569
	data->done_head = data->head;
2570 2571 2572 2573 2574 2575 2576 2577 2578 2579

	if (!handle->locked)
		goto out;

again:
	/*
	 * The xchg implies a full barrier that ensures all writes are done
	 * before we publish the new head, matched by a rmb() in userspace when
	 * reading this position.
	 */
2580
	while ((head = atomic_long_xchg(&data->done_head, 0)))
2581 2582 2583
		data->user_page->data_head = head;

	/*
2584
	 * NMI can happen here, which means we can miss a done_head update.
2585 2586
	 */

2587
	cpu = atomic_xchg(&data->lock, -1);
2588 2589 2590 2591 2592
	WARN_ON_ONCE(cpu != smp_processor_id());

	/*
	 * Therefore we have to validate we did not indeed do so.
	 */
2593
	if (unlikely(atomic_long_read(&data->done_head))) {
2594 2595 2596
		/*
		 * Since we had it locked, we can lock it again.
		 */
2597
		while (atomic_cmpxchg(&data->lock, -1, cpu) != -1)
2598 2599 2600 2601 2602
			cpu_relax();

		goto again;
	}

2603
	if (atomic_xchg(&data->wakeup, 0))
2604 2605 2606 2607 2608
		perf_output_wakeup(handle);
out:
	local_irq_restore(handle->flags);
}

2609 2610
void perf_output_copy(struct perf_output_handle *handle,
		      const void *buf, unsigned int len)
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
{
	unsigned int pages_mask;
	unsigned int offset;
	unsigned int size;
	void **pages;

	offset		= handle->offset;
	pages_mask	= handle->data->nr_pages - 1;
	pages		= handle->data->data_pages;

	do {
		unsigned int page_offset;
		int nr;

		nr	    = (offset >> PAGE_SHIFT) & pages_mask;
		page_offset = offset & (PAGE_SIZE - 1);
		size	    = min_t(unsigned int, PAGE_SIZE - page_offset, len);

		memcpy(pages[nr] + page_offset, buf, size);

		len	    -= size;
		buf	    += size;
		offset	    += size;
	} while (len);

	handle->offset = offset;

	/*
	 * Check we didn't copy past our reservation window, taking the
	 * possible unsigned int wrap into account.
	 */
	WARN_ON_ONCE(((long)(handle->head - handle->offset)) < 0);
}

2645
int perf_output_begin(struct perf_output_handle *handle,
2646
		      struct perf_event *event, unsigned int size,
2647
		      int nmi, int sample)
2648
{
2649
	struct perf_event *output_event;
2650
	struct perf_mmap_data *data;
2651
	unsigned long tail, offset, head;
2652 2653 2654 2655 2656 2657
	int have_lost;
	struct {
		struct perf_event_header header;
		u64			 id;
		u64			 lost;
	} lost_event;
2658

2659
	rcu_read_lock();
2660
	/*
2661
	 * For inherited events we send all the output towards the parent.
2662
	 */
2663 2664
	if (event->parent)
		event = event->parent;
2665

2666 2667 2668
	output_event = rcu_dereference(event->output);
	if (output_event)
		event = output_event;
2669

2670
	data = rcu_dereference(event->data);
2671 2672 2673
	if (!data)
		goto out;

2674
	handle->data	= data;
2675
	handle->event	= event;
2676 2677
	handle->nmi	= nmi;
	handle->sample	= sample;
2678

2679
	if (!data->nr_pages)
2680
		goto fail;
2681

2682 2683 2684 2685
	have_lost = atomic_read(&data->lost);
	if (have_lost)
		size += sizeof(lost_event);

2686 2687
	perf_output_lock(handle);

2688
	do {
2689 2690 2691 2692 2693 2694 2695
		/*
		 * Userspace could choose to issue a mb() before updating the
		 * tail pointer. So that all reads will be completed before the
		 * write is issued.
		 */
		tail = ACCESS_ONCE(data->user_page->data_tail);
		smp_rmb();
2696
		offset = head = atomic_long_read(&data->head);
P
Peter Zijlstra 已提交
2697
		head += size;
2698
		if (unlikely(!perf_output_space(data, tail, offset, head)))
2699
			goto fail;
2700
	} while (atomic_long_cmpxchg(&data->head, offset, head) != offset);
2701

2702
	handle->offset	= offset;
2703
	handle->head	= head;
2704

2705
	if (head - tail > data->watermark)
2706
		atomic_set(&data->wakeup, 1);
2707

2708
	if (have_lost) {
2709
		lost_event.header.type = PERF_RECORD_LOST;
2710 2711
		lost_event.header.misc = 0;
		lost_event.header.size = sizeof(lost_event);
2712
		lost_event.id          = event->id;
2713 2714 2715 2716 2717
		lost_event.lost        = atomic_xchg(&data->lost, 0);

		perf_output_put(handle, lost_event);
	}

2718
	return 0;
2719

2720
fail:
2721 2722
	atomic_inc(&data->lost);
	perf_output_unlock(handle);
2723 2724
out:
	rcu_read_unlock();
2725

2726 2727
	return -ENOSPC;
}
2728

2729
void perf_output_end(struct perf_output_handle *handle)
2730
{
2731
	struct perf_event *event = handle->event;
2732 2733
	struct perf_mmap_data *data = handle->data;

2734
	int wakeup_events = event->attr.wakeup_events;
P
Peter Zijlstra 已提交
2735

2736
	if (handle->sample && wakeup_events) {
2737
		int events = atomic_inc_return(&data->events);
P
Peter Zijlstra 已提交
2738
		if (events >= wakeup_events) {
2739
			atomic_sub(wakeup_events, &data->events);
2740
			atomic_set(&data->wakeup, 1);
P
Peter Zijlstra 已提交
2741
		}
2742 2743 2744
	}

	perf_output_unlock(handle);
2745
	rcu_read_unlock();
2746 2747
}

2748
static u32 perf_event_pid(struct perf_event *event, struct task_struct *p)
2749 2750
{
	/*
2751
	 * only top level events have the pid namespace they were created in
2752
	 */
2753 2754
	if (event->parent)
		event = event->parent;
2755

2756
	return task_tgid_nr_ns(p, event->ns);
2757 2758
}

2759
static u32 perf_event_tid(struct perf_event *event, struct task_struct *p)
2760 2761
{
	/*
2762
	 * only top level events have the pid namespace they were created in
2763
	 */
2764 2765
	if (event->parent)
		event = event->parent;
2766

2767
	return task_pid_nr_ns(p, event->ns);
2768 2769
}

2770
static void perf_output_read_one(struct perf_output_handle *handle,
2771
				 struct perf_event *event)
2772
{
2773
	u64 read_format = event->attr.read_format;
2774 2775 2776
	u64 values[4];
	int n = 0;

2777
	values[n++] = atomic64_read(&event->count);
2778
	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2779 2780
		values[n++] = event->total_time_enabled +
			atomic64_read(&event->child_total_time_enabled);
2781 2782
	}
	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2783 2784
		values[n++] = event->total_time_running +
			atomic64_read(&event->child_total_time_running);
2785 2786
	}
	if (read_format & PERF_FORMAT_ID)
2787
		values[n++] = primary_event_id(event);
2788 2789 2790 2791 2792

	perf_output_copy(handle, values, n * sizeof(u64));
}

/*
2793
 * XXX PERF_FORMAT_GROUP vs inherited events seems difficult.
2794 2795
 */
static void perf_output_read_group(struct perf_output_handle *handle,
2796
			    struct perf_event *event)
2797
{
2798 2799
	struct perf_event *leader = event->group_leader, *sub;
	u64 read_format = event->attr.read_format;
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810
	u64 values[5];
	int n = 0;

	values[n++] = 1 + leader->nr_siblings;

	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
		values[n++] = leader->total_time_enabled;

	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
		values[n++] = leader->total_time_running;

2811
	if (leader != event)
2812 2813 2814 2815
		leader->pmu->read(leader);

	values[n++] = atomic64_read(&leader->count);
	if (read_format & PERF_FORMAT_ID)
2816
		values[n++] = primary_event_id(leader);
2817 2818 2819

	perf_output_copy(handle, values, n * sizeof(u64));

2820
	list_for_each_entry(sub, &leader->sibling_list, group_entry) {
2821 2822
		n = 0;

2823
		if (sub != event)
2824 2825 2826 2827
			sub->pmu->read(sub);

		values[n++] = atomic64_read(&sub->count);
		if (read_format & PERF_FORMAT_ID)
2828
			values[n++] = primary_event_id(sub);
2829 2830 2831 2832 2833 2834

		perf_output_copy(handle, values, n * sizeof(u64));
	}
}

static void perf_output_read(struct perf_output_handle *handle,
2835
			     struct perf_event *event)
2836
{
2837 2838
	if (event->attr.read_format & PERF_FORMAT_GROUP)
		perf_output_read_group(handle, event);
2839
	else
2840
		perf_output_read_one(handle, event);
2841 2842
}

2843 2844 2845
void perf_output_sample(struct perf_output_handle *handle,
			struct perf_event_header *header,
			struct perf_sample_data *data,
2846
			struct perf_event *event)
2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876
{
	u64 sample_type = data->type;

	perf_output_put(handle, *header);

	if (sample_type & PERF_SAMPLE_IP)
		perf_output_put(handle, data->ip);

	if (sample_type & PERF_SAMPLE_TID)
		perf_output_put(handle, data->tid_entry);

	if (sample_type & PERF_SAMPLE_TIME)
		perf_output_put(handle, data->time);

	if (sample_type & PERF_SAMPLE_ADDR)
		perf_output_put(handle, data->addr);

	if (sample_type & PERF_SAMPLE_ID)
		perf_output_put(handle, data->id);

	if (sample_type & PERF_SAMPLE_STREAM_ID)
		perf_output_put(handle, data->stream_id);

	if (sample_type & PERF_SAMPLE_CPU)
		perf_output_put(handle, data->cpu_entry);

	if (sample_type & PERF_SAMPLE_PERIOD)
		perf_output_put(handle, data->period);

	if (sample_type & PERF_SAMPLE_READ)
2877
		perf_output_read(handle, event);
2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914

	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
		if (data->callchain) {
			int size = 1;

			if (data->callchain)
				size += data->callchain->nr;

			size *= sizeof(u64);

			perf_output_copy(handle, data->callchain, size);
		} else {
			u64 nr = 0;
			perf_output_put(handle, nr);
		}
	}

	if (sample_type & PERF_SAMPLE_RAW) {
		if (data->raw) {
			perf_output_put(handle, data->raw->size);
			perf_output_copy(handle, data->raw->data,
					 data->raw->size);
		} else {
			struct {
				u32	size;
				u32	data;
			} raw = {
				.size = sizeof(u32),
				.data = 0,
			};
			perf_output_put(handle, raw);
		}
	}
}

void perf_prepare_sample(struct perf_event_header *header,
			 struct perf_sample_data *data,
2915
			 struct perf_event *event,
2916
			 struct pt_regs *regs)
2917
{
2918
	u64 sample_type = event->attr.sample_type;
2919

2920
	data->type = sample_type;
2921

2922
	header->type = PERF_RECORD_SAMPLE;
2923 2924 2925 2926
	header->size = sizeof(*header);

	header->misc = 0;
	header->misc |= perf_misc_flags(regs);
2927

2928
	if (sample_type & PERF_SAMPLE_IP) {
2929 2930 2931
		data->ip = perf_instruction_pointer(regs);

		header->size += sizeof(data->ip);
2932
	}
2933

2934
	if (sample_type & PERF_SAMPLE_TID) {
2935
		/* namespace issues */
2936 2937
		data->tid_entry.pid = perf_event_pid(event, current);
		data->tid_entry.tid = perf_event_tid(event, current);
2938

2939
		header->size += sizeof(data->tid_entry);
2940 2941
	}

2942
	if (sample_type & PERF_SAMPLE_TIME) {
P
Peter Zijlstra 已提交
2943
		data->time = perf_clock();
2944

2945
		header->size += sizeof(data->time);
2946 2947
	}

2948
	if (sample_type & PERF_SAMPLE_ADDR)
2949
		header->size += sizeof(data->addr);
2950

2951
	if (sample_type & PERF_SAMPLE_ID) {
2952
		data->id = primary_event_id(event);
2953

2954 2955 2956 2957
		header->size += sizeof(data->id);
	}

	if (sample_type & PERF_SAMPLE_STREAM_ID) {
2958
		data->stream_id = event->id;
2959 2960 2961

		header->size += sizeof(data->stream_id);
	}
2962

2963
	if (sample_type & PERF_SAMPLE_CPU) {
2964 2965
		data->cpu_entry.cpu		= raw_smp_processor_id();
		data->cpu_entry.reserved	= 0;
2966

2967
		header->size += sizeof(data->cpu_entry);
2968 2969
	}

2970
	if (sample_type & PERF_SAMPLE_PERIOD)
2971
		header->size += sizeof(data->period);
2972

2973
	if (sample_type & PERF_SAMPLE_READ)
2974
		header->size += perf_event_read_size(event);
2975

2976
	if (sample_type & PERF_SAMPLE_CALLCHAIN) {
2977
		int size = 1;
2978

2979 2980 2981 2982 2983 2984
		data->callchain = perf_callchain(regs);

		if (data->callchain)
			size += data->callchain->nr;

		header->size += size * sizeof(u64);
2985 2986
	}

2987
	if (sample_type & PERF_SAMPLE_RAW) {
2988 2989 2990 2991 2992 2993 2994 2995
		int size = sizeof(u32);

		if (data->raw)
			size += data->raw->size;
		else
			size += sizeof(u32);

		WARN_ON_ONCE(size & (sizeof(u64)-1));
2996
		header->size += size;
2997
	}
2998
}
2999

3000
static void perf_event_output(struct perf_event *event, int nmi,
3001 3002 3003 3004 3005
				struct perf_sample_data *data,
				struct pt_regs *regs)
{
	struct perf_output_handle handle;
	struct perf_event_header header;
3006

3007
	perf_prepare_sample(&header, data, event, regs);
P
Peter Zijlstra 已提交
3008

3009
	if (perf_output_begin(&handle, event, header.size, nmi, 1))
3010
		return;
3011

3012
	perf_output_sample(&handle, &header, data, event);
3013

3014
	perf_output_end(&handle);
3015 3016
}

3017
/*
3018
 * read event_id
3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
 */

struct perf_read_event {
	struct perf_event_header	header;

	u32				pid;
	u32				tid;
};

static void
3029
perf_event_read_event(struct perf_event *event,
3030 3031 3032
			struct task_struct *task)
{
	struct perf_output_handle handle;
3033
	struct perf_read_event read_event = {
3034
		.header = {
3035
			.type = PERF_RECORD_READ,
3036
			.misc = 0,
3037
			.size = sizeof(read_event) + perf_event_read_size(event),
3038
		},
3039 3040
		.pid = perf_event_pid(event, task),
		.tid = perf_event_tid(event, task),
3041
	};
3042
	int ret;
3043

3044
	ret = perf_output_begin(&handle, event, read_event.header.size, 0, 0);
3045 3046 3047
	if (ret)
		return;

3048
	perf_output_put(&handle, read_event);
3049
	perf_output_read(&handle, event);
3050

3051 3052 3053
	perf_output_end(&handle);
}

P
Peter Zijlstra 已提交
3054
/*
P
Peter Zijlstra 已提交
3055 3056 3057
 * task tracking -- fork/exit
 *
 * enabled by: attr.comm | attr.mmap | attr.task
P
Peter Zijlstra 已提交
3058 3059
 */

P
Peter Zijlstra 已提交
3060
struct perf_task_event {
3061
	struct task_struct		*task;
3062
	struct perf_event_context	*task_ctx;
P
Peter Zijlstra 已提交
3063 3064 3065 3066 3067 3068

	struct {
		struct perf_event_header	header;

		u32				pid;
		u32				ppid;
P
Peter Zijlstra 已提交
3069 3070
		u32				tid;
		u32				ptid;
3071
		u64				time;
3072
	} event_id;
P
Peter Zijlstra 已提交
3073 3074
};

3075
static void perf_event_task_output(struct perf_event *event,
P
Peter Zijlstra 已提交
3076
				     struct perf_task_event *task_event)
P
Peter Zijlstra 已提交
3077 3078
{
	struct perf_output_handle handle;
3079
	int size;
P
Peter Zijlstra 已提交
3080
	struct task_struct *task = task_event->task;
3081 3082
	int ret;

3083 3084
	size  = task_event->event_id.header.size;
	ret = perf_output_begin(&handle, event, size, 0, 0);
P
Peter Zijlstra 已提交
3085 3086 3087 3088

	if (ret)
		return;

3089 3090
	task_event->event_id.pid = perf_event_pid(event, task);
	task_event->event_id.ppid = perf_event_pid(event, current);
P
Peter Zijlstra 已提交
3091

3092 3093
	task_event->event_id.tid = perf_event_tid(event, task);
	task_event->event_id.ptid = perf_event_tid(event, current);
P
Peter Zijlstra 已提交
3094

3095
	task_event->event_id.time = perf_clock();
3096

3097
	perf_output_put(&handle, task_event->event_id);
3098

P
Peter Zijlstra 已提交
3099 3100 3101
	perf_output_end(&handle);
}

3102
static int perf_event_task_match(struct perf_event *event)
P
Peter Zijlstra 已提交
3103
{
3104
	if (event->attr.comm || event->attr.mmap || event->attr.task)
P
Peter Zijlstra 已提交
3105 3106 3107 3108 3109
		return 1;

	return 0;
}

3110
static void perf_event_task_ctx(struct perf_event_context *ctx,
P
Peter Zijlstra 已提交
3111
				  struct perf_task_event *task_event)
P
Peter Zijlstra 已提交
3112
{
3113
	struct perf_event *event;
P
Peter Zijlstra 已提交
3114 3115 3116 3117 3118

	if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
		return;

	rcu_read_lock();
3119 3120 3121
	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
		if (perf_event_task_match(event))
			perf_event_task_output(event, task_event);
P
Peter Zijlstra 已提交
3122 3123 3124 3125
	}
	rcu_read_unlock();
}

3126
static void perf_event_task_event(struct perf_task_event *task_event)
P
Peter Zijlstra 已提交
3127 3128
{
	struct perf_cpu_context *cpuctx;
3129
	struct perf_event_context *ctx = task_event->task_ctx;
P
Peter Zijlstra 已提交
3130 3131

	cpuctx = &get_cpu_var(perf_cpu_context);
3132
	perf_event_task_ctx(&cpuctx->ctx, task_event);
P
Peter Zijlstra 已提交
3133 3134 3135
	put_cpu_var(perf_cpu_context);

	rcu_read_lock();
3136
	if (!ctx)
3137
		ctx = rcu_dereference(task_event->task->perf_event_ctxp);
P
Peter Zijlstra 已提交
3138
	if (ctx)
3139
		perf_event_task_ctx(ctx, task_event);
P
Peter Zijlstra 已提交
3140 3141 3142
	rcu_read_unlock();
}

3143 3144
static void perf_event_task(struct task_struct *task,
			      struct perf_event_context *task_ctx,
3145
			      int new)
P
Peter Zijlstra 已提交
3146
{
P
Peter Zijlstra 已提交
3147
	struct perf_task_event task_event;
P
Peter Zijlstra 已提交
3148

3149 3150 3151
	if (!atomic_read(&nr_comm_events) &&
	    !atomic_read(&nr_mmap_events) &&
	    !atomic_read(&nr_task_events))
P
Peter Zijlstra 已提交
3152 3153
		return;

P
Peter Zijlstra 已提交
3154
	task_event = (struct perf_task_event){
3155 3156
		.task	  = task,
		.task_ctx = task_ctx,
3157
		.event_id    = {
P
Peter Zijlstra 已提交
3158
			.header = {
3159
				.type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT,
3160
				.misc = 0,
3161
				.size = sizeof(task_event.event_id),
P
Peter Zijlstra 已提交
3162
			},
3163 3164
			/* .pid  */
			/* .ppid */
P
Peter Zijlstra 已提交
3165 3166
			/* .tid  */
			/* .ptid */
P
Peter Zijlstra 已提交
3167 3168 3169
		},
	};

3170
	perf_event_task_event(&task_event);
P
Peter Zijlstra 已提交
3171 3172
}

3173
void perf_event_fork(struct task_struct *task)
P
Peter Zijlstra 已提交
3174
{
3175
	perf_event_task(task, NULL, 1);
P
Peter Zijlstra 已提交
3176 3177
}

3178 3179 3180 3181 3182
/*
 * comm tracking
 */

struct perf_comm_event {
3183 3184
	struct task_struct	*task;
	char			*comm;
3185 3186 3187 3188 3189 3190 3191
	int			comm_size;

	struct {
		struct perf_event_header	header;

		u32				pid;
		u32				tid;
3192
	} event_id;
3193 3194
};

3195
static void perf_event_comm_output(struct perf_event *event,
3196 3197 3198
				     struct perf_comm_event *comm_event)
{
	struct perf_output_handle handle;
3199 3200
	int size = comm_event->event_id.header.size;
	int ret = perf_output_begin(&handle, event, size, 0, 0);
3201 3202 3203 3204

	if (ret)
		return;

3205 3206
	comm_event->event_id.pid = perf_event_pid(event, comm_event->task);
	comm_event->event_id.tid = perf_event_tid(event, comm_event->task);
3207

3208
	perf_output_put(&handle, comm_event->event_id);
3209 3210 3211 3212 3213
	perf_output_copy(&handle, comm_event->comm,
				   comm_event->comm_size);
	perf_output_end(&handle);
}

3214
static int perf_event_comm_match(struct perf_event *event)
3215
{
3216
	if (event->attr.comm)
3217 3218 3219 3220 3221
		return 1;

	return 0;
}

3222
static void perf_event_comm_ctx(struct perf_event_context *ctx,
3223 3224
				  struct perf_comm_event *comm_event)
{
3225
	struct perf_event *event;
3226 3227 3228 3229 3230

	if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
		return;

	rcu_read_lock();
3231 3232 3233
	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
		if (perf_event_comm_match(event))
			perf_event_comm_output(event, comm_event);
3234 3235 3236 3237
	}
	rcu_read_unlock();
}

3238
static void perf_event_comm_event(struct perf_comm_event *comm_event)
3239 3240
{
	struct perf_cpu_context *cpuctx;
3241
	struct perf_event_context *ctx;
3242
	unsigned int size;
3243
	char comm[TASK_COMM_LEN];
3244

3245 3246
	memset(comm, 0, sizeof(comm));
	strncpy(comm, comm_event->task->comm, sizeof(comm));
3247
	size = ALIGN(strlen(comm)+1, sizeof(u64));
3248 3249 3250 3251

	comm_event->comm = comm;
	comm_event->comm_size = size;

3252
	comm_event->event_id.header.size = sizeof(comm_event->event_id) + size;
3253 3254

	cpuctx = &get_cpu_var(perf_cpu_context);
3255
	perf_event_comm_ctx(&cpuctx->ctx, comm_event);
3256
	put_cpu_var(perf_cpu_context);
3257 3258 3259 3260 3261 3262

	rcu_read_lock();
	/*
	 * doesn't really matter which of the child contexts the
	 * events ends up in.
	 */
3263
	ctx = rcu_dereference(current->perf_event_ctxp);
3264
	if (ctx)
3265
		perf_event_comm_ctx(ctx, comm_event);
3266
	rcu_read_unlock();
3267 3268
}

3269
void perf_event_comm(struct task_struct *task)
3270
{
3271 3272
	struct perf_comm_event comm_event;

3273 3274
	if (task->perf_event_ctxp)
		perf_event_enable_on_exec(task);
3275

3276
	if (!atomic_read(&nr_comm_events))
3277
		return;
3278

3279
	comm_event = (struct perf_comm_event){
3280
		.task	= task,
3281 3282
		/* .comm      */
		/* .comm_size */
3283
		.event_id  = {
3284
			.header = {
3285
				.type = PERF_RECORD_COMM,
3286 3287 3288 3289 3290
				.misc = 0,
				/* .size */
			},
			/* .pid */
			/* .tid */
3291 3292 3293
		},
	};

3294
	perf_event_comm_event(&comm_event);
3295 3296
}

3297 3298 3299 3300 3301
/*
 * mmap tracking
 */

struct perf_mmap_event {
3302 3303 3304 3305
	struct vm_area_struct	*vma;

	const char		*file_name;
	int			file_size;
3306 3307 3308 3309 3310 3311 3312 3313 3314

	struct {
		struct perf_event_header	header;

		u32				pid;
		u32				tid;
		u64				start;
		u64				len;
		u64				pgoff;
3315
	} event_id;
3316 3317
};

3318
static void perf_event_mmap_output(struct perf_event *event,
3319 3320 3321
				     struct perf_mmap_event *mmap_event)
{
	struct perf_output_handle handle;
3322 3323
	int size = mmap_event->event_id.header.size;
	int ret = perf_output_begin(&handle, event, size, 0, 0);
3324 3325 3326 3327

	if (ret)
		return;

3328 3329
	mmap_event->event_id.pid = perf_event_pid(event, current);
	mmap_event->event_id.tid = perf_event_tid(event, current);
3330

3331
	perf_output_put(&handle, mmap_event->event_id);
3332 3333
	perf_output_copy(&handle, mmap_event->file_name,
				   mmap_event->file_size);
3334
	perf_output_end(&handle);
3335 3336
}

3337
static int perf_event_mmap_match(struct perf_event *event,
3338 3339
				   struct perf_mmap_event *mmap_event)
{
3340
	if (event->attr.mmap)
3341 3342 3343 3344 3345
		return 1;

	return 0;
}

3346
static void perf_event_mmap_ctx(struct perf_event_context *ctx,
3347 3348
				  struct perf_mmap_event *mmap_event)
{
3349
	struct perf_event *event;
3350 3351 3352 3353 3354

	if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
		return;

	rcu_read_lock();
3355 3356 3357
	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
		if (perf_event_mmap_match(event, mmap_event))
			perf_event_mmap_output(event, mmap_event);
3358 3359 3360 3361
	}
	rcu_read_unlock();
}

3362
static void perf_event_mmap_event(struct perf_mmap_event *mmap_event)
3363 3364
{
	struct perf_cpu_context *cpuctx;
3365
	struct perf_event_context *ctx;
3366 3367
	struct vm_area_struct *vma = mmap_event->vma;
	struct file *file = vma->vm_file;
3368 3369 3370
	unsigned int size;
	char tmp[16];
	char *buf = NULL;
3371
	const char *name;
3372

3373 3374
	memset(tmp, 0, sizeof(tmp));

3375
	if (file) {
3376 3377 3378 3379 3380 3381
		/*
		 * d_path works from the end of the buffer backwards, so we
		 * need to add enough zero bytes after the string to handle
		 * the 64bit alignment we do later.
		 */
		buf = kzalloc(PATH_MAX + sizeof(u64), GFP_KERNEL);
3382 3383 3384 3385
		if (!buf) {
			name = strncpy(tmp, "//enomem", sizeof(tmp));
			goto got_name;
		}
3386
		name = d_path(&file->f_path, buf, PATH_MAX);
3387 3388 3389 3390 3391
		if (IS_ERR(name)) {
			name = strncpy(tmp, "//toolong", sizeof(tmp));
			goto got_name;
		}
	} else {
3392 3393 3394
		if (arch_vma_name(mmap_event->vma)) {
			name = strncpy(tmp, arch_vma_name(mmap_event->vma),
				       sizeof(tmp));
3395
			goto got_name;
3396
		}
3397 3398 3399 3400 3401 3402

		if (!vma->vm_mm) {
			name = strncpy(tmp, "[vdso]", sizeof(tmp));
			goto got_name;
		}

3403 3404 3405 3406 3407
		name = strncpy(tmp, "//anon", sizeof(tmp));
		goto got_name;
	}

got_name:
3408
	size = ALIGN(strlen(name)+1, sizeof(u64));
3409 3410 3411 3412

	mmap_event->file_name = name;
	mmap_event->file_size = size;

3413
	mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size;
3414 3415

	cpuctx = &get_cpu_var(perf_cpu_context);
3416
	perf_event_mmap_ctx(&cpuctx->ctx, mmap_event);
3417 3418
	put_cpu_var(perf_cpu_context);

3419 3420 3421 3422 3423
	rcu_read_lock();
	/*
	 * doesn't really matter which of the child contexts the
	 * events ends up in.
	 */
3424
	ctx = rcu_dereference(current->perf_event_ctxp);
3425
	if (ctx)
3426
		perf_event_mmap_ctx(ctx, mmap_event);
3427 3428
	rcu_read_unlock();

3429 3430 3431
	kfree(buf);
}

3432
void __perf_event_mmap(struct vm_area_struct *vma)
3433
{
3434 3435
	struct perf_mmap_event mmap_event;

3436
	if (!atomic_read(&nr_mmap_events))
3437 3438 3439
		return;

	mmap_event = (struct perf_mmap_event){
3440
		.vma	= vma,
3441 3442
		/* .file_name */
		/* .file_size */
3443
		.event_id  = {
3444
			.header = {
3445
				.type = PERF_RECORD_MMAP,
3446 3447 3448 3449 3450
				.misc = 0,
				/* .size */
			},
			/* .pid */
			/* .tid */
3451 3452 3453
			.start  = vma->vm_start,
			.len    = vma->vm_end - vma->vm_start,
			.pgoff  = vma->vm_pgoff,
3454 3455 3456
		},
	};

3457
	perf_event_mmap_event(&mmap_event);
3458 3459
}

3460 3461 3462 3463
/*
 * IRQ throttle logging
 */

3464
static void perf_log_throttle(struct perf_event *event, int enable)
3465 3466 3467 3468 3469 3470 3471
{
	struct perf_output_handle handle;
	int ret;

	struct {
		struct perf_event_header	header;
		u64				time;
3472
		u64				id;
3473
		u64				stream_id;
3474 3475
	} throttle_event = {
		.header = {
3476
			.type = PERF_RECORD_THROTTLE,
3477 3478 3479
			.misc = 0,
			.size = sizeof(throttle_event),
		},
P
Peter Zijlstra 已提交
3480
		.time		= perf_clock(),
3481 3482
		.id		= primary_event_id(event),
		.stream_id	= event->id,
3483 3484
	};

3485
	if (enable)
3486
		throttle_event.header.type = PERF_RECORD_UNTHROTTLE;
3487

3488
	ret = perf_output_begin(&handle, event, sizeof(throttle_event), 1, 0);
3489 3490 3491 3492 3493 3494 3495
	if (ret)
		return;

	perf_output_put(&handle, throttle_event);
	perf_output_end(&handle);
}

3496
/*
3497
 * Generic event overflow handling, sampling.
3498 3499
 */

3500
static int __perf_event_overflow(struct perf_event *event, int nmi,
3501 3502
				   int throttle, struct perf_sample_data *data,
				   struct pt_regs *regs)
3503
{
3504 3505
	int events = atomic_read(&event->event_limit);
	struct hw_perf_event *hwc = &event->hw;
3506 3507
	int ret = 0;

3508
	throttle = (throttle && event->pmu->unthrottle != NULL);
3509

3510
	if (!throttle) {
3511
		hwc->interrupts++;
3512
	} else {
3513 3514
		if (hwc->interrupts != MAX_INTERRUPTS) {
			hwc->interrupts++;
3515
			if (HZ * hwc->interrupts >
3516
					(u64)sysctl_perf_event_sample_rate) {
3517
				hwc->interrupts = MAX_INTERRUPTS;
3518
				perf_log_throttle(event, 0);
3519 3520 3521 3522
				ret = 1;
			}
		} else {
			/*
3523
			 * Keep re-disabling events even though on the previous
3524
			 * pass we disabled it - just in case we raced with a
3525
			 * sched-in and the event got enabled again:
3526
			 */
3527 3528 3529
			ret = 1;
		}
	}
3530

3531
	if (event->attr.freq) {
P
Peter Zijlstra 已提交
3532
		u64 now = perf_clock();
3533 3534 3535 3536 3537
		s64 delta = now - hwc->freq_stamp;

		hwc->freq_stamp = now;

		if (delta > 0 && delta < TICK_NSEC)
3538
			perf_adjust_period(event, NSEC_PER_SEC / (int)delta);
3539 3540
	}

3541 3542
	/*
	 * XXX event_limit might not quite work as expected on inherited
3543
	 * events
3544 3545
	 */

3546 3547
	event->pending_kill = POLL_IN;
	if (events && atomic_dec_and_test(&event->event_limit)) {
3548
		ret = 1;
3549
		event->pending_kill = POLL_HUP;
3550
		if (nmi) {
3551 3552 3553
			event->pending_disable = 1;
			perf_pending_queue(&event->pending,
					   perf_pending_event);
3554
		} else
3555
			perf_event_disable(event);
3556 3557
	}

3558
	perf_event_output(event, nmi, data, regs);
3559
	return ret;
3560 3561
}

3562
int perf_event_overflow(struct perf_event *event, int nmi,
3563 3564
			  struct perf_sample_data *data,
			  struct pt_regs *regs)
3565
{
3566
	return __perf_event_overflow(event, nmi, 1, data, regs);
3567 3568
}

3569
/*
3570
 * Generic software event infrastructure
3571 3572
 */

3573
/*
3574 3575
 * We directly increment event->count and keep a second value in
 * event->hw.period_left to count intervals. This period event
3576 3577 3578 3579
 * is kept in the range [-sample_period, 0] so that we can use the
 * sign as trigger.
 */

3580
static u64 perf_swevent_set_period(struct perf_event *event)
3581
{
3582
	struct hw_perf_event *hwc = &event->hw;
3583 3584 3585 3586 3587
	u64 period = hwc->last_period;
	u64 nr, offset;
	s64 old, val;

	hwc->last_period = hwc->sample_period;
3588 3589

again:
3590 3591 3592
	old = val = atomic64_read(&hwc->period_left);
	if (val < 0)
		return 0;
3593

3594 3595 3596 3597 3598
	nr = div64_u64(period + val, period);
	offset = nr * period;
	val -= offset;
	if (atomic64_cmpxchg(&hwc->period_left, old, val) != old)
		goto again;
3599

3600
	return nr;
3601 3602
}

3603
static void perf_swevent_overflow(struct perf_event *event,
3604 3605
				    int nmi, struct perf_sample_data *data,
				    struct pt_regs *regs)
3606
{
3607
	struct hw_perf_event *hwc = &event->hw;
3608
	int throttle = 0;
3609
	u64 overflow;
3610

3611 3612
	data->period = event->hw.last_period;
	overflow = perf_swevent_set_period(event);
3613

3614 3615
	if (hwc->interrupts == MAX_INTERRUPTS)
		return;
3616

3617
	for (; overflow; overflow--) {
3618
		if (__perf_event_overflow(event, nmi, throttle,
3619
					    data, regs)) {
3620 3621 3622 3623 3624 3625
			/*
			 * We inhibit the overflow from happening when
			 * hwc->interrupts == MAX_INTERRUPTS.
			 */
			break;
		}
3626
		throttle = 1;
3627
	}
3628 3629
}

3630
static void perf_swevent_unthrottle(struct perf_event *event)
3631 3632
{
	/*
3633
	 * Nothing to do, we already reset hwc->interrupts.
3634
	 */
3635
}
3636

3637
static void perf_swevent_add(struct perf_event *event, u64 nr,
3638 3639
			       int nmi, struct perf_sample_data *data,
			       struct pt_regs *regs)
3640
{
3641
	struct hw_perf_event *hwc = &event->hw;
3642

3643
	atomic64_add(nr, &event->count);
3644

3645 3646
	if (!hwc->sample_period)
		return;
3647

3648
	if (!regs)
3649
		return;
3650

3651
	if (!atomic64_add_negative(nr, &hwc->period_left))
3652
		perf_swevent_overflow(event, nmi, data, regs);
3653 3654
}

3655
static int perf_swevent_is_counting(struct perf_event *event)
3656
{
3657
	/*
3658
	 * The event is active, we're good!
3659
	 */
3660
	if (event->state == PERF_EVENT_STATE_ACTIVE)
3661 3662
		return 1;

3663
	/*
3664
	 * The event is off/error, not counting.
3665
	 */
3666
	if (event->state != PERF_EVENT_STATE_INACTIVE)
3667 3668 3669
		return 0;

	/*
3670
	 * The event is inactive, if the context is active
3671 3672
	 * we're part of a group that didn't make it on the 'pmu',
	 * not counting.
3673
	 */
3674
	if (event->ctx->is_active)
3675 3676 3677 3678 3679 3680 3681 3682
		return 0;

	/*
	 * We're inactive and the context is too, this means the
	 * task is scheduled out, we're counting events that happen
	 * to us, like migration events.
	 */
	return 1;
3683 3684
}

3685
static int perf_swevent_match(struct perf_event *event,
P
Peter Zijlstra 已提交
3686
				enum perf_type_id type,
3687
				u32 event_id, struct pt_regs *regs)
3688
{
3689
	if (!perf_swevent_is_counting(event))
3690 3691
		return 0;

3692
	if (event->attr.type != type)
3693
		return 0;
3694
	if (event->attr.config != event_id)
3695 3696
		return 0;

3697
	if (regs) {
3698
		if (event->attr.exclude_user && user_mode(regs))
3699
			return 0;
3700

3701
		if (event->attr.exclude_kernel && !user_mode(regs))
3702 3703
			return 0;
	}
3704 3705 3706 3707

	return 1;
}

3708
static void perf_swevent_ctx_event(struct perf_event_context *ctx,
3709
				     enum perf_type_id type,
3710
				     u32 event_id, u64 nr, int nmi,
3711 3712
				     struct perf_sample_data *data,
				     struct pt_regs *regs)
3713
{
3714
	struct perf_event *event;
3715

3716
	if (system_state != SYSTEM_RUNNING || list_empty(&ctx->event_list))
3717 3718
		return;

P
Peter Zijlstra 已提交
3719
	rcu_read_lock();
3720 3721 3722
	list_for_each_entry_rcu(event, &ctx->event_list, event_entry) {
		if (perf_swevent_match(event, type, event_id, regs))
			perf_swevent_add(event, nr, nmi, data, regs);
3723
	}
P
Peter Zijlstra 已提交
3724
	rcu_read_unlock();
3725 3726
}

3727
static int *perf_swevent_recursion_context(struct perf_cpu_context *cpuctx)
P
Peter Zijlstra 已提交
3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740
{
	if (in_nmi())
		return &cpuctx->recursion[3];

	if (in_irq())
		return &cpuctx->recursion[2];

	if (in_softirq())
		return &cpuctx->recursion[1];

	return &cpuctx->recursion[0];
}

3741
static void do_perf_sw_event(enum perf_type_id type, u32 event_id,
3742
				    u64 nr, int nmi,
3743 3744
				    struct perf_sample_data *data,
				    struct pt_regs *regs)
3745 3746
{
	struct perf_cpu_context *cpuctx = &get_cpu_var(perf_cpu_context);
3747 3748
	int *recursion = perf_swevent_recursion_context(cpuctx);
	struct perf_event_context *ctx;
P
Peter Zijlstra 已提交
3749 3750 3751 3752 3753 3754

	if (*recursion)
		goto out;

	(*recursion)++;
	barrier();
3755

3756
	perf_swevent_ctx_event(&cpuctx->ctx, type, event_id,
3757
				 nr, nmi, data, regs);
3758 3759 3760 3761 3762
	rcu_read_lock();
	/*
	 * doesn't really matter which of the child contexts the
	 * events ends up in.
	 */
3763
	ctx = rcu_dereference(current->perf_event_ctxp);
3764
	if (ctx)
3765
		perf_swevent_ctx_event(ctx, type, event_id, nr, nmi, data, regs);
3766
	rcu_read_unlock();
3767

P
Peter Zijlstra 已提交
3768 3769 3770 3771
	barrier();
	(*recursion)--;

out:
3772 3773 3774
	put_cpu_var(perf_cpu_context);
}

3775
void __perf_sw_event(u32 event_id, u64 nr, int nmi,
3776
			    struct pt_regs *regs, u64 addr)
3777
{
3778 3779 3780 3781
	struct perf_sample_data data = {
		.addr = addr,
	};

3782
	do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, nmi,
3783
				&data, regs);
3784 3785
}

3786
static void perf_swevent_read(struct perf_event *event)
3787 3788 3789
{
}

3790
static int perf_swevent_enable(struct perf_event *event)
3791
{
3792
	struct hw_perf_event *hwc = &event->hw;
3793 3794 3795

	if (hwc->sample_period) {
		hwc->last_period = hwc->sample_period;
3796
		perf_swevent_set_period(event);
3797
	}
3798 3799 3800
	return 0;
}

3801
static void perf_swevent_disable(struct perf_event *event)
3802 3803 3804
{
}

3805
static const struct pmu perf_ops_generic = {
3806 3807 3808 3809
	.enable		= perf_swevent_enable,
	.disable	= perf_swevent_disable,
	.read		= perf_swevent_read,
	.unthrottle	= perf_swevent_unthrottle,
3810 3811
};

3812
/*
3813
 * hrtimer based swevent callback
3814 3815
 */

3816
static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer)
3817 3818 3819
{
	enum hrtimer_restart ret = HRTIMER_RESTART;
	struct perf_sample_data data;
3820
	struct pt_regs *regs;
3821
	struct perf_event *event;
3822 3823
	u64 period;

3824 3825
	event	= container_of(hrtimer, struct perf_event, hw.hrtimer);
	event->pmu->read(event);
3826 3827

	data.addr = 0;
3828
	regs = get_irq_regs();
3829 3830 3831 3832
	/*
	 * In case we exclude kernel IPs or are somehow not in interrupt
	 * context, provide the next best thing, the user IP.
	 */
3833 3834
	if ((event->attr.exclude_kernel || !regs) &&
			!event->attr.exclude_user)
3835
		regs = task_pt_regs(current);
3836

3837
	if (regs) {
3838
		if (perf_event_overflow(event, 0, &data, regs))
3839 3840 3841
			ret = HRTIMER_NORESTART;
	}

3842
	period = max_t(u64, 10000, event->hw.sample_period);
3843 3844 3845 3846 3847
	hrtimer_forward_now(hrtimer, ns_to_ktime(period));

	return ret;
}

3848
/*
3849
 * Software event: cpu wall time clock
3850 3851
 */

3852
static void cpu_clock_perf_event_update(struct perf_event *event)
3853 3854 3855 3856 3857 3858
{
	int cpu = raw_smp_processor_id();
	s64 prev;
	u64 now;

	now = cpu_clock(cpu);
3859 3860 3861
	prev = atomic64_read(&event->hw.prev_count);
	atomic64_set(&event->hw.prev_count, now);
	atomic64_add(now - prev, &event->count);
3862 3863
}

3864
static int cpu_clock_perf_event_enable(struct perf_event *event)
3865
{
3866
	struct hw_perf_event *hwc = &event->hw;
3867 3868 3869
	int cpu = raw_smp_processor_id();

	atomic64_set(&hwc->prev_count, cpu_clock(cpu));
3870
	hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3871
	hwc->hrtimer.function = perf_swevent_hrtimer;
3872 3873
	if (hwc->sample_period) {
		u64 period = max_t(u64, 10000, hwc->sample_period);
3874
		__hrtimer_start_range_ns(&hwc->hrtimer,
3875
				ns_to_ktime(period), 0,
3876 3877 3878 3879 3880 3881
				HRTIMER_MODE_REL, 0);
	}

	return 0;
}

3882
static void cpu_clock_perf_event_disable(struct perf_event *event)
3883
{
3884 3885 3886
	if (event->hw.sample_period)
		hrtimer_cancel(&event->hw.hrtimer);
	cpu_clock_perf_event_update(event);
3887 3888
}

3889
static void cpu_clock_perf_event_read(struct perf_event *event)
3890
{
3891
	cpu_clock_perf_event_update(event);
3892 3893
}

3894
static const struct pmu perf_ops_cpu_clock = {
3895 3896 3897
	.enable		= cpu_clock_perf_event_enable,
	.disable	= cpu_clock_perf_event_disable,
	.read		= cpu_clock_perf_event_read,
3898 3899
};

3900
/*
3901
 * Software event: task time clock
3902 3903
 */

3904
static void task_clock_perf_event_update(struct perf_event *event, u64 now)
I
Ingo Molnar 已提交
3905
{
3906
	u64 prev;
I
Ingo Molnar 已提交
3907 3908
	s64 delta;

3909
	prev = atomic64_xchg(&event->hw.prev_count, now);
I
Ingo Molnar 已提交
3910
	delta = now - prev;
3911
	atomic64_add(delta, &event->count);
3912 3913
}

3914
static int task_clock_perf_event_enable(struct perf_event *event)
I
Ingo Molnar 已提交
3915
{
3916
	struct hw_perf_event *hwc = &event->hw;
3917 3918
	u64 now;

3919
	now = event->ctx->time;
3920

3921
	atomic64_set(&hwc->prev_count, now);
3922
	hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
3923
	hwc->hrtimer.function = perf_swevent_hrtimer;
3924 3925
	if (hwc->sample_period) {
		u64 period = max_t(u64, 10000, hwc->sample_period);
3926
		__hrtimer_start_range_ns(&hwc->hrtimer,
3927
				ns_to_ktime(period), 0,
3928 3929
				HRTIMER_MODE_REL, 0);
	}
3930 3931

	return 0;
I
Ingo Molnar 已提交
3932 3933
}

3934
static void task_clock_perf_event_disable(struct perf_event *event)
3935
{
3936 3937 3938
	if (event->hw.sample_period)
		hrtimer_cancel(&event->hw.hrtimer);
	task_clock_perf_event_update(event, event->ctx->time);
3939

3940
}
I
Ingo Molnar 已提交
3941

3942
static void task_clock_perf_event_read(struct perf_event *event)
3943
{
3944 3945 3946
	u64 time;

	if (!in_nmi()) {
3947 3948
		update_context_time(event->ctx);
		time = event->ctx->time;
3949 3950
	} else {
		u64 now = perf_clock();
3951 3952
		u64 delta = now - event->ctx->timestamp;
		time = event->ctx->time + delta;
3953 3954
	}

3955
	task_clock_perf_event_update(event, time);
3956 3957
}

3958
static const struct pmu perf_ops_task_clock = {
3959 3960 3961
	.enable		= task_clock_perf_event_enable,
	.disable	= task_clock_perf_event_disable,
	.read		= task_clock_perf_event_read,
3962 3963
};

3964
#ifdef CONFIG_EVENT_PROFILE
3965
void perf_tp_event(int event_id, u64 addr, u64 count, void *record,
3966
			  int entry_size)
3967
{
3968
	struct perf_raw_record raw = {
3969
		.size = entry_size,
3970
		.data = record,
3971 3972
	};

3973
	struct perf_sample_data data = {
3974
		.addr = addr,
3975
		.raw = &raw,
3976
	};
3977

3978 3979 3980 3981
	struct pt_regs *regs = get_irq_regs();

	if (!regs)
		regs = task_pt_regs(current);
3982

3983
	do_perf_sw_event(PERF_TYPE_TRACEPOINT, event_id, count, 1,
3984
				&data, regs);
3985
}
3986
EXPORT_SYMBOL_GPL(perf_tp_event);
3987 3988 3989 3990

extern int ftrace_profile_enable(int);
extern void ftrace_profile_disable(int);

3991
static void tp_perf_event_destroy(struct perf_event *event)
3992
{
3993
	ftrace_profile_disable(event->attr.config);
3994 3995
}

3996
static const struct pmu *tp_perf_event_init(struct perf_event *event)
3997
{
3998 3999 4000 4001
	/*
	 * Raw tracepoint data is a severe data leak, only allow root to
	 * have these.
	 */
4002
	if ((event->attr.sample_type & PERF_SAMPLE_RAW) &&
4003
			perf_paranoid_tracepoint_raw() &&
4004 4005 4006
			!capable(CAP_SYS_ADMIN))
		return ERR_PTR(-EPERM);

4007
	if (ftrace_profile_enable(event->attr.config))
4008 4009
		return NULL;

4010
	event->destroy = tp_perf_event_destroy;
4011 4012 4013 4014

	return &perf_ops_generic;
}
#else
4015
static const struct pmu *tp_perf_event_init(struct perf_event *event)
4016 4017 4018 4019 4020
{
	return NULL;
}
#endif

4021
atomic_t perf_swevent_enabled[PERF_COUNT_SW_MAX];
4022

4023
static void sw_perf_event_destroy(struct perf_event *event)
4024
{
4025
	u64 event_id = event->attr.config;
4026

4027
	WARN_ON(event->parent);
4028

4029
	atomic_dec(&perf_swevent_enabled[event_id]);
4030 4031
}

4032
static const struct pmu *sw_perf_event_init(struct perf_event *event)
4033
{
4034
	const struct pmu *pmu = NULL;
4035
	u64 event_id = event->attr.config;
4036

4037
	/*
4038
	 * Software events (currently) can't in general distinguish
4039 4040 4041 4042 4043
	 * between user, kernel and hypervisor events.
	 * However, context switches and cpu migrations are considered
	 * to be kernel events, and page faults are never hypervisor
	 * events.
	 */
4044
	switch (event_id) {
4045
	case PERF_COUNT_SW_CPU_CLOCK:
4046
		pmu = &perf_ops_cpu_clock;
4047

4048
		break;
4049
	case PERF_COUNT_SW_TASK_CLOCK:
4050
		/*
4051 4052
		 * If the user instantiates this as a per-cpu event,
		 * use the cpu_clock event instead.
4053
		 */
4054
		if (event->ctx->task)
4055
			pmu = &perf_ops_task_clock;
4056
		else
4057
			pmu = &perf_ops_cpu_clock;
4058

4059
		break;
4060 4061 4062 4063 4064
	case PERF_COUNT_SW_PAGE_FAULTS:
	case PERF_COUNT_SW_PAGE_FAULTS_MIN:
	case PERF_COUNT_SW_PAGE_FAULTS_MAJ:
	case PERF_COUNT_SW_CONTEXT_SWITCHES:
	case PERF_COUNT_SW_CPU_MIGRATIONS:
4065 4066 4067
		if (!event->parent) {
			atomic_inc(&perf_swevent_enabled[event_id]);
			event->destroy = sw_perf_event_destroy;
4068
		}
4069
		pmu = &perf_ops_generic;
4070
		break;
4071
	}
4072

4073
	return pmu;
4074 4075
}

T
Thomas Gleixner 已提交
4076
/*
4077
 * Allocate and initialize a event structure
T
Thomas Gleixner 已提交
4078
 */
4079 4080
static struct perf_event *
perf_event_alloc(struct perf_event_attr *attr,
4081
		   int cpu,
4082 4083 4084
		   struct perf_event_context *ctx,
		   struct perf_event *group_leader,
		   struct perf_event *parent_event,
4085
		   gfp_t gfpflags)
T
Thomas Gleixner 已提交
4086
{
4087
	const struct pmu *pmu;
4088 4089
	struct perf_event *event;
	struct hw_perf_event *hwc;
4090
	long err;
T
Thomas Gleixner 已提交
4091

4092 4093
	event = kzalloc(sizeof(*event), gfpflags);
	if (!event)
4094
		return ERR_PTR(-ENOMEM);
T
Thomas Gleixner 已提交
4095

4096
	/*
4097
	 * Single events are their own group leaders, with an
4098 4099 4100
	 * empty sibling list:
	 */
	if (!group_leader)
4101
		group_leader = event;
4102

4103 4104
	mutex_init(&event->child_mutex);
	INIT_LIST_HEAD(&event->child_list);
4105

4106 4107 4108 4109
	INIT_LIST_HEAD(&event->group_entry);
	INIT_LIST_HEAD(&event->event_entry);
	INIT_LIST_HEAD(&event->sibling_list);
	init_waitqueue_head(&event->waitq);
T
Thomas Gleixner 已提交
4110

4111
	mutex_init(&event->mmap_mutex);
4112

4113 4114 4115 4116 4117 4118
	event->cpu		= cpu;
	event->attr		= *attr;
	event->group_leader	= group_leader;
	event->pmu		= NULL;
	event->ctx		= ctx;
	event->oncpu		= -1;
4119

4120
	event->parent		= parent_event;
4121

4122 4123
	event->ns		= get_pid_ns(current->nsproxy->pid_ns);
	event->id		= atomic64_inc_return(&perf_event_id);
4124

4125
	event->state		= PERF_EVENT_STATE_INACTIVE;
4126

4127
	if (attr->disabled)
4128
		event->state = PERF_EVENT_STATE_OFF;
4129

4130
	pmu = NULL;
4131

4132
	hwc = &event->hw;
4133
	hwc->sample_period = attr->sample_period;
4134
	if (attr->freq && attr->sample_freq)
4135
		hwc->sample_period = 1;
4136
	hwc->last_period = hwc->sample_period;
4137 4138

	atomic64_set(&hwc->period_left, hwc->sample_period);
4139

4140
	/*
4141
	 * we currently do not support PERF_FORMAT_GROUP on inherited events
4142
	 */
4143
	if (attr->inherit && (attr->read_format & PERF_FORMAT_GROUP))
4144 4145
		goto done;

4146
	switch (attr->type) {
4147
	case PERF_TYPE_RAW:
4148
	case PERF_TYPE_HARDWARE:
4149
	case PERF_TYPE_HW_CACHE:
4150
		pmu = hw_perf_event_init(event);
4151 4152 4153
		break;

	case PERF_TYPE_SOFTWARE:
4154
		pmu = sw_perf_event_init(event);
4155 4156 4157
		break;

	case PERF_TYPE_TRACEPOINT:
4158
		pmu = tp_perf_event_init(event);
4159
		break;
4160 4161 4162

	default:
		break;
4163
	}
4164 4165
done:
	err = 0;
4166
	if (!pmu)
4167
		err = -EINVAL;
4168 4169
	else if (IS_ERR(pmu))
		err = PTR_ERR(pmu);
4170

4171
	if (err) {
4172 4173 4174
		if (event->ns)
			put_pid_ns(event->ns);
		kfree(event);
4175
		return ERR_PTR(err);
I
Ingo Molnar 已提交
4176
	}
4177

4178
	event->pmu = pmu;
T
Thomas Gleixner 已提交
4179

4180 4181 4182 4183 4184 4185 4186 4187
	if (!event->parent) {
		atomic_inc(&nr_events);
		if (event->attr.mmap)
			atomic_inc(&nr_mmap_events);
		if (event->attr.comm)
			atomic_inc(&nr_comm_events);
		if (event->attr.task)
			atomic_inc(&nr_task_events);
4188
	}
4189

4190
	return event;
T
Thomas Gleixner 已提交
4191 4192
}

4193 4194
static int perf_copy_attr(struct perf_event_attr __user *uattr,
			  struct perf_event_attr *attr)
4195 4196
{
	u32 size;
4197
	int ret;
4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221

	if (!access_ok(VERIFY_WRITE, uattr, PERF_ATTR_SIZE_VER0))
		return -EFAULT;

	/*
	 * zero the full structure, so that a short copy will be nice.
	 */
	memset(attr, 0, sizeof(*attr));

	ret = get_user(size, &uattr->size);
	if (ret)
		return ret;

	if (size > PAGE_SIZE)	/* silly large */
		goto err_size;

	if (!size)		/* abi compat */
		size = PERF_ATTR_SIZE_VER0;

	if (size < PERF_ATTR_SIZE_VER0)
		goto err_size;

	/*
	 * If we're handed a bigger struct than we know of,
4222 4223 4224
	 * ensure all the unknown bits are 0 - i.e. new
	 * user-space does not rely on any kernel feature
	 * extensions we dont know about yet.
4225 4226
	 */
	if (size > sizeof(*attr)) {
4227 4228 4229
		unsigned char __user *addr;
		unsigned char __user *end;
		unsigned char val;
4230

4231 4232
		addr = (void __user *)uattr + sizeof(*attr);
		end  = (void __user *)uattr + size;
4233

4234
		for (; addr < end; addr++) {
4235 4236 4237 4238 4239 4240
			ret = get_user(val, addr);
			if (ret)
				return ret;
			if (val)
				goto err_size;
		}
4241
		size = sizeof(*attr);
4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272
	}

	ret = copy_from_user(attr, uattr, size);
	if (ret)
		return -EFAULT;

	/*
	 * If the type exists, the corresponding creation will verify
	 * the attr->config.
	 */
	if (attr->type >= PERF_TYPE_MAX)
		return -EINVAL;

	if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3)
		return -EINVAL;

	if (attr->sample_type & ~(PERF_SAMPLE_MAX-1))
		return -EINVAL;

	if (attr->read_format & ~(PERF_FORMAT_MAX-1))
		return -EINVAL;

out:
	return ret;

err_size:
	put_user(sizeof(*attr), &uattr->size);
	ret = -E2BIG;
	goto out;
}

4273
int perf_event_set_output(struct perf_event *event, int output_fd)
4274
{
4275
	struct perf_event *output_event = NULL;
4276
	struct file *output_file = NULL;
4277
	struct perf_event *old_output;
4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290
	int fput_needed = 0;
	int ret = -EINVAL;

	if (!output_fd)
		goto set;

	output_file = fget_light(output_fd, &fput_needed);
	if (!output_file)
		return -EBADF;

	if (output_file->f_op != &perf_fops)
		goto out;

4291
	output_event = output_file->private_data;
4292 4293

	/* Don't chain output fds */
4294
	if (output_event->output)
4295 4296 4297
		goto out;

	/* Don't set an output fd when we already have an output channel */
4298
	if (event->data)
4299 4300 4301 4302 4303
		goto out;

	atomic_long_inc(&output_file->f_count);

set:
4304 4305 4306 4307
	mutex_lock(&event->mmap_mutex);
	old_output = event->output;
	rcu_assign_pointer(event->output, output_event);
	mutex_unlock(&event->mmap_mutex);
4308 4309 4310 4311

	if (old_output) {
		/*
		 * we need to make sure no existing perf_output_*()
4312
		 * is still referencing this event.
4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323
		 */
		synchronize_rcu();
		fput(old_output->filp);
	}

	ret = 0;
out:
	fput_light(output_file, fput_needed);
	return ret;
}

T
Thomas Gleixner 已提交
4324
/**
4325
 * sys_perf_event_open - open a performance event, associate it to a task/cpu
I
Ingo Molnar 已提交
4326
 *
4327
 * @attr_uptr:	event_id type attributes for monitoring/sampling
T
Thomas Gleixner 已提交
4328
 * @pid:		target pid
I
Ingo Molnar 已提交
4329
 * @cpu:		target cpu
4330
 * @group_fd:		group leader event fd
T
Thomas Gleixner 已提交
4331
 */
4332 4333
SYSCALL_DEFINE5(perf_event_open,
		struct perf_event_attr __user *, attr_uptr,
4334
		pid_t, pid, int, cpu, int, group_fd, unsigned long, flags)
T
Thomas Gleixner 已提交
4335
{
4336 4337 4338 4339
	struct perf_event *event, *group_leader;
	struct perf_event_attr attr;
	struct perf_event_context *ctx;
	struct file *event_file = NULL;
4340 4341
	struct file *group_file = NULL;
	int fput_needed = 0;
4342
	int fput_needed2 = 0;
4343
	int err;
T
Thomas Gleixner 已提交
4344

4345
	/* for future expandability... */
4346
	if (flags & ~(PERF_FLAG_FD_NO_GROUP | PERF_FLAG_FD_OUTPUT))
4347 4348
		return -EINVAL;

4349 4350 4351
	err = perf_copy_attr(attr_uptr, &attr);
	if (err)
		return err;
4352

4353 4354 4355 4356 4357
	if (!attr.exclude_kernel) {
		if (perf_paranoid_kernel() && !capable(CAP_SYS_ADMIN))
			return -EACCES;
	}

4358
	if (attr.freq) {
4359
		if (attr.sample_freq > sysctl_perf_event_sample_rate)
4360 4361 4362
			return -EINVAL;
	}

4363
	/*
I
Ingo Molnar 已提交
4364 4365 4366 4367 4368 4369 4370
	 * Get the target context (task or percpu):
	 */
	ctx = find_get_context(pid, cpu);
	if (IS_ERR(ctx))
		return PTR_ERR(ctx);

	/*
4371
	 * Look up the group leader (we will attach this event to it):
4372 4373
	 */
	group_leader = NULL;
4374
	if (group_fd != -1 && !(flags & PERF_FLAG_FD_NO_GROUP)) {
4375
		err = -EINVAL;
4376 4377
		group_file = fget_light(group_fd, &fput_needed);
		if (!group_file)
I
Ingo Molnar 已提交
4378
			goto err_put_context;
4379
		if (group_file->f_op != &perf_fops)
I
Ingo Molnar 已提交
4380
			goto err_put_context;
4381 4382 4383

		group_leader = group_file->private_data;
		/*
I
Ingo Molnar 已提交
4384 4385 4386 4387 4388 4389 4390 4391
		 * Do not allow a recursive hierarchy (this new sibling
		 * becoming part of another group-sibling):
		 */
		if (group_leader->group_leader != group_leader)
			goto err_put_context;
		/*
		 * Do not allow to attach to a group in a different
		 * task or CPU context:
4392
		 */
I
Ingo Molnar 已提交
4393 4394
		if (group_leader->ctx != ctx)
			goto err_put_context;
4395 4396 4397
		/*
		 * Only a group leader can be exclusive or pinned
		 */
4398
		if (attr.exclusive || attr.pinned)
4399
			goto err_put_context;
4400 4401
	}

4402
	event = perf_event_alloc(&attr, cpu, ctx, group_leader,
4403
				     NULL, GFP_KERNEL);
4404 4405
	err = PTR_ERR(event);
	if (IS_ERR(event))
T
Thomas Gleixner 已提交
4406 4407
		goto err_put_context;

4408
	err = anon_inode_getfd("[perf_event]", &perf_fops, event, 0);
4409
	if (err < 0)
4410 4411
		goto err_free_put_context;

4412 4413
	event_file = fget_light(err, &fput_needed2);
	if (!event_file)
4414 4415
		goto err_free_put_context;

4416
	if (flags & PERF_FLAG_FD_OUTPUT) {
4417
		err = perf_event_set_output(event, group_fd);
4418 4419
		if (err)
			goto err_fput_free_put_context;
4420 4421
	}

4422
	event->filp = event_file;
4423
	WARN_ON_ONCE(ctx->parent_ctx);
4424
	mutex_lock(&ctx->mutex);
4425
	perf_install_in_context(ctx, event, cpu);
4426
	++ctx->generation;
4427
	mutex_unlock(&ctx->mutex);
4428

4429
	event->owner = current;
4430
	get_task_struct(current);
4431 4432 4433
	mutex_lock(&current->perf_event_mutex);
	list_add_tail(&event->owner_entry, &current->perf_event_list);
	mutex_unlock(&current->perf_event_mutex);
4434

4435
err_fput_free_put_context:
4436
	fput_light(event_file, fput_needed2);
T
Thomas Gleixner 已提交
4437

4438
err_free_put_context:
4439
	if (err < 0)
4440
		kfree(event);
T
Thomas Gleixner 已提交
4441 4442

err_put_context:
4443 4444 4445 4446
	if (err < 0)
		put_ctx(ctx);

	fput_light(group_file, fput_needed);
T
Thomas Gleixner 已提交
4447

4448
	return err;
T
Thomas Gleixner 已提交
4449 4450
}

4451
/*
4452
 * inherit a event from parent task to child task:
4453
 */
4454 4455
static struct perf_event *
inherit_event(struct perf_event *parent_event,
4456
	      struct task_struct *parent,
4457
	      struct perf_event_context *parent_ctx,
4458
	      struct task_struct *child,
4459 4460
	      struct perf_event *group_leader,
	      struct perf_event_context *child_ctx)
4461
{
4462
	struct perf_event *child_event;
4463

4464
	/*
4465 4466
	 * Instead of creating recursive hierarchies of events,
	 * we link inherited events back to the original parent,
4467 4468 4469
	 * which has a filp for sure, which we use as the reference
	 * count:
	 */
4470 4471
	if (parent_event->parent)
		parent_event = parent_event->parent;
4472

4473 4474 4475
	child_event = perf_event_alloc(&parent_event->attr,
					   parent_event->cpu, child_ctx,
					   group_leader, parent_event,
4476
					   GFP_KERNEL);
4477 4478
	if (IS_ERR(child_event))
		return child_event;
4479
	get_ctx(child_ctx);
4480

4481
	/*
4482
	 * Make the child state follow the state of the parent event,
4483
	 * not its attr.disabled bit.  We hold the parent's mutex,
4484
	 * so we won't race with perf_event_{en, dis}able_family.
4485
	 */
4486 4487
	if (parent_event->state >= PERF_EVENT_STATE_INACTIVE)
		child_event->state = PERF_EVENT_STATE_INACTIVE;
4488
	else
4489
		child_event->state = PERF_EVENT_STATE_OFF;
4490

4491 4492
	if (parent_event->attr.freq)
		child_event->hw.sample_period = parent_event->hw.sample_period;
4493

4494 4495 4496
	/*
	 * Link it up in the child's context:
	 */
4497
	add_event_to_ctx(child_event, child_ctx);
4498 4499 4500

	/*
	 * Get a reference to the parent filp - we will fput it
4501
	 * when the child event exits. This is safe to do because
4502 4503 4504
	 * we are in the parent and we know that the filp still
	 * exists and has a nonzero count:
	 */
4505
	atomic_long_inc(&parent_event->filp->f_count);
4506

4507
	/*
4508
	 * Link this into the parent event's child list
4509
	 */
4510 4511 4512 4513
	WARN_ON_ONCE(parent_event->ctx->parent_ctx);
	mutex_lock(&parent_event->child_mutex);
	list_add_tail(&child_event->child_list, &parent_event->child_list);
	mutex_unlock(&parent_event->child_mutex);
4514

4515
	return child_event;
4516 4517
}

4518
static int inherit_group(struct perf_event *parent_event,
4519
	      struct task_struct *parent,
4520
	      struct perf_event_context *parent_ctx,
4521
	      struct task_struct *child,
4522
	      struct perf_event_context *child_ctx)
4523
{
4524 4525 4526
	struct perf_event *leader;
	struct perf_event *sub;
	struct perf_event *child_ctr;
4527

4528
	leader = inherit_event(parent_event, parent, parent_ctx,
4529
				 child, NULL, child_ctx);
4530 4531
	if (IS_ERR(leader))
		return PTR_ERR(leader);
4532 4533
	list_for_each_entry(sub, &parent_event->sibling_list, group_entry) {
		child_ctr = inherit_event(sub, parent, parent_ctx,
4534 4535 4536
					    child, leader, child_ctx);
		if (IS_ERR(child_ctr))
			return PTR_ERR(child_ctr);
4537
	}
4538 4539 4540
	return 0;
}

4541
static void sync_child_event(struct perf_event *child_event,
4542
			       struct task_struct *child)
4543
{
4544
	struct perf_event *parent_event = child_event->parent;
4545
	u64 child_val;
4546

4547 4548
	if (child_event->attr.inherit_stat)
		perf_event_read_event(child_event, child);
4549

4550
	child_val = atomic64_read(&child_event->count);
4551 4552 4553 4554

	/*
	 * Add back the child's count to the parent's count:
	 */
4555 4556 4557 4558 4559
	atomic64_add(child_val, &parent_event->count);
	atomic64_add(child_event->total_time_enabled,
		     &parent_event->child_total_time_enabled);
	atomic64_add(child_event->total_time_running,
		     &parent_event->child_total_time_running);
4560 4561

	/*
4562
	 * Remove this event from the parent's list
4563
	 */
4564 4565 4566 4567
	WARN_ON_ONCE(parent_event->ctx->parent_ctx);
	mutex_lock(&parent_event->child_mutex);
	list_del_init(&child_event->child_list);
	mutex_unlock(&parent_event->child_mutex);
4568 4569

	/*
4570
	 * Release the parent event, if this was the last
4571 4572
	 * reference to it.
	 */
4573
	fput(parent_event->filp);
4574 4575
}

4576
static void
4577 4578
__perf_event_exit_task(struct perf_event *child_event,
			 struct perf_event_context *child_ctx,
4579
			 struct task_struct *child)
4580
{
4581
	struct perf_event *parent_event;
4582

4583 4584
	update_event_times(child_event);
	perf_event_remove_from_context(child_event);
4585

4586
	parent_event = child_event->parent;
4587
	/*
4588
	 * It can happen that parent exits first, and has events
4589
	 * that are still around due to the child reference. These
4590
	 * events need to be zapped - but otherwise linger.
4591
	 */
4592 4593 4594
	if (parent_event) {
		sync_child_event(child_event, child);
		free_event(child_event);
4595
	}
4596 4597 4598
}

/*
4599
 * When a child task exits, feed back event values to parent events.
4600
 */
4601
void perf_event_exit_task(struct task_struct *child)
4602
{
4603 4604
	struct perf_event *child_event, *tmp;
	struct perf_event_context *child_ctx;
4605
	unsigned long flags;
4606

4607 4608
	if (likely(!child->perf_event_ctxp)) {
		perf_event_task(child, NULL, 0);
4609
		return;
P
Peter Zijlstra 已提交
4610
	}
4611

4612
	local_irq_save(flags);
4613 4614 4615 4616 4617 4618
	/*
	 * We can't reschedule here because interrupts are disabled,
	 * and either child is current or it is a task that can't be
	 * scheduled, so we are now safe from rescheduling changing
	 * our context.
	 */
4619 4620
	child_ctx = child->perf_event_ctxp;
	__perf_event_task_sched_out(child_ctx);
4621 4622 4623

	/*
	 * Take the context lock here so that if find_get_context is
4624
	 * reading child->perf_event_ctxp, we wait until it has
4625 4626 4627
	 * incremented the context's refcount before we do put_ctx below.
	 */
	spin_lock(&child_ctx->lock);
4628
	child->perf_event_ctxp = NULL;
4629 4630 4631
	/*
	 * If this context is a clone; unclone it so it can't get
	 * swapped to another process while we're removing all
4632
	 * the events from it.
4633 4634
	 */
	unclone_ctx(child_ctx);
P
Peter Zijlstra 已提交
4635 4636 4637
	spin_unlock_irqrestore(&child_ctx->lock, flags);

	/*
4638 4639 4640
	 * Report the task dead after unscheduling the events so that we
	 * won't get any samples after PERF_RECORD_EXIT. We can however still
	 * get a few PERF_RECORD_READ events.
P
Peter Zijlstra 已提交
4641
	 */
4642
	perf_event_task(child, child_ctx, 0);
4643

4644 4645 4646
	/*
	 * We can recurse on the same lock type through:
	 *
4647 4648 4649
	 *   __perf_event_exit_task()
	 *     sync_child_event()
	 *       fput(parent_event->filp)
4650 4651 4652 4653 4654 4655
	 *         perf_release()
	 *           mutex_lock(&ctx->mutex)
	 *
	 * But since its the parent context it won't be the same instance.
	 */
	mutex_lock_nested(&child_ctx->mutex, SINGLE_DEPTH_NESTING);
4656

4657
again:
4658
	list_for_each_entry_safe(child_event, tmp, &child_ctx->group_list,
4659
				 group_entry)
4660
		__perf_event_exit_task(child_event, child_ctx, child);
4661 4662

	/*
4663
	 * If the last event was a group event, it will have appended all
4664 4665 4666
	 * its siblings to the list, but we obtained 'tmp' before that which
	 * will still point to the list head terminating the iteration.
	 */
4667
	if (!list_empty(&child_ctx->group_list))
4668
		goto again;
4669 4670 4671 4672

	mutex_unlock(&child_ctx->mutex);

	put_ctx(child_ctx);
4673 4674
}

4675 4676 4677 4678
/*
 * free an unexposed, unused context as created by inheritance by
 * init_task below, used by fork() in case of fail.
 */
4679
void perf_event_free_task(struct task_struct *task)
4680
{
4681 4682
	struct perf_event_context *ctx = task->perf_event_ctxp;
	struct perf_event *event, *tmp;
4683 4684 4685 4686 4687 4688

	if (!ctx)
		return;

	mutex_lock(&ctx->mutex);
again:
4689 4690
	list_for_each_entry_safe(event, tmp, &ctx->group_list, group_entry) {
		struct perf_event *parent = event->parent;
4691 4692 4693 4694 4695

		if (WARN_ON_ONCE(!parent))
			continue;

		mutex_lock(&parent->child_mutex);
4696
		list_del_init(&event->child_list);
4697 4698 4699 4700
		mutex_unlock(&parent->child_mutex);

		fput(parent->filp);

4701 4702
		list_del_event(event, ctx);
		free_event(event);
4703 4704
	}

4705
	if (!list_empty(&ctx->group_list))
4706 4707 4708 4709 4710 4711 4712
		goto again;

	mutex_unlock(&ctx->mutex);

	put_ctx(ctx);
}

4713
/*
4714
 * Initialize the perf_event context in task_struct
4715
 */
4716
int perf_event_init_task(struct task_struct *child)
4717
{
4718 4719 4720
	struct perf_event_context *child_ctx, *parent_ctx;
	struct perf_event_context *cloned_ctx;
	struct perf_event *event;
4721
	struct task_struct *parent = current;
4722
	int inherited_all = 1;
4723
	int ret = 0;
4724

4725
	child->perf_event_ctxp = NULL;
4726

4727 4728
	mutex_init(&child->perf_event_mutex);
	INIT_LIST_HEAD(&child->perf_event_list);
4729

4730
	if (likely(!parent->perf_event_ctxp))
4731 4732
		return 0;

4733 4734
	/*
	 * This is executed from the parent task context, so inherit
4735
	 * events that have been marked for cloning.
4736
	 * First allocate and initialize a context for the child.
4737 4738
	 */

4739
	child_ctx = kmalloc(sizeof(struct perf_event_context), GFP_KERNEL);
4740
	if (!child_ctx)
4741
		return -ENOMEM;
4742

4743 4744
	__perf_event_init_context(child_ctx, child);
	child->perf_event_ctxp = child_ctx;
4745
	get_task_struct(child);
4746

4747
	/*
4748 4749
	 * If the parent's context is a clone, pin it so it won't get
	 * swapped under us.
4750
	 */
4751 4752
	parent_ctx = perf_pin_task_context(parent);

4753 4754 4755 4756 4757 4758 4759
	/*
	 * No need to check if parent_ctx != NULL here; since we saw
	 * it non-NULL earlier, the only reason for it to become NULL
	 * is if we exit, and since we're currently in the middle of
	 * a fork we can't be exiting at the same time.
	 */

4760 4761 4762 4763
	/*
	 * Lock the parent list. No need to lock the child - not PID
	 * hashed yet and not running, so nobody can access it.
	 */
4764
	mutex_lock(&parent_ctx->mutex);
4765 4766 4767 4768 4769

	/*
	 * We dont have to disable NMIs - we are only looking at
	 * the list, not manipulating it:
	 */
4770 4771
	list_for_each_entry_rcu(event, &parent_ctx->event_list, event_entry) {
		if (event != event->group_leader)
4772 4773
			continue;

4774
		if (!event->attr.inherit) {
4775
			inherited_all = 0;
4776
			continue;
4777
		}
4778

4779
		ret = inherit_group(event, parent, parent_ctx,
4780 4781
					     child, child_ctx);
		if (ret) {
4782
			inherited_all = 0;
4783
			break;
4784 4785 4786 4787 4788 4789 4790
		}
	}

	if (inherited_all) {
		/*
		 * Mark the child context as a clone of the parent
		 * context, or of whatever the parent is a clone of.
4791 4792
		 * Note that if the parent is a clone, it could get
		 * uncloned at any point, but that doesn't matter
4793
		 * because the list of events and the generation
4794
		 * count can't have changed since we took the mutex.
4795
		 */
4796 4797 4798
		cloned_ctx = rcu_dereference(parent_ctx->parent_ctx);
		if (cloned_ctx) {
			child_ctx->parent_ctx = cloned_ctx;
4799
			child_ctx->parent_gen = parent_ctx->parent_gen;
4800 4801 4802 4803 4804
		} else {
			child_ctx->parent_ctx = parent_ctx;
			child_ctx->parent_gen = parent_ctx->generation;
		}
		get_ctx(child_ctx->parent_ctx);
4805 4806
	}

4807
	mutex_unlock(&parent_ctx->mutex);
4808

4809
	perf_unpin_context(parent_ctx);
4810

4811
	return ret;
4812 4813
}

4814
static void __cpuinit perf_event_init_cpu(int cpu)
T
Thomas Gleixner 已提交
4815
{
4816
	struct perf_cpu_context *cpuctx;
T
Thomas Gleixner 已提交
4817

4818
	cpuctx = &per_cpu(perf_cpu_context, cpu);
4819
	__perf_event_init_context(&cpuctx->ctx, NULL);
T
Thomas Gleixner 已提交
4820

4821
	spin_lock(&perf_resource_lock);
4822
	cpuctx->max_pertask = perf_max_events - perf_reserved_percpu;
4823
	spin_unlock(&perf_resource_lock);
4824

4825
	hw_perf_event_setup(cpu);
T
Thomas Gleixner 已提交
4826 4827 4828
}

#ifdef CONFIG_HOTPLUG_CPU
4829
static void __perf_event_exit_cpu(void *info)
T
Thomas Gleixner 已提交
4830 4831
{
	struct perf_cpu_context *cpuctx = &__get_cpu_var(perf_cpu_context);
4832 4833
	struct perf_event_context *ctx = &cpuctx->ctx;
	struct perf_event *event, *tmp;
T
Thomas Gleixner 已提交
4834

4835 4836
	list_for_each_entry_safe(event, tmp, &ctx->group_list, group_entry)
		__perf_event_remove_from_context(event);
T
Thomas Gleixner 已提交
4837
}
4838
static void perf_event_exit_cpu(int cpu)
T
Thomas Gleixner 已提交
4839
{
4840
	struct perf_cpu_context *cpuctx = &per_cpu(perf_cpu_context, cpu);
4841
	struct perf_event_context *ctx = &cpuctx->ctx;
4842 4843

	mutex_lock(&ctx->mutex);
4844
	smp_call_function_single(cpu, __perf_event_exit_cpu, NULL, 1);
4845
	mutex_unlock(&ctx->mutex);
T
Thomas Gleixner 已提交
4846 4847
}
#else
4848
static inline void perf_event_exit_cpu(int cpu) { }
T
Thomas Gleixner 已提交
4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859
#endif

static int __cpuinit
perf_cpu_notify(struct notifier_block *self, unsigned long action, void *hcpu)
{
	unsigned int cpu = (long)hcpu;

	switch (action) {

	case CPU_UP_PREPARE:
	case CPU_UP_PREPARE_FROZEN:
4860
		perf_event_init_cpu(cpu);
T
Thomas Gleixner 已提交
4861 4862
		break;

4863 4864
	case CPU_ONLINE:
	case CPU_ONLINE_FROZEN:
4865
		hw_perf_event_setup_online(cpu);
4866 4867
		break;

T
Thomas Gleixner 已提交
4868 4869
	case CPU_DOWN_PREPARE:
	case CPU_DOWN_PREPARE_FROZEN:
4870
		perf_event_exit_cpu(cpu);
T
Thomas Gleixner 已提交
4871 4872 4873 4874 4875 4876 4877 4878 4879
		break;

	default:
		break;
	}

	return NOTIFY_OK;
}

4880 4881 4882
/*
 * This has to have a higher priority than migration_notifier in sched.c.
 */
T
Thomas Gleixner 已提交
4883 4884
static struct notifier_block __cpuinitdata perf_cpu_nb = {
	.notifier_call		= perf_cpu_notify,
4885
	.priority		= 20,
T
Thomas Gleixner 已提交
4886 4887
};

4888
void __init perf_event_init(void)
T
Thomas Gleixner 已提交
4889 4890 4891
{
	perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_UP_PREPARE,
			(void *)(long)smp_processor_id());
4892 4893
	perf_cpu_notify(&perf_cpu_nb, (unsigned long)CPU_ONLINE,
			(void *)(long)smp_processor_id());
T
Thomas Gleixner 已提交
4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913
	register_cpu_notifier(&perf_cpu_nb);
}

static ssize_t perf_show_reserve_percpu(struct sysdev_class *class, char *buf)
{
	return sprintf(buf, "%d\n", perf_reserved_percpu);
}

static ssize_t
perf_set_reserve_percpu(struct sysdev_class *class,
			const char *buf,
			size_t count)
{
	struct perf_cpu_context *cpuctx;
	unsigned long val;
	int err, cpu, mpt;

	err = strict_strtoul(buf, 10, &val);
	if (err)
		return err;
4914
	if (val > perf_max_events)
T
Thomas Gleixner 已提交
4915 4916
		return -EINVAL;

4917
	spin_lock(&perf_resource_lock);
T
Thomas Gleixner 已提交
4918 4919 4920 4921
	perf_reserved_percpu = val;
	for_each_online_cpu(cpu) {
		cpuctx = &per_cpu(perf_cpu_context, cpu);
		spin_lock_irq(&cpuctx->ctx.lock);
4922 4923
		mpt = min(perf_max_events - cpuctx->ctx.nr_events,
			  perf_max_events - perf_reserved_percpu);
T
Thomas Gleixner 已提交
4924 4925 4926
		cpuctx->max_pertask = mpt;
		spin_unlock_irq(&cpuctx->ctx.lock);
	}
4927
	spin_unlock(&perf_resource_lock);
T
Thomas Gleixner 已提交
4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948

	return count;
}

static ssize_t perf_show_overcommit(struct sysdev_class *class, char *buf)
{
	return sprintf(buf, "%d\n", perf_overcommit);
}

static ssize_t
perf_set_overcommit(struct sysdev_class *class, const char *buf, size_t count)
{
	unsigned long val;
	int err;

	err = strict_strtoul(buf, 10, &val);
	if (err)
		return err;
	if (val > 1)
		return -EINVAL;

4949
	spin_lock(&perf_resource_lock);
T
Thomas Gleixner 已提交
4950
	perf_overcommit = val;
4951
	spin_unlock(&perf_resource_lock);
T
Thomas Gleixner 已提交
4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977

	return count;
}

static SYSDEV_CLASS_ATTR(
				reserve_percpu,
				0644,
				perf_show_reserve_percpu,
				perf_set_reserve_percpu
			);

static SYSDEV_CLASS_ATTR(
				overcommit,
				0644,
				perf_show_overcommit,
				perf_set_overcommit
			);

static struct attribute *perfclass_attrs[] = {
	&attr_reserve_percpu.attr,
	&attr_overcommit.attr,
	NULL
};

static struct attribute_group perfclass_attr_group = {
	.attrs			= perfclass_attrs,
4978
	.name			= "perf_events",
T
Thomas Gleixner 已提交
4979 4980
};

4981
static int __init perf_event_sysfs_init(void)
T
Thomas Gleixner 已提交
4982 4983 4984 4985
{
	return sysfs_create_group(&cpu_sysdev_class.kset.kobj,
				  &perfclass_attr_group);
}
4986
device_initcall(perf_event_sysfs_init);