1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Performance events core code: 4 * 5 * Copyright (C) 2008 Thomas Gleixner <tglx@linutronix.de> 6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar 7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra 8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com> 9 */ 10 11 #include <linux/fs.h> 12 #include <linux/mm.h> 13 #include <linux/cpu.h> 14 #include <linux/smp.h> 15 #include <linux/idr.h> 16 #include <linux/file.h> 17 #include <linux/poll.h> 18 #include <linux/slab.h> 19 #include <linux/hash.h> 20 #include <linux/tick.h> 21 #include <linux/sysfs.h> 22 #include <linux/dcache.h> 23 #include <linux/percpu.h> 24 #include <linux/ptrace.h> 25 #include <linux/reboot.h> 26 #include <linux/vmstat.h> 27 #include <linux/device.h> 28 #include <linux/export.h> 29 #include <linux/vmalloc.h> 30 #include <linux/hardirq.h> 31 #include <linux/hugetlb.h> 32 #include <linux/rculist.h> 33 #include <linux/uaccess.h> 34 #include <linux/syscalls.h> 35 #include <linux/anon_inodes.h> 36 #include <linux/kernel_stat.h> 37 #include <linux/cgroup.h> 38 #include <linux/perf_event.h> 39 #include <linux/trace_events.h> 40 #include <linux/hw_breakpoint.h> 41 #include <linux/mm_types.h> 42 #include <linux/module.h> 43 #include <linux/mman.h> 44 #include <linux/compat.h> 45 #include <linux/bpf.h> 46 #include <linux/filter.h> 47 #include <linux/namei.h> 48 #include <linux/parser.h> 49 #include <linux/sched/clock.h> 50 #include <linux/sched/mm.h> 51 #include <linux/proc_ns.h> 52 #include <linux/mount.h> 53 #include <linux/min_heap.h> 54 55 #include "internal.h" 56 57 #include <asm/irq_regs.h> 58 59 typedef int (*remote_function_f)(void *); 60 61 struct remote_function_call { 62 struct task_struct *p; 63 remote_function_f func; 64 void *info; 65 int ret; 66 }; 67 68 static void remote_function(void *data) 69 { 70 struct remote_function_call *tfc = data; 71 struct task_struct *p = tfc->p; 72 73 if (p) { 74 /* -EAGAIN */ 75 if (task_cpu(p) != smp_processor_id()) 76 return; 77 78 /* 79 * Now that we're on right CPU with IRQs disabled, we can test 80 * if we hit the right task without races. 81 */ 82 83 tfc->ret = -ESRCH; /* No such (running) process */ 84 if (p != current) 85 return; 86 } 87 88 tfc->ret = tfc->func(tfc->info); 89 } 90 91 /** 92 * task_function_call - call a function on the cpu on which a task runs 93 * @p: the task to evaluate 94 * @func: the function to be called 95 * @info: the function call argument 96 * 97 * Calls the function @func when the task is currently running. This might 98 * be on the current CPU, which just calls the function directly. This will 99 * retry due to any failures in smp_call_function_single(), such as if the 100 * task_cpu() goes offline concurrently. 101 * 102 * returns @func return value or -ESRCH when the process isn't running 103 */ 104 static int 105 task_function_call(struct task_struct *p, remote_function_f func, void *info) 106 { 107 struct remote_function_call data = { 108 .p = p, 109 .func = func, 110 .info = info, 111 .ret = -EAGAIN, 112 }; 113 int ret; 114 115 for (;;) { 116 ret = smp_call_function_single(task_cpu(p), remote_function, 117 &data, 1); 118 ret = !ret ? data.ret : -EAGAIN; 119 120 if (ret != -EAGAIN) 121 break; 122 123 cond_resched(); 124 } 125 126 return ret; 127 } 128 129 /** 130 * cpu_function_call - call a function on the cpu 131 * @func: the function to be called 132 * @info: the function call argument 133 * 134 * Calls the function @func on the remote cpu. 135 * 136 * returns: @func return value or -ENXIO when the cpu is offline 137 */ 138 static int cpu_function_call(int cpu, remote_function_f func, void *info) 139 { 140 struct remote_function_call data = { 141 .p = NULL, 142 .func = func, 143 .info = info, 144 .ret = -ENXIO, /* No such CPU */ 145 }; 146 147 smp_call_function_single(cpu, remote_function, &data, 1); 148 149 return data.ret; 150 } 151 152 static inline struct perf_cpu_context * 153 __get_cpu_context(struct perf_event_context *ctx) 154 { 155 return this_cpu_ptr(ctx->pmu->pmu_cpu_context); 156 } 157 158 static void perf_ctx_lock(struct perf_cpu_context *cpuctx, 159 struct perf_event_context *ctx) 160 { 161 raw_spin_lock(&cpuctx->ctx.lock); 162 if (ctx) 163 raw_spin_lock(&ctx->lock); 164 } 165 166 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx, 167 struct perf_event_context *ctx) 168 { 169 if (ctx) 170 raw_spin_unlock(&ctx->lock); 171 raw_spin_unlock(&cpuctx->ctx.lock); 172 } 173 174 #define TASK_TOMBSTONE ((void *)-1L) 175 176 static bool is_kernel_event(struct perf_event *event) 177 { 178 return READ_ONCE(event->owner) == TASK_TOMBSTONE; 179 } 180 181 /* 182 * On task ctx scheduling... 183 * 184 * When !ctx->nr_events a task context will not be scheduled. This means 185 * we can disable the scheduler hooks (for performance) without leaving 186 * pending task ctx state. 187 * 188 * This however results in two special cases: 189 * 190 * - removing the last event from a task ctx; this is relatively straight 191 * forward and is done in __perf_remove_from_context. 192 * 193 * - adding the first event to a task ctx; this is tricky because we cannot 194 * rely on ctx->is_active and therefore cannot use event_function_call(). 195 * See perf_install_in_context(). 196 * 197 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set. 198 */ 199 200 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *, 201 struct perf_event_context *, void *); 202 203 struct event_function_struct { 204 struct perf_event *event; 205 event_f func; 206 void *data; 207 }; 208 209 static int event_function(void *info) 210 { 211 struct event_function_struct *efs = info; 212 struct perf_event *event = efs->event; 213 struct perf_event_context *ctx = event->ctx; 214 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); 215 struct perf_event_context *task_ctx = cpuctx->task_ctx; 216 int ret = 0; 217 218 lockdep_assert_irqs_disabled(); 219 220 perf_ctx_lock(cpuctx, task_ctx); 221 /* 222 * Since we do the IPI call without holding ctx->lock things can have 223 * changed, double check we hit the task we set out to hit. 224 */ 225 if (ctx->task) { 226 if (ctx->task != current) { 227 ret = -ESRCH; 228 goto unlock; 229 } 230 231 /* 232 * We only use event_function_call() on established contexts, 233 * and event_function() is only ever called when active (or 234 * rather, we'll have bailed in task_function_call() or the 235 * above ctx->task != current test), therefore we must have 236 * ctx->is_active here. 237 */ 238 WARN_ON_ONCE(!ctx->is_active); 239 /* 240 * And since we have ctx->is_active, cpuctx->task_ctx must 241 * match. 242 */ 243 WARN_ON_ONCE(task_ctx != ctx); 244 } else { 245 WARN_ON_ONCE(&cpuctx->ctx != ctx); 246 } 247 248 efs->func(event, cpuctx, ctx, efs->data); 249 unlock: 250 perf_ctx_unlock(cpuctx, task_ctx); 251 252 return ret; 253 } 254 255 static void event_function_call(struct perf_event *event, event_f func, void *data) 256 { 257 struct perf_event_context *ctx = event->ctx; 258 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */ 259 struct event_function_struct efs = { 260 .event = event, 261 .func = func, 262 .data = data, 263 }; 264 265 if (!event->parent) { 266 /* 267 * If this is a !child event, we must hold ctx::mutex to 268 * stabilize the the event->ctx relation. See 269 * perf_event_ctx_lock(). 270 */ 271 lockdep_assert_held(&ctx->mutex); 272 } 273 274 if (!task) { 275 cpu_function_call(event->cpu, event_function, &efs); 276 return; 277 } 278 279 if (task == TASK_TOMBSTONE) 280 return; 281 282 again: 283 if (!task_function_call(task, event_function, &efs)) 284 return; 285 286 raw_spin_lock_irq(&ctx->lock); 287 /* 288 * Reload the task pointer, it might have been changed by 289 * a concurrent perf_event_context_sched_out(). 290 */ 291 task = ctx->task; 292 if (task == TASK_TOMBSTONE) { 293 raw_spin_unlock_irq(&ctx->lock); 294 return; 295 } 296 if (ctx->is_active) { 297 raw_spin_unlock_irq(&ctx->lock); 298 goto again; 299 } 300 func(event, NULL, ctx, data); 301 raw_spin_unlock_irq(&ctx->lock); 302 } 303 304 /* 305 * Similar to event_function_call() + event_function(), but hard assumes IRQs 306 * are already disabled and we're on the right CPU. 307 */ 308 static void event_function_local(struct perf_event *event, event_f func, void *data) 309 { 310 struct perf_event_context *ctx = event->ctx; 311 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); 312 struct task_struct *task = READ_ONCE(ctx->task); 313 struct perf_event_context *task_ctx = NULL; 314 315 lockdep_assert_irqs_disabled(); 316 317 if (task) { 318 if (task == TASK_TOMBSTONE) 319 return; 320 321 task_ctx = ctx; 322 } 323 324 perf_ctx_lock(cpuctx, task_ctx); 325 326 task = ctx->task; 327 if (task == TASK_TOMBSTONE) 328 goto unlock; 329 330 if (task) { 331 /* 332 * We must be either inactive or active and the right task, 333 * otherwise we're screwed, since we cannot IPI to somewhere 334 * else. 335 */ 336 if (ctx->is_active) { 337 if (WARN_ON_ONCE(task != current)) 338 goto unlock; 339 340 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx)) 341 goto unlock; 342 } 343 } else { 344 WARN_ON_ONCE(&cpuctx->ctx != ctx); 345 } 346 347 func(event, cpuctx, ctx, data); 348 unlock: 349 perf_ctx_unlock(cpuctx, task_ctx); 350 } 351 352 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\ 353 PERF_FLAG_FD_OUTPUT |\ 354 PERF_FLAG_PID_CGROUP |\ 355 PERF_FLAG_FD_CLOEXEC) 356 357 /* 358 * branch priv levels that need permission checks 359 */ 360 #define PERF_SAMPLE_BRANCH_PERM_PLM \ 361 (PERF_SAMPLE_BRANCH_KERNEL |\ 362 PERF_SAMPLE_BRANCH_HV) 363 364 enum event_type_t { 365 EVENT_FLEXIBLE = 0x1, 366 EVENT_PINNED = 0x2, 367 EVENT_TIME = 0x4, 368 /* see ctx_resched() for details */ 369 EVENT_CPU = 0x8, 370 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED, 371 }; 372 373 /* 374 * perf_sched_events : >0 events exist 375 * perf_cgroup_events: >0 per-cpu cgroup events exist on this cpu 376 */ 377 378 static void perf_sched_delayed(struct work_struct *work); 379 DEFINE_STATIC_KEY_FALSE(perf_sched_events); 380 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed); 381 static DEFINE_MUTEX(perf_sched_mutex); 382 static atomic_t perf_sched_count; 383 384 static DEFINE_PER_CPU(atomic_t, perf_cgroup_events); 385 static DEFINE_PER_CPU(int, perf_sched_cb_usages); 386 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events); 387 388 static atomic_t nr_mmap_events __read_mostly; 389 static atomic_t nr_comm_events __read_mostly; 390 static atomic_t nr_namespaces_events __read_mostly; 391 static atomic_t nr_task_events __read_mostly; 392 static atomic_t nr_freq_events __read_mostly; 393 static atomic_t nr_switch_events __read_mostly; 394 static atomic_t nr_ksymbol_events __read_mostly; 395 static atomic_t nr_bpf_events __read_mostly; 396 static atomic_t nr_cgroup_events __read_mostly; 397 398 static LIST_HEAD(pmus); 399 static DEFINE_MUTEX(pmus_lock); 400 static struct srcu_struct pmus_srcu; 401 static cpumask_var_t perf_online_mask; 402 403 /* 404 * perf event paranoia level: 405 * -1 - not paranoid at all 406 * 0 - disallow raw tracepoint access for unpriv 407 * 1 - disallow cpu events for unpriv 408 * 2 - disallow kernel profiling for unpriv 409 */ 410 int sysctl_perf_event_paranoid __read_mostly = 2; 411 412 /* Minimum for 512 kiB + 1 user control page */ 413 int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); /* 'free' kiB per user */ 414 415 /* 416 * max perf event sample rate 417 */ 418 #define DEFAULT_MAX_SAMPLE_RATE 100000 419 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE) 420 #define DEFAULT_CPU_TIME_MAX_PERCENT 25 421 422 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE; 423 424 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ); 425 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS; 426 427 static int perf_sample_allowed_ns __read_mostly = 428 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100; 429 430 static void update_perf_cpu_limits(void) 431 { 432 u64 tmp = perf_sample_period_ns; 433 434 tmp *= sysctl_perf_cpu_time_max_percent; 435 tmp = div_u64(tmp, 100); 436 if (!tmp) 437 tmp = 1; 438 439 WRITE_ONCE(perf_sample_allowed_ns, tmp); 440 } 441 442 static bool perf_rotate_context(struct perf_cpu_context *cpuctx); 443 444 int perf_proc_update_handler(struct ctl_table *table, int write, 445 void __user *buffer, size_t *lenp, 446 loff_t *ppos) 447 { 448 int ret; 449 int perf_cpu = sysctl_perf_cpu_time_max_percent; 450 /* 451 * If throttling is disabled don't allow the write: 452 */ 453 if (write && (perf_cpu == 100 || perf_cpu == 0)) 454 return -EINVAL; 455 456 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 457 if (ret || !write) 458 return ret; 459 460 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ); 461 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; 462 update_perf_cpu_limits(); 463 464 return 0; 465 } 466 467 int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT; 468 469 int perf_cpu_time_max_percent_handler(struct ctl_table *table, int write, 470 void __user *buffer, size_t *lenp, 471 loff_t *ppos) 472 { 473 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 474 475 if (ret || !write) 476 return ret; 477 478 if (sysctl_perf_cpu_time_max_percent == 100 || 479 sysctl_perf_cpu_time_max_percent == 0) { 480 printk(KERN_WARNING 481 "perf: Dynamic interrupt throttling disabled, can hang your system!\n"); 482 WRITE_ONCE(perf_sample_allowed_ns, 0); 483 } else { 484 update_perf_cpu_limits(); 485 } 486 487 return 0; 488 } 489 490 /* 491 * perf samples are done in some very critical code paths (NMIs). 492 * If they take too much CPU time, the system can lock up and not 493 * get any real work done. This will drop the sample rate when 494 * we detect that events are taking too long. 495 */ 496 #define NR_ACCUMULATED_SAMPLES 128 497 static DEFINE_PER_CPU(u64, running_sample_length); 498 499 static u64 __report_avg; 500 static u64 __report_allowed; 501 502 static void perf_duration_warn(struct irq_work *w) 503 { 504 printk_ratelimited(KERN_INFO 505 "perf: interrupt took too long (%lld > %lld), lowering " 506 "kernel.perf_event_max_sample_rate to %d\n", 507 __report_avg, __report_allowed, 508 sysctl_perf_event_sample_rate); 509 } 510 511 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn); 512 513 void perf_sample_event_took(u64 sample_len_ns) 514 { 515 u64 max_len = READ_ONCE(perf_sample_allowed_ns); 516 u64 running_len; 517 u64 avg_len; 518 u32 max; 519 520 if (max_len == 0) 521 return; 522 523 /* Decay the counter by 1 average sample. */ 524 running_len = __this_cpu_read(running_sample_length); 525 running_len -= running_len/NR_ACCUMULATED_SAMPLES; 526 running_len += sample_len_ns; 527 __this_cpu_write(running_sample_length, running_len); 528 529 /* 530 * Note: this will be biased artifically low until we have 531 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us 532 * from having to maintain a count. 533 */ 534 avg_len = running_len/NR_ACCUMULATED_SAMPLES; 535 if (avg_len <= max_len) 536 return; 537 538 __report_avg = avg_len; 539 __report_allowed = max_len; 540 541 /* 542 * Compute a throttle threshold 25% below the current duration. 543 */ 544 avg_len += avg_len / 4; 545 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent; 546 if (avg_len < max) 547 max /= (u32)avg_len; 548 else 549 max = 1; 550 551 WRITE_ONCE(perf_sample_allowed_ns, avg_len); 552 WRITE_ONCE(max_samples_per_tick, max); 553 554 sysctl_perf_event_sample_rate = max * HZ; 555 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; 556 557 if (!irq_work_queue(&perf_duration_work)) { 558 early_printk("perf: interrupt took too long (%lld > %lld), lowering " 559 "kernel.perf_event_max_sample_rate to %d\n", 560 __report_avg, __report_allowed, 561 sysctl_perf_event_sample_rate); 562 } 563 } 564 565 static atomic64_t perf_event_id; 566 567 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx, 568 enum event_type_t event_type); 569 570 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx, 571 enum event_type_t event_type, 572 struct task_struct *task); 573 574 static void update_context_time(struct perf_event_context *ctx); 575 static u64 perf_event_time(struct perf_event *event); 576 577 void __weak perf_event_print_debug(void) { } 578 579 extern __weak const char *perf_pmu_name(void) 580 { 581 return "pmu"; 582 } 583 584 static inline u64 perf_clock(void) 585 { 586 return local_clock(); 587 } 588 589 static inline u64 perf_event_clock(struct perf_event *event) 590 { 591 return event->clock(); 592 } 593 594 /* 595 * State based event timekeeping... 596 * 597 * The basic idea is to use event->state to determine which (if any) time 598 * fields to increment with the current delta. This means we only need to 599 * update timestamps when we change state or when they are explicitly requested 600 * (read). 601 * 602 * Event groups make things a little more complicated, but not terribly so. The 603 * rules for a group are that if the group leader is OFF the entire group is 604 * OFF, irrespecive of what the group member states are. This results in 605 * __perf_effective_state(). 606 * 607 * A futher ramification is that when a group leader flips between OFF and 608 * !OFF, we need to update all group member times. 609 * 610 * 611 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we 612 * need to make sure the relevant context time is updated before we try and 613 * update our timestamps. 614 */ 615 616 static __always_inline enum perf_event_state 617 __perf_effective_state(struct perf_event *event) 618 { 619 struct perf_event *leader = event->group_leader; 620 621 if (leader->state <= PERF_EVENT_STATE_OFF) 622 return leader->state; 623 624 return event->state; 625 } 626 627 static __always_inline void 628 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running) 629 { 630 enum perf_event_state state = __perf_effective_state(event); 631 u64 delta = now - event->tstamp; 632 633 *enabled = event->total_time_enabled; 634 if (state >= PERF_EVENT_STATE_INACTIVE) 635 *enabled += delta; 636 637 *running = event->total_time_running; 638 if (state >= PERF_EVENT_STATE_ACTIVE) 639 *running += delta; 640 } 641 642 static void perf_event_update_time(struct perf_event *event) 643 { 644 u64 now = perf_event_time(event); 645 646 __perf_update_times(event, now, &event->total_time_enabled, 647 &event->total_time_running); 648 event->tstamp = now; 649 } 650 651 static void perf_event_update_sibling_time(struct perf_event *leader) 652 { 653 struct perf_event *sibling; 654 655 for_each_sibling_event(sibling, leader) 656 perf_event_update_time(sibling); 657 } 658 659 static void 660 perf_event_set_state(struct perf_event *event, enum perf_event_state state) 661 { 662 if (event->state == state) 663 return; 664 665 perf_event_update_time(event); 666 /* 667 * If a group leader gets enabled/disabled all its siblings 668 * are affected too. 669 */ 670 if ((event->state < 0) ^ (state < 0)) 671 perf_event_update_sibling_time(event); 672 673 WRITE_ONCE(event->state, state); 674 } 675 676 #ifdef CONFIG_CGROUP_PERF 677 678 static inline bool 679 perf_cgroup_match(struct perf_event *event) 680 { 681 struct perf_event_context *ctx = event->ctx; 682 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); 683 684 /* @event doesn't care about cgroup */ 685 if (!event->cgrp) 686 return true; 687 688 /* wants specific cgroup scope but @cpuctx isn't associated with any */ 689 if (!cpuctx->cgrp) 690 return false; 691 692 /* 693 * Cgroup scoping is recursive. An event enabled for a cgroup is 694 * also enabled for all its descendant cgroups. If @cpuctx's 695 * cgroup is a descendant of @event's (the test covers identity 696 * case), it's a match. 697 */ 698 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup, 699 event->cgrp->css.cgroup); 700 } 701 702 static inline void perf_detach_cgroup(struct perf_event *event) 703 { 704 css_put(&event->cgrp->css); 705 event->cgrp = NULL; 706 } 707 708 static inline int is_cgroup_event(struct perf_event *event) 709 { 710 return event->cgrp != NULL; 711 } 712 713 static inline u64 perf_cgroup_event_time(struct perf_event *event) 714 { 715 struct perf_cgroup_info *t; 716 717 t = per_cpu_ptr(event->cgrp->info, event->cpu); 718 return t->time; 719 } 720 721 static inline void __update_cgrp_time(struct perf_cgroup *cgrp) 722 { 723 struct perf_cgroup_info *info; 724 u64 now; 725 726 now = perf_clock(); 727 728 info = this_cpu_ptr(cgrp->info); 729 730 info->time += now - info->timestamp; 731 info->timestamp = now; 732 } 733 734 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx) 735 { 736 struct perf_cgroup *cgrp = cpuctx->cgrp; 737 struct cgroup_subsys_state *css; 738 739 if (cgrp) { 740 for (css = &cgrp->css; css; css = css->parent) { 741 cgrp = container_of(css, struct perf_cgroup, css); 742 __update_cgrp_time(cgrp); 743 } 744 } 745 } 746 747 static inline void update_cgrp_time_from_event(struct perf_event *event) 748 { 749 struct perf_cgroup *cgrp; 750 751 /* 752 * ensure we access cgroup data only when needed and 753 * when we know the cgroup is pinned (css_get) 754 */ 755 if (!is_cgroup_event(event)) 756 return; 757 758 cgrp = perf_cgroup_from_task(current, event->ctx); 759 /* 760 * Do not update time when cgroup is not active 761 */ 762 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup)) 763 __update_cgrp_time(event->cgrp); 764 } 765 766 static inline void 767 perf_cgroup_set_timestamp(struct task_struct *task, 768 struct perf_event_context *ctx) 769 { 770 struct perf_cgroup *cgrp; 771 struct perf_cgroup_info *info; 772 struct cgroup_subsys_state *css; 773 774 /* 775 * ctx->lock held by caller 776 * ensure we do not access cgroup data 777 * unless we have the cgroup pinned (css_get) 778 */ 779 if (!task || !ctx->nr_cgroups) 780 return; 781 782 cgrp = perf_cgroup_from_task(task, ctx); 783 784 for (css = &cgrp->css; css; css = css->parent) { 785 cgrp = container_of(css, struct perf_cgroup, css); 786 info = this_cpu_ptr(cgrp->info); 787 info->timestamp = ctx->timestamp; 788 } 789 } 790 791 static DEFINE_PER_CPU(struct list_head, cgrp_cpuctx_list); 792 793 #define PERF_CGROUP_SWOUT 0x1 /* cgroup switch out every event */ 794 #define PERF_CGROUP_SWIN 0x2 /* cgroup switch in events based on task */ 795 796 /* 797 * reschedule events based on the cgroup constraint of task. 798 * 799 * mode SWOUT : schedule out everything 800 * mode SWIN : schedule in based on cgroup for next 801 */ 802 static void perf_cgroup_switch(struct task_struct *task, int mode) 803 { 804 struct perf_cpu_context *cpuctx; 805 struct list_head *list; 806 unsigned long flags; 807 808 /* 809 * Disable interrupts and preemption to avoid this CPU's 810 * cgrp_cpuctx_entry to change under us. 811 */ 812 local_irq_save(flags); 813 814 list = this_cpu_ptr(&cgrp_cpuctx_list); 815 list_for_each_entry(cpuctx, list, cgrp_cpuctx_entry) { 816 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0); 817 818 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 819 perf_pmu_disable(cpuctx->ctx.pmu); 820 821 if (mode & PERF_CGROUP_SWOUT) { 822 cpu_ctx_sched_out(cpuctx, EVENT_ALL); 823 /* 824 * must not be done before ctxswout due 825 * to event_filter_match() in event_sched_out() 826 */ 827 cpuctx->cgrp = NULL; 828 } 829 830 if (mode & PERF_CGROUP_SWIN) { 831 WARN_ON_ONCE(cpuctx->cgrp); 832 /* 833 * set cgrp before ctxsw in to allow 834 * event_filter_match() to not have to pass 835 * task around 836 * we pass the cpuctx->ctx to perf_cgroup_from_task() 837 * because cgorup events are only per-cpu 838 */ 839 cpuctx->cgrp = perf_cgroup_from_task(task, 840 &cpuctx->ctx); 841 cpu_ctx_sched_in(cpuctx, EVENT_ALL, task); 842 } 843 perf_pmu_enable(cpuctx->ctx.pmu); 844 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 845 } 846 847 local_irq_restore(flags); 848 } 849 850 static inline void perf_cgroup_sched_out(struct task_struct *task, 851 struct task_struct *next) 852 { 853 struct perf_cgroup *cgrp1; 854 struct perf_cgroup *cgrp2 = NULL; 855 856 rcu_read_lock(); 857 /* 858 * we come here when we know perf_cgroup_events > 0 859 * we do not need to pass the ctx here because we know 860 * we are holding the rcu lock 861 */ 862 cgrp1 = perf_cgroup_from_task(task, NULL); 863 cgrp2 = perf_cgroup_from_task(next, NULL); 864 865 /* 866 * only schedule out current cgroup events if we know 867 * that we are switching to a different cgroup. Otherwise, 868 * do no touch the cgroup events. 869 */ 870 if (cgrp1 != cgrp2) 871 perf_cgroup_switch(task, PERF_CGROUP_SWOUT); 872 873 rcu_read_unlock(); 874 } 875 876 static inline void perf_cgroup_sched_in(struct task_struct *prev, 877 struct task_struct *task) 878 { 879 struct perf_cgroup *cgrp1; 880 struct perf_cgroup *cgrp2 = NULL; 881 882 rcu_read_lock(); 883 /* 884 * we come here when we know perf_cgroup_events > 0 885 * we do not need to pass the ctx here because we know 886 * we are holding the rcu lock 887 */ 888 cgrp1 = perf_cgroup_from_task(task, NULL); 889 cgrp2 = perf_cgroup_from_task(prev, NULL); 890 891 /* 892 * only need to schedule in cgroup events if we are changing 893 * cgroup during ctxsw. Cgroup events were not scheduled 894 * out of ctxsw out if that was not the case. 895 */ 896 if (cgrp1 != cgrp2) 897 perf_cgroup_switch(task, PERF_CGROUP_SWIN); 898 899 rcu_read_unlock(); 900 } 901 902 static int perf_cgroup_ensure_storage(struct perf_event *event, 903 struct cgroup_subsys_state *css) 904 { 905 struct perf_cpu_context *cpuctx; 906 struct perf_event **storage; 907 int cpu, heap_size, ret = 0; 908 909 /* 910 * Allow storage to have sufficent space for an iterator for each 911 * possibly nested cgroup plus an iterator for events with no cgroup. 912 */ 913 for (heap_size = 1; css; css = css->parent) 914 heap_size++; 915 916 for_each_possible_cpu(cpu) { 917 cpuctx = per_cpu_ptr(event->pmu->pmu_cpu_context, cpu); 918 if (heap_size <= cpuctx->heap_size) 919 continue; 920 921 storage = kmalloc_node(heap_size * sizeof(struct perf_event *), 922 GFP_KERNEL, cpu_to_node(cpu)); 923 if (!storage) { 924 ret = -ENOMEM; 925 break; 926 } 927 928 raw_spin_lock_irq(&cpuctx->ctx.lock); 929 if (cpuctx->heap_size < heap_size) { 930 swap(cpuctx->heap, storage); 931 if (storage == cpuctx->heap_default) 932 storage = NULL; 933 cpuctx->heap_size = heap_size; 934 } 935 raw_spin_unlock_irq(&cpuctx->ctx.lock); 936 937 kfree(storage); 938 } 939 940 return ret; 941 } 942 943 static inline int perf_cgroup_connect(int fd, struct perf_event *event, 944 struct perf_event_attr *attr, 945 struct perf_event *group_leader) 946 { 947 struct perf_cgroup *cgrp; 948 struct cgroup_subsys_state *css; 949 struct fd f = fdget(fd); 950 int ret = 0; 951 952 if (!f.file) 953 return -EBADF; 954 955 css = css_tryget_online_from_dir(f.file->f_path.dentry, 956 &perf_event_cgrp_subsys); 957 if (IS_ERR(css)) { 958 ret = PTR_ERR(css); 959 goto out; 960 } 961 962 ret = perf_cgroup_ensure_storage(event, css); 963 if (ret) 964 goto out; 965 966 cgrp = container_of(css, struct perf_cgroup, css); 967 event->cgrp = cgrp; 968 969 /* 970 * all events in a group must monitor 971 * the same cgroup because a task belongs 972 * to only one perf cgroup at a time 973 */ 974 if (group_leader && group_leader->cgrp != cgrp) { 975 perf_detach_cgroup(event); 976 ret = -EINVAL; 977 } 978 out: 979 fdput(f); 980 return ret; 981 } 982 983 static inline void 984 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now) 985 { 986 struct perf_cgroup_info *t; 987 t = per_cpu_ptr(event->cgrp->info, event->cpu); 988 event->shadow_ctx_time = now - t->timestamp; 989 } 990 991 static inline void 992 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx) 993 { 994 struct perf_cpu_context *cpuctx; 995 996 if (!is_cgroup_event(event)) 997 return; 998 999 /* 1000 * Because cgroup events are always per-cpu events, 1001 * @ctx == &cpuctx->ctx. 1002 */ 1003 cpuctx = container_of(ctx, struct perf_cpu_context, ctx); 1004 1005 /* 1006 * Since setting cpuctx->cgrp is conditional on the current @cgrp 1007 * matching the event's cgroup, we must do this for every new event, 1008 * because if the first would mismatch, the second would not try again 1009 * and we would leave cpuctx->cgrp unset. 1010 */ 1011 if (ctx->is_active && !cpuctx->cgrp) { 1012 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx); 1013 1014 if (cgroup_is_descendant(cgrp->css.cgroup, event->cgrp->css.cgroup)) 1015 cpuctx->cgrp = cgrp; 1016 } 1017 1018 if (ctx->nr_cgroups++) 1019 return; 1020 1021 list_add(&cpuctx->cgrp_cpuctx_entry, 1022 per_cpu_ptr(&cgrp_cpuctx_list, event->cpu)); 1023 } 1024 1025 static inline void 1026 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx) 1027 { 1028 struct perf_cpu_context *cpuctx; 1029 1030 if (!is_cgroup_event(event)) 1031 return; 1032 1033 /* 1034 * Because cgroup events are always per-cpu events, 1035 * @ctx == &cpuctx->ctx. 1036 */ 1037 cpuctx = container_of(ctx, struct perf_cpu_context, ctx); 1038 1039 if (--ctx->nr_cgroups) 1040 return; 1041 1042 if (ctx->is_active && cpuctx->cgrp) 1043 cpuctx->cgrp = NULL; 1044 1045 list_del(&cpuctx->cgrp_cpuctx_entry); 1046 } 1047 1048 #else /* !CONFIG_CGROUP_PERF */ 1049 1050 static inline bool 1051 perf_cgroup_match(struct perf_event *event) 1052 { 1053 return true; 1054 } 1055 1056 static inline void perf_detach_cgroup(struct perf_event *event) 1057 {} 1058 1059 static inline int is_cgroup_event(struct perf_event *event) 1060 { 1061 return 0; 1062 } 1063 1064 static inline void update_cgrp_time_from_event(struct perf_event *event) 1065 { 1066 } 1067 1068 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx) 1069 { 1070 } 1071 1072 static inline void perf_cgroup_sched_out(struct task_struct *task, 1073 struct task_struct *next) 1074 { 1075 } 1076 1077 static inline void perf_cgroup_sched_in(struct task_struct *prev, 1078 struct task_struct *task) 1079 { 1080 } 1081 1082 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event, 1083 struct perf_event_attr *attr, 1084 struct perf_event *group_leader) 1085 { 1086 return -EINVAL; 1087 } 1088 1089 static inline void 1090 perf_cgroup_set_timestamp(struct task_struct *task, 1091 struct perf_event_context *ctx) 1092 { 1093 } 1094 1095 static inline void 1096 perf_cgroup_switch(struct task_struct *task, struct task_struct *next) 1097 { 1098 } 1099 1100 static inline void 1101 perf_cgroup_set_shadow_time(struct perf_event *event, u64 now) 1102 { 1103 } 1104 1105 static inline u64 perf_cgroup_event_time(struct perf_event *event) 1106 { 1107 return 0; 1108 } 1109 1110 static inline void 1111 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx) 1112 { 1113 } 1114 1115 static inline void 1116 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx) 1117 { 1118 } 1119 #endif 1120 1121 /* 1122 * set default to be dependent on timer tick just 1123 * like original code 1124 */ 1125 #define PERF_CPU_HRTIMER (1000 / HZ) 1126 /* 1127 * function must be called with interrupts disabled 1128 */ 1129 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr) 1130 { 1131 struct perf_cpu_context *cpuctx; 1132 bool rotations; 1133 1134 lockdep_assert_irqs_disabled(); 1135 1136 cpuctx = container_of(hr, struct perf_cpu_context, hrtimer); 1137 rotations = perf_rotate_context(cpuctx); 1138 1139 raw_spin_lock(&cpuctx->hrtimer_lock); 1140 if (rotations) 1141 hrtimer_forward_now(hr, cpuctx->hrtimer_interval); 1142 else 1143 cpuctx->hrtimer_active = 0; 1144 raw_spin_unlock(&cpuctx->hrtimer_lock); 1145 1146 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART; 1147 } 1148 1149 static void __perf_mux_hrtimer_init(struct perf_cpu_context *cpuctx, int cpu) 1150 { 1151 struct hrtimer *timer = &cpuctx->hrtimer; 1152 struct pmu *pmu = cpuctx->ctx.pmu; 1153 u64 interval; 1154 1155 /* no multiplexing needed for SW PMU */ 1156 if (pmu->task_ctx_nr == perf_sw_context) 1157 return; 1158 1159 /* 1160 * check default is sane, if not set then force to 1161 * default interval (1/tick) 1162 */ 1163 interval = pmu->hrtimer_interval_ms; 1164 if (interval < 1) 1165 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER; 1166 1167 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval); 1168 1169 raw_spin_lock_init(&cpuctx->hrtimer_lock); 1170 hrtimer_init(timer, CLOCK_MONOTONIC, HRTIMER_MODE_ABS_PINNED_HARD); 1171 timer->function = perf_mux_hrtimer_handler; 1172 } 1173 1174 static int perf_mux_hrtimer_restart(struct perf_cpu_context *cpuctx) 1175 { 1176 struct hrtimer *timer = &cpuctx->hrtimer; 1177 struct pmu *pmu = cpuctx->ctx.pmu; 1178 unsigned long flags; 1179 1180 /* not for SW PMU */ 1181 if (pmu->task_ctx_nr == perf_sw_context) 1182 return 0; 1183 1184 raw_spin_lock_irqsave(&cpuctx->hrtimer_lock, flags); 1185 if (!cpuctx->hrtimer_active) { 1186 cpuctx->hrtimer_active = 1; 1187 hrtimer_forward_now(timer, cpuctx->hrtimer_interval); 1188 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD); 1189 } 1190 raw_spin_unlock_irqrestore(&cpuctx->hrtimer_lock, flags); 1191 1192 return 0; 1193 } 1194 1195 void perf_pmu_disable(struct pmu *pmu) 1196 { 1197 int *count = this_cpu_ptr(pmu->pmu_disable_count); 1198 if (!(*count)++) 1199 pmu->pmu_disable(pmu); 1200 } 1201 1202 void perf_pmu_enable(struct pmu *pmu) 1203 { 1204 int *count = this_cpu_ptr(pmu->pmu_disable_count); 1205 if (!--(*count)) 1206 pmu->pmu_enable(pmu); 1207 } 1208 1209 static DEFINE_PER_CPU(struct list_head, active_ctx_list); 1210 1211 /* 1212 * perf_event_ctx_activate(), perf_event_ctx_deactivate(), and 1213 * perf_event_task_tick() are fully serialized because they're strictly cpu 1214 * affine and perf_event_ctx{activate,deactivate} are called with IRQs 1215 * disabled, while perf_event_task_tick is called from IRQ context. 1216 */ 1217 static void perf_event_ctx_activate(struct perf_event_context *ctx) 1218 { 1219 struct list_head *head = this_cpu_ptr(&active_ctx_list); 1220 1221 lockdep_assert_irqs_disabled(); 1222 1223 WARN_ON(!list_empty(&ctx->active_ctx_list)); 1224 1225 list_add(&ctx->active_ctx_list, head); 1226 } 1227 1228 static void perf_event_ctx_deactivate(struct perf_event_context *ctx) 1229 { 1230 lockdep_assert_irqs_disabled(); 1231 1232 WARN_ON(list_empty(&ctx->active_ctx_list)); 1233 1234 list_del_init(&ctx->active_ctx_list); 1235 } 1236 1237 static void get_ctx(struct perf_event_context *ctx) 1238 { 1239 refcount_inc(&ctx->refcount); 1240 } 1241 1242 static void free_ctx(struct rcu_head *head) 1243 { 1244 struct perf_event_context *ctx; 1245 1246 ctx = container_of(head, struct perf_event_context, rcu_head); 1247 kfree(ctx->task_ctx_data); 1248 kfree(ctx); 1249 } 1250 1251 static void put_ctx(struct perf_event_context *ctx) 1252 { 1253 if (refcount_dec_and_test(&ctx->refcount)) { 1254 if (ctx->parent_ctx) 1255 put_ctx(ctx->parent_ctx); 1256 if (ctx->task && ctx->task != TASK_TOMBSTONE) 1257 put_task_struct(ctx->task); 1258 call_rcu(&ctx->rcu_head, free_ctx); 1259 } 1260 } 1261 1262 /* 1263 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and 1264 * perf_pmu_migrate_context() we need some magic. 1265 * 1266 * Those places that change perf_event::ctx will hold both 1267 * perf_event_ctx::mutex of the 'old' and 'new' ctx value. 1268 * 1269 * Lock ordering is by mutex address. There are two other sites where 1270 * perf_event_context::mutex nests and those are: 1271 * 1272 * - perf_event_exit_task_context() [ child , 0 ] 1273 * perf_event_exit_event() 1274 * put_event() [ parent, 1 ] 1275 * 1276 * - perf_event_init_context() [ parent, 0 ] 1277 * inherit_task_group() 1278 * inherit_group() 1279 * inherit_event() 1280 * perf_event_alloc() 1281 * perf_init_event() 1282 * perf_try_init_event() [ child , 1 ] 1283 * 1284 * While it appears there is an obvious deadlock here -- the parent and child 1285 * nesting levels are inverted between the two. This is in fact safe because 1286 * life-time rules separate them. That is an exiting task cannot fork, and a 1287 * spawning task cannot (yet) exit. 1288 * 1289 * But remember that that these are parent<->child context relations, and 1290 * migration does not affect children, therefore these two orderings should not 1291 * interact. 1292 * 1293 * The change in perf_event::ctx does not affect children (as claimed above) 1294 * because the sys_perf_event_open() case will install a new event and break 1295 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only 1296 * concerned with cpuctx and that doesn't have children. 1297 * 1298 * The places that change perf_event::ctx will issue: 1299 * 1300 * perf_remove_from_context(); 1301 * synchronize_rcu(); 1302 * perf_install_in_context(); 1303 * 1304 * to affect the change. The remove_from_context() + synchronize_rcu() should 1305 * quiesce the event, after which we can install it in the new location. This 1306 * means that only external vectors (perf_fops, prctl) can perturb the event 1307 * while in transit. Therefore all such accessors should also acquire 1308 * perf_event_context::mutex to serialize against this. 1309 * 1310 * However; because event->ctx can change while we're waiting to acquire 1311 * ctx->mutex we must be careful and use the below perf_event_ctx_lock() 1312 * function. 1313 * 1314 * Lock order: 1315 * exec_update_mutex 1316 * task_struct::perf_event_mutex 1317 * perf_event_context::mutex 1318 * perf_event::child_mutex; 1319 * perf_event_context::lock 1320 * perf_event::mmap_mutex 1321 * mmap_sem 1322 * perf_addr_filters_head::lock 1323 * 1324 * cpu_hotplug_lock 1325 * pmus_lock 1326 * cpuctx->mutex / perf_event_context::mutex 1327 */ 1328 static struct perf_event_context * 1329 perf_event_ctx_lock_nested(struct perf_event *event, int nesting) 1330 { 1331 struct perf_event_context *ctx; 1332 1333 again: 1334 rcu_read_lock(); 1335 ctx = READ_ONCE(event->ctx); 1336 if (!refcount_inc_not_zero(&ctx->refcount)) { 1337 rcu_read_unlock(); 1338 goto again; 1339 } 1340 rcu_read_unlock(); 1341 1342 mutex_lock_nested(&ctx->mutex, nesting); 1343 if (event->ctx != ctx) { 1344 mutex_unlock(&ctx->mutex); 1345 put_ctx(ctx); 1346 goto again; 1347 } 1348 1349 return ctx; 1350 } 1351 1352 static inline struct perf_event_context * 1353 perf_event_ctx_lock(struct perf_event *event) 1354 { 1355 return perf_event_ctx_lock_nested(event, 0); 1356 } 1357 1358 static void perf_event_ctx_unlock(struct perf_event *event, 1359 struct perf_event_context *ctx) 1360 { 1361 mutex_unlock(&ctx->mutex); 1362 put_ctx(ctx); 1363 } 1364 1365 /* 1366 * This must be done under the ctx->lock, such as to serialize against 1367 * context_equiv(), therefore we cannot call put_ctx() since that might end up 1368 * calling scheduler related locks and ctx->lock nests inside those. 1369 */ 1370 static __must_check struct perf_event_context * 1371 unclone_ctx(struct perf_event_context *ctx) 1372 { 1373 struct perf_event_context *parent_ctx = ctx->parent_ctx; 1374 1375 lockdep_assert_held(&ctx->lock); 1376 1377 if (parent_ctx) 1378 ctx->parent_ctx = NULL; 1379 ctx->generation++; 1380 1381 return parent_ctx; 1382 } 1383 1384 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p, 1385 enum pid_type type) 1386 { 1387 u32 nr; 1388 /* 1389 * only top level events have the pid namespace they were created in 1390 */ 1391 if (event->parent) 1392 event = event->parent; 1393 1394 nr = __task_pid_nr_ns(p, type, event->ns); 1395 /* avoid -1 if it is idle thread or runs in another ns */ 1396 if (!nr && !pid_alive(p)) 1397 nr = -1; 1398 return nr; 1399 } 1400 1401 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p) 1402 { 1403 return perf_event_pid_type(event, p, PIDTYPE_TGID); 1404 } 1405 1406 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p) 1407 { 1408 return perf_event_pid_type(event, p, PIDTYPE_PID); 1409 } 1410 1411 /* 1412 * If we inherit events we want to return the parent event id 1413 * to userspace. 1414 */ 1415 static u64 primary_event_id(struct perf_event *event) 1416 { 1417 u64 id = event->id; 1418 1419 if (event->parent) 1420 id = event->parent->id; 1421 1422 return id; 1423 } 1424 1425 /* 1426 * Get the perf_event_context for a task and lock it. 1427 * 1428 * This has to cope with with the fact that until it is locked, 1429 * the context could get moved to another task. 1430 */ 1431 static struct perf_event_context * 1432 perf_lock_task_context(struct task_struct *task, int ctxn, unsigned long *flags) 1433 { 1434 struct perf_event_context *ctx; 1435 1436 retry: 1437 /* 1438 * One of the few rules of preemptible RCU is that one cannot do 1439 * rcu_read_unlock() while holding a scheduler (or nested) lock when 1440 * part of the read side critical section was irqs-enabled -- see 1441 * rcu_read_unlock_special(). 1442 * 1443 * Since ctx->lock nests under rq->lock we must ensure the entire read 1444 * side critical section has interrupts disabled. 1445 */ 1446 local_irq_save(*flags); 1447 rcu_read_lock(); 1448 ctx = rcu_dereference(task->perf_event_ctxp[ctxn]); 1449 if (ctx) { 1450 /* 1451 * If this context is a clone of another, it might 1452 * get swapped for another underneath us by 1453 * perf_event_task_sched_out, though the 1454 * rcu_read_lock() protects us from any context 1455 * getting freed. Lock the context and check if it 1456 * got swapped before we could get the lock, and retry 1457 * if so. If we locked the right context, then it 1458 * can't get swapped on us any more. 1459 */ 1460 raw_spin_lock(&ctx->lock); 1461 if (ctx != rcu_dereference(task->perf_event_ctxp[ctxn])) { 1462 raw_spin_unlock(&ctx->lock); 1463 rcu_read_unlock(); 1464 local_irq_restore(*flags); 1465 goto retry; 1466 } 1467 1468 if (ctx->task == TASK_TOMBSTONE || 1469 !refcount_inc_not_zero(&ctx->refcount)) { 1470 raw_spin_unlock(&ctx->lock); 1471 ctx = NULL; 1472 } else { 1473 WARN_ON_ONCE(ctx->task != task); 1474 } 1475 } 1476 rcu_read_unlock(); 1477 if (!ctx) 1478 local_irq_restore(*flags); 1479 return ctx; 1480 } 1481 1482 /* 1483 * Get the context for a task and increment its pin_count so it 1484 * can't get swapped to another task. This also increments its 1485 * reference count so that the context can't get freed. 1486 */ 1487 static struct perf_event_context * 1488 perf_pin_task_context(struct task_struct *task, int ctxn) 1489 { 1490 struct perf_event_context *ctx; 1491 unsigned long flags; 1492 1493 ctx = perf_lock_task_context(task, ctxn, &flags); 1494 if (ctx) { 1495 ++ctx->pin_count; 1496 raw_spin_unlock_irqrestore(&ctx->lock, flags); 1497 } 1498 return ctx; 1499 } 1500 1501 static void perf_unpin_context(struct perf_event_context *ctx) 1502 { 1503 unsigned long flags; 1504 1505 raw_spin_lock_irqsave(&ctx->lock, flags); 1506 --ctx->pin_count; 1507 raw_spin_unlock_irqrestore(&ctx->lock, flags); 1508 } 1509 1510 /* 1511 * Update the record of the current time in a context. 1512 */ 1513 static void update_context_time(struct perf_event_context *ctx) 1514 { 1515 u64 now = perf_clock(); 1516 1517 ctx->time += now - ctx->timestamp; 1518 ctx->timestamp = now; 1519 } 1520 1521 static u64 perf_event_time(struct perf_event *event) 1522 { 1523 struct perf_event_context *ctx = event->ctx; 1524 1525 if (is_cgroup_event(event)) 1526 return perf_cgroup_event_time(event); 1527 1528 return ctx ? ctx->time : 0; 1529 } 1530 1531 static enum event_type_t get_event_type(struct perf_event *event) 1532 { 1533 struct perf_event_context *ctx = event->ctx; 1534 enum event_type_t event_type; 1535 1536 lockdep_assert_held(&ctx->lock); 1537 1538 /* 1539 * It's 'group type', really, because if our group leader is 1540 * pinned, so are we. 1541 */ 1542 if (event->group_leader != event) 1543 event = event->group_leader; 1544 1545 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE; 1546 if (!ctx->task) 1547 event_type |= EVENT_CPU; 1548 1549 return event_type; 1550 } 1551 1552 /* 1553 * Helper function to initialize event group nodes. 1554 */ 1555 static void init_event_group(struct perf_event *event) 1556 { 1557 RB_CLEAR_NODE(&event->group_node); 1558 event->group_index = 0; 1559 } 1560 1561 /* 1562 * Extract pinned or flexible groups from the context 1563 * based on event attrs bits. 1564 */ 1565 static struct perf_event_groups * 1566 get_event_groups(struct perf_event *event, struct perf_event_context *ctx) 1567 { 1568 if (event->attr.pinned) 1569 return &ctx->pinned_groups; 1570 else 1571 return &ctx->flexible_groups; 1572 } 1573 1574 /* 1575 * Helper function to initializes perf_event_group trees. 1576 */ 1577 static void perf_event_groups_init(struct perf_event_groups *groups) 1578 { 1579 groups->tree = RB_ROOT; 1580 groups->index = 0; 1581 } 1582 1583 /* 1584 * Compare function for event groups; 1585 * 1586 * Implements complex key that first sorts by CPU and then by virtual index 1587 * which provides ordering when rotating groups for the same CPU. 1588 */ 1589 static bool 1590 perf_event_groups_less(struct perf_event *left, struct perf_event *right) 1591 { 1592 if (left->cpu < right->cpu) 1593 return true; 1594 if (left->cpu > right->cpu) 1595 return false; 1596 1597 #ifdef CONFIG_CGROUP_PERF 1598 if (left->cgrp != right->cgrp) { 1599 if (!left->cgrp || !left->cgrp->css.cgroup) { 1600 /* 1601 * Left has no cgroup but right does, no cgroups come 1602 * first. 1603 */ 1604 return true; 1605 } 1606 if (!right->cgrp || !right->cgrp->css.cgroup) { 1607 /* 1608 * Right has no cgroup but left does, no cgroups come 1609 * first. 1610 */ 1611 return false; 1612 } 1613 /* Two dissimilar cgroups, order by id. */ 1614 if (left->cgrp->css.cgroup->kn->id < right->cgrp->css.cgroup->kn->id) 1615 return true; 1616 1617 return false; 1618 } 1619 #endif 1620 1621 if (left->group_index < right->group_index) 1622 return true; 1623 if (left->group_index > right->group_index) 1624 return false; 1625 1626 return false; 1627 } 1628 1629 /* 1630 * Insert @event into @groups' tree; using {@event->cpu, ++@groups->index} for 1631 * key (see perf_event_groups_less). This places it last inside the CPU 1632 * subtree. 1633 */ 1634 static void 1635 perf_event_groups_insert(struct perf_event_groups *groups, 1636 struct perf_event *event) 1637 { 1638 struct perf_event *node_event; 1639 struct rb_node *parent; 1640 struct rb_node **node; 1641 1642 event->group_index = ++groups->index; 1643 1644 node = &groups->tree.rb_node; 1645 parent = *node; 1646 1647 while (*node) { 1648 parent = *node; 1649 node_event = container_of(*node, struct perf_event, group_node); 1650 1651 if (perf_event_groups_less(event, node_event)) 1652 node = &parent->rb_left; 1653 else 1654 node = &parent->rb_right; 1655 } 1656 1657 rb_link_node(&event->group_node, parent, node); 1658 rb_insert_color(&event->group_node, &groups->tree); 1659 } 1660 1661 /* 1662 * Helper function to insert event into the pinned or flexible groups. 1663 */ 1664 static void 1665 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx) 1666 { 1667 struct perf_event_groups *groups; 1668 1669 groups = get_event_groups(event, ctx); 1670 perf_event_groups_insert(groups, event); 1671 } 1672 1673 /* 1674 * Delete a group from a tree. 1675 */ 1676 static void 1677 perf_event_groups_delete(struct perf_event_groups *groups, 1678 struct perf_event *event) 1679 { 1680 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) || 1681 RB_EMPTY_ROOT(&groups->tree)); 1682 1683 rb_erase(&event->group_node, &groups->tree); 1684 init_event_group(event); 1685 } 1686 1687 /* 1688 * Helper function to delete event from its groups. 1689 */ 1690 static void 1691 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx) 1692 { 1693 struct perf_event_groups *groups; 1694 1695 groups = get_event_groups(event, ctx); 1696 perf_event_groups_delete(groups, event); 1697 } 1698 1699 /* 1700 * Get the leftmost event in the cpu/cgroup subtree. 1701 */ 1702 static struct perf_event * 1703 perf_event_groups_first(struct perf_event_groups *groups, int cpu, 1704 struct cgroup *cgrp) 1705 { 1706 struct perf_event *node_event = NULL, *match = NULL; 1707 struct rb_node *node = groups->tree.rb_node; 1708 #ifdef CONFIG_CGROUP_PERF 1709 u64 node_cgrp_id, cgrp_id = 0; 1710 1711 if (cgrp) 1712 cgrp_id = cgrp->kn->id; 1713 #endif 1714 1715 while (node) { 1716 node_event = container_of(node, struct perf_event, group_node); 1717 1718 if (cpu < node_event->cpu) { 1719 node = node->rb_left; 1720 continue; 1721 } 1722 if (cpu > node_event->cpu) { 1723 node = node->rb_right; 1724 continue; 1725 } 1726 #ifdef CONFIG_CGROUP_PERF 1727 node_cgrp_id = 0; 1728 if (node_event->cgrp && node_event->cgrp->css.cgroup) 1729 node_cgrp_id = node_event->cgrp->css.cgroup->kn->id; 1730 1731 if (cgrp_id < node_cgrp_id) { 1732 node = node->rb_left; 1733 continue; 1734 } 1735 if (cgrp_id > node_cgrp_id) { 1736 node = node->rb_right; 1737 continue; 1738 } 1739 #endif 1740 match = node_event; 1741 node = node->rb_left; 1742 } 1743 1744 return match; 1745 } 1746 1747 /* 1748 * Like rb_entry_next_safe() for the @cpu subtree. 1749 */ 1750 static struct perf_event * 1751 perf_event_groups_next(struct perf_event *event) 1752 { 1753 struct perf_event *next; 1754 #ifdef CONFIG_CGROUP_PERF 1755 u64 curr_cgrp_id = 0; 1756 u64 next_cgrp_id = 0; 1757 #endif 1758 1759 next = rb_entry_safe(rb_next(&event->group_node), typeof(*event), group_node); 1760 if (next == NULL || next->cpu != event->cpu) 1761 return NULL; 1762 1763 #ifdef CONFIG_CGROUP_PERF 1764 if (event->cgrp && event->cgrp->css.cgroup) 1765 curr_cgrp_id = event->cgrp->css.cgroup->kn->id; 1766 1767 if (next->cgrp && next->cgrp->css.cgroup) 1768 next_cgrp_id = next->cgrp->css.cgroup->kn->id; 1769 1770 if (curr_cgrp_id != next_cgrp_id) 1771 return NULL; 1772 #endif 1773 return next; 1774 } 1775 1776 /* 1777 * Iterate through the whole groups tree. 1778 */ 1779 #define perf_event_groups_for_each(event, groups) \ 1780 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \ 1781 typeof(*event), group_node); event; \ 1782 event = rb_entry_safe(rb_next(&event->group_node), \ 1783 typeof(*event), group_node)) 1784 1785 /* 1786 * Add an event from the lists for its context. 1787 * Must be called with ctx->mutex and ctx->lock held. 1788 */ 1789 static void 1790 list_add_event(struct perf_event *event, struct perf_event_context *ctx) 1791 { 1792 lockdep_assert_held(&ctx->lock); 1793 1794 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT); 1795 event->attach_state |= PERF_ATTACH_CONTEXT; 1796 1797 event->tstamp = perf_event_time(event); 1798 1799 /* 1800 * If we're a stand alone event or group leader, we go to the context 1801 * list, group events are kept attached to the group so that 1802 * perf_group_detach can, at all times, locate all siblings. 1803 */ 1804 if (event->group_leader == event) { 1805 event->group_caps = event->event_caps; 1806 add_event_to_groups(event, ctx); 1807 } 1808 1809 list_add_rcu(&event->event_entry, &ctx->event_list); 1810 ctx->nr_events++; 1811 if (event->attr.inherit_stat) 1812 ctx->nr_stat++; 1813 1814 if (event->state > PERF_EVENT_STATE_OFF) 1815 perf_cgroup_event_enable(event, ctx); 1816 1817 ctx->generation++; 1818 } 1819 1820 /* 1821 * Initialize event state based on the perf_event_attr::disabled. 1822 */ 1823 static inline void perf_event__state_init(struct perf_event *event) 1824 { 1825 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF : 1826 PERF_EVENT_STATE_INACTIVE; 1827 } 1828 1829 static void __perf_event_read_size(struct perf_event *event, int nr_siblings) 1830 { 1831 int entry = sizeof(u64); /* value */ 1832 int size = 0; 1833 int nr = 1; 1834 1835 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 1836 size += sizeof(u64); 1837 1838 if (event->attr.read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 1839 size += sizeof(u64); 1840 1841 if (event->attr.read_format & PERF_FORMAT_ID) 1842 entry += sizeof(u64); 1843 1844 if (event->attr.read_format & PERF_FORMAT_GROUP) { 1845 nr += nr_siblings; 1846 size += sizeof(u64); 1847 } 1848 1849 size += entry * nr; 1850 event->read_size = size; 1851 } 1852 1853 static void __perf_event_header_size(struct perf_event *event, u64 sample_type) 1854 { 1855 struct perf_sample_data *data; 1856 u16 size = 0; 1857 1858 if (sample_type & PERF_SAMPLE_IP) 1859 size += sizeof(data->ip); 1860 1861 if (sample_type & PERF_SAMPLE_ADDR) 1862 size += sizeof(data->addr); 1863 1864 if (sample_type & PERF_SAMPLE_PERIOD) 1865 size += sizeof(data->period); 1866 1867 if (sample_type & PERF_SAMPLE_WEIGHT) 1868 size += sizeof(data->weight); 1869 1870 if (sample_type & PERF_SAMPLE_READ) 1871 size += event->read_size; 1872 1873 if (sample_type & PERF_SAMPLE_DATA_SRC) 1874 size += sizeof(data->data_src.val); 1875 1876 if (sample_type & PERF_SAMPLE_TRANSACTION) 1877 size += sizeof(data->txn); 1878 1879 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 1880 size += sizeof(data->phys_addr); 1881 1882 if (sample_type & PERF_SAMPLE_CGROUP) 1883 size += sizeof(data->cgroup); 1884 1885 event->header_size = size; 1886 } 1887 1888 /* 1889 * Called at perf_event creation and when events are attached/detached from a 1890 * group. 1891 */ 1892 static void perf_event__header_size(struct perf_event *event) 1893 { 1894 __perf_event_read_size(event, 1895 event->group_leader->nr_siblings); 1896 __perf_event_header_size(event, event->attr.sample_type); 1897 } 1898 1899 static void perf_event__id_header_size(struct perf_event *event) 1900 { 1901 struct perf_sample_data *data; 1902 u64 sample_type = event->attr.sample_type; 1903 u16 size = 0; 1904 1905 if (sample_type & PERF_SAMPLE_TID) 1906 size += sizeof(data->tid_entry); 1907 1908 if (sample_type & PERF_SAMPLE_TIME) 1909 size += sizeof(data->time); 1910 1911 if (sample_type & PERF_SAMPLE_IDENTIFIER) 1912 size += sizeof(data->id); 1913 1914 if (sample_type & PERF_SAMPLE_ID) 1915 size += sizeof(data->id); 1916 1917 if (sample_type & PERF_SAMPLE_STREAM_ID) 1918 size += sizeof(data->stream_id); 1919 1920 if (sample_type & PERF_SAMPLE_CPU) 1921 size += sizeof(data->cpu_entry); 1922 1923 event->id_header_size = size; 1924 } 1925 1926 static bool perf_event_validate_size(struct perf_event *event) 1927 { 1928 /* 1929 * The values computed here will be over-written when we actually 1930 * attach the event. 1931 */ 1932 __perf_event_read_size(event, event->group_leader->nr_siblings + 1); 1933 __perf_event_header_size(event, event->attr.sample_type & ~PERF_SAMPLE_READ); 1934 perf_event__id_header_size(event); 1935 1936 /* 1937 * Sum the lot; should not exceed the 64k limit we have on records. 1938 * Conservative limit to allow for callchains and other variable fields. 1939 */ 1940 if (event->read_size + event->header_size + 1941 event->id_header_size + sizeof(struct perf_event_header) >= 16*1024) 1942 return false; 1943 1944 return true; 1945 } 1946 1947 static void perf_group_attach(struct perf_event *event) 1948 { 1949 struct perf_event *group_leader = event->group_leader, *pos; 1950 1951 lockdep_assert_held(&event->ctx->lock); 1952 1953 /* 1954 * We can have double attach due to group movement in perf_event_open. 1955 */ 1956 if (event->attach_state & PERF_ATTACH_GROUP) 1957 return; 1958 1959 event->attach_state |= PERF_ATTACH_GROUP; 1960 1961 if (group_leader == event) 1962 return; 1963 1964 WARN_ON_ONCE(group_leader->ctx != event->ctx); 1965 1966 group_leader->group_caps &= event->event_caps; 1967 1968 list_add_tail(&event->sibling_list, &group_leader->sibling_list); 1969 group_leader->nr_siblings++; 1970 1971 perf_event__header_size(group_leader); 1972 1973 for_each_sibling_event(pos, group_leader) 1974 perf_event__header_size(pos); 1975 } 1976 1977 /* 1978 * Remove an event from the lists for its context. 1979 * Must be called with ctx->mutex and ctx->lock held. 1980 */ 1981 static void 1982 list_del_event(struct perf_event *event, struct perf_event_context *ctx) 1983 { 1984 WARN_ON_ONCE(event->ctx != ctx); 1985 lockdep_assert_held(&ctx->lock); 1986 1987 /* 1988 * We can have double detach due to exit/hot-unplug + close. 1989 */ 1990 if (!(event->attach_state & PERF_ATTACH_CONTEXT)) 1991 return; 1992 1993 event->attach_state &= ~PERF_ATTACH_CONTEXT; 1994 1995 ctx->nr_events--; 1996 if (event->attr.inherit_stat) 1997 ctx->nr_stat--; 1998 1999 list_del_rcu(&event->event_entry); 2000 2001 if (event->group_leader == event) 2002 del_event_from_groups(event, ctx); 2003 2004 /* 2005 * If event was in error state, then keep it 2006 * that way, otherwise bogus counts will be 2007 * returned on read(). The only way to get out 2008 * of error state is by explicit re-enabling 2009 * of the event 2010 */ 2011 if (event->state > PERF_EVENT_STATE_OFF) { 2012 perf_cgroup_event_disable(event, ctx); 2013 perf_event_set_state(event, PERF_EVENT_STATE_OFF); 2014 } 2015 2016 ctx->generation++; 2017 } 2018 2019 static int 2020 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event) 2021 { 2022 if (!has_aux(aux_event)) 2023 return 0; 2024 2025 if (!event->pmu->aux_output_match) 2026 return 0; 2027 2028 return event->pmu->aux_output_match(aux_event); 2029 } 2030 2031 static void put_event(struct perf_event *event); 2032 static void event_sched_out(struct perf_event *event, 2033 struct perf_cpu_context *cpuctx, 2034 struct perf_event_context *ctx); 2035 2036 static void perf_put_aux_event(struct perf_event *event) 2037 { 2038 struct perf_event_context *ctx = event->ctx; 2039 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); 2040 struct perf_event *iter; 2041 2042 /* 2043 * If event uses aux_event tear down the link 2044 */ 2045 if (event->aux_event) { 2046 iter = event->aux_event; 2047 event->aux_event = NULL; 2048 put_event(iter); 2049 return; 2050 } 2051 2052 /* 2053 * If the event is an aux_event, tear down all links to 2054 * it from other events. 2055 */ 2056 for_each_sibling_event(iter, event->group_leader) { 2057 if (iter->aux_event != event) 2058 continue; 2059 2060 iter->aux_event = NULL; 2061 put_event(event); 2062 2063 /* 2064 * If it's ACTIVE, schedule it out and put it into ERROR 2065 * state so that we don't try to schedule it again. Note 2066 * that perf_event_enable() will clear the ERROR status. 2067 */ 2068 event_sched_out(iter, cpuctx, ctx); 2069 perf_event_set_state(event, PERF_EVENT_STATE_ERROR); 2070 } 2071 } 2072 2073 static bool perf_need_aux_event(struct perf_event *event) 2074 { 2075 return !!event->attr.aux_output || !!event->attr.aux_sample_size; 2076 } 2077 2078 static int perf_get_aux_event(struct perf_event *event, 2079 struct perf_event *group_leader) 2080 { 2081 /* 2082 * Our group leader must be an aux event if we want to be 2083 * an aux_output. This way, the aux event will precede its 2084 * aux_output events in the group, and therefore will always 2085 * schedule first. 2086 */ 2087 if (!group_leader) 2088 return 0; 2089 2090 /* 2091 * aux_output and aux_sample_size are mutually exclusive. 2092 */ 2093 if (event->attr.aux_output && event->attr.aux_sample_size) 2094 return 0; 2095 2096 if (event->attr.aux_output && 2097 !perf_aux_output_match(event, group_leader)) 2098 return 0; 2099 2100 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux) 2101 return 0; 2102 2103 if (!atomic_long_inc_not_zero(&group_leader->refcount)) 2104 return 0; 2105 2106 /* 2107 * Link aux_outputs to their aux event; this is undone in 2108 * perf_group_detach() by perf_put_aux_event(). When the 2109 * group in torn down, the aux_output events loose their 2110 * link to the aux_event and can't schedule any more. 2111 */ 2112 event->aux_event = group_leader; 2113 2114 return 1; 2115 } 2116 2117 static inline struct list_head *get_event_list(struct perf_event *event) 2118 { 2119 struct perf_event_context *ctx = event->ctx; 2120 return event->attr.pinned ? &ctx->pinned_active : &ctx->flexible_active; 2121 } 2122 2123 static void perf_group_detach(struct perf_event *event) 2124 { 2125 struct perf_event *sibling, *tmp; 2126 struct perf_event_context *ctx = event->ctx; 2127 2128 lockdep_assert_held(&ctx->lock); 2129 2130 /* 2131 * We can have double detach due to exit/hot-unplug + close. 2132 */ 2133 if (!(event->attach_state & PERF_ATTACH_GROUP)) 2134 return; 2135 2136 event->attach_state &= ~PERF_ATTACH_GROUP; 2137 2138 perf_put_aux_event(event); 2139 2140 /* 2141 * If this is a sibling, remove it from its group. 2142 */ 2143 if (event->group_leader != event) { 2144 list_del_init(&event->sibling_list); 2145 event->group_leader->nr_siblings--; 2146 goto out; 2147 } 2148 2149 /* 2150 * If this was a group event with sibling events then 2151 * upgrade the siblings to singleton events by adding them 2152 * to whatever list we are on. 2153 */ 2154 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) { 2155 2156 sibling->group_leader = sibling; 2157 list_del_init(&sibling->sibling_list); 2158 2159 /* Inherit group flags from the previous leader */ 2160 sibling->group_caps = event->group_caps; 2161 2162 if (!RB_EMPTY_NODE(&event->group_node)) { 2163 add_event_to_groups(sibling, event->ctx); 2164 2165 if (sibling->state == PERF_EVENT_STATE_ACTIVE) 2166 list_add_tail(&sibling->active_list, get_event_list(sibling)); 2167 } 2168 2169 WARN_ON_ONCE(sibling->ctx != event->ctx); 2170 } 2171 2172 out: 2173 perf_event__header_size(event->group_leader); 2174 2175 for_each_sibling_event(tmp, event->group_leader) 2176 perf_event__header_size(tmp); 2177 } 2178 2179 static bool is_orphaned_event(struct perf_event *event) 2180 { 2181 return event->state == PERF_EVENT_STATE_DEAD; 2182 } 2183 2184 static inline int __pmu_filter_match(struct perf_event *event) 2185 { 2186 struct pmu *pmu = event->pmu; 2187 return pmu->filter_match ? pmu->filter_match(event) : 1; 2188 } 2189 2190 /* 2191 * Check whether we should attempt to schedule an event group based on 2192 * PMU-specific filtering. An event group can consist of HW and SW events, 2193 * potentially with a SW leader, so we must check all the filters, to 2194 * determine whether a group is schedulable: 2195 */ 2196 static inline int pmu_filter_match(struct perf_event *event) 2197 { 2198 struct perf_event *sibling; 2199 2200 if (!__pmu_filter_match(event)) 2201 return 0; 2202 2203 for_each_sibling_event(sibling, event) { 2204 if (!__pmu_filter_match(sibling)) 2205 return 0; 2206 } 2207 2208 return 1; 2209 } 2210 2211 static inline int 2212 event_filter_match(struct perf_event *event) 2213 { 2214 return (event->cpu == -1 || event->cpu == smp_processor_id()) && 2215 perf_cgroup_match(event) && pmu_filter_match(event); 2216 } 2217 2218 static void 2219 event_sched_out(struct perf_event *event, 2220 struct perf_cpu_context *cpuctx, 2221 struct perf_event_context *ctx) 2222 { 2223 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE; 2224 2225 WARN_ON_ONCE(event->ctx != ctx); 2226 lockdep_assert_held(&ctx->lock); 2227 2228 if (event->state != PERF_EVENT_STATE_ACTIVE) 2229 return; 2230 2231 /* 2232 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but 2233 * we can schedule events _OUT_ individually through things like 2234 * __perf_remove_from_context(). 2235 */ 2236 list_del_init(&event->active_list); 2237 2238 perf_pmu_disable(event->pmu); 2239 2240 event->pmu->del(event, 0); 2241 event->oncpu = -1; 2242 2243 if (READ_ONCE(event->pending_disable) >= 0) { 2244 WRITE_ONCE(event->pending_disable, -1); 2245 perf_cgroup_event_disable(event, ctx); 2246 state = PERF_EVENT_STATE_OFF; 2247 } 2248 perf_event_set_state(event, state); 2249 2250 if (!is_software_event(event)) 2251 cpuctx->active_oncpu--; 2252 if (!--ctx->nr_active) 2253 perf_event_ctx_deactivate(ctx); 2254 if (event->attr.freq && event->attr.sample_freq) 2255 ctx->nr_freq--; 2256 if (event->attr.exclusive || !cpuctx->active_oncpu) 2257 cpuctx->exclusive = 0; 2258 2259 perf_pmu_enable(event->pmu); 2260 } 2261 2262 static void 2263 group_sched_out(struct perf_event *group_event, 2264 struct perf_cpu_context *cpuctx, 2265 struct perf_event_context *ctx) 2266 { 2267 struct perf_event *event; 2268 2269 if (group_event->state != PERF_EVENT_STATE_ACTIVE) 2270 return; 2271 2272 perf_pmu_disable(ctx->pmu); 2273 2274 event_sched_out(group_event, cpuctx, ctx); 2275 2276 /* 2277 * Schedule out siblings (if any): 2278 */ 2279 for_each_sibling_event(event, group_event) 2280 event_sched_out(event, cpuctx, ctx); 2281 2282 perf_pmu_enable(ctx->pmu); 2283 2284 if (group_event->attr.exclusive) 2285 cpuctx->exclusive = 0; 2286 } 2287 2288 #define DETACH_GROUP 0x01UL 2289 2290 /* 2291 * Cross CPU call to remove a performance event 2292 * 2293 * We disable the event on the hardware level first. After that we 2294 * remove it from the context list. 2295 */ 2296 static void 2297 __perf_remove_from_context(struct perf_event *event, 2298 struct perf_cpu_context *cpuctx, 2299 struct perf_event_context *ctx, 2300 void *info) 2301 { 2302 unsigned long flags = (unsigned long)info; 2303 2304 if (ctx->is_active & EVENT_TIME) { 2305 update_context_time(ctx); 2306 update_cgrp_time_from_cpuctx(cpuctx); 2307 } 2308 2309 event_sched_out(event, cpuctx, ctx); 2310 if (flags & DETACH_GROUP) 2311 perf_group_detach(event); 2312 list_del_event(event, ctx); 2313 2314 if (!ctx->nr_events && ctx->is_active) { 2315 ctx->is_active = 0; 2316 ctx->rotate_necessary = 0; 2317 if (ctx->task) { 2318 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 2319 cpuctx->task_ctx = NULL; 2320 } 2321 } 2322 } 2323 2324 /* 2325 * Remove the event from a task's (or a CPU's) list of events. 2326 * 2327 * If event->ctx is a cloned context, callers must make sure that 2328 * every task struct that event->ctx->task could possibly point to 2329 * remains valid. This is OK when called from perf_release since 2330 * that only calls us on the top-level context, which can't be a clone. 2331 * When called from perf_event_exit_task, it's OK because the 2332 * context has been detached from its task. 2333 */ 2334 static void perf_remove_from_context(struct perf_event *event, unsigned long flags) 2335 { 2336 struct perf_event_context *ctx = event->ctx; 2337 2338 lockdep_assert_held(&ctx->mutex); 2339 2340 event_function_call(event, __perf_remove_from_context, (void *)flags); 2341 2342 /* 2343 * The above event_function_call() can NO-OP when it hits 2344 * TASK_TOMBSTONE. In that case we must already have been detached 2345 * from the context (by perf_event_exit_event()) but the grouping 2346 * might still be in-tact. 2347 */ 2348 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT); 2349 if ((flags & DETACH_GROUP) && 2350 (event->attach_state & PERF_ATTACH_GROUP)) { 2351 /* 2352 * Since in that case we cannot possibly be scheduled, simply 2353 * detach now. 2354 */ 2355 raw_spin_lock_irq(&ctx->lock); 2356 perf_group_detach(event); 2357 raw_spin_unlock_irq(&ctx->lock); 2358 } 2359 } 2360 2361 /* 2362 * Cross CPU call to disable a performance event 2363 */ 2364 static void __perf_event_disable(struct perf_event *event, 2365 struct perf_cpu_context *cpuctx, 2366 struct perf_event_context *ctx, 2367 void *info) 2368 { 2369 if (event->state < PERF_EVENT_STATE_INACTIVE) 2370 return; 2371 2372 if (ctx->is_active & EVENT_TIME) { 2373 update_context_time(ctx); 2374 update_cgrp_time_from_event(event); 2375 } 2376 2377 if (event == event->group_leader) 2378 group_sched_out(event, cpuctx, ctx); 2379 else 2380 event_sched_out(event, cpuctx, ctx); 2381 2382 perf_event_set_state(event, PERF_EVENT_STATE_OFF); 2383 perf_cgroup_event_disable(event, ctx); 2384 } 2385 2386 /* 2387 * Disable an event. 2388 * 2389 * If event->ctx is a cloned context, callers must make sure that 2390 * every task struct that event->ctx->task could possibly point to 2391 * remains valid. This condition is satisfied when called through 2392 * perf_event_for_each_child or perf_event_for_each because they 2393 * hold the top-level event's child_mutex, so any descendant that 2394 * goes to exit will block in perf_event_exit_event(). 2395 * 2396 * When called from perf_pending_event it's OK because event->ctx 2397 * is the current context on this CPU and preemption is disabled, 2398 * hence we can't get into perf_event_task_sched_out for this context. 2399 */ 2400 static void _perf_event_disable(struct perf_event *event) 2401 { 2402 struct perf_event_context *ctx = event->ctx; 2403 2404 raw_spin_lock_irq(&ctx->lock); 2405 if (event->state <= PERF_EVENT_STATE_OFF) { 2406 raw_spin_unlock_irq(&ctx->lock); 2407 return; 2408 } 2409 raw_spin_unlock_irq(&ctx->lock); 2410 2411 event_function_call(event, __perf_event_disable, NULL); 2412 } 2413 2414 void perf_event_disable_local(struct perf_event *event) 2415 { 2416 event_function_local(event, __perf_event_disable, NULL); 2417 } 2418 2419 /* 2420 * Strictly speaking kernel users cannot create groups and therefore this 2421 * interface does not need the perf_event_ctx_lock() magic. 2422 */ 2423 void perf_event_disable(struct perf_event *event) 2424 { 2425 struct perf_event_context *ctx; 2426 2427 ctx = perf_event_ctx_lock(event); 2428 _perf_event_disable(event); 2429 perf_event_ctx_unlock(event, ctx); 2430 } 2431 EXPORT_SYMBOL_GPL(perf_event_disable); 2432 2433 void perf_event_disable_inatomic(struct perf_event *event) 2434 { 2435 WRITE_ONCE(event->pending_disable, smp_processor_id()); 2436 /* can fail, see perf_pending_event_disable() */ 2437 irq_work_queue(&event->pending); 2438 } 2439 2440 static void perf_set_shadow_time(struct perf_event *event, 2441 struct perf_event_context *ctx) 2442 { 2443 /* 2444 * use the correct time source for the time snapshot 2445 * 2446 * We could get by without this by leveraging the 2447 * fact that to get to this function, the caller 2448 * has most likely already called update_context_time() 2449 * and update_cgrp_time_xx() and thus both timestamp 2450 * are identical (or very close). Given that tstamp is, 2451 * already adjusted for cgroup, we could say that: 2452 * tstamp - ctx->timestamp 2453 * is equivalent to 2454 * tstamp - cgrp->timestamp. 2455 * 2456 * Then, in perf_output_read(), the calculation would 2457 * work with no changes because: 2458 * - event is guaranteed scheduled in 2459 * - no scheduled out in between 2460 * - thus the timestamp would be the same 2461 * 2462 * But this is a bit hairy. 2463 * 2464 * So instead, we have an explicit cgroup call to remain 2465 * within the time time source all along. We believe it 2466 * is cleaner and simpler to understand. 2467 */ 2468 if (is_cgroup_event(event)) 2469 perf_cgroup_set_shadow_time(event, event->tstamp); 2470 else 2471 event->shadow_ctx_time = event->tstamp - ctx->timestamp; 2472 } 2473 2474 #define MAX_INTERRUPTS (~0ULL) 2475 2476 static void perf_log_throttle(struct perf_event *event, int enable); 2477 static void perf_log_itrace_start(struct perf_event *event); 2478 2479 static int 2480 event_sched_in(struct perf_event *event, 2481 struct perf_cpu_context *cpuctx, 2482 struct perf_event_context *ctx) 2483 { 2484 int ret = 0; 2485 2486 WARN_ON_ONCE(event->ctx != ctx); 2487 2488 lockdep_assert_held(&ctx->lock); 2489 2490 if (event->state <= PERF_EVENT_STATE_OFF) 2491 return 0; 2492 2493 WRITE_ONCE(event->oncpu, smp_processor_id()); 2494 /* 2495 * Order event::oncpu write to happen before the ACTIVE state is 2496 * visible. This allows perf_event_{stop,read}() to observe the correct 2497 * ->oncpu if it sees ACTIVE. 2498 */ 2499 smp_wmb(); 2500 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE); 2501 2502 /* 2503 * Unthrottle events, since we scheduled we might have missed several 2504 * ticks already, also for a heavily scheduling task there is little 2505 * guarantee it'll get a tick in a timely manner. 2506 */ 2507 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) { 2508 perf_log_throttle(event, 1); 2509 event->hw.interrupts = 0; 2510 } 2511 2512 perf_pmu_disable(event->pmu); 2513 2514 perf_set_shadow_time(event, ctx); 2515 2516 perf_log_itrace_start(event); 2517 2518 if (event->pmu->add(event, PERF_EF_START)) { 2519 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 2520 event->oncpu = -1; 2521 ret = -EAGAIN; 2522 goto out; 2523 } 2524 2525 if (!is_software_event(event)) 2526 cpuctx->active_oncpu++; 2527 if (!ctx->nr_active++) 2528 perf_event_ctx_activate(ctx); 2529 if (event->attr.freq && event->attr.sample_freq) 2530 ctx->nr_freq++; 2531 2532 if (event->attr.exclusive) 2533 cpuctx->exclusive = 1; 2534 2535 out: 2536 perf_pmu_enable(event->pmu); 2537 2538 return ret; 2539 } 2540 2541 static int 2542 group_sched_in(struct perf_event *group_event, 2543 struct perf_cpu_context *cpuctx, 2544 struct perf_event_context *ctx) 2545 { 2546 struct perf_event *event, *partial_group = NULL; 2547 struct pmu *pmu = ctx->pmu; 2548 2549 if (group_event->state == PERF_EVENT_STATE_OFF) 2550 return 0; 2551 2552 pmu->start_txn(pmu, PERF_PMU_TXN_ADD); 2553 2554 if (event_sched_in(group_event, cpuctx, ctx)) { 2555 pmu->cancel_txn(pmu); 2556 perf_mux_hrtimer_restart(cpuctx); 2557 return -EAGAIN; 2558 } 2559 2560 /* 2561 * Schedule in siblings as one group (if any): 2562 */ 2563 for_each_sibling_event(event, group_event) { 2564 if (event_sched_in(event, cpuctx, ctx)) { 2565 partial_group = event; 2566 goto group_error; 2567 } 2568 } 2569 2570 if (!pmu->commit_txn(pmu)) 2571 return 0; 2572 2573 group_error: 2574 /* 2575 * Groups can be scheduled in as one unit only, so undo any 2576 * partial group before returning: 2577 * The events up to the failed event are scheduled out normally. 2578 */ 2579 for_each_sibling_event(event, group_event) { 2580 if (event == partial_group) 2581 break; 2582 2583 event_sched_out(event, cpuctx, ctx); 2584 } 2585 event_sched_out(group_event, cpuctx, ctx); 2586 2587 pmu->cancel_txn(pmu); 2588 2589 perf_mux_hrtimer_restart(cpuctx); 2590 2591 return -EAGAIN; 2592 } 2593 2594 /* 2595 * Work out whether we can put this event group on the CPU now. 2596 */ 2597 static int group_can_go_on(struct perf_event *event, 2598 struct perf_cpu_context *cpuctx, 2599 int can_add_hw) 2600 { 2601 /* 2602 * Groups consisting entirely of software events can always go on. 2603 */ 2604 if (event->group_caps & PERF_EV_CAP_SOFTWARE) 2605 return 1; 2606 /* 2607 * If an exclusive group is already on, no other hardware 2608 * events can go on. 2609 */ 2610 if (cpuctx->exclusive) 2611 return 0; 2612 /* 2613 * If this group is exclusive and there are already 2614 * events on the CPU, it can't go on. 2615 */ 2616 if (event->attr.exclusive && cpuctx->active_oncpu) 2617 return 0; 2618 /* 2619 * Otherwise, try to add it if all previous groups were able 2620 * to go on. 2621 */ 2622 return can_add_hw; 2623 } 2624 2625 static void add_event_to_ctx(struct perf_event *event, 2626 struct perf_event_context *ctx) 2627 { 2628 list_add_event(event, ctx); 2629 perf_group_attach(event); 2630 } 2631 2632 static void ctx_sched_out(struct perf_event_context *ctx, 2633 struct perf_cpu_context *cpuctx, 2634 enum event_type_t event_type); 2635 static void 2636 ctx_sched_in(struct perf_event_context *ctx, 2637 struct perf_cpu_context *cpuctx, 2638 enum event_type_t event_type, 2639 struct task_struct *task); 2640 2641 static void task_ctx_sched_out(struct perf_cpu_context *cpuctx, 2642 struct perf_event_context *ctx, 2643 enum event_type_t event_type) 2644 { 2645 if (!cpuctx->task_ctx) 2646 return; 2647 2648 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx)) 2649 return; 2650 2651 ctx_sched_out(ctx, cpuctx, event_type); 2652 } 2653 2654 static void perf_event_sched_in(struct perf_cpu_context *cpuctx, 2655 struct perf_event_context *ctx, 2656 struct task_struct *task) 2657 { 2658 cpu_ctx_sched_in(cpuctx, EVENT_PINNED, task); 2659 if (ctx) 2660 ctx_sched_in(ctx, cpuctx, EVENT_PINNED, task); 2661 cpu_ctx_sched_in(cpuctx, EVENT_FLEXIBLE, task); 2662 if (ctx) 2663 ctx_sched_in(ctx, cpuctx, EVENT_FLEXIBLE, task); 2664 } 2665 2666 /* 2667 * We want to maintain the following priority of scheduling: 2668 * - CPU pinned (EVENT_CPU | EVENT_PINNED) 2669 * - task pinned (EVENT_PINNED) 2670 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE) 2671 * - task flexible (EVENT_FLEXIBLE). 2672 * 2673 * In order to avoid unscheduling and scheduling back in everything every 2674 * time an event is added, only do it for the groups of equal priority and 2675 * below. 2676 * 2677 * This can be called after a batch operation on task events, in which case 2678 * event_type is a bit mask of the types of events involved. For CPU events, 2679 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE. 2680 */ 2681 static void ctx_resched(struct perf_cpu_context *cpuctx, 2682 struct perf_event_context *task_ctx, 2683 enum event_type_t event_type) 2684 { 2685 enum event_type_t ctx_event_type; 2686 bool cpu_event = !!(event_type & EVENT_CPU); 2687 2688 /* 2689 * If pinned groups are involved, flexible groups also need to be 2690 * scheduled out. 2691 */ 2692 if (event_type & EVENT_PINNED) 2693 event_type |= EVENT_FLEXIBLE; 2694 2695 ctx_event_type = event_type & EVENT_ALL; 2696 2697 perf_pmu_disable(cpuctx->ctx.pmu); 2698 if (task_ctx) 2699 task_ctx_sched_out(cpuctx, task_ctx, event_type); 2700 2701 /* 2702 * Decide which cpu ctx groups to schedule out based on the types 2703 * of events that caused rescheduling: 2704 * - EVENT_CPU: schedule out corresponding groups; 2705 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups; 2706 * - otherwise, do nothing more. 2707 */ 2708 if (cpu_event) 2709 cpu_ctx_sched_out(cpuctx, ctx_event_type); 2710 else if (ctx_event_type & EVENT_PINNED) 2711 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE); 2712 2713 perf_event_sched_in(cpuctx, task_ctx, current); 2714 perf_pmu_enable(cpuctx->ctx.pmu); 2715 } 2716 2717 void perf_pmu_resched(struct pmu *pmu) 2718 { 2719 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); 2720 struct perf_event_context *task_ctx = cpuctx->task_ctx; 2721 2722 perf_ctx_lock(cpuctx, task_ctx); 2723 ctx_resched(cpuctx, task_ctx, EVENT_ALL|EVENT_CPU); 2724 perf_ctx_unlock(cpuctx, task_ctx); 2725 } 2726 2727 /* 2728 * Cross CPU call to install and enable a performance event 2729 * 2730 * Very similar to remote_function() + event_function() but cannot assume that 2731 * things like ctx->is_active and cpuctx->task_ctx are set. 2732 */ 2733 static int __perf_install_in_context(void *info) 2734 { 2735 struct perf_event *event = info; 2736 struct perf_event_context *ctx = event->ctx; 2737 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); 2738 struct perf_event_context *task_ctx = cpuctx->task_ctx; 2739 bool reprogram = true; 2740 int ret = 0; 2741 2742 raw_spin_lock(&cpuctx->ctx.lock); 2743 if (ctx->task) { 2744 raw_spin_lock(&ctx->lock); 2745 task_ctx = ctx; 2746 2747 reprogram = (ctx->task == current); 2748 2749 /* 2750 * If the task is running, it must be running on this CPU, 2751 * otherwise we cannot reprogram things. 2752 * 2753 * If its not running, we don't care, ctx->lock will 2754 * serialize against it becoming runnable. 2755 */ 2756 if (task_curr(ctx->task) && !reprogram) { 2757 ret = -ESRCH; 2758 goto unlock; 2759 } 2760 2761 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx); 2762 } else if (task_ctx) { 2763 raw_spin_lock(&task_ctx->lock); 2764 } 2765 2766 #ifdef CONFIG_CGROUP_PERF 2767 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) { 2768 /* 2769 * If the current cgroup doesn't match the event's 2770 * cgroup, we should not try to schedule it. 2771 */ 2772 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx); 2773 reprogram = cgroup_is_descendant(cgrp->css.cgroup, 2774 event->cgrp->css.cgroup); 2775 } 2776 #endif 2777 2778 if (reprogram) { 2779 ctx_sched_out(ctx, cpuctx, EVENT_TIME); 2780 add_event_to_ctx(event, ctx); 2781 ctx_resched(cpuctx, task_ctx, get_event_type(event)); 2782 } else { 2783 add_event_to_ctx(event, ctx); 2784 } 2785 2786 unlock: 2787 perf_ctx_unlock(cpuctx, task_ctx); 2788 2789 return ret; 2790 } 2791 2792 static bool exclusive_event_installable(struct perf_event *event, 2793 struct perf_event_context *ctx); 2794 2795 /* 2796 * Attach a performance event to a context. 2797 * 2798 * Very similar to event_function_call, see comment there. 2799 */ 2800 static void 2801 perf_install_in_context(struct perf_event_context *ctx, 2802 struct perf_event *event, 2803 int cpu) 2804 { 2805 struct task_struct *task = READ_ONCE(ctx->task); 2806 2807 lockdep_assert_held(&ctx->mutex); 2808 2809 WARN_ON_ONCE(!exclusive_event_installable(event, ctx)); 2810 2811 if (event->cpu != -1) 2812 event->cpu = cpu; 2813 2814 /* 2815 * Ensures that if we can observe event->ctx, both the event and ctx 2816 * will be 'complete'. See perf_iterate_sb_cpu(). 2817 */ 2818 smp_store_release(&event->ctx, ctx); 2819 2820 /* 2821 * perf_event_attr::disabled events will not run and can be initialized 2822 * without IPI. Except when this is the first event for the context, in 2823 * that case we need the magic of the IPI to set ctx->is_active. 2824 * 2825 * The IOC_ENABLE that is sure to follow the creation of a disabled 2826 * event will issue the IPI and reprogram the hardware. 2827 */ 2828 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && ctx->nr_events) { 2829 raw_spin_lock_irq(&ctx->lock); 2830 if (ctx->task == TASK_TOMBSTONE) { 2831 raw_spin_unlock_irq(&ctx->lock); 2832 return; 2833 } 2834 add_event_to_ctx(event, ctx); 2835 raw_spin_unlock_irq(&ctx->lock); 2836 return; 2837 } 2838 2839 if (!task) { 2840 cpu_function_call(cpu, __perf_install_in_context, event); 2841 return; 2842 } 2843 2844 /* 2845 * Should not happen, we validate the ctx is still alive before calling. 2846 */ 2847 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) 2848 return; 2849 2850 /* 2851 * Installing events is tricky because we cannot rely on ctx->is_active 2852 * to be set in case this is the nr_events 0 -> 1 transition. 2853 * 2854 * Instead we use task_curr(), which tells us if the task is running. 2855 * However, since we use task_curr() outside of rq::lock, we can race 2856 * against the actual state. This means the result can be wrong. 2857 * 2858 * If we get a false positive, we retry, this is harmless. 2859 * 2860 * If we get a false negative, things are complicated. If we are after 2861 * perf_event_context_sched_in() ctx::lock will serialize us, and the 2862 * value must be correct. If we're before, it doesn't matter since 2863 * perf_event_context_sched_in() will program the counter. 2864 * 2865 * However, this hinges on the remote context switch having observed 2866 * our task->perf_event_ctxp[] store, such that it will in fact take 2867 * ctx::lock in perf_event_context_sched_in(). 2868 * 2869 * We do this by task_function_call(), if the IPI fails to hit the task 2870 * we know any future context switch of task must see the 2871 * perf_event_ctpx[] store. 2872 */ 2873 2874 /* 2875 * This smp_mb() orders the task->perf_event_ctxp[] store with the 2876 * task_cpu() load, such that if the IPI then does not find the task 2877 * running, a future context switch of that task must observe the 2878 * store. 2879 */ 2880 smp_mb(); 2881 again: 2882 if (!task_function_call(task, __perf_install_in_context, event)) 2883 return; 2884 2885 raw_spin_lock_irq(&ctx->lock); 2886 task = ctx->task; 2887 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) { 2888 /* 2889 * Cannot happen because we already checked above (which also 2890 * cannot happen), and we hold ctx->mutex, which serializes us 2891 * against perf_event_exit_task_context(). 2892 */ 2893 raw_spin_unlock_irq(&ctx->lock); 2894 return; 2895 } 2896 /* 2897 * If the task is not running, ctx->lock will avoid it becoming so, 2898 * thus we can safely install the event. 2899 */ 2900 if (task_curr(task)) { 2901 raw_spin_unlock_irq(&ctx->lock); 2902 goto again; 2903 } 2904 add_event_to_ctx(event, ctx); 2905 raw_spin_unlock_irq(&ctx->lock); 2906 } 2907 2908 /* 2909 * Cross CPU call to enable a performance event 2910 */ 2911 static void __perf_event_enable(struct perf_event *event, 2912 struct perf_cpu_context *cpuctx, 2913 struct perf_event_context *ctx, 2914 void *info) 2915 { 2916 struct perf_event *leader = event->group_leader; 2917 struct perf_event_context *task_ctx; 2918 2919 if (event->state >= PERF_EVENT_STATE_INACTIVE || 2920 event->state <= PERF_EVENT_STATE_ERROR) 2921 return; 2922 2923 if (ctx->is_active) 2924 ctx_sched_out(ctx, cpuctx, EVENT_TIME); 2925 2926 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 2927 perf_cgroup_event_enable(event, ctx); 2928 2929 if (!ctx->is_active) 2930 return; 2931 2932 if (!event_filter_match(event)) { 2933 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current); 2934 return; 2935 } 2936 2937 /* 2938 * If the event is in a group and isn't the group leader, 2939 * then don't put it on unless the group is on. 2940 */ 2941 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) { 2942 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current); 2943 return; 2944 } 2945 2946 task_ctx = cpuctx->task_ctx; 2947 if (ctx->task) 2948 WARN_ON_ONCE(task_ctx != ctx); 2949 2950 ctx_resched(cpuctx, task_ctx, get_event_type(event)); 2951 } 2952 2953 /* 2954 * Enable an event. 2955 * 2956 * If event->ctx is a cloned context, callers must make sure that 2957 * every task struct that event->ctx->task could possibly point to 2958 * remains valid. This condition is satisfied when called through 2959 * perf_event_for_each_child or perf_event_for_each as described 2960 * for perf_event_disable. 2961 */ 2962 static void _perf_event_enable(struct perf_event *event) 2963 { 2964 struct perf_event_context *ctx = event->ctx; 2965 2966 raw_spin_lock_irq(&ctx->lock); 2967 if (event->state >= PERF_EVENT_STATE_INACTIVE || 2968 event->state < PERF_EVENT_STATE_ERROR) { 2969 raw_spin_unlock_irq(&ctx->lock); 2970 return; 2971 } 2972 2973 /* 2974 * If the event is in error state, clear that first. 2975 * 2976 * That way, if we see the event in error state below, we know that it 2977 * has gone back into error state, as distinct from the task having 2978 * been scheduled away before the cross-call arrived. 2979 */ 2980 if (event->state == PERF_EVENT_STATE_ERROR) 2981 event->state = PERF_EVENT_STATE_OFF; 2982 raw_spin_unlock_irq(&ctx->lock); 2983 2984 event_function_call(event, __perf_event_enable, NULL); 2985 } 2986 2987 /* 2988 * See perf_event_disable(); 2989 */ 2990 void perf_event_enable(struct perf_event *event) 2991 { 2992 struct perf_event_context *ctx; 2993 2994 ctx = perf_event_ctx_lock(event); 2995 _perf_event_enable(event); 2996 perf_event_ctx_unlock(event, ctx); 2997 } 2998 EXPORT_SYMBOL_GPL(perf_event_enable); 2999 3000 struct stop_event_data { 3001 struct perf_event *event; 3002 unsigned int restart; 3003 }; 3004 3005 static int __perf_event_stop(void *info) 3006 { 3007 struct stop_event_data *sd = info; 3008 struct perf_event *event = sd->event; 3009 3010 /* if it's already INACTIVE, do nothing */ 3011 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) 3012 return 0; 3013 3014 /* matches smp_wmb() in event_sched_in() */ 3015 smp_rmb(); 3016 3017 /* 3018 * There is a window with interrupts enabled before we get here, 3019 * so we need to check again lest we try to stop another CPU's event. 3020 */ 3021 if (READ_ONCE(event->oncpu) != smp_processor_id()) 3022 return -EAGAIN; 3023 3024 event->pmu->stop(event, PERF_EF_UPDATE); 3025 3026 /* 3027 * May race with the actual stop (through perf_pmu_output_stop()), 3028 * but it is only used for events with AUX ring buffer, and such 3029 * events will refuse to restart because of rb::aux_mmap_count==0, 3030 * see comments in perf_aux_output_begin(). 3031 * 3032 * Since this is happening on an event-local CPU, no trace is lost 3033 * while restarting. 3034 */ 3035 if (sd->restart) 3036 event->pmu->start(event, 0); 3037 3038 return 0; 3039 } 3040 3041 static int perf_event_stop(struct perf_event *event, int restart) 3042 { 3043 struct stop_event_data sd = { 3044 .event = event, 3045 .restart = restart, 3046 }; 3047 int ret = 0; 3048 3049 do { 3050 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) 3051 return 0; 3052 3053 /* matches smp_wmb() in event_sched_in() */ 3054 smp_rmb(); 3055 3056 /* 3057 * We only want to restart ACTIVE events, so if the event goes 3058 * inactive here (event->oncpu==-1), there's nothing more to do; 3059 * fall through with ret==-ENXIO. 3060 */ 3061 ret = cpu_function_call(READ_ONCE(event->oncpu), 3062 __perf_event_stop, &sd); 3063 } while (ret == -EAGAIN); 3064 3065 return ret; 3066 } 3067 3068 /* 3069 * In order to contain the amount of racy and tricky in the address filter 3070 * configuration management, it is a two part process: 3071 * 3072 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below, 3073 * we update the addresses of corresponding vmas in 3074 * event::addr_filter_ranges array and bump the event::addr_filters_gen; 3075 * (p2) when an event is scheduled in (pmu::add), it calls 3076 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync() 3077 * if the generation has changed since the previous call. 3078 * 3079 * If (p1) happens while the event is active, we restart it to force (p2). 3080 * 3081 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on 3082 * pre-existing mappings, called once when new filters arrive via SET_FILTER 3083 * ioctl; 3084 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly 3085 * registered mapping, called for every new mmap(), with mm::mmap_sem down 3086 * for reading; 3087 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process 3088 * of exec. 3089 */ 3090 void perf_event_addr_filters_sync(struct perf_event *event) 3091 { 3092 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 3093 3094 if (!has_addr_filter(event)) 3095 return; 3096 3097 raw_spin_lock(&ifh->lock); 3098 if (event->addr_filters_gen != event->hw.addr_filters_gen) { 3099 event->pmu->addr_filters_sync(event); 3100 event->hw.addr_filters_gen = event->addr_filters_gen; 3101 } 3102 raw_spin_unlock(&ifh->lock); 3103 } 3104 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync); 3105 3106 static int _perf_event_refresh(struct perf_event *event, int refresh) 3107 { 3108 /* 3109 * not supported on inherited events 3110 */ 3111 if (event->attr.inherit || !is_sampling_event(event)) 3112 return -EINVAL; 3113 3114 atomic_add(refresh, &event->event_limit); 3115 _perf_event_enable(event); 3116 3117 return 0; 3118 } 3119 3120 /* 3121 * See perf_event_disable() 3122 */ 3123 int perf_event_refresh(struct perf_event *event, int refresh) 3124 { 3125 struct perf_event_context *ctx; 3126 int ret; 3127 3128 ctx = perf_event_ctx_lock(event); 3129 ret = _perf_event_refresh(event, refresh); 3130 perf_event_ctx_unlock(event, ctx); 3131 3132 return ret; 3133 } 3134 EXPORT_SYMBOL_GPL(perf_event_refresh); 3135 3136 static int perf_event_modify_breakpoint(struct perf_event *bp, 3137 struct perf_event_attr *attr) 3138 { 3139 int err; 3140 3141 _perf_event_disable(bp); 3142 3143 err = modify_user_hw_breakpoint_check(bp, attr, true); 3144 3145 if (!bp->attr.disabled) 3146 _perf_event_enable(bp); 3147 3148 return err; 3149 } 3150 3151 static int perf_event_modify_attr(struct perf_event *event, 3152 struct perf_event_attr *attr) 3153 { 3154 if (event->attr.type != attr->type) 3155 return -EINVAL; 3156 3157 switch (event->attr.type) { 3158 case PERF_TYPE_BREAKPOINT: 3159 return perf_event_modify_breakpoint(event, attr); 3160 default: 3161 /* Place holder for future additions. */ 3162 return -EOPNOTSUPP; 3163 } 3164 } 3165 3166 static void ctx_sched_out(struct perf_event_context *ctx, 3167 struct perf_cpu_context *cpuctx, 3168 enum event_type_t event_type) 3169 { 3170 struct perf_event *event, *tmp; 3171 int is_active = ctx->is_active; 3172 3173 lockdep_assert_held(&ctx->lock); 3174 3175 if (likely(!ctx->nr_events)) { 3176 /* 3177 * See __perf_remove_from_context(). 3178 */ 3179 WARN_ON_ONCE(ctx->is_active); 3180 if (ctx->task) 3181 WARN_ON_ONCE(cpuctx->task_ctx); 3182 return; 3183 } 3184 3185 ctx->is_active &= ~event_type; 3186 if (!(ctx->is_active & EVENT_ALL)) 3187 ctx->is_active = 0; 3188 3189 if (ctx->task) { 3190 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 3191 if (!ctx->is_active) 3192 cpuctx->task_ctx = NULL; 3193 } 3194 3195 /* 3196 * Always update time if it was set; not only when it changes. 3197 * Otherwise we can 'forget' to update time for any but the last 3198 * context we sched out. For example: 3199 * 3200 * ctx_sched_out(.event_type = EVENT_FLEXIBLE) 3201 * ctx_sched_out(.event_type = EVENT_PINNED) 3202 * 3203 * would only update time for the pinned events. 3204 */ 3205 if (is_active & EVENT_TIME) { 3206 /* update (and stop) ctx time */ 3207 update_context_time(ctx); 3208 update_cgrp_time_from_cpuctx(cpuctx); 3209 } 3210 3211 is_active ^= ctx->is_active; /* changed bits */ 3212 3213 if (!ctx->nr_active || !(is_active & EVENT_ALL)) 3214 return; 3215 3216 perf_pmu_disable(ctx->pmu); 3217 if (is_active & EVENT_PINNED) { 3218 list_for_each_entry_safe(event, tmp, &ctx->pinned_active, active_list) 3219 group_sched_out(event, cpuctx, ctx); 3220 } 3221 3222 if (is_active & EVENT_FLEXIBLE) { 3223 list_for_each_entry_safe(event, tmp, &ctx->flexible_active, active_list) 3224 group_sched_out(event, cpuctx, ctx); 3225 3226 /* 3227 * Since we cleared EVENT_FLEXIBLE, also clear 3228 * rotate_necessary, is will be reset by 3229 * ctx_flexible_sched_in() when needed. 3230 */ 3231 ctx->rotate_necessary = 0; 3232 } 3233 perf_pmu_enable(ctx->pmu); 3234 } 3235 3236 /* 3237 * Test whether two contexts are equivalent, i.e. whether they have both been 3238 * cloned from the same version of the same context. 3239 * 3240 * Equivalence is measured using a generation number in the context that is 3241 * incremented on each modification to it; see unclone_ctx(), list_add_event() 3242 * and list_del_event(). 3243 */ 3244 static int context_equiv(struct perf_event_context *ctx1, 3245 struct perf_event_context *ctx2) 3246 { 3247 lockdep_assert_held(&ctx1->lock); 3248 lockdep_assert_held(&ctx2->lock); 3249 3250 /* Pinning disables the swap optimization */ 3251 if (ctx1->pin_count || ctx2->pin_count) 3252 return 0; 3253 3254 /* If ctx1 is the parent of ctx2 */ 3255 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen) 3256 return 1; 3257 3258 /* If ctx2 is the parent of ctx1 */ 3259 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation) 3260 return 1; 3261 3262 /* 3263 * If ctx1 and ctx2 have the same parent; we flatten the parent 3264 * hierarchy, see perf_event_init_context(). 3265 */ 3266 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx && 3267 ctx1->parent_gen == ctx2->parent_gen) 3268 return 1; 3269 3270 /* Unmatched */ 3271 return 0; 3272 } 3273 3274 static void __perf_event_sync_stat(struct perf_event *event, 3275 struct perf_event *next_event) 3276 { 3277 u64 value; 3278 3279 if (!event->attr.inherit_stat) 3280 return; 3281 3282 /* 3283 * Update the event value, we cannot use perf_event_read() 3284 * because we're in the middle of a context switch and have IRQs 3285 * disabled, which upsets smp_call_function_single(), however 3286 * we know the event must be on the current CPU, therefore we 3287 * don't need to use it. 3288 */ 3289 if (event->state == PERF_EVENT_STATE_ACTIVE) 3290 event->pmu->read(event); 3291 3292 perf_event_update_time(event); 3293 3294 /* 3295 * In order to keep per-task stats reliable we need to flip the event 3296 * values when we flip the contexts. 3297 */ 3298 value = local64_read(&next_event->count); 3299 value = local64_xchg(&event->count, value); 3300 local64_set(&next_event->count, value); 3301 3302 swap(event->total_time_enabled, next_event->total_time_enabled); 3303 swap(event->total_time_running, next_event->total_time_running); 3304 3305 /* 3306 * Since we swizzled the values, update the user visible data too. 3307 */ 3308 perf_event_update_userpage(event); 3309 perf_event_update_userpage(next_event); 3310 } 3311 3312 static void perf_event_sync_stat(struct perf_event_context *ctx, 3313 struct perf_event_context *next_ctx) 3314 { 3315 struct perf_event *event, *next_event; 3316 3317 if (!ctx->nr_stat) 3318 return; 3319 3320 update_context_time(ctx); 3321 3322 event = list_first_entry(&ctx->event_list, 3323 struct perf_event, event_entry); 3324 3325 next_event = list_first_entry(&next_ctx->event_list, 3326 struct perf_event, event_entry); 3327 3328 while (&event->event_entry != &ctx->event_list && 3329 &next_event->event_entry != &next_ctx->event_list) { 3330 3331 __perf_event_sync_stat(event, next_event); 3332 3333 event = list_next_entry(event, event_entry); 3334 next_event = list_next_entry(next_event, event_entry); 3335 } 3336 } 3337 3338 static void perf_event_context_sched_out(struct task_struct *task, int ctxn, 3339 struct task_struct *next) 3340 { 3341 struct perf_event_context *ctx = task->perf_event_ctxp[ctxn]; 3342 struct perf_event_context *next_ctx; 3343 struct perf_event_context *parent, *next_parent; 3344 struct perf_cpu_context *cpuctx; 3345 int do_switch = 1; 3346 3347 if (likely(!ctx)) 3348 return; 3349 3350 cpuctx = __get_cpu_context(ctx); 3351 if (!cpuctx->task_ctx) 3352 return; 3353 3354 rcu_read_lock(); 3355 next_ctx = next->perf_event_ctxp[ctxn]; 3356 if (!next_ctx) 3357 goto unlock; 3358 3359 parent = rcu_dereference(ctx->parent_ctx); 3360 next_parent = rcu_dereference(next_ctx->parent_ctx); 3361 3362 /* If neither context have a parent context; they cannot be clones. */ 3363 if (!parent && !next_parent) 3364 goto unlock; 3365 3366 if (next_parent == ctx || next_ctx == parent || next_parent == parent) { 3367 /* 3368 * Looks like the two contexts are clones, so we might be 3369 * able to optimize the context switch. We lock both 3370 * contexts and check that they are clones under the 3371 * lock (including re-checking that neither has been 3372 * uncloned in the meantime). It doesn't matter which 3373 * order we take the locks because no other cpu could 3374 * be trying to lock both of these tasks. 3375 */ 3376 raw_spin_lock(&ctx->lock); 3377 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING); 3378 if (context_equiv(ctx, next_ctx)) { 3379 struct pmu *pmu = ctx->pmu; 3380 3381 WRITE_ONCE(ctx->task, next); 3382 WRITE_ONCE(next_ctx->task, task); 3383 3384 /* 3385 * PMU specific parts of task perf context can require 3386 * additional synchronization. As an example of such 3387 * synchronization see implementation details of Intel 3388 * LBR call stack data profiling; 3389 */ 3390 if (pmu->swap_task_ctx) 3391 pmu->swap_task_ctx(ctx, next_ctx); 3392 else 3393 swap(ctx->task_ctx_data, next_ctx->task_ctx_data); 3394 3395 /* 3396 * RCU_INIT_POINTER here is safe because we've not 3397 * modified the ctx and the above modification of 3398 * ctx->task and ctx->task_ctx_data are immaterial 3399 * since those values are always verified under 3400 * ctx->lock which we're now holding. 3401 */ 3402 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], next_ctx); 3403 RCU_INIT_POINTER(next->perf_event_ctxp[ctxn], ctx); 3404 3405 do_switch = 0; 3406 3407 perf_event_sync_stat(ctx, next_ctx); 3408 } 3409 raw_spin_unlock(&next_ctx->lock); 3410 raw_spin_unlock(&ctx->lock); 3411 } 3412 unlock: 3413 rcu_read_unlock(); 3414 3415 if (do_switch) { 3416 raw_spin_lock(&ctx->lock); 3417 task_ctx_sched_out(cpuctx, ctx, EVENT_ALL); 3418 raw_spin_unlock(&ctx->lock); 3419 } 3420 } 3421 3422 static DEFINE_PER_CPU(struct list_head, sched_cb_list); 3423 3424 void perf_sched_cb_dec(struct pmu *pmu) 3425 { 3426 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); 3427 3428 this_cpu_dec(perf_sched_cb_usages); 3429 3430 if (!--cpuctx->sched_cb_usage) 3431 list_del(&cpuctx->sched_cb_entry); 3432 } 3433 3434 3435 void perf_sched_cb_inc(struct pmu *pmu) 3436 { 3437 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); 3438 3439 if (!cpuctx->sched_cb_usage++) 3440 list_add(&cpuctx->sched_cb_entry, this_cpu_ptr(&sched_cb_list)); 3441 3442 this_cpu_inc(perf_sched_cb_usages); 3443 } 3444 3445 /* 3446 * This function provides the context switch callback to the lower code 3447 * layer. It is invoked ONLY when the context switch callback is enabled. 3448 * 3449 * This callback is relevant even to per-cpu events; for example multi event 3450 * PEBS requires this to provide PID/TID information. This requires we flush 3451 * all queued PEBS records before we context switch to a new task. 3452 */ 3453 static void perf_pmu_sched_task(struct task_struct *prev, 3454 struct task_struct *next, 3455 bool sched_in) 3456 { 3457 struct perf_cpu_context *cpuctx; 3458 struct pmu *pmu; 3459 3460 if (prev == next) 3461 return; 3462 3463 list_for_each_entry(cpuctx, this_cpu_ptr(&sched_cb_list), sched_cb_entry) { 3464 pmu = cpuctx->ctx.pmu; /* software PMUs will not have sched_task */ 3465 3466 if (WARN_ON_ONCE(!pmu->sched_task)) 3467 continue; 3468 3469 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 3470 perf_pmu_disable(pmu); 3471 3472 pmu->sched_task(cpuctx->task_ctx, sched_in); 3473 3474 perf_pmu_enable(pmu); 3475 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 3476 } 3477 } 3478 3479 static void perf_event_switch(struct task_struct *task, 3480 struct task_struct *next_prev, bool sched_in); 3481 3482 #define for_each_task_context_nr(ctxn) \ 3483 for ((ctxn) = 0; (ctxn) < perf_nr_task_contexts; (ctxn)++) 3484 3485 /* 3486 * Called from scheduler to remove the events of the current task, 3487 * with interrupts disabled. 3488 * 3489 * We stop each event and update the event value in event->count. 3490 * 3491 * This does not protect us against NMI, but disable() 3492 * sets the disabled bit in the control field of event _before_ 3493 * accessing the event control register. If a NMI hits, then it will 3494 * not restart the event. 3495 */ 3496 void __perf_event_task_sched_out(struct task_struct *task, 3497 struct task_struct *next) 3498 { 3499 int ctxn; 3500 3501 if (__this_cpu_read(perf_sched_cb_usages)) 3502 perf_pmu_sched_task(task, next, false); 3503 3504 if (atomic_read(&nr_switch_events)) 3505 perf_event_switch(task, next, false); 3506 3507 for_each_task_context_nr(ctxn) 3508 perf_event_context_sched_out(task, ctxn, next); 3509 3510 /* 3511 * if cgroup events exist on this CPU, then we need 3512 * to check if we have to switch out PMU state. 3513 * cgroup event are system-wide mode only 3514 */ 3515 if (atomic_read(this_cpu_ptr(&perf_cgroup_events))) 3516 perf_cgroup_sched_out(task, next); 3517 } 3518 3519 /* 3520 * Called with IRQs disabled 3521 */ 3522 static void cpu_ctx_sched_out(struct perf_cpu_context *cpuctx, 3523 enum event_type_t event_type) 3524 { 3525 ctx_sched_out(&cpuctx->ctx, cpuctx, event_type); 3526 } 3527 3528 static bool perf_less_group_idx(const void *l, const void *r) 3529 { 3530 const struct perf_event *le = *(const struct perf_event **)l; 3531 const struct perf_event *re = *(const struct perf_event **)r; 3532 3533 return le->group_index < re->group_index; 3534 } 3535 3536 static void swap_ptr(void *l, void *r) 3537 { 3538 void **lp = l, **rp = r; 3539 3540 swap(*lp, *rp); 3541 } 3542 3543 static const struct min_heap_callbacks perf_min_heap = { 3544 .elem_size = sizeof(struct perf_event *), 3545 .less = perf_less_group_idx, 3546 .swp = swap_ptr, 3547 }; 3548 3549 static void __heap_add(struct min_heap *heap, struct perf_event *event) 3550 { 3551 struct perf_event **itrs = heap->data; 3552 3553 if (event) { 3554 itrs[heap->nr] = event; 3555 heap->nr++; 3556 } 3557 } 3558 3559 static noinline int visit_groups_merge(struct perf_cpu_context *cpuctx, 3560 struct perf_event_groups *groups, int cpu, 3561 int (*func)(struct perf_event *, void *), 3562 void *data) 3563 { 3564 #ifdef CONFIG_CGROUP_PERF 3565 struct cgroup_subsys_state *css = NULL; 3566 #endif 3567 /* Space for per CPU and/or any CPU event iterators. */ 3568 struct perf_event *itrs[2]; 3569 struct min_heap event_heap; 3570 struct perf_event **evt; 3571 int ret; 3572 3573 if (cpuctx) { 3574 event_heap = (struct min_heap){ 3575 .data = cpuctx->heap, 3576 .nr = 0, 3577 .size = cpuctx->heap_size, 3578 }; 3579 3580 lockdep_assert_held(&cpuctx->ctx.lock); 3581 3582 #ifdef CONFIG_CGROUP_PERF 3583 if (cpuctx->cgrp) 3584 css = &cpuctx->cgrp->css; 3585 #endif 3586 } else { 3587 event_heap = (struct min_heap){ 3588 .data = itrs, 3589 .nr = 0, 3590 .size = ARRAY_SIZE(itrs), 3591 }; 3592 /* Events not within a CPU context may be on any CPU. */ 3593 __heap_add(&event_heap, perf_event_groups_first(groups, -1, NULL)); 3594 } 3595 evt = event_heap.data; 3596 3597 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, NULL)); 3598 3599 #ifdef CONFIG_CGROUP_PERF 3600 for (; css; css = css->parent) 3601 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, css->cgroup)); 3602 #endif 3603 3604 min_heapify_all(&event_heap, &perf_min_heap); 3605 3606 while (event_heap.nr) { 3607 ret = func(*evt, data); 3608 if (ret) 3609 return ret; 3610 3611 *evt = perf_event_groups_next(*evt); 3612 if (*evt) 3613 min_heapify(&event_heap, 0, &perf_min_heap); 3614 else 3615 min_heap_pop(&event_heap, &perf_min_heap); 3616 } 3617 3618 return 0; 3619 } 3620 3621 static int merge_sched_in(struct perf_event *event, void *data) 3622 { 3623 struct perf_event_context *ctx = event->ctx; 3624 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); 3625 int *can_add_hw = data; 3626 3627 if (event->state <= PERF_EVENT_STATE_OFF) 3628 return 0; 3629 3630 if (!event_filter_match(event)) 3631 return 0; 3632 3633 if (group_can_go_on(event, cpuctx, *can_add_hw)) { 3634 if (!group_sched_in(event, cpuctx, ctx)) 3635 list_add_tail(&event->active_list, get_event_list(event)); 3636 } 3637 3638 if (event->state == PERF_EVENT_STATE_INACTIVE) { 3639 if (event->attr.pinned) { 3640 perf_cgroup_event_disable(event, ctx); 3641 perf_event_set_state(event, PERF_EVENT_STATE_ERROR); 3642 } 3643 3644 *can_add_hw = 0; 3645 ctx->rotate_necessary = 1; 3646 } 3647 3648 return 0; 3649 } 3650 3651 static void 3652 ctx_pinned_sched_in(struct perf_event_context *ctx, 3653 struct perf_cpu_context *cpuctx) 3654 { 3655 int can_add_hw = 1; 3656 3657 if (ctx != &cpuctx->ctx) 3658 cpuctx = NULL; 3659 3660 visit_groups_merge(cpuctx, &ctx->pinned_groups, 3661 smp_processor_id(), 3662 merge_sched_in, &can_add_hw); 3663 } 3664 3665 static void 3666 ctx_flexible_sched_in(struct perf_event_context *ctx, 3667 struct perf_cpu_context *cpuctx) 3668 { 3669 int can_add_hw = 1; 3670 3671 if (ctx != &cpuctx->ctx) 3672 cpuctx = NULL; 3673 3674 visit_groups_merge(cpuctx, &ctx->flexible_groups, 3675 smp_processor_id(), 3676 merge_sched_in, &can_add_hw); 3677 } 3678 3679 static void 3680 ctx_sched_in(struct perf_event_context *ctx, 3681 struct perf_cpu_context *cpuctx, 3682 enum event_type_t event_type, 3683 struct task_struct *task) 3684 { 3685 int is_active = ctx->is_active; 3686 u64 now; 3687 3688 lockdep_assert_held(&ctx->lock); 3689 3690 if (likely(!ctx->nr_events)) 3691 return; 3692 3693 ctx->is_active |= (event_type | EVENT_TIME); 3694 if (ctx->task) { 3695 if (!is_active) 3696 cpuctx->task_ctx = ctx; 3697 else 3698 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 3699 } 3700 3701 is_active ^= ctx->is_active; /* changed bits */ 3702 3703 if (is_active & EVENT_TIME) { 3704 /* start ctx time */ 3705 now = perf_clock(); 3706 ctx->timestamp = now; 3707 perf_cgroup_set_timestamp(task, ctx); 3708 } 3709 3710 /* 3711 * First go through the list and put on any pinned groups 3712 * in order to give them the best chance of going on. 3713 */ 3714 if (is_active & EVENT_PINNED) 3715 ctx_pinned_sched_in(ctx, cpuctx); 3716 3717 /* Then walk through the lower prio flexible groups */ 3718 if (is_active & EVENT_FLEXIBLE) 3719 ctx_flexible_sched_in(ctx, cpuctx); 3720 } 3721 3722 static void cpu_ctx_sched_in(struct perf_cpu_context *cpuctx, 3723 enum event_type_t event_type, 3724 struct task_struct *task) 3725 { 3726 struct perf_event_context *ctx = &cpuctx->ctx; 3727 3728 ctx_sched_in(ctx, cpuctx, event_type, task); 3729 } 3730 3731 static void perf_event_context_sched_in(struct perf_event_context *ctx, 3732 struct task_struct *task) 3733 { 3734 struct perf_cpu_context *cpuctx; 3735 3736 cpuctx = __get_cpu_context(ctx); 3737 if (cpuctx->task_ctx == ctx) 3738 return; 3739 3740 perf_ctx_lock(cpuctx, ctx); 3741 /* 3742 * We must check ctx->nr_events while holding ctx->lock, such 3743 * that we serialize against perf_install_in_context(). 3744 */ 3745 if (!ctx->nr_events) 3746 goto unlock; 3747 3748 perf_pmu_disable(ctx->pmu); 3749 /* 3750 * We want to keep the following priority order: 3751 * cpu pinned (that don't need to move), task pinned, 3752 * cpu flexible, task flexible. 3753 * 3754 * However, if task's ctx is not carrying any pinned 3755 * events, no need to flip the cpuctx's events around. 3756 */ 3757 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) 3758 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE); 3759 perf_event_sched_in(cpuctx, ctx, task); 3760 perf_pmu_enable(ctx->pmu); 3761 3762 unlock: 3763 perf_ctx_unlock(cpuctx, ctx); 3764 } 3765 3766 /* 3767 * Called from scheduler to add the events of the current task 3768 * with interrupts disabled. 3769 * 3770 * We restore the event value and then enable it. 3771 * 3772 * This does not protect us against NMI, but enable() 3773 * sets the enabled bit in the control field of event _before_ 3774 * accessing the event control register. If a NMI hits, then it will 3775 * keep the event running. 3776 */ 3777 void __perf_event_task_sched_in(struct task_struct *prev, 3778 struct task_struct *task) 3779 { 3780 struct perf_event_context *ctx; 3781 int ctxn; 3782 3783 /* 3784 * If cgroup events exist on this CPU, then we need to check if we have 3785 * to switch in PMU state; cgroup event are system-wide mode only. 3786 * 3787 * Since cgroup events are CPU events, we must schedule these in before 3788 * we schedule in the task events. 3789 */ 3790 if (atomic_read(this_cpu_ptr(&perf_cgroup_events))) 3791 perf_cgroup_sched_in(prev, task); 3792 3793 for_each_task_context_nr(ctxn) { 3794 ctx = task->perf_event_ctxp[ctxn]; 3795 if (likely(!ctx)) 3796 continue; 3797 3798 perf_event_context_sched_in(ctx, task); 3799 } 3800 3801 if (atomic_read(&nr_switch_events)) 3802 perf_event_switch(task, prev, true); 3803 3804 if (__this_cpu_read(perf_sched_cb_usages)) 3805 perf_pmu_sched_task(prev, task, true); 3806 } 3807 3808 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count) 3809 { 3810 u64 frequency = event->attr.sample_freq; 3811 u64 sec = NSEC_PER_SEC; 3812 u64 divisor, dividend; 3813 3814 int count_fls, nsec_fls, frequency_fls, sec_fls; 3815 3816 count_fls = fls64(count); 3817 nsec_fls = fls64(nsec); 3818 frequency_fls = fls64(frequency); 3819 sec_fls = 30; 3820 3821 /* 3822 * We got @count in @nsec, with a target of sample_freq HZ 3823 * the target period becomes: 3824 * 3825 * @count * 10^9 3826 * period = ------------------- 3827 * @nsec * sample_freq 3828 * 3829 */ 3830 3831 /* 3832 * Reduce accuracy by one bit such that @a and @b converge 3833 * to a similar magnitude. 3834 */ 3835 #define REDUCE_FLS(a, b) \ 3836 do { \ 3837 if (a##_fls > b##_fls) { \ 3838 a >>= 1; \ 3839 a##_fls--; \ 3840 } else { \ 3841 b >>= 1; \ 3842 b##_fls--; \ 3843 } \ 3844 } while (0) 3845 3846 /* 3847 * Reduce accuracy until either term fits in a u64, then proceed with 3848 * the other, so that finally we can do a u64/u64 division. 3849 */ 3850 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) { 3851 REDUCE_FLS(nsec, frequency); 3852 REDUCE_FLS(sec, count); 3853 } 3854 3855 if (count_fls + sec_fls > 64) { 3856 divisor = nsec * frequency; 3857 3858 while (count_fls + sec_fls > 64) { 3859 REDUCE_FLS(count, sec); 3860 divisor >>= 1; 3861 } 3862 3863 dividend = count * sec; 3864 } else { 3865 dividend = count * sec; 3866 3867 while (nsec_fls + frequency_fls > 64) { 3868 REDUCE_FLS(nsec, frequency); 3869 dividend >>= 1; 3870 } 3871 3872 divisor = nsec * frequency; 3873 } 3874 3875 if (!divisor) 3876 return dividend; 3877 3878 return div64_u64(dividend, divisor); 3879 } 3880 3881 static DEFINE_PER_CPU(int, perf_throttled_count); 3882 static DEFINE_PER_CPU(u64, perf_throttled_seq); 3883 3884 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable) 3885 { 3886 struct hw_perf_event *hwc = &event->hw; 3887 s64 period, sample_period; 3888 s64 delta; 3889 3890 period = perf_calculate_period(event, nsec, count); 3891 3892 delta = (s64)(period - hwc->sample_period); 3893 delta = (delta + 7) / 8; /* low pass filter */ 3894 3895 sample_period = hwc->sample_period + delta; 3896 3897 if (!sample_period) 3898 sample_period = 1; 3899 3900 hwc->sample_period = sample_period; 3901 3902 if (local64_read(&hwc->period_left) > 8*sample_period) { 3903 if (disable) 3904 event->pmu->stop(event, PERF_EF_UPDATE); 3905 3906 local64_set(&hwc->period_left, 0); 3907 3908 if (disable) 3909 event->pmu->start(event, PERF_EF_RELOAD); 3910 } 3911 } 3912 3913 /* 3914 * combine freq adjustment with unthrottling to avoid two passes over the 3915 * events. At the same time, make sure, having freq events does not change 3916 * the rate of unthrottling as that would introduce bias. 3917 */ 3918 static void perf_adjust_freq_unthr_context(struct perf_event_context *ctx, 3919 int needs_unthr) 3920 { 3921 struct perf_event *event; 3922 struct hw_perf_event *hwc; 3923 u64 now, period = TICK_NSEC; 3924 s64 delta; 3925 3926 /* 3927 * only need to iterate over all events iff: 3928 * - context have events in frequency mode (needs freq adjust) 3929 * - there are events to unthrottle on this cpu 3930 */ 3931 if (!(ctx->nr_freq || needs_unthr)) 3932 return; 3933 3934 raw_spin_lock(&ctx->lock); 3935 perf_pmu_disable(ctx->pmu); 3936 3937 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { 3938 if (event->state != PERF_EVENT_STATE_ACTIVE) 3939 continue; 3940 3941 if (!event_filter_match(event)) 3942 continue; 3943 3944 perf_pmu_disable(event->pmu); 3945 3946 hwc = &event->hw; 3947 3948 if (hwc->interrupts == MAX_INTERRUPTS) { 3949 hwc->interrupts = 0; 3950 perf_log_throttle(event, 1); 3951 event->pmu->start(event, 0); 3952 } 3953 3954 if (!event->attr.freq || !event->attr.sample_freq) 3955 goto next; 3956 3957 /* 3958 * stop the event and update event->count 3959 */ 3960 event->pmu->stop(event, PERF_EF_UPDATE); 3961 3962 now = local64_read(&event->count); 3963 delta = now - hwc->freq_count_stamp; 3964 hwc->freq_count_stamp = now; 3965 3966 /* 3967 * restart the event 3968 * reload only if value has changed 3969 * we have stopped the event so tell that 3970 * to perf_adjust_period() to avoid stopping it 3971 * twice. 3972 */ 3973 if (delta > 0) 3974 perf_adjust_period(event, period, delta, false); 3975 3976 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0); 3977 next: 3978 perf_pmu_enable(event->pmu); 3979 } 3980 3981 perf_pmu_enable(ctx->pmu); 3982 raw_spin_unlock(&ctx->lock); 3983 } 3984 3985 /* 3986 * Move @event to the tail of the @ctx's elegible events. 3987 */ 3988 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event) 3989 { 3990 /* 3991 * Rotate the first entry last of non-pinned groups. Rotation might be 3992 * disabled by the inheritance code. 3993 */ 3994 if (ctx->rotate_disable) 3995 return; 3996 3997 perf_event_groups_delete(&ctx->flexible_groups, event); 3998 perf_event_groups_insert(&ctx->flexible_groups, event); 3999 } 4000 4001 /* pick an event from the flexible_groups to rotate */ 4002 static inline struct perf_event * 4003 ctx_event_to_rotate(struct perf_event_context *ctx) 4004 { 4005 struct perf_event *event; 4006 4007 /* pick the first active flexible event */ 4008 event = list_first_entry_or_null(&ctx->flexible_active, 4009 struct perf_event, active_list); 4010 4011 /* if no active flexible event, pick the first event */ 4012 if (!event) { 4013 event = rb_entry_safe(rb_first(&ctx->flexible_groups.tree), 4014 typeof(*event), group_node); 4015 } 4016 4017 /* 4018 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in() 4019 * finds there are unschedulable events, it will set it again. 4020 */ 4021 ctx->rotate_necessary = 0; 4022 4023 return event; 4024 } 4025 4026 static bool perf_rotate_context(struct perf_cpu_context *cpuctx) 4027 { 4028 struct perf_event *cpu_event = NULL, *task_event = NULL; 4029 struct perf_event_context *task_ctx = NULL; 4030 int cpu_rotate, task_rotate; 4031 4032 /* 4033 * Since we run this from IRQ context, nobody can install new 4034 * events, thus the event count values are stable. 4035 */ 4036 4037 cpu_rotate = cpuctx->ctx.rotate_necessary; 4038 task_ctx = cpuctx->task_ctx; 4039 task_rotate = task_ctx ? task_ctx->rotate_necessary : 0; 4040 4041 if (!(cpu_rotate || task_rotate)) 4042 return false; 4043 4044 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 4045 perf_pmu_disable(cpuctx->ctx.pmu); 4046 4047 if (task_rotate) 4048 task_event = ctx_event_to_rotate(task_ctx); 4049 if (cpu_rotate) 4050 cpu_event = ctx_event_to_rotate(&cpuctx->ctx); 4051 4052 /* 4053 * As per the order given at ctx_resched() first 'pop' task flexible 4054 * and then, if needed CPU flexible. 4055 */ 4056 if (task_event || (task_ctx && cpu_event)) 4057 ctx_sched_out(task_ctx, cpuctx, EVENT_FLEXIBLE); 4058 if (cpu_event) 4059 cpu_ctx_sched_out(cpuctx, EVENT_FLEXIBLE); 4060 4061 if (task_event) 4062 rotate_ctx(task_ctx, task_event); 4063 if (cpu_event) 4064 rotate_ctx(&cpuctx->ctx, cpu_event); 4065 4066 perf_event_sched_in(cpuctx, task_ctx, current); 4067 4068 perf_pmu_enable(cpuctx->ctx.pmu); 4069 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 4070 4071 return true; 4072 } 4073 4074 void perf_event_task_tick(void) 4075 { 4076 struct list_head *head = this_cpu_ptr(&active_ctx_list); 4077 struct perf_event_context *ctx, *tmp; 4078 int throttled; 4079 4080 lockdep_assert_irqs_disabled(); 4081 4082 __this_cpu_inc(perf_throttled_seq); 4083 throttled = __this_cpu_xchg(perf_throttled_count, 0); 4084 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 4085 4086 list_for_each_entry_safe(ctx, tmp, head, active_ctx_list) 4087 perf_adjust_freq_unthr_context(ctx, throttled); 4088 } 4089 4090 static int event_enable_on_exec(struct perf_event *event, 4091 struct perf_event_context *ctx) 4092 { 4093 if (!event->attr.enable_on_exec) 4094 return 0; 4095 4096 event->attr.enable_on_exec = 0; 4097 if (event->state >= PERF_EVENT_STATE_INACTIVE) 4098 return 0; 4099 4100 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 4101 4102 return 1; 4103 } 4104 4105 /* 4106 * Enable all of a task's events that have been marked enable-on-exec. 4107 * This expects task == current. 4108 */ 4109 static void perf_event_enable_on_exec(int ctxn) 4110 { 4111 struct perf_event_context *ctx, *clone_ctx = NULL; 4112 enum event_type_t event_type = 0; 4113 struct perf_cpu_context *cpuctx; 4114 struct perf_event *event; 4115 unsigned long flags; 4116 int enabled = 0; 4117 4118 local_irq_save(flags); 4119 ctx = current->perf_event_ctxp[ctxn]; 4120 if (!ctx || !ctx->nr_events) 4121 goto out; 4122 4123 cpuctx = __get_cpu_context(ctx); 4124 perf_ctx_lock(cpuctx, ctx); 4125 ctx_sched_out(ctx, cpuctx, EVENT_TIME); 4126 list_for_each_entry(event, &ctx->event_list, event_entry) { 4127 enabled |= event_enable_on_exec(event, ctx); 4128 event_type |= get_event_type(event); 4129 } 4130 4131 /* 4132 * Unclone and reschedule this context if we enabled any event. 4133 */ 4134 if (enabled) { 4135 clone_ctx = unclone_ctx(ctx); 4136 ctx_resched(cpuctx, ctx, event_type); 4137 } else { 4138 ctx_sched_in(ctx, cpuctx, EVENT_TIME, current); 4139 } 4140 perf_ctx_unlock(cpuctx, ctx); 4141 4142 out: 4143 local_irq_restore(flags); 4144 4145 if (clone_ctx) 4146 put_ctx(clone_ctx); 4147 } 4148 4149 struct perf_read_data { 4150 struct perf_event *event; 4151 bool group; 4152 int ret; 4153 }; 4154 4155 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu) 4156 { 4157 u16 local_pkg, event_pkg; 4158 4159 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) { 4160 int local_cpu = smp_processor_id(); 4161 4162 event_pkg = topology_physical_package_id(event_cpu); 4163 local_pkg = topology_physical_package_id(local_cpu); 4164 4165 if (event_pkg == local_pkg) 4166 return local_cpu; 4167 } 4168 4169 return event_cpu; 4170 } 4171 4172 /* 4173 * Cross CPU call to read the hardware event 4174 */ 4175 static void __perf_event_read(void *info) 4176 { 4177 struct perf_read_data *data = info; 4178 struct perf_event *sub, *event = data->event; 4179 struct perf_event_context *ctx = event->ctx; 4180 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); 4181 struct pmu *pmu = event->pmu; 4182 4183 /* 4184 * If this is a task context, we need to check whether it is 4185 * the current task context of this cpu. If not it has been 4186 * scheduled out before the smp call arrived. In that case 4187 * event->count would have been updated to a recent sample 4188 * when the event was scheduled out. 4189 */ 4190 if (ctx->task && cpuctx->task_ctx != ctx) 4191 return; 4192 4193 raw_spin_lock(&ctx->lock); 4194 if (ctx->is_active & EVENT_TIME) { 4195 update_context_time(ctx); 4196 update_cgrp_time_from_event(event); 4197 } 4198 4199 perf_event_update_time(event); 4200 if (data->group) 4201 perf_event_update_sibling_time(event); 4202 4203 if (event->state != PERF_EVENT_STATE_ACTIVE) 4204 goto unlock; 4205 4206 if (!data->group) { 4207 pmu->read(event); 4208 data->ret = 0; 4209 goto unlock; 4210 } 4211 4212 pmu->start_txn(pmu, PERF_PMU_TXN_READ); 4213 4214 pmu->read(event); 4215 4216 for_each_sibling_event(sub, event) { 4217 if (sub->state == PERF_EVENT_STATE_ACTIVE) { 4218 /* 4219 * Use sibling's PMU rather than @event's since 4220 * sibling could be on different (eg: software) PMU. 4221 */ 4222 sub->pmu->read(sub); 4223 } 4224 } 4225 4226 data->ret = pmu->commit_txn(pmu); 4227 4228 unlock: 4229 raw_spin_unlock(&ctx->lock); 4230 } 4231 4232 static inline u64 perf_event_count(struct perf_event *event) 4233 { 4234 return local64_read(&event->count) + atomic64_read(&event->child_count); 4235 } 4236 4237 /* 4238 * NMI-safe method to read a local event, that is an event that 4239 * is: 4240 * - either for the current task, or for this CPU 4241 * - does not have inherit set, for inherited task events 4242 * will not be local and we cannot read them atomically 4243 * - must not have a pmu::count method 4244 */ 4245 int perf_event_read_local(struct perf_event *event, u64 *value, 4246 u64 *enabled, u64 *running) 4247 { 4248 unsigned long flags; 4249 int ret = 0; 4250 4251 /* 4252 * Disabling interrupts avoids all counter scheduling (context 4253 * switches, timer based rotation and IPIs). 4254 */ 4255 local_irq_save(flags); 4256 4257 /* 4258 * It must not be an event with inherit set, we cannot read 4259 * all child counters from atomic context. 4260 */ 4261 if (event->attr.inherit) { 4262 ret = -EOPNOTSUPP; 4263 goto out; 4264 } 4265 4266 /* If this is a per-task event, it must be for current */ 4267 if ((event->attach_state & PERF_ATTACH_TASK) && 4268 event->hw.target != current) { 4269 ret = -EINVAL; 4270 goto out; 4271 } 4272 4273 /* If this is a per-CPU event, it must be for this CPU */ 4274 if (!(event->attach_state & PERF_ATTACH_TASK) && 4275 event->cpu != smp_processor_id()) { 4276 ret = -EINVAL; 4277 goto out; 4278 } 4279 4280 /* If this is a pinned event it must be running on this CPU */ 4281 if (event->attr.pinned && event->oncpu != smp_processor_id()) { 4282 ret = -EBUSY; 4283 goto out; 4284 } 4285 4286 /* 4287 * If the event is currently on this CPU, its either a per-task event, 4288 * or local to this CPU. Furthermore it means its ACTIVE (otherwise 4289 * oncpu == -1). 4290 */ 4291 if (event->oncpu == smp_processor_id()) 4292 event->pmu->read(event); 4293 4294 *value = local64_read(&event->count); 4295 if (enabled || running) { 4296 u64 now = event->shadow_ctx_time + perf_clock(); 4297 u64 __enabled, __running; 4298 4299 __perf_update_times(event, now, &__enabled, &__running); 4300 if (enabled) 4301 *enabled = __enabled; 4302 if (running) 4303 *running = __running; 4304 } 4305 out: 4306 local_irq_restore(flags); 4307 4308 return ret; 4309 } 4310 4311 static int perf_event_read(struct perf_event *event, bool group) 4312 { 4313 enum perf_event_state state = READ_ONCE(event->state); 4314 int event_cpu, ret = 0; 4315 4316 /* 4317 * If event is enabled and currently active on a CPU, update the 4318 * value in the event structure: 4319 */ 4320 again: 4321 if (state == PERF_EVENT_STATE_ACTIVE) { 4322 struct perf_read_data data; 4323 4324 /* 4325 * Orders the ->state and ->oncpu loads such that if we see 4326 * ACTIVE we must also see the right ->oncpu. 4327 * 4328 * Matches the smp_wmb() from event_sched_in(). 4329 */ 4330 smp_rmb(); 4331 4332 event_cpu = READ_ONCE(event->oncpu); 4333 if ((unsigned)event_cpu >= nr_cpu_ids) 4334 return 0; 4335 4336 data = (struct perf_read_data){ 4337 .event = event, 4338 .group = group, 4339 .ret = 0, 4340 }; 4341 4342 preempt_disable(); 4343 event_cpu = __perf_event_read_cpu(event, event_cpu); 4344 4345 /* 4346 * Purposely ignore the smp_call_function_single() return 4347 * value. 4348 * 4349 * If event_cpu isn't a valid CPU it means the event got 4350 * scheduled out and that will have updated the event count. 4351 * 4352 * Therefore, either way, we'll have an up-to-date event count 4353 * after this. 4354 */ 4355 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1); 4356 preempt_enable(); 4357 ret = data.ret; 4358 4359 } else if (state == PERF_EVENT_STATE_INACTIVE) { 4360 struct perf_event_context *ctx = event->ctx; 4361 unsigned long flags; 4362 4363 raw_spin_lock_irqsave(&ctx->lock, flags); 4364 state = event->state; 4365 if (state != PERF_EVENT_STATE_INACTIVE) { 4366 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4367 goto again; 4368 } 4369 4370 /* 4371 * May read while context is not active (e.g., thread is 4372 * blocked), in that case we cannot update context time 4373 */ 4374 if (ctx->is_active & EVENT_TIME) { 4375 update_context_time(ctx); 4376 update_cgrp_time_from_event(event); 4377 } 4378 4379 perf_event_update_time(event); 4380 if (group) 4381 perf_event_update_sibling_time(event); 4382 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4383 } 4384 4385 return ret; 4386 } 4387 4388 /* 4389 * Initialize the perf_event context in a task_struct: 4390 */ 4391 static void __perf_event_init_context(struct perf_event_context *ctx) 4392 { 4393 raw_spin_lock_init(&ctx->lock); 4394 mutex_init(&ctx->mutex); 4395 INIT_LIST_HEAD(&ctx->active_ctx_list); 4396 perf_event_groups_init(&ctx->pinned_groups); 4397 perf_event_groups_init(&ctx->flexible_groups); 4398 INIT_LIST_HEAD(&ctx->event_list); 4399 INIT_LIST_HEAD(&ctx->pinned_active); 4400 INIT_LIST_HEAD(&ctx->flexible_active); 4401 refcount_set(&ctx->refcount, 1); 4402 } 4403 4404 static struct perf_event_context * 4405 alloc_perf_context(struct pmu *pmu, struct task_struct *task) 4406 { 4407 struct perf_event_context *ctx; 4408 4409 ctx = kzalloc(sizeof(struct perf_event_context), GFP_KERNEL); 4410 if (!ctx) 4411 return NULL; 4412 4413 __perf_event_init_context(ctx); 4414 if (task) 4415 ctx->task = get_task_struct(task); 4416 ctx->pmu = pmu; 4417 4418 return ctx; 4419 } 4420 4421 static struct task_struct * 4422 find_lively_task_by_vpid(pid_t vpid) 4423 { 4424 struct task_struct *task; 4425 4426 rcu_read_lock(); 4427 if (!vpid) 4428 task = current; 4429 else 4430 task = find_task_by_vpid(vpid); 4431 if (task) 4432 get_task_struct(task); 4433 rcu_read_unlock(); 4434 4435 if (!task) 4436 return ERR_PTR(-ESRCH); 4437 4438 return task; 4439 } 4440 4441 /* 4442 * Returns a matching context with refcount and pincount. 4443 */ 4444 static struct perf_event_context * 4445 find_get_context(struct pmu *pmu, struct task_struct *task, 4446 struct perf_event *event) 4447 { 4448 struct perf_event_context *ctx, *clone_ctx = NULL; 4449 struct perf_cpu_context *cpuctx; 4450 void *task_ctx_data = NULL; 4451 unsigned long flags; 4452 int ctxn, err; 4453 int cpu = event->cpu; 4454 4455 if (!task) { 4456 /* Must be root to operate on a CPU event: */ 4457 err = perf_allow_cpu(&event->attr); 4458 if (err) 4459 return ERR_PTR(err); 4460 4461 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); 4462 ctx = &cpuctx->ctx; 4463 get_ctx(ctx); 4464 ++ctx->pin_count; 4465 4466 return ctx; 4467 } 4468 4469 err = -EINVAL; 4470 ctxn = pmu->task_ctx_nr; 4471 if (ctxn < 0) 4472 goto errout; 4473 4474 if (event->attach_state & PERF_ATTACH_TASK_DATA) { 4475 task_ctx_data = kzalloc(pmu->task_ctx_size, GFP_KERNEL); 4476 if (!task_ctx_data) { 4477 err = -ENOMEM; 4478 goto errout; 4479 } 4480 } 4481 4482 retry: 4483 ctx = perf_lock_task_context(task, ctxn, &flags); 4484 if (ctx) { 4485 clone_ctx = unclone_ctx(ctx); 4486 ++ctx->pin_count; 4487 4488 if (task_ctx_data && !ctx->task_ctx_data) { 4489 ctx->task_ctx_data = task_ctx_data; 4490 task_ctx_data = NULL; 4491 } 4492 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4493 4494 if (clone_ctx) 4495 put_ctx(clone_ctx); 4496 } else { 4497 ctx = alloc_perf_context(pmu, task); 4498 err = -ENOMEM; 4499 if (!ctx) 4500 goto errout; 4501 4502 if (task_ctx_data) { 4503 ctx->task_ctx_data = task_ctx_data; 4504 task_ctx_data = NULL; 4505 } 4506 4507 err = 0; 4508 mutex_lock(&task->perf_event_mutex); 4509 /* 4510 * If it has already passed perf_event_exit_task(). 4511 * we must see PF_EXITING, it takes this mutex too. 4512 */ 4513 if (task->flags & PF_EXITING) 4514 err = -ESRCH; 4515 else if (task->perf_event_ctxp[ctxn]) 4516 err = -EAGAIN; 4517 else { 4518 get_ctx(ctx); 4519 ++ctx->pin_count; 4520 rcu_assign_pointer(task->perf_event_ctxp[ctxn], ctx); 4521 } 4522 mutex_unlock(&task->perf_event_mutex); 4523 4524 if (unlikely(err)) { 4525 put_ctx(ctx); 4526 4527 if (err == -EAGAIN) 4528 goto retry; 4529 goto errout; 4530 } 4531 } 4532 4533 kfree(task_ctx_data); 4534 return ctx; 4535 4536 errout: 4537 kfree(task_ctx_data); 4538 return ERR_PTR(err); 4539 } 4540 4541 static void perf_event_free_filter(struct perf_event *event); 4542 static void perf_event_free_bpf_prog(struct perf_event *event); 4543 4544 static void free_event_rcu(struct rcu_head *head) 4545 { 4546 struct perf_event *event; 4547 4548 event = container_of(head, struct perf_event, rcu_head); 4549 if (event->ns) 4550 put_pid_ns(event->ns); 4551 perf_event_free_filter(event); 4552 kfree(event); 4553 } 4554 4555 static void ring_buffer_attach(struct perf_event *event, 4556 struct perf_buffer *rb); 4557 4558 static void detach_sb_event(struct perf_event *event) 4559 { 4560 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 4561 4562 raw_spin_lock(&pel->lock); 4563 list_del_rcu(&event->sb_list); 4564 raw_spin_unlock(&pel->lock); 4565 } 4566 4567 static bool is_sb_event(struct perf_event *event) 4568 { 4569 struct perf_event_attr *attr = &event->attr; 4570 4571 if (event->parent) 4572 return false; 4573 4574 if (event->attach_state & PERF_ATTACH_TASK) 4575 return false; 4576 4577 if (attr->mmap || attr->mmap_data || attr->mmap2 || 4578 attr->comm || attr->comm_exec || 4579 attr->task || attr->ksymbol || 4580 attr->context_switch || 4581 attr->bpf_event) 4582 return true; 4583 return false; 4584 } 4585 4586 static void unaccount_pmu_sb_event(struct perf_event *event) 4587 { 4588 if (is_sb_event(event)) 4589 detach_sb_event(event); 4590 } 4591 4592 static void unaccount_event_cpu(struct perf_event *event, int cpu) 4593 { 4594 if (event->parent) 4595 return; 4596 4597 if (is_cgroup_event(event)) 4598 atomic_dec(&per_cpu(perf_cgroup_events, cpu)); 4599 } 4600 4601 #ifdef CONFIG_NO_HZ_FULL 4602 static DEFINE_SPINLOCK(nr_freq_lock); 4603 #endif 4604 4605 static void unaccount_freq_event_nohz(void) 4606 { 4607 #ifdef CONFIG_NO_HZ_FULL 4608 spin_lock(&nr_freq_lock); 4609 if (atomic_dec_and_test(&nr_freq_events)) 4610 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS); 4611 spin_unlock(&nr_freq_lock); 4612 #endif 4613 } 4614 4615 static void unaccount_freq_event(void) 4616 { 4617 if (tick_nohz_full_enabled()) 4618 unaccount_freq_event_nohz(); 4619 else 4620 atomic_dec(&nr_freq_events); 4621 } 4622 4623 static void unaccount_event(struct perf_event *event) 4624 { 4625 bool dec = false; 4626 4627 if (event->parent) 4628 return; 4629 4630 if (event->attach_state & PERF_ATTACH_TASK) 4631 dec = true; 4632 if (event->attr.mmap || event->attr.mmap_data) 4633 atomic_dec(&nr_mmap_events); 4634 if (event->attr.comm) 4635 atomic_dec(&nr_comm_events); 4636 if (event->attr.namespaces) 4637 atomic_dec(&nr_namespaces_events); 4638 if (event->attr.cgroup) 4639 atomic_dec(&nr_cgroup_events); 4640 if (event->attr.task) 4641 atomic_dec(&nr_task_events); 4642 if (event->attr.freq) 4643 unaccount_freq_event(); 4644 if (event->attr.context_switch) { 4645 dec = true; 4646 atomic_dec(&nr_switch_events); 4647 } 4648 if (is_cgroup_event(event)) 4649 dec = true; 4650 if (has_branch_stack(event)) 4651 dec = true; 4652 if (event->attr.ksymbol) 4653 atomic_dec(&nr_ksymbol_events); 4654 if (event->attr.bpf_event) 4655 atomic_dec(&nr_bpf_events); 4656 4657 if (dec) { 4658 if (!atomic_add_unless(&perf_sched_count, -1, 1)) 4659 schedule_delayed_work(&perf_sched_work, HZ); 4660 } 4661 4662 unaccount_event_cpu(event, event->cpu); 4663 4664 unaccount_pmu_sb_event(event); 4665 } 4666 4667 static void perf_sched_delayed(struct work_struct *work) 4668 { 4669 mutex_lock(&perf_sched_mutex); 4670 if (atomic_dec_and_test(&perf_sched_count)) 4671 static_branch_disable(&perf_sched_events); 4672 mutex_unlock(&perf_sched_mutex); 4673 } 4674 4675 /* 4676 * The following implement mutual exclusion of events on "exclusive" pmus 4677 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled 4678 * at a time, so we disallow creating events that might conflict, namely: 4679 * 4680 * 1) cpu-wide events in the presence of per-task events, 4681 * 2) per-task events in the presence of cpu-wide events, 4682 * 3) two matching events on the same context. 4683 * 4684 * The former two cases are handled in the allocation path (perf_event_alloc(), 4685 * _free_event()), the latter -- before the first perf_install_in_context(). 4686 */ 4687 static int exclusive_event_init(struct perf_event *event) 4688 { 4689 struct pmu *pmu = event->pmu; 4690 4691 if (!is_exclusive_pmu(pmu)) 4692 return 0; 4693 4694 /* 4695 * Prevent co-existence of per-task and cpu-wide events on the 4696 * same exclusive pmu. 4697 * 4698 * Negative pmu::exclusive_cnt means there are cpu-wide 4699 * events on this "exclusive" pmu, positive means there are 4700 * per-task events. 4701 * 4702 * Since this is called in perf_event_alloc() path, event::ctx 4703 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK 4704 * to mean "per-task event", because unlike other attach states it 4705 * never gets cleared. 4706 */ 4707 if (event->attach_state & PERF_ATTACH_TASK) { 4708 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt)) 4709 return -EBUSY; 4710 } else { 4711 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt)) 4712 return -EBUSY; 4713 } 4714 4715 return 0; 4716 } 4717 4718 static void exclusive_event_destroy(struct perf_event *event) 4719 { 4720 struct pmu *pmu = event->pmu; 4721 4722 if (!is_exclusive_pmu(pmu)) 4723 return; 4724 4725 /* see comment in exclusive_event_init() */ 4726 if (event->attach_state & PERF_ATTACH_TASK) 4727 atomic_dec(&pmu->exclusive_cnt); 4728 else 4729 atomic_inc(&pmu->exclusive_cnt); 4730 } 4731 4732 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2) 4733 { 4734 if ((e1->pmu == e2->pmu) && 4735 (e1->cpu == e2->cpu || 4736 e1->cpu == -1 || 4737 e2->cpu == -1)) 4738 return true; 4739 return false; 4740 } 4741 4742 static bool exclusive_event_installable(struct perf_event *event, 4743 struct perf_event_context *ctx) 4744 { 4745 struct perf_event *iter_event; 4746 struct pmu *pmu = event->pmu; 4747 4748 lockdep_assert_held(&ctx->mutex); 4749 4750 if (!is_exclusive_pmu(pmu)) 4751 return true; 4752 4753 list_for_each_entry(iter_event, &ctx->event_list, event_entry) { 4754 if (exclusive_event_match(iter_event, event)) 4755 return false; 4756 } 4757 4758 return true; 4759 } 4760 4761 static void perf_addr_filters_splice(struct perf_event *event, 4762 struct list_head *head); 4763 4764 static void _free_event(struct perf_event *event) 4765 { 4766 irq_work_sync(&event->pending); 4767 4768 unaccount_event(event); 4769 4770 security_perf_event_free(event); 4771 4772 if (event->rb) { 4773 /* 4774 * Can happen when we close an event with re-directed output. 4775 * 4776 * Since we have a 0 refcount, perf_mmap_close() will skip 4777 * over us; possibly making our ring_buffer_put() the last. 4778 */ 4779 mutex_lock(&event->mmap_mutex); 4780 ring_buffer_attach(event, NULL); 4781 mutex_unlock(&event->mmap_mutex); 4782 } 4783 4784 if (is_cgroup_event(event)) 4785 perf_detach_cgroup(event); 4786 4787 if (!event->parent) { 4788 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) 4789 put_callchain_buffers(); 4790 } 4791 4792 perf_event_free_bpf_prog(event); 4793 perf_addr_filters_splice(event, NULL); 4794 kfree(event->addr_filter_ranges); 4795 4796 if (event->destroy) 4797 event->destroy(event); 4798 4799 /* 4800 * Must be after ->destroy(), due to uprobe_perf_close() using 4801 * hw.target. 4802 */ 4803 if (event->hw.target) 4804 put_task_struct(event->hw.target); 4805 4806 /* 4807 * perf_event_free_task() relies on put_ctx() being 'last', in particular 4808 * all task references must be cleaned up. 4809 */ 4810 if (event->ctx) 4811 put_ctx(event->ctx); 4812 4813 exclusive_event_destroy(event); 4814 module_put(event->pmu->module); 4815 4816 call_rcu(&event->rcu_head, free_event_rcu); 4817 } 4818 4819 /* 4820 * Used to free events which have a known refcount of 1, such as in error paths 4821 * where the event isn't exposed yet and inherited events. 4822 */ 4823 static void free_event(struct perf_event *event) 4824 { 4825 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1, 4826 "unexpected event refcount: %ld; ptr=%p\n", 4827 atomic_long_read(&event->refcount), event)) { 4828 /* leak to avoid use-after-free */ 4829 return; 4830 } 4831 4832 _free_event(event); 4833 } 4834 4835 /* 4836 * Remove user event from the owner task. 4837 */ 4838 static void perf_remove_from_owner(struct perf_event *event) 4839 { 4840 struct task_struct *owner; 4841 4842 rcu_read_lock(); 4843 /* 4844 * Matches the smp_store_release() in perf_event_exit_task(). If we 4845 * observe !owner it means the list deletion is complete and we can 4846 * indeed free this event, otherwise we need to serialize on 4847 * owner->perf_event_mutex. 4848 */ 4849 owner = READ_ONCE(event->owner); 4850 if (owner) { 4851 /* 4852 * Since delayed_put_task_struct() also drops the last 4853 * task reference we can safely take a new reference 4854 * while holding the rcu_read_lock(). 4855 */ 4856 get_task_struct(owner); 4857 } 4858 rcu_read_unlock(); 4859 4860 if (owner) { 4861 /* 4862 * If we're here through perf_event_exit_task() we're already 4863 * holding ctx->mutex which would be an inversion wrt. the 4864 * normal lock order. 4865 * 4866 * However we can safely take this lock because its the child 4867 * ctx->mutex. 4868 */ 4869 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING); 4870 4871 /* 4872 * We have to re-check the event->owner field, if it is cleared 4873 * we raced with perf_event_exit_task(), acquiring the mutex 4874 * ensured they're done, and we can proceed with freeing the 4875 * event. 4876 */ 4877 if (event->owner) { 4878 list_del_init(&event->owner_entry); 4879 smp_store_release(&event->owner, NULL); 4880 } 4881 mutex_unlock(&owner->perf_event_mutex); 4882 put_task_struct(owner); 4883 } 4884 } 4885 4886 static void put_event(struct perf_event *event) 4887 { 4888 if (!atomic_long_dec_and_test(&event->refcount)) 4889 return; 4890 4891 _free_event(event); 4892 } 4893 4894 /* 4895 * Kill an event dead; while event:refcount will preserve the event 4896 * object, it will not preserve its functionality. Once the last 'user' 4897 * gives up the object, we'll destroy the thing. 4898 */ 4899 int perf_event_release_kernel(struct perf_event *event) 4900 { 4901 struct perf_event_context *ctx = event->ctx; 4902 struct perf_event *child, *tmp; 4903 LIST_HEAD(free_list); 4904 4905 /* 4906 * If we got here through err_file: fput(event_file); we will not have 4907 * attached to a context yet. 4908 */ 4909 if (!ctx) { 4910 WARN_ON_ONCE(event->attach_state & 4911 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP)); 4912 goto no_ctx; 4913 } 4914 4915 if (!is_kernel_event(event)) 4916 perf_remove_from_owner(event); 4917 4918 ctx = perf_event_ctx_lock(event); 4919 WARN_ON_ONCE(ctx->parent_ctx); 4920 perf_remove_from_context(event, DETACH_GROUP); 4921 4922 raw_spin_lock_irq(&ctx->lock); 4923 /* 4924 * Mark this event as STATE_DEAD, there is no external reference to it 4925 * anymore. 4926 * 4927 * Anybody acquiring event->child_mutex after the below loop _must_ 4928 * also see this, most importantly inherit_event() which will avoid 4929 * placing more children on the list. 4930 * 4931 * Thus this guarantees that we will in fact observe and kill _ALL_ 4932 * child events. 4933 */ 4934 event->state = PERF_EVENT_STATE_DEAD; 4935 raw_spin_unlock_irq(&ctx->lock); 4936 4937 perf_event_ctx_unlock(event, ctx); 4938 4939 again: 4940 mutex_lock(&event->child_mutex); 4941 list_for_each_entry(child, &event->child_list, child_list) { 4942 4943 /* 4944 * Cannot change, child events are not migrated, see the 4945 * comment with perf_event_ctx_lock_nested(). 4946 */ 4947 ctx = READ_ONCE(child->ctx); 4948 /* 4949 * Since child_mutex nests inside ctx::mutex, we must jump 4950 * through hoops. We start by grabbing a reference on the ctx. 4951 * 4952 * Since the event cannot get freed while we hold the 4953 * child_mutex, the context must also exist and have a !0 4954 * reference count. 4955 */ 4956 get_ctx(ctx); 4957 4958 /* 4959 * Now that we have a ctx ref, we can drop child_mutex, and 4960 * acquire ctx::mutex without fear of it going away. Then we 4961 * can re-acquire child_mutex. 4962 */ 4963 mutex_unlock(&event->child_mutex); 4964 mutex_lock(&ctx->mutex); 4965 mutex_lock(&event->child_mutex); 4966 4967 /* 4968 * Now that we hold ctx::mutex and child_mutex, revalidate our 4969 * state, if child is still the first entry, it didn't get freed 4970 * and we can continue doing so. 4971 */ 4972 tmp = list_first_entry_or_null(&event->child_list, 4973 struct perf_event, child_list); 4974 if (tmp == child) { 4975 perf_remove_from_context(child, DETACH_GROUP); 4976 list_move(&child->child_list, &free_list); 4977 /* 4978 * This matches the refcount bump in inherit_event(); 4979 * this can't be the last reference. 4980 */ 4981 put_event(event); 4982 } 4983 4984 mutex_unlock(&event->child_mutex); 4985 mutex_unlock(&ctx->mutex); 4986 put_ctx(ctx); 4987 goto again; 4988 } 4989 mutex_unlock(&event->child_mutex); 4990 4991 list_for_each_entry_safe(child, tmp, &free_list, child_list) { 4992 void *var = &child->ctx->refcount; 4993 4994 list_del(&child->child_list); 4995 free_event(child); 4996 4997 /* 4998 * Wake any perf_event_free_task() waiting for this event to be 4999 * freed. 5000 */ 5001 smp_mb(); /* pairs with wait_var_event() */ 5002 wake_up_var(var); 5003 } 5004 5005 no_ctx: 5006 put_event(event); /* Must be the 'last' reference */ 5007 return 0; 5008 } 5009 EXPORT_SYMBOL_GPL(perf_event_release_kernel); 5010 5011 /* 5012 * Called when the last reference to the file is gone. 5013 */ 5014 static int perf_release(struct inode *inode, struct file *file) 5015 { 5016 perf_event_release_kernel(file->private_data); 5017 return 0; 5018 } 5019 5020 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 5021 { 5022 struct perf_event *child; 5023 u64 total = 0; 5024 5025 *enabled = 0; 5026 *running = 0; 5027 5028 mutex_lock(&event->child_mutex); 5029 5030 (void)perf_event_read(event, false); 5031 total += perf_event_count(event); 5032 5033 *enabled += event->total_time_enabled + 5034 atomic64_read(&event->child_total_time_enabled); 5035 *running += event->total_time_running + 5036 atomic64_read(&event->child_total_time_running); 5037 5038 list_for_each_entry(child, &event->child_list, child_list) { 5039 (void)perf_event_read(child, false); 5040 total += perf_event_count(child); 5041 *enabled += child->total_time_enabled; 5042 *running += child->total_time_running; 5043 } 5044 mutex_unlock(&event->child_mutex); 5045 5046 return total; 5047 } 5048 5049 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 5050 { 5051 struct perf_event_context *ctx; 5052 u64 count; 5053 5054 ctx = perf_event_ctx_lock(event); 5055 count = __perf_event_read_value(event, enabled, running); 5056 perf_event_ctx_unlock(event, ctx); 5057 5058 return count; 5059 } 5060 EXPORT_SYMBOL_GPL(perf_event_read_value); 5061 5062 static int __perf_read_group_add(struct perf_event *leader, 5063 u64 read_format, u64 *values) 5064 { 5065 struct perf_event_context *ctx = leader->ctx; 5066 struct perf_event *sub; 5067 unsigned long flags; 5068 int n = 1; /* skip @nr */ 5069 int ret; 5070 5071 ret = perf_event_read(leader, true); 5072 if (ret) 5073 return ret; 5074 5075 raw_spin_lock_irqsave(&ctx->lock, flags); 5076 5077 /* 5078 * Since we co-schedule groups, {enabled,running} times of siblings 5079 * will be identical to those of the leader, so we only publish one 5080 * set. 5081 */ 5082 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 5083 values[n++] += leader->total_time_enabled + 5084 atomic64_read(&leader->child_total_time_enabled); 5085 } 5086 5087 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 5088 values[n++] += leader->total_time_running + 5089 atomic64_read(&leader->child_total_time_running); 5090 } 5091 5092 /* 5093 * Write {count,id} tuples for every sibling. 5094 */ 5095 values[n++] += perf_event_count(leader); 5096 if (read_format & PERF_FORMAT_ID) 5097 values[n++] = primary_event_id(leader); 5098 5099 for_each_sibling_event(sub, leader) { 5100 values[n++] += perf_event_count(sub); 5101 if (read_format & PERF_FORMAT_ID) 5102 values[n++] = primary_event_id(sub); 5103 } 5104 5105 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5106 return 0; 5107 } 5108 5109 static int perf_read_group(struct perf_event *event, 5110 u64 read_format, char __user *buf) 5111 { 5112 struct perf_event *leader = event->group_leader, *child; 5113 struct perf_event_context *ctx = leader->ctx; 5114 int ret; 5115 u64 *values; 5116 5117 lockdep_assert_held(&ctx->mutex); 5118 5119 values = kzalloc(event->read_size, GFP_KERNEL); 5120 if (!values) 5121 return -ENOMEM; 5122 5123 values[0] = 1 + leader->nr_siblings; 5124 5125 /* 5126 * By locking the child_mutex of the leader we effectively 5127 * lock the child list of all siblings.. XXX explain how. 5128 */ 5129 mutex_lock(&leader->child_mutex); 5130 5131 ret = __perf_read_group_add(leader, read_format, values); 5132 if (ret) 5133 goto unlock; 5134 5135 list_for_each_entry(child, &leader->child_list, child_list) { 5136 ret = __perf_read_group_add(child, read_format, values); 5137 if (ret) 5138 goto unlock; 5139 } 5140 5141 mutex_unlock(&leader->child_mutex); 5142 5143 ret = event->read_size; 5144 if (copy_to_user(buf, values, event->read_size)) 5145 ret = -EFAULT; 5146 goto out; 5147 5148 unlock: 5149 mutex_unlock(&leader->child_mutex); 5150 out: 5151 kfree(values); 5152 return ret; 5153 } 5154 5155 static int perf_read_one(struct perf_event *event, 5156 u64 read_format, char __user *buf) 5157 { 5158 u64 enabled, running; 5159 u64 values[4]; 5160 int n = 0; 5161 5162 values[n++] = __perf_event_read_value(event, &enabled, &running); 5163 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 5164 values[n++] = enabled; 5165 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 5166 values[n++] = running; 5167 if (read_format & PERF_FORMAT_ID) 5168 values[n++] = primary_event_id(event); 5169 5170 if (copy_to_user(buf, values, n * sizeof(u64))) 5171 return -EFAULT; 5172 5173 return n * sizeof(u64); 5174 } 5175 5176 static bool is_event_hup(struct perf_event *event) 5177 { 5178 bool no_children; 5179 5180 if (event->state > PERF_EVENT_STATE_EXIT) 5181 return false; 5182 5183 mutex_lock(&event->child_mutex); 5184 no_children = list_empty(&event->child_list); 5185 mutex_unlock(&event->child_mutex); 5186 return no_children; 5187 } 5188 5189 /* 5190 * Read the performance event - simple non blocking version for now 5191 */ 5192 static ssize_t 5193 __perf_read(struct perf_event *event, char __user *buf, size_t count) 5194 { 5195 u64 read_format = event->attr.read_format; 5196 int ret; 5197 5198 /* 5199 * Return end-of-file for a read on an event that is in 5200 * error state (i.e. because it was pinned but it couldn't be 5201 * scheduled on to the CPU at some point). 5202 */ 5203 if (event->state == PERF_EVENT_STATE_ERROR) 5204 return 0; 5205 5206 if (count < event->read_size) 5207 return -ENOSPC; 5208 5209 WARN_ON_ONCE(event->ctx->parent_ctx); 5210 if (read_format & PERF_FORMAT_GROUP) 5211 ret = perf_read_group(event, read_format, buf); 5212 else 5213 ret = perf_read_one(event, read_format, buf); 5214 5215 return ret; 5216 } 5217 5218 static ssize_t 5219 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) 5220 { 5221 struct perf_event *event = file->private_data; 5222 struct perf_event_context *ctx; 5223 int ret; 5224 5225 ret = security_perf_event_read(event); 5226 if (ret) 5227 return ret; 5228 5229 ctx = perf_event_ctx_lock(event); 5230 ret = __perf_read(event, buf, count); 5231 perf_event_ctx_unlock(event, ctx); 5232 5233 return ret; 5234 } 5235 5236 static __poll_t perf_poll(struct file *file, poll_table *wait) 5237 { 5238 struct perf_event *event = file->private_data; 5239 struct perf_buffer *rb; 5240 __poll_t events = EPOLLHUP; 5241 5242 poll_wait(file, &event->waitq, wait); 5243 5244 if (is_event_hup(event)) 5245 return events; 5246 5247 /* 5248 * Pin the event->rb by taking event->mmap_mutex; otherwise 5249 * perf_event_set_output() can swizzle our rb and make us miss wakeups. 5250 */ 5251 mutex_lock(&event->mmap_mutex); 5252 rb = event->rb; 5253 if (rb) 5254 events = atomic_xchg(&rb->poll, 0); 5255 mutex_unlock(&event->mmap_mutex); 5256 return events; 5257 } 5258 5259 static void _perf_event_reset(struct perf_event *event) 5260 { 5261 (void)perf_event_read(event, false); 5262 local64_set(&event->count, 0); 5263 perf_event_update_userpage(event); 5264 } 5265 5266 /* Assume it's not an event with inherit set. */ 5267 u64 perf_event_pause(struct perf_event *event, bool reset) 5268 { 5269 struct perf_event_context *ctx; 5270 u64 count; 5271 5272 ctx = perf_event_ctx_lock(event); 5273 WARN_ON_ONCE(event->attr.inherit); 5274 _perf_event_disable(event); 5275 count = local64_read(&event->count); 5276 if (reset) 5277 local64_set(&event->count, 0); 5278 perf_event_ctx_unlock(event, ctx); 5279 5280 return count; 5281 } 5282 EXPORT_SYMBOL_GPL(perf_event_pause); 5283 5284 /* 5285 * Holding the top-level event's child_mutex means that any 5286 * descendant process that has inherited this event will block 5287 * in perf_event_exit_event() if it goes to exit, thus satisfying the 5288 * task existence requirements of perf_event_enable/disable. 5289 */ 5290 static void perf_event_for_each_child(struct perf_event *event, 5291 void (*func)(struct perf_event *)) 5292 { 5293 struct perf_event *child; 5294 5295 WARN_ON_ONCE(event->ctx->parent_ctx); 5296 5297 mutex_lock(&event->child_mutex); 5298 func(event); 5299 list_for_each_entry(child, &event->child_list, child_list) 5300 func(child); 5301 mutex_unlock(&event->child_mutex); 5302 } 5303 5304 static void perf_event_for_each(struct perf_event *event, 5305 void (*func)(struct perf_event *)) 5306 { 5307 struct perf_event_context *ctx = event->ctx; 5308 struct perf_event *sibling; 5309 5310 lockdep_assert_held(&ctx->mutex); 5311 5312 event = event->group_leader; 5313 5314 perf_event_for_each_child(event, func); 5315 for_each_sibling_event(sibling, event) 5316 perf_event_for_each_child(sibling, func); 5317 } 5318 5319 static void __perf_event_period(struct perf_event *event, 5320 struct perf_cpu_context *cpuctx, 5321 struct perf_event_context *ctx, 5322 void *info) 5323 { 5324 u64 value = *((u64 *)info); 5325 bool active; 5326 5327 if (event->attr.freq) { 5328 event->attr.sample_freq = value; 5329 } else { 5330 event->attr.sample_period = value; 5331 event->hw.sample_period = value; 5332 } 5333 5334 active = (event->state == PERF_EVENT_STATE_ACTIVE); 5335 if (active) { 5336 perf_pmu_disable(ctx->pmu); 5337 /* 5338 * We could be throttled; unthrottle now to avoid the tick 5339 * trying to unthrottle while we already re-started the event. 5340 */ 5341 if (event->hw.interrupts == MAX_INTERRUPTS) { 5342 event->hw.interrupts = 0; 5343 perf_log_throttle(event, 1); 5344 } 5345 event->pmu->stop(event, PERF_EF_UPDATE); 5346 } 5347 5348 local64_set(&event->hw.period_left, 0); 5349 5350 if (active) { 5351 event->pmu->start(event, PERF_EF_RELOAD); 5352 perf_pmu_enable(ctx->pmu); 5353 } 5354 } 5355 5356 static int perf_event_check_period(struct perf_event *event, u64 value) 5357 { 5358 return event->pmu->check_period(event, value); 5359 } 5360 5361 static int _perf_event_period(struct perf_event *event, u64 value) 5362 { 5363 if (!is_sampling_event(event)) 5364 return -EINVAL; 5365 5366 if (!value) 5367 return -EINVAL; 5368 5369 if (event->attr.freq && value > sysctl_perf_event_sample_rate) 5370 return -EINVAL; 5371 5372 if (perf_event_check_period(event, value)) 5373 return -EINVAL; 5374 5375 if (!event->attr.freq && (value & (1ULL << 63))) 5376 return -EINVAL; 5377 5378 event_function_call(event, __perf_event_period, &value); 5379 5380 return 0; 5381 } 5382 5383 int perf_event_period(struct perf_event *event, u64 value) 5384 { 5385 struct perf_event_context *ctx; 5386 int ret; 5387 5388 ctx = perf_event_ctx_lock(event); 5389 ret = _perf_event_period(event, value); 5390 perf_event_ctx_unlock(event, ctx); 5391 5392 return ret; 5393 } 5394 EXPORT_SYMBOL_GPL(perf_event_period); 5395 5396 static const struct file_operations perf_fops; 5397 5398 static inline int perf_fget_light(int fd, struct fd *p) 5399 { 5400 struct fd f = fdget(fd); 5401 if (!f.file) 5402 return -EBADF; 5403 5404 if (f.file->f_op != &perf_fops) { 5405 fdput(f); 5406 return -EBADF; 5407 } 5408 *p = f; 5409 return 0; 5410 } 5411 5412 static int perf_event_set_output(struct perf_event *event, 5413 struct perf_event *output_event); 5414 static int perf_event_set_filter(struct perf_event *event, void __user *arg); 5415 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd); 5416 static int perf_copy_attr(struct perf_event_attr __user *uattr, 5417 struct perf_event_attr *attr); 5418 5419 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg) 5420 { 5421 void (*func)(struct perf_event *); 5422 u32 flags = arg; 5423 5424 switch (cmd) { 5425 case PERF_EVENT_IOC_ENABLE: 5426 func = _perf_event_enable; 5427 break; 5428 case PERF_EVENT_IOC_DISABLE: 5429 func = _perf_event_disable; 5430 break; 5431 case PERF_EVENT_IOC_RESET: 5432 func = _perf_event_reset; 5433 break; 5434 5435 case PERF_EVENT_IOC_REFRESH: 5436 return _perf_event_refresh(event, arg); 5437 5438 case PERF_EVENT_IOC_PERIOD: 5439 { 5440 u64 value; 5441 5442 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value))) 5443 return -EFAULT; 5444 5445 return _perf_event_period(event, value); 5446 } 5447 case PERF_EVENT_IOC_ID: 5448 { 5449 u64 id = primary_event_id(event); 5450 5451 if (copy_to_user((void __user *)arg, &id, sizeof(id))) 5452 return -EFAULT; 5453 return 0; 5454 } 5455 5456 case PERF_EVENT_IOC_SET_OUTPUT: 5457 { 5458 int ret; 5459 if (arg != -1) { 5460 struct perf_event *output_event; 5461 struct fd output; 5462 ret = perf_fget_light(arg, &output); 5463 if (ret) 5464 return ret; 5465 output_event = output.file->private_data; 5466 ret = perf_event_set_output(event, output_event); 5467 fdput(output); 5468 } else { 5469 ret = perf_event_set_output(event, NULL); 5470 } 5471 return ret; 5472 } 5473 5474 case PERF_EVENT_IOC_SET_FILTER: 5475 return perf_event_set_filter(event, (void __user *)arg); 5476 5477 case PERF_EVENT_IOC_SET_BPF: 5478 return perf_event_set_bpf_prog(event, arg); 5479 5480 case PERF_EVENT_IOC_PAUSE_OUTPUT: { 5481 struct perf_buffer *rb; 5482 5483 rcu_read_lock(); 5484 rb = rcu_dereference(event->rb); 5485 if (!rb || !rb->nr_pages) { 5486 rcu_read_unlock(); 5487 return -EINVAL; 5488 } 5489 rb_toggle_paused(rb, !!arg); 5490 rcu_read_unlock(); 5491 return 0; 5492 } 5493 5494 case PERF_EVENT_IOC_QUERY_BPF: 5495 return perf_event_query_prog_array(event, (void __user *)arg); 5496 5497 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: { 5498 struct perf_event_attr new_attr; 5499 int err = perf_copy_attr((struct perf_event_attr __user *)arg, 5500 &new_attr); 5501 5502 if (err) 5503 return err; 5504 5505 return perf_event_modify_attr(event, &new_attr); 5506 } 5507 default: 5508 return -ENOTTY; 5509 } 5510 5511 if (flags & PERF_IOC_FLAG_GROUP) 5512 perf_event_for_each(event, func); 5513 else 5514 perf_event_for_each_child(event, func); 5515 5516 return 0; 5517 } 5518 5519 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg) 5520 { 5521 struct perf_event *event = file->private_data; 5522 struct perf_event_context *ctx; 5523 long ret; 5524 5525 /* Treat ioctl like writes as it is likely a mutating operation. */ 5526 ret = security_perf_event_write(event); 5527 if (ret) 5528 return ret; 5529 5530 ctx = perf_event_ctx_lock(event); 5531 ret = _perf_ioctl(event, cmd, arg); 5532 perf_event_ctx_unlock(event, ctx); 5533 5534 return ret; 5535 } 5536 5537 #ifdef CONFIG_COMPAT 5538 static long perf_compat_ioctl(struct file *file, unsigned int cmd, 5539 unsigned long arg) 5540 { 5541 switch (_IOC_NR(cmd)) { 5542 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER): 5543 case _IOC_NR(PERF_EVENT_IOC_ID): 5544 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF): 5545 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES): 5546 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */ 5547 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) { 5548 cmd &= ~IOCSIZE_MASK; 5549 cmd |= sizeof(void *) << IOCSIZE_SHIFT; 5550 } 5551 break; 5552 } 5553 return perf_ioctl(file, cmd, arg); 5554 } 5555 #else 5556 # define perf_compat_ioctl NULL 5557 #endif 5558 5559 int perf_event_task_enable(void) 5560 { 5561 struct perf_event_context *ctx; 5562 struct perf_event *event; 5563 5564 mutex_lock(¤t->perf_event_mutex); 5565 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) { 5566 ctx = perf_event_ctx_lock(event); 5567 perf_event_for_each_child(event, _perf_event_enable); 5568 perf_event_ctx_unlock(event, ctx); 5569 } 5570 mutex_unlock(¤t->perf_event_mutex); 5571 5572 return 0; 5573 } 5574 5575 int perf_event_task_disable(void) 5576 { 5577 struct perf_event_context *ctx; 5578 struct perf_event *event; 5579 5580 mutex_lock(¤t->perf_event_mutex); 5581 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) { 5582 ctx = perf_event_ctx_lock(event); 5583 perf_event_for_each_child(event, _perf_event_disable); 5584 perf_event_ctx_unlock(event, ctx); 5585 } 5586 mutex_unlock(¤t->perf_event_mutex); 5587 5588 return 0; 5589 } 5590 5591 static int perf_event_index(struct perf_event *event) 5592 { 5593 if (event->hw.state & PERF_HES_STOPPED) 5594 return 0; 5595 5596 if (event->state != PERF_EVENT_STATE_ACTIVE) 5597 return 0; 5598 5599 return event->pmu->event_idx(event); 5600 } 5601 5602 static void calc_timer_values(struct perf_event *event, 5603 u64 *now, 5604 u64 *enabled, 5605 u64 *running) 5606 { 5607 u64 ctx_time; 5608 5609 *now = perf_clock(); 5610 ctx_time = event->shadow_ctx_time + *now; 5611 __perf_update_times(event, ctx_time, enabled, running); 5612 } 5613 5614 static void perf_event_init_userpage(struct perf_event *event) 5615 { 5616 struct perf_event_mmap_page *userpg; 5617 struct perf_buffer *rb; 5618 5619 rcu_read_lock(); 5620 rb = rcu_dereference(event->rb); 5621 if (!rb) 5622 goto unlock; 5623 5624 userpg = rb->user_page; 5625 5626 /* Allow new userspace to detect that bit 0 is deprecated */ 5627 userpg->cap_bit0_is_deprecated = 1; 5628 userpg->size = offsetof(struct perf_event_mmap_page, __reserved); 5629 userpg->data_offset = PAGE_SIZE; 5630 userpg->data_size = perf_data_size(rb); 5631 5632 unlock: 5633 rcu_read_unlock(); 5634 } 5635 5636 void __weak arch_perf_update_userpage( 5637 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now) 5638 { 5639 } 5640 5641 /* 5642 * Callers need to ensure there can be no nesting of this function, otherwise 5643 * the seqlock logic goes bad. We can not serialize this because the arch 5644 * code calls this from NMI context. 5645 */ 5646 void perf_event_update_userpage(struct perf_event *event) 5647 { 5648 struct perf_event_mmap_page *userpg; 5649 struct perf_buffer *rb; 5650 u64 enabled, running, now; 5651 5652 rcu_read_lock(); 5653 rb = rcu_dereference(event->rb); 5654 if (!rb) 5655 goto unlock; 5656 5657 /* 5658 * compute total_time_enabled, total_time_running 5659 * based on snapshot values taken when the event 5660 * was last scheduled in. 5661 * 5662 * we cannot simply called update_context_time() 5663 * because of locking issue as we can be called in 5664 * NMI context 5665 */ 5666 calc_timer_values(event, &now, &enabled, &running); 5667 5668 userpg = rb->user_page; 5669 /* 5670 * Disable preemption to guarantee consistent time stamps are stored to 5671 * the user page. 5672 */ 5673 preempt_disable(); 5674 ++userpg->lock; 5675 barrier(); 5676 userpg->index = perf_event_index(event); 5677 userpg->offset = perf_event_count(event); 5678 if (userpg->index) 5679 userpg->offset -= local64_read(&event->hw.prev_count); 5680 5681 userpg->time_enabled = enabled + 5682 atomic64_read(&event->child_total_time_enabled); 5683 5684 userpg->time_running = running + 5685 atomic64_read(&event->child_total_time_running); 5686 5687 arch_perf_update_userpage(event, userpg, now); 5688 5689 barrier(); 5690 ++userpg->lock; 5691 preempt_enable(); 5692 unlock: 5693 rcu_read_unlock(); 5694 } 5695 EXPORT_SYMBOL_GPL(perf_event_update_userpage); 5696 5697 static vm_fault_t perf_mmap_fault(struct vm_fault *vmf) 5698 { 5699 struct perf_event *event = vmf->vma->vm_file->private_data; 5700 struct perf_buffer *rb; 5701 vm_fault_t ret = VM_FAULT_SIGBUS; 5702 5703 if (vmf->flags & FAULT_FLAG_MKWRITE) { 5704 if (vmf->pgoff == 0) 5705 ret = 0; 5706 return ret; 5707 } 5708 5709 rcu_read_lock(); 5710 rb = rcu_dereference(event->rb); 5711 if (!rb) 5712 goto unlock; 5713 5714 if (vmf->pgoff && (vmf->flags & FAULT_FLAG_WRITE)) 5715 goto unlock; 5716 5717 vmf->page = perf_mmap_to_page(rb, vmf->pgoff); 5718 if (!vmf->page) 5719 goto unlock; 5720 5721 get_page(vmf->page); 5722 vmf->page->mapping = vmf->vma->vm_file->f_mapping; 5723 vmf->page->index = vmf->pgoff; 5724 5725 ret = 0; 5726 unlock: 5727 rcu_read_unlock(); 5728 5729 return ret; 5730 } 5731 5732 static void ring_buffer_attach(struct perf_event *event, 5733 struct perf_buffer *rb) 5734 { 5735 struct perf_buffer *old_rb = NULL; 5736 unsigned long flags; 5737 5738 if (event->rb) { 5739 /* 5740 * Should be impossible, we set this when removing 5741 * event->rb_entry and wait/clear when adding event->rb_entry. 5742 */ 5743 WARN_ON_ONCE(event->rcu_pending); 5744 5745 old_rb = event->rb; 5746 spin_lock_irqsave(&old_rb->event_lock, flags); 5747 list_del_rcu(&event->rb_entry); 5748 spin_unlock_irqrestore(&old_rb->event_lock, flags); 5749 5750 event->rcu_batches = get_state_synchronize_rcu(); 5751 event->rcu_pending = 1; 5752 } 5753 5754 if (rb) { 5755 if (event->rcu_pending) { 5756 cond_synchronize_rcu(event->rcu_batches); 5757 event->rcu_pending = 0; 5758 } 5759 5760 spin_lock_irqsave(&rb->event_lock, flags); 5761 list_add_rcu(&event->rb_entry, &rb->event_list); 5762 spin_unlock_irqrestore(&rb->event_lock, flags); 5763 } 5764 5765 /* 5766 * Avoid racing with perf_mmap_close(AUX): stop the event 5767 * before swizzling the event::rb pointer; if it's getting 5768 * unmapped, its aux_mmap_count will be 0 and it won't 5769 * restart. See the comment in __perf_pmu_output_stop(). 5770 * 5771 * Data will inevitably be lost when set_output is done in 5772 * mid-air, but then again, whoever does it like this is 5773 * not in for the data anyway. 5774 */ 5775 if (has_aux(event)) 5776 perf_event_stop(event, 0); 5777 5778 rcu_assign_pointer(event->rb, rb); 5779 5780 if (old_rb) { 5781 ring_buffer_put(old_rb); 5782 /* 5783 * Since we detached before setting the new rb, so that we 5784 * could attach the new rb, we could have missed a wakeup. 5785 * Provide it now. 5786 */ 5787 wake_up_all(&event->waitq); 5788 } 5789 } 5790 5791 static void ring_buffer_wakeup(struct perf_event *event) 5792 { 5793 struct perf_buffer *rb; 5794 5795 rcu_read_lock(); 5796 rb = rcu_dereference(event->rb); 5797 if (rb) { 5798 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) 5799 wake_up_all(&event->waitq); 5800 } 5801 rcu_read_unlock(); 5802 } 5803 5804 struct perf_buffer *ring_buffer_get(struct perf_event *event) 5805 { 5806 struct perf_buffer *rb; 5807 5808 rcu_read_lock(); 5809 rb = rcu_dereference(event->rb); 5810 if (rb) { 5811 if (!refcount_inc_not_zero(&rb->refcount)) 5812 rb = NULL; 5813 } 5814 rcu_read_unlock(); 5815 5816 return rb; 5817 } 5818 5819 void ring_buffer_put(struct perf_buffer *rb) 5820 { 5821 if (!refcount_dec_and_test(&rb->refcount)) 5822 return; 5823 5824 WARN_ON_ONCE(!list_empty(&rb->event_list)); 5825 5826 call_rcu(&rb->rcu_head, rb_free_rcu); 5827 } 5828 5829 static void perf_mmap_open(struct vm_area_struct *vma) 5830 { 5831 struct perf_event *event = vma->vm_file->private_data; 5832 5833 atomic_inc(&event->mmap_count); 5834 atomic_inc(&event->rb->mmap_count); 5835 5836 if (vma->vm_pgoff) 5837 atomic_inc(&event->rb->aux_mmap_count); 5838 5839 if (event->pmu->event_mapped) 5840 event->pmu->event_mapped(event, vma->vm_mm); 5841 } 5842 5843 static void perf_pmu_output_stop(struct perf_event *event); 5844 5845 /* 5846 * A buffer can be mmap()ed multiple times; either directly through the same 5847 * event, or through other events by use of perf_event_set_output(). 5848 * 5849 * In order to undo the VM accounting done by perf_mmap() we need to destroy 5850 * the buffer here, where we still have a VM context. This means we need 5851 * to detach all events redirecting to us. 5852 */ 5853 static void perf_mmap_close(struct vm_area_struct *vma) 5854 { 5855 struct perf_event *event = vma->vm_file->private_data; 5856 5857 struct perf_buffer *rb = ring_buffer_get(event); 5858 struct user_struct *mmap_user = rb->mmap_user; 5859 int mmap_locked = rb->mmap_locked; 5860 unsigned long size = perf_data_size(rb); 5861 5862 if (event->pmu->event_unmapped) 5863 event->pmu->event_unmapped(event, vma->vm_mm); 5864 5865 /* 5866 * rb->aux_mmap_count will always drop before rb->mmap_count and 5867 * event->mmap_count, so it is ok to use event->mmap_mutex to 5868 * serialize with perf_mmap here. 5869 */ 5870 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff && 5871 atomic_dec_and_mutex_lock(&rb->aux_mmap_count, &event->mmap_mutex)) { 5872 /* 5873 * Stop all AUX events that are writing to this buffer, 5874 * so that we can free its AUX pages and corresponding PMU 5875 * data. Note that after rb::aux_mmap_count dropped to zero, 5876 * they won't start any more (see perf_aux_output_begin()). 5877 */ 5878 perf_pmu_output_stop(event); 5879 5880 /* now it's safe to free the pages */ 5881 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm); 5882 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm); 5883 5884 /* this has to be the last one */ 5885 rb_free_aux(rb); 5886 WARN_ON_ONCE(refcount_read(&rb->aux_refcount)); 5887 5888 mutex_unlock(&event->mmap_mutex); 5889 } 5890 5891 atomic_dec(&rb->mmap_count); 5892 5893 if (!atomic_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) 5894 goto out_put; 5895 5896 ring_buffer_attach(event, NULL); 5897 mutex_unlock(&event->mmap_mutex); 5898 5899 /* If there's still other mmap()s of this buffer, we're done. */ 5900 if (atomic_read(&rb->mmap_count)) 5901 goto out_put; 5902 5903 /* 5904 * No other mmap()s, detach from all other events that might redirect 5905 * into the now unreachable buffer. Somewhat complicated by the 5906 * fact that rb::event_lock otherwise nests inside mmap_mutex. 5907 */ 5908 again: 5909 rcu_read_lock(); 5910 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) { 5911 if (!atomic_long_inc_not_zero(&event->refcount)) { 5912 /* 5913 * This event is en-route to free_event() which will 5914 * detach it and remove it from the list. 5915 */ 5916 continue; 5917 } 5918 rcu_read_unlock(); 5919 5920 mutex_lock(&event->mmap_mutex); 5921 /* 5922 * Check we didn't race with perf_event_set_output() which can 5923 * swizzle the rb from under us while we were waiting to 5924 * acquire mmap_mutex. 5925 * 5926 * If we find a different rb; ignore this event, a next 5927 * iteration will no longer find it on the list. We have to 5928 * still restart the iteration to make sure we're not now 5929 * iterating the wrong list. 5930 */ 5931 if (event->rb == rb) 5932 ring_buffer_attach(event, NULL); 5933 5934 mutex_unlock(&event->mmap_mutex); 5935 put_event(event); 5936 5937 /* 5938 * Restart the iteration; either we're on the wrong list or 5939 * destroyed its integrity by doing a deletion. 5940 */ 5941 goto again; 5942 } 5943 rcu_read_unlock(); 5944 5945 /* 5946 * It could be there's still a few 0-ref events on the list; they'll 5947 * get cleaned up by free_event() -- they'll also still have their 5948 * ref on the rb and will free it whenever they are done with it. 5949 * 5950 * Aside from that, this buffer is 'fully' detached and unmapped, 5951 * undo the VM accounting. 5952 */ 5953 5954 atomic_long_sub((size >> PAGE_SHIFT) + 1 - mmap_locked, 5955 &mmap_user->locked_vm); 5956 atomic64_sub(mmap_locked, &vma->vm_mm->pinned_vm); 5957 free_uid(mmap_user); 5958 5959 out_put: 5960 ring_buffer_put(rb); /* could be last */ 5961 } 5962 5963 static const struct vm_operations_struct perf_mmap_vmops = { 5964 .open = perf_mmap_open, 5965 .close = perf_mmap_close, /* non mergeable */ 5966 .fault = perf_mmap_fault, 5967 .page_mkwrite = perf_mmap_fault, 5968 }; 5969 5970 static int perf_mmap(struct file *file, struct vm_area_struct *vma) 5971 { 5972 struct perf_event *event = file->private_data; 5973 unsigned long user_locked, user_lock_limit; 5974 struct user_struct *user = current_user(); 5975 struct perf_buffer *rb = NULL; 5976 unsigned long locked, lock_limit; 5977 unsigned long vma_size; 5978 unsigned long nr_pages; 5979 long user_extra = 0, extra = 0; 5980 int ret = 0, flags = 0; 5981 5982 /* 5983 * Don't allow mmap() of inherited per-task counters. This would 5984 * create a performance issue due to all children writing to the 5985 * same rb. 5986 */ 5987 if (event->cpu == -1 && event->attr.inherit) 5988 return -EINVAL; 5989 5990 if (!(vma->vm_flags & VM_SHARED)) 5991 return -EINVAL; 5992 5993 ret = security_perf_event_read(event); 5994 if (ret) 5995 return ret; 5996 5997 vma_size = vma->vm_end - vma->vm_start; 5998 5999 if (vma->vm_pgoff == 0) { 6000 nr_pages = (vma_size / PAGE_SIZE) - 1; 6001 } else { 6002 /* 6003 * AUX area mapping: if rb->aux_nr_pages != 0, it's already 6004 * mapped, all subsequent mappings should have the same size 6005 * and offset. Must be above the normal perf buffer. 6006 */ 6007 u64 aux_offset, aux_size; 6008 6009 if (!event->rb) 6010 return -EINVAL; 6011 6012 nr_pages = vma_size / PAGE_SIZE; 6013 6014 mutex_lock(&event->mmap_mutex); 6015 ret = -EINVAL; 6016 6017 rb = event->rb; 6018 if (!rb) 6019 goto aux_unlock; 6020 6021 aux_offset = READ_ONCE(rb->user_page->aux_offset); 6022 aux_size = READ_ONCE(rb->user_page->aux_size); 6023 6024 if (aux_offset < perf_data_size(rb) + PAGE_SIZE) 6025 goto aux_unlock; 6026 6027 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT) 6028 goto aux_unlock; 6029 6030 /* already mapped with a different offset */ 6031 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff) 6032 goto aux_unlock; 6033 6034 if (aux_size != vma_size || aux_size != nr_pages * PAGE_SIZE) 6035 goto aux_unlock; 6036 6037 /* already mapped with a different size */ 6038 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages) 6039 goto aux_unlock; 6040 6041 if (!is_power_of_2(nr_pages)) 6042 goto aux_unlock; 6043 6044 if (!atomic_inc_not_zero(&rb->mmap_count)) 6045 goto aux_unlock; 6046 6047 if (rb_has_aux(rb)) { 6048 atomic_inc(&rb->aux_mmap_count); 6049 ret = 0; 6050 goto unlock; 6051 } 6052 6053 atomic_set(&rb->aux_mmap_count, 1); 6054 user_extra = nr_pages; 6055 6056 goto accounting; 6057 } 6058 6059 /* 6060 * If we have rb pages ensure they're a power-of-two number, so we 6061 * can do bitmasks instead of modulo. 6062 */ 6063 if (nr_pages != 0 && !is_power_of_2(nr_pages)) 6064 return -EINVAL; 6065 6066 if (vma_size != PAGE_SIZE * (1 + nr_pages)) 6067 return -EINVAL; 6068 6069 WARN_ON_ONCE(event->ctx->parent_ctx); 6070 again: 6071 mutex_lock(&event->mmap_mutex); 6072 if (event->rb) { 6073 if (event->rb->nr_pages != nr_pages) { 6074 ret = -EINVAL; 6075 goto unlock; 6076 } 6077 6078 if (!atomic_inc_not_zero(&event->rb->mmap_count)) { 6079 /* 6080 * Raced against perf_mmap_close() through 6081 * perf_event_set_output(). Try again, hope for better 6082 * luck. 6083 */ 6084 mutex_unlock(&event->mmap_mutex); 6085 goto again; 6086 } 6087 6088 goto unlock; 6089 } 6090 6091 user_extra = nr_pages + 1; 6092 6093 accounting: 6094 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10); 6095 6096 /* 6097 * Increase the limit linearly with more CPUs: 6098 */ 6099 user_lock_limit *= num_online_cpus(); 6100 6101 user_locked = atomic_long_read(&user->locked_vm); 6102 6103 /* 6104 * sysctl_perf_event_mlock may have changed, so that 6105 * user->locked_vm > user_lock_limit 6106 */ 6107 if (user_locked > user_lock_limit) 6108 user_locked = user_lock_limit; 6109 user_locked += user_extra; 6110 6111 if (user_locked > user_lock_limit) { 6112 /* 6113 * charge locked_vm until it hits user_lock_limit; 6114 * charge the rest from pinned_vm 6115 */ 6116 extra = user_locked - user_lock_limit; 6117 user_extra -= extra; 6118 } 6119 6120 lock_limit = rlimit(RLIMIT_MEMLOCK); 6121 lock_limit >>= PAGE_SHIFT; 6122 locked = atomic64_read(&vma->vm_mm->pinned_vm) + extra; 6123 6124 if ((locked > lock_limit) && perf_is_paranoid() && 6125 !capable(CAP_IPC_LOCK)) { 6126 ret = -EPERM; 6127 goto unlock; 6128 } 6129 6130 WARN_ON(!rb && event->rb); 6131 6132 if (vma->vm_flags & VM_WRITE) 6133 flags |= RING_BUFFER_WRITABLE; 6134 6135 if (!rb) { 6136 rb = rb_alloc(nr_pages, 6137 event->attr.watermark ? event->attr.wakeup_watermark : 0, 6138 event->cpu, flags); 6139 6140 if (!rb) { 6141 ret = -ENOMEM; 6142 goto unlock; 6143 } 6144 6145 atomic_set(&rb->mmap_count, 1); 6146 rb->mmap_user = get_current_user(); 6147 rb->mmap_locked = extra; 6148 6149 ring_buffer_attach(event, rb); 6150 6151 perf_event_init_userpage(event); 6152 perf_event_update_userpage(event); 6153 } else { 6154 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages, 6155 event->attr.aux_watermark, flags); 6156 if (!ret) 6157 rb->aux_mmap_locked = extra; 6158 } 6159 6160 unlock: 6161 if (!ret) { 6162 atomic_long_add(user_extra, &user->locked_vm); 6163 atomic64_add(extra, &vma->vm_mm->pinned_vm); 6164 6165 atomic_inc(&event->mmap_count); 6166 } else if (rb) { 6167 atomic_dec(&rb->mmap_count); 6168 } 6169 aux_unlock: 6170 mutex_unlock(&event->mmap_mutex); 6171 6172 /* 6173 * Since pinned accounting is per vm we cannot allow fork() to copy our 6174 * vma. 6175 */ 6176 vma->vm_flags |= VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP; 6177 vma->vm_ops = &perf_mmap_vmops; 6178 6179 if (event->pmu->event_mapped) 6180 event->pmu->event_mapped(event, vma->vm_mm); 6181 6182 return ret; 6183 } 6184 6185 static int perf_fasync(int fd, struct file *filp, int on) 6186 { 6187 struct inode *inode = file_inode(filp); 6188 struct perf_event *event = filp->private_data; 6189 int retval; 6190 6191 inode_lock(inode); 6192 retval = fasync_helper(fd, filp, on, &event->fasync); 6193 inode_unlock(inode); 6194 6195 if (retval < 0) 6196 return retval; 6197 6198 return 0; 6199 } 6200 6201 static const struct file_operations perf_fops = { 6202 .llseek = no_llseek, 6203 .release = perf_release, 6204 .read = perf_read, 6205 .poll = perf_poll, 6206 .unlocked_ioctl = perf_ioctl, 6207 .compat_ioctl = perf_compat_ioctl, 6208 .mmap = perf_mmap, 6209 .fasync = perf_fasync, 6210 }; 6211 6212 /* 6213 * Perf event wakeup 6214 * 6215 * If there's data, ensure we set the poll() state and publish everything 6216 * to user-space before waking everybody up. 6217 */ 6218 6219 static inline struct fasync_struct **perf_event_fasync(struct perf_event *event) 6220 { 6221 /* only the parent has fasync state */ 6222 if (event->parent) 6223 event = event->parent; 6224 return &event->fasync; 6225 } 6226 6227 void perf_event_wakeup(struct perf_event *event) 6228 { 6229 ring_buffer_wakeup(event); 6230 6231 if (event->pending_kill) { 6232 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill); 6233 event->pending_kill = 0; 6234 } 6235 } 6236 6237 static void perf_pending_event_disable(struct perf_event *event) 6238 { 6239 int cpu = READ_ONCE(event->pending_disable); 6240 6241 if (cpu < 0) 6242 return; 6243 6244 if (cpu == smp_processor_id()) { 6245 WRITE_ONCE(event->pending_disable, -1); 6246 perf_event_disable_local(event); 6247 return; 6248 } 6249 6250 /* 6251 * CPU-A CPU-B 6252 * 6253 * perf_event_disable_inatomic() 6254 * @pending_disable = CPU-A; 6255 * irq_work_queue(); 6256 * 6257 * sched-out 6258 * @pending_disable = -1; 6259 * 6260 * sched-in 6261 * perf_event_disable_inatomic() 6262 * @pending_disable = CPU-B; 6263 * irq_work_queue(); // FAILS 6264 * 6265 * irq_work_run() 6266 * perf_pending_event() 6267 * 6268 * But the event runs on CPU-B and wants disabling there. 6269 */ 6270 irq_work_queue_on(&event->pending, cpu); 6271 } 6272 6273 static void perf_pending_event(struct irq_work *entry) 6274 { 6275 struct perf_event *event = container_of(entry, struct perf_event, pending); 6276 int rctx; 6277 6278 rctx = perf_swevent_get_recursion_context(); 6279 /* 6280 * If we 'fail' here, that's OK, it means recursion is already disabled 6281 * and we won't recurse 'further'. 6282 */ 6283 6284 perf_pending_event_disable(event); 6285 6286 if (event->pending_wakeup) { 6287 event->pending_wakeup = 0; 6288 perf_event_wakeup(event); 6289 } 6290 6291 if (rctx >= 0) 6292 perf_swevent_put_recursion_context(rctx); 6293 } 6294 6295 /* 6296 * We assume there is only KVM supporting the callbacks. 6297 * Later on, we might change it to a list if there is 6298 * another virtualization implementation supporting the callbacks. 6299 */ 6300 struct perf_guest_info_callbacks *perf_guest_cbs; 6301 6302 int perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 6303 { 6304 perf_guest_cbs = cbs; 6305 return 0; 6306 } 6307 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks); 6308 6309 int perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 6310 { 6311 perf_guest_cbs = NULL; 6312 return 0; 6313 } 6314 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks); 6315 6316 static void 6317 perf_output_sample_regs(struct perf_output_handle *handle, 6318 struct pt_regs *regs, u64 mask) 6319 { 6320 int bit; 6321 DECLARE_BITMAP(_mask, 64); 6322 6323 bitmap_from_u64(_mask, mask); 6324 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) { 6325 u64 val; 6326 6327 val = perf_reg_value(regs, bit); 6328 perf_output_put(handle, val); 6329 } 6330 } 6331 6332 static void perf_sample_regs_user(struct perf_regs *regs_user, 6333 struct pt_regs *regs, 6334 struct pt_regs *regs_user_copy) 6335 { 6336 if (user_mode(regs)) { 6337 regs_user->abi = perf_reg_abi(current); 6338 regs_user->regs = regs; 6339 } else if (!(current->flags & PF_KTHREAD)) { 6340 perf_get_regs_user(regs_user, regs, regs_user_copy); 6341 } else { 6342 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE; 6343 regs_user->regs = NULL; 6344 } 6345 } 6346 6347 static void perf_sample_regs_intr(struct perf_regs *regs_intr, 6348 struct pt_regs *regs) 6349 { 6350 regs_intr->regs = regs; 6351 regs_intr->abi = perf_reg_abi(current); 6352 } 6353 6354 6355 /* 6356 * Get remaining task size from user stack pointer. 6357 * 6358 * It'd be better to take stack vma map and limit this more 6359 * precisely, but there's no way to get it safely under interrupt, 6360 * so using TASK_SIZE as limit. 6361 */ 6362 static u64 perf_ustack_task_size(struct pt_regs *regs) 6363 { 6364 unsigned long addr = perf_user_stack_pointer(regs); 6365 6366 if (!addr || addr >= TASK_SIZE) 6367 return 0; 6368 6369 return TASK_SIZE - addr; 6370 } 6371 6372 static u16 6373 perf_sample_ustack_size(u16 stack_size, u16 header_size, 6374 struct pt_regs *regs) 6375 { 6376 u64 task_size; 6377 6378 /* No regs, no stack pointer, no dump. */ 6379 if (!regs) 6380 return 0; 6381 6382 /* 6383 * Check if we fit in with the requested stack size into the: 6384 * - TASK_SIZE 6385 * If we don't, we limit the size to the TASK_SIZE. 6386 * 6387 * - remaining sample size 6388 * If we don't, we customize the stack size to 6389 * fit in to the remaining sample size. 6390 */ 6391 6392 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs)); 6393 stack_size = min(stack_size, (u16) task_size); 6394 6395 /* Current header size plus static size and dynamic size. */ 6396 header_size += 2 * sizeof(u64); 6397 6398 /* Do we fit in with the current stack dump size? */ 6399 if ((u16) (header_size + stack_size) < header_size) { 6400 /* 6401 * If we overflow the maximum size for the sample, 6402 * we customize the stack dump size to fit in. 6403 */ 6404 stack_size = USHRT_MAX - header_size - sizeof(u64); 6405 stack_size = round_up(stack_size, sizeof(u64)); 6406 } 6407 6408 return stack_size; 6409 } 6410 6411 static void 6412 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size, 6413 struct pt_regs *regs) 6414 { 6415 /* Case of a kernel thread, nothing to dump */ 6416 if (!regs) { 6417 u64 size = 0; 6418 perf_output_put(handle, size); 6419 } else { 6420 unsigned long sp; 6421 unsigned int rem; 6422 u64 dyn_size; 6423 mm_segment_t fs; 6424 6425 /* 6426 * We dump: 6427 * static size 6428 * - the size requested by user or the best one we can fit 6429 * in to the sample max size 6430 * data 6431 * - user stack dump data 6432 * dynamic size 6433 * - the actual dumped size 6434 */ 6435 6436 /* Static size. */ 6437 perf_output_put(handle, dump_size); 6438 6439 /* Data. */ 6440 sp = perf_user_stack_pointer(regs); 6441 fs = get_fs(); 6442 set_fs(USER_DS); 6443 rem = __output_copy_user(handle, (void *) sp, dump_size); 6444 set_fs(fs); 6445 dyn_size = dump_size - rem; 6446 6447 perf_output_skip(handle, rem); 6448 6449 /* Dynamic size. */ 6450 perf_output_put(handle, dyn_size); 6451 } 6452 } 6453 6454 static unsigned long perf_prepare_sample_aux(struct perf_event *event, 6455 struct perf_sample_data *data, 6456 size_t size) 6457 { 6458 struct perf_event *sampler = event->aux_event; 6459 struct perf_buffer *rb; 6460 6461 data->aux_size = 0; 6462 6463 if (!sampler) 6464 goto out; 6465 6466 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE)) 6467 goto out; 6468 6469 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id())) 6470 goto out; 6471 6472 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler); 6473 if (!rb) 6474 goto out; 6475 6476 /* 6477 * If this is an NMI hit inside sampling code, don't take 6478 * the sample. See also perf_aux_sample_output(). 6479 */ 6480 if (READ_ONCE(rb->aux_in_sampling)) { 6481 data->aux_size = 0; 6482 } else { 6483 size = min_t(size_t, size, perf_aux_size(rb)); 6484 data->aux_size = ALIGN(size, sizeof(u64)); 6485 } 6486 ring_buffer_put(rb); 6487 6488 out: 6489 return data->aux_size; 6490 } 6491 6492 long perf_pmu_snapshot_aux(struct perf_buffer *rb, 6493 struct perf_event *event, 6494 struct perf_output_handle *handle, 6495 unsigned long size) 6496 { 6497 unsigned long flags; 6498 long ret; 6499 6500 /* 6501 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler 6502 * paths. If we start calling them in NMI context, they may race with 6503 * the IRQ ones, that is, for example, re-starting an event that's just 6504 * been stopped, which is why we're using a separate callback that 6505 * doesn't change the event state. 6506 * 6507 * IRQs need to be disabled to prevent IPIs from racing with us. 6508 */ 6509 local_irq_save(flags); 6510 /* 6511 * Guard against NMI hits inside the critical section; 6512 * see also perf_prepare_sample_aux(). 6513 */ 6514 WRITE_ONCE(rb->aux_in_sampling, 1); 6515 barrier(); 6516 6517 ret = event->pmu->snapshot_aux(event, handle, size); 6518 6519 barrier(); 6520 WRITE_ONCE(rb->aux_in_sampling, 0); 6521 local_irq_restore(flags); 6522 6523 return ret; 6524 } 6525 6526 static void perf_aux_sample_output(struct perf_event *event, 6527 struct perf_output_handle *handle, 6528 struct perf_sample_data *data) 6529 { 6530 struct perf_event *sampler = event->aux_event; 6531 struct perf_buffer *rb; 6532 unsigned long pad; 6533 long size; 6534 6535 if (WARN_ON_ONCE(!sampler || !data->aux_size)) 6536 return; 6537 6538 rb = ring_buffer_get(sampler->parent ? sampler->parent : sampler); 6539 if (!rb) 6540 return; 6541 6542 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size); 6543 6544 /* 6545 * An error here means that perf_output_copy() failed (returned a 6546 * non-zero surplus that it didn't copy), which in its current 6547 * enlightened implementation is not possible. If that changes, we'd 6548 * like to know. 6549 */ 6550 if (WARN_ON_ONCE(size < 0)) 6551 goto out_put; 6552 6553 /* 6554 * The pad comes from ALIGN()ing data->aux_size up to u64 in 6555 * perf_prepare_sample_aux(), so should not be more than that. 6556 */ 6557 pad = data->aux_size - size; 6558 if (WARN_ON_ONCE(pad >= sizeof(u64))) 6559 pad = 8; 6560 6561 if (pad) { 6562 u64 zero = 0; 6563 perf_output_copy(handle, &zero, pad); 6564 } 6565 6566 out_put: 6567 ring_buffer_put(rb); 6568 } 6569 6570 static void __perf_event_header__init_id(struct perf_event_header *header, 6571 struct perf_sample_data *data, 6572 struct perf_event *event) 6573 { 6574 u64 sample_type = event->attr.sample_type; 6575 6576 data->type = sample_type; 6577 header->size += event->id_header_size; 6578 6579 if (sample_type & PERF_SAMPLE_TID) { 6580 /* namespace issues */ 6581 data->tid_entry.pid = perf_event_pid(event, current); 6582 data->tid_entry.tid = perf_event_tid(event, current); 6583 } 6584 6585 if (sample_type & PERF_SAMPLE_TIME) 6586 data->time = perf_event_clock(event); 6587 6588 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) 6589 data->id = primary_event_id(event); 6590 6591 if (sample_type & PERF_SAMPLE_STREAM_ID) 6592 data->stream_id = event->id; 6593 6594 if (sample_type & PERF_SAMPLE_CPU) { 6595 data->cpu_entry.cpu = raw_smp_processor_id(); 6596 data->cpu_entry.reserved = 0; 6597 } 6598 } 6599 6600 void perf_event_header__init_id(struct perf_event_header *header, 6601 struct perf_sample_data *data, 6602 struct perf_event *event) 6603 { 6604 if (event->attr.sample_id_all) 6605 __perf_event_header__init_id(header, data, event); 6606 } 6607 6608 static void __perf_event__output_id_sample(struct perf_output_handle *handle, 6609 struct perf_sample_data *data) 6610 { 6611 u64 sample_type = data->type; 6612 6613 if (sample_type & PERF_SAMPLE_TID) 6614 perf_output_put(handle, data->tid_entry); 6615 6616 if (sample_type & PERF_SAMPLE_TIME) 6617 perf_output_put(handle, data->time); 6618 6619 if (sample_type & PERF_SAMPLE_ID) 6620 perf_output_put(handle, data->id); 6621 6622 if (sample_type & PERF_SAMPLE_STREAM_ID) 6623 perf_output_put(handle, data->stream_id); 6624 6625 if (sample_type & PERF_SAMPLE_CPU) 6626 perf_output_put(handle, data->cpu_entry); 6627 6628 if (sample_type & PERF_SAMPLE_IDENTIFIER) 6629 perf_output_put(handle, data->id); 6630 } 6631 6632 void perf_event__output_id_sample(struct perf_event *event, 6633 struct perf_output_handle *handle, 6634 struct perf_sample_data *sample) 6635 { 6636 if (event->attr.sample_id_all) 6637 __perf_event__output_id_sample(handle, sample); 6638 } 6639 6640 static void perf_output_read_one(struct perf_output_handle *handle, 6641 struct perf_event *event, 6642 u64 enabled, u64 running) 6643 { 6644 u64 read_format = event->attr.read_format; 6645 u64 values[4]; 6646 int n = 0; 6647 6648 values[n++] = perf_event_count(event); 6649 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 6650 values[n++] = enabled + 6651 atomic64_read(&event->child_total_time_enabled); 6652 } 6653 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 6654 values[n++] = running + 6655 atomic64_read(&event->child_total_time_running); 6656 } 6657 if (read_format & PERF_FORMAT_ID) 6658 values[n++] = primary_event_id(event); 6659 6660 __output_copy(handle, values, n * sizeof(u64)); 6661 } 6662 6663 static void perf_output_read_group(struct perf_output_handle *handle, 6664 struct perf_event *event, 6665 u64 enabled, u64 running) 6666 { 6667 struct perf_event *leader = event->group_leader, *sub; 6668 u64 read_format = event->attr.read_format; 6669 u64 values[5]; 6670 int n = 0; 6671 6672 values[n++] = 1 + leader->nr_siblings; 6673 6674 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 6675 values[n++] = enabled; 6676 6677 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 6678 values[n++] = running; 6679 6680 if ((leader != event) && 6681 (leader->state == PERF_EVENT_STATE_ACTIVE)) 6682 leader->pmu->read(leader); 6683 6684 values[n++] = perf_event_count(leader); 6685 if (read_format & PERF_FORMAT_ID) 6686 values[n++] = primary_event_id(leader); 6687 6688 __output_copy(handle, values, n * sizeof(u64)); 6689 6690 for_each_sibling_event(sub, leader) { 6691 n = 0; 6692 6693 if ((sub != event) && 6694 (sub->state == PERF_EVENT_STATE_ACTIVE)) 6695 sub->pmu->read(sub); 6696 6697 values[n++] = perf_event_count(sub); 6698 if (read_format & PERF_FORMAT_ID) 6699 values[n++] = primary_event_id(sub); 6700 6701 __output_copy(handle, values, n * sizeof(u64)); 6702 } 6703 } 6704 6705 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\ 6706 PERF_FORMAT_TOTAL_TIME_RUNNING) 6707 6708 /* 6709 * XXX PERF_SAMPLE_READ vs inherited events seems difficult. 6710 * 6711 * The problem is that its both hard and excessively expensive to iterate the 6712 * child list, not to mention that its impossible to IPI the children running 6713 * on another CPU, from interrupt/NMI context. 6714 */ 6715 static void perf_output_read(struct perf_output_handle *handle, 6716 struct perf_event *event) 6717 { 6718 u64 enabled = 0, running = 0, now; 6719 u64 read_format = event->attr.read_format; 6720 6721 /* 6722 * compute total_time_enabled, total_time_running 6723 * based on snapshot values taken when the event 6724 * was last scheduled in. 6725 * 6726 * we cannot simply called update_context_time() 6727 * because of locking issue as we are called in 6728 * NMI context 6729 */ 6730 if (read_format & PERF_FORMAT_TOTAL_TIMES) 6731 calc_timer_values(event, &now, &enabled, &running); 6732 6733 if (event->attr.read_format & PERF_FORMAT_GROUP) 6734 perf_output_read_group(handle, event, enabled, running); 6735 else 6736 perf_output_read_one(handle, event, enabled, running); 6737 } 6738 6739 static inline bool perf_sample_save_hw_index(struct perf_event *event) 6740 { 6741 return event->attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX; 6742 } 6743 6744 void perf_output_sample(struct perf_output_handle *handle, 6745 struct perf_event_header *header, 6746 struct perf_sample_data *data, 6747 struct perf_event *event) 6748 { 6749 u64 sample_type = data->type; 6750 6751 perf_output_put(handle, *header); 6752 6753 if (sample_type & PERF_SAMPLE_IDENTIFIER) 6754 perf_output_put(handle, data->id); 6755 6756 if (sample_type & PERF_SAMPLE_IP) 6757 perf_output_put(handle, data->ip); 6758 6759 if (sample_type & PERF_SAMPLE_TID) 6760 perf_output_put(handle, data->tid_entry); 6761 6762 if (sample_type & PERF_SAMPLE_TIME) 6763 perf_output_put(handle, data->time); 6764 6765 if (sample_type & PERF_SAMPLE_ADDR) 6766 perf_output_put(handle, data->addr); 6767 6768 if (sample_type & PERF_SAMPLE_ID) 6769 perf_output_put(handle, data->id); 6770 6771 if (sample_type & PERF_SAMPLE_STREAM_ID) 6772 perf_output_put(handle, data->stream_id); 6773 6774 if (sample_type & PERF_SAMPLE_CPU) 6775 perf_output_put(handle, data->cpu_entry); 6776 6777 if (sample_type & PERF_SAMPLE_PERIOD) 6778 perf_output_put(handle, data->period); 6779 6780 if (sample_type & PERF_SAMPLE_READ) 6781 perf_output_read(handle, event); 6782 6783 if (sample_type & PERF_SAMPLE_CALLCHAIN) { 6784 int size = 1; 6785 6786 size += data->callchain->nr; 6787 size *= sizeof(u64); 6788 __output_copy(handle, data->callchain, size); 6789 } 6790 6791 if (sample_type & PERF_SAMPLE_RAW) { 6792 struct perf_raw_record *raw = data->raw; 6793 6794 if (raw) { 6795 struct perf_raw_frag *frag = &raw->frag; 6796 6797 perf_output_put(handle, raw->size); 6798 do { 6799 if (frag->copy) { 6800 __output_custom(handle, frag->copy, 6801 frag->data, frag->size); 6802 } else { 6803 __output_copy(handle, frag->data, 6804 frag->size); 6805 } 6806 if (perf_raw_frag_last(frag)) 6807 break; 6808 frag = frag->next; 6809 } while (1); 6810 if (frag->pad) 6811 __output_skip(handle, NULL, frag->pad); 6812 } else { 6813 struct { 6814 u32 size; 6815 u32 data; 6816 } raw = { 6817 .size = sizeof(u32), 6818 .data = 0, 6819 }; 6820 perf_output_put(handle, raw); 6821 } 6822 } 6823 6824 if (sample_type & PERF_SAMPLE_BRANCH_STACK) { 6825 if (data->br_stack) { 6826 size_t size; 6827 6828 size = data->br_stack->nr 6829 * sizeof(struct perf_branch_entry); 6830 6831 perf_output_put(handle, data->br_stack->nr); 6832 if (perf_sample_save_hw_index(event)) 6833 perf_output_put(handle, data->br_stack->hw_idx); 6834 perf_output_copy(handle, data->br_stack->entries, size); 6835 } else { 6836 /* 6837 * we always store at least the value of nr 6838 */ 6839 u64 nr = 0; 6840 perf_output_put(handle, nr); 6841 } 6842 } 6843 6844 if (sample_type & PERF_SAMPLE_REGS_USER) { 6845 u64 abi = data->regs_user.abi; 6846 6847 /* 6848 * If there are no regs to dump, notice it through 6849 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 6850 */ 6851 perf_output_put(handle, abi); 6852 6853 if (abi) { 6854 u64 mask = event->attr.sample_regs_user; 6855 perf_output_sample_regs(handle, 6856 data->regs_user.regs, 6857 mask); 6858 } 6859 } 6860 6861 if (sample_type & PERF_SAMPLE_STACK_USER) { 6862 perf_output_sample_ustack(handle, 6863 data->stack_user_size, 6864 data->regs_user.regs); 6865 } 6866 6867 if (sample_type & PERF_SAMPLE_WEIGHT) 6868 perf_output_put(handle, data->weight); 6869 6870 if (sample_type & PERF_SAMPLE_DATA_SRC) 6871 perf_output_put(handle, data->data_src.val); 6872 6873 if (sample_type & PERF_SAMPLE_TRANSACTION) 6874 perf_output_put(handle, data->txn); 6875 6876 if (sample_type & PERF_SAMPLE_REGS_INTR) { 6877 u64 abi = data->regs_intr.abi; 6878 /* 6879 * If there are no regs to dump, notice it through 6880 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 6881 */ 6882 perf_output_put(handle, abi); 6883 6884 if (abi) { 6885 u64 mask = event->attr.sample_regs_intr; 6886 6887 perf_output_sample_regs(handle, 6888 data->regs_intr.regs, 6889 mask); 6890 } 6891 } 6892 6893 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 6894 perf_output_put(handle, data->phys_addr); 6895 6896 if (sample_type & PERF_SAMPLE_CGROUP) 6897 perf_output_put(handle, data->cgroup); 6898 6899 if (sample_type & PERF_SAMPLE_AUX) { 6900 perf_output_put(handle, data->aux_size); 6901 6902 if (data->aux_size) 6903 perf_aux_sample_output(event, handle, data); 6904 } 6905 6906 if (!event->attr.watermark) { 6907 int wakeup_events = event->attr.wakeup_events; 6908 6909 if (wakeup_events) { 6910 struct perf_buffer *rb = handle->rb; 6911 int events = local_inc_return(&rb->events); 6912 6913 if (events >= wakeup_events) { 6914 local_sub(wakeup_events, &rb->events); 6915 local_inc(&rb->wakeup); 6916 } 6917 } 6918 } 6919 } 6920 6921 static u64 perf_virt_to_phys(u64 virt) 6922 { 6923 u64 phys_addr = 0; 6924 struct page *p = NULL; 6925 6926 if (!virt) 6927 return 0; 6928 6929 if (virt >= TASK_SIZE) { 6930 /* If it's vmalloc()d memory, leave phys_addr as 0 */ 6931 if (virt_addr_valid((void *)(uintptr_t)virt) && 6932 !(virt >= VMALLOC_START && virt < VMALLOC_END)) 6933 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt); 6934 } else { 6935 /* 6936 * Walking the pages tables for user address. 6937 * Interrupts are disabled, so it prevents any tear down 6938 * of the page tables. 6939 * Try IRQ-safe __get_user_pages_fast first. 6940 * If failed, leave phys_addr as 0. 6941 */ 6942 if (current->mm != NULL) { 6943 pagefault_disable(); 6944 if (__get_user_pages_fast(virt, 1, 0, &p) == 1) 6945 phys_addr = page_to_phys(p) + virt % PAGE_SIZE; 6946 pagefault_enable(); 6947 } 6948 6949 if (p) 6950 put_page(p); 6951 } 6952 6953 return phys_addr; 6954 } 6955 6956 static struct perf_callchain_entry __empty_callchain = { .nr = 0, }; 6957 6958 struct perf_callchain_entry * 6959 perf_callchain(struct perf_event *event, struct pt_regs *regs) 6960 { 6961 bool kernel = !event->attr.exclude_callchain_kernel; 6962 bool user = !event->attr.exclude_callchain_user; 6963 /* Disallow cross-task user callchains. */ 6964 bool crosstask = event->ctx->task && event->ctx->task != current; 6965 const u32 max_stack = event->attr.sample_max_stack; 6966 struct perf_callchain_entry *callchain; 6967 6968 if (!kernel && !user) 6969 return &__empty_callchain; 6970 6971 callchain = get_perf_callchain(regs, 0, kernel, user, 6972 max_stack, crosstask, true); 6973 return callchain ?: &__empty_callchain; 6974 } 6975 6976 void perf_prepare_sample(struct perf_event_header *header, 6977 struct perf_sample_data *data, 6978 struct perf_event *event, 6979 struct pt_regs *regs) 6980 { 6981 u64 sample_type = event->attr.sample_type; 6982 6983 header->type = PERF_RECORD_SAMPLE; 6984 header->size = sizeof(*header) + event->header_size; 6985 6986 header->misc = 0; 6987 header->misc |= perf_misc_flags(regs); 6988 6989 __perf_event_header__init_id(header, data, event); 6990 6991 if (sample_type & PERF_SAMPLE_IP) 6992 data->ip = perf_instruction_pointer(regs); 6993 6994 if (sample_type & PERF_SAMPLE_CALLCHAIN) { 6995 int size = 1; 6996 6997 if (!(sample_type & __PERF_SAMPLE_CALLCHAIN_EARLY)) 6998 data->callchain = perf_callchain(event, regs); 6999 7000 size += data->callchain->nr; 7001 7002 header->size += size * sizeof(u64); 7003 } 7004 7005 if (sample_type & PERF_SAMPLE_RAW) { 7006 struct perf_raw_record *raw = data->raw; 7007 int size; 7008 7009 if (raw) { 7010 struct perf_raw_frag *frag = &raw->frag; 7011 u32 sum = 0; 7012 7013 do { 7014 sum += frag->size; 7015 if (perf_raw_frag_last(frag)) 7016 break; 7017 frag = frag->next; 7018 } while (1); 7019 7020 size = round_up(sum + sizeof(u32), sizeof(u64)); 7021 raw->size = size - sizeof(u32); 7022 frag->pad = raw->size - sum; 7023 } else { 7024 size = sizeof(u64); 7025 } 7026 7027 header->size += size; 7028 } 7029 7030 if (sample_type & PERF_SAMPLE_BRANCH_STACK) { 7031 int size = sizeof(u64); /* nr */ 7032 if (data->br_stack) { 7033 if (perf_sample_save_hw_index(event)) 7034 size += sizeof(u64); 7035 7036 size += data->br_stack->nr 7037 * sizeof(struct perf_branch_entry); 7038 } 7039 header->size += size; 7040 } 7041 7042 if (sample_type & (PERF_SAMPLE_REGS_USER | PERF_SAMPLE_STACK_USER)) 7043 perf_sample_regs_user(&data->regs_user, regs, 7044 &data->regs_user_copy); 7045 7046 if (sample_type & PERF_SAMPLE_REGS_USER) { 7047 /* regs dump ABI info */ 7048 int size = sizeof(u64); 7049 7050 if (data->regs_user.regs) { 7051 u64 mask = event->attr.sample_regs_user; 7052 size += hweight64(mask) * sizeof(u64); 7053 } 7054 7055 header->size += size; 7056 } 7057 7058 if (sample_type & PERF_SAMPLE_STACK_USER) { 7059 /* 7060 * Either we need PERF_SAMPLE_STACK_USER bit to be always 7061 * processed as the last one or have additional check added 7062 * in case new sample type is added, because we could eat 7063 * up the rest of the sample size. 7064 */ 7065 u16 stack_size = event->attr.sample_stack_user; 7066 u16 size = sizeof(u64); 7067 7068 stack_size = perf_sample_ustack_size(stack_size, header->size, 7069 data->regs_user.regs); 7070 7071 /* 7072 * If there is something to dump, add space for the dump 7073 * itself and for the field that tells the dynamic size, 7074 * which is how many have been actually dumped. 7075 */ 7076 if (stack_size) 7077 size += sizeof(u64) + stack_size; 7078 7079 data->stack_user_size = stack_size; 7080 header->size += size; 7081 } 7082 7083 if (sample_type & PERF_SAMPLE_REGS_INTR) { 7084 /* regs dump ABI info */ 7085 int size = sizeof(u64); 7086 7087 perf_sample_regs_intr(&data->regs_intr, regs); 7088 7089 if (data->regs_intr.regs) { 7090 u64 mask = event->attr.sample_regs_intr; 7091 7092 size += hweight64(mask) * sizeof(u64); 7093 } 7094 7095 header->size += size; 7096 } 7097 7098 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 7099 data->phys_addr = perf_virt_to_phys(data->addr); 7100 7101 #ifdef CONFIG_CGROUP_PERF 7102 if (sample_type & PERF_SAMPLE_CGROUP) { 7103 struct cgroup *cgrp; 7104 7105 /* protected by RCU */ 7106 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup; 7107 data->cgroup = cgroup_id(cgrp); 7108 } 7109 #endif 7110 7111 if (sample_type & PERF_SAMPLE_AUX) { 7112 u64 size; 7113 7114 header->size += sizeof(u64); /* size */ 7115 7116 /* 7117 * Given the 16bit nature of header::size, an AUX sample can 7118 * easily overflow it, what with all the preceding sample bits. 7119 * Make sure this doesn't happen by using up to U16_MAX bytes 7120 * per sample in total (rounded down to 8 byte boundary). 7121 */ 7122 size = min_t(size_t, U16_MAX - header->size, 7123 event->attr.aux_sample_size); 7124 size = rounddown(size, 8); 7125 size = perf_prepare_sample_aux(event, data, size); 7126 7127 WARN_ON_ONCE(size + header->size > U16_MAX); 7128 header->size += size; 7129 } 7130 /* 7131 * If you're adding more sample types here, you likely need to do 7132 * something about the overflowing header::size, like repurpose the 7133 * lowest 3 bits of size, which should be always zero at the moment. 7134 * This raises a more important question, do we really need 512k sized 7135 * samples and why, so good argumentation is in order for whatever you 7136 * do here next. 7137 */ 7138 WARN_ON_ONCE(header->size & 7); 7139 } 7140 7141 static __always_inline int 7142 __perf_event_output(struct perf_event *event, 7143 struct perf_sample_data *data, 7144 struct pt_regs *regs, 7145 int (*output_begin)(struct perf_output_handle *, 7146 struct perf_event *, 7147 unsigned int)) 7148 { 7149 struct perf_output_handle handle; 7150 struct perf_event_header header; 7151 int err; 7152 7153 /* protect the callchain buffers */ 7154 rcu_read_lock(); 7155 7156 perf_prepare_sample(&header, data, event, regs); 7157 7158 err = output_begin(&handle, event, header.size); 7159 if (err) 7160 goto exit; 7161 7162 perf_output_sample(&handle, &header, data, event); 7163 7164 perf_output_end(&handle); 7165 7166 exit: 7167 rcu_read_unlock(); 7168 return err; 7169 } 7170 7171 void 7172 perf_event_output_forward(struct perf_event *event, 7173 struct perf_sample_data *data, 7174 struct pt_regs *regs) 7175 { 7176 __perf_event_output(event, data, regs, perf_output_begin_forward); 7177 } 7178 7179 void 7180 perf_event_output_backward(struct perf_event *event, 7181 struct perf_sample_data *data, 7182 struct pt_regs *regs) 7183 { 7184 __perf_event_output(event, data, regs, perf_output_begin_backward); 7185 } 7186 7187 int 7188 perf_event_output(struct perf_event *event, 7189 struct perf_sample_data *data, 7190 struct pt_regs *regs) 7191 { 7192 return __perf_event_output(event, data, regs, perf_output_begin); 7193 } 7194 7195 /* 7196 * read event_id 7197 */ 7198 7199 struct perf_read_event { 7200 struct perf_event_header header; 7201 7202 u32 pid; 7203 u32 tid; 7204 }; 7205 7206 static void 7207 perf_event_read_event(struct perf_event *event, 7208 struct task_struct *task) 7209 { 7210 struct perf_output_handle handle; 7211 struct perf_sample_data sample; 7212 struct perf_read_event read_event = { 7213 .header = { 7214 .type = PERF_RECORD_READ, 7215 .misc = 0, 7216 .size = sizeof(read_event) + event->read_size, 7217 }, 7218 .pid = perf_event_pid(event, task), 7219 .tid = perf_event_tid(event, task), 7220 }; 7221 int ret; 7222 7223 perf_event_header__init_id(&read_event.header, &sample, event); 7224 ret = perf_output_begin(&handle, event, read_event.header.size); 7225 if (ret) 7226 return; 7227 7228 perf_output_put(&handle, read_event); 7229 perf_output_read(&handle, event); 7230 perf_event__output_id_sample(event, &handle, &sample); 7231 7232 perf_output_end(&handle); 7233 } 7234 7235 typedef void (perf_iterate_f)(struct perf_event *event, void *data); 7236 7237 static void 7238 perf_iterate_ctx(struct perf_event_context *ctx, 7239 perf_iterate_f output, 7240 void *data, bool all) 7241 { 7242 struct perf_event *event; 7243 7244 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { 7245 if (!all) { 7246 if (event->state < PERF_EVENT_STATE_INACTIVE) 7247 continue; 7248 if (!event_filter_match(event)) 7249 continue; 7250 } 7251 7252 output(event, data); 7253 } 7254 } 7255 7256 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data) 7257 { 7258 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events); 7259 struct perf_event *event; 7260 7261 list_for_each_entry_rcu(event, &pel->list, sb_list) { 7262 /* 7263 * Skip events that are not fully formed yet; ensure that 7264 * if we observe event->ctx, both event and ctx will be 7265 * complete enough. See perf_install_in_context(). 7266 */ 7267 if (!smp_load_acquire(&event->ctx)) 7268 continue; 7269 7270 if (event->state < PERF_EVENT_STATE_INACTIVE) 7271 continue; 7272 if (!event_filter_match(event)) 7273 continue; 7274 output(event, data); 7275 } 7276 } 7277 7278 /* 7279 * Iterate all events that need to receive side-band events. 7280 * 7281 * For new callers; ensure that account_pmu_sb_event() includes 7282 * your event, otherwise it might not get delivered. 7283 */ 7284 static void 7285 perf_iterate_sb(perf_iterate_f output, void *data, 7286 struct perf_event_context *task_ctx) 7287 { 7288 struct perf_event_context *ctx; 7289 int ctxn; 7290 7291 rcu_read_lock(); 7292 preempt_disable(); 7293 7294 /* 7295 * If we have task_ctx != NULL we only notify the task context itself. 7296 * The task_ctx is set only for EXIT events before releasing task 7297 * context. 7298 */ 7299 if (task_ctx) { 7300 perf_iterate_ctx(task_ctx, output, data, false); 7301 goto done; 7302 } 7303 7304 perf_iterate_sb_cpu(output, data); 7305 7306 for_each_task_context_nr(ctxn) { 7307 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]); 7308 if (ctx) 7309 perf_iterate_ctx(ctx, output, data, false); 7310 } 7311 done: 7312 preempt_enable(); 7313 rcu_read_unlock(); 7314 } 7315 7316 /* 7317 * Clear all file-based filters at exec, they'll have to be 7318 * re-instated when/if these objects are mmapped again. 7319 */ 7320 static void perf_event_addr_filters_exec(struct perf_event *event, void *data) 7321 { 7322 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 7323 struct perf_addr_filter *filter; 7324 unsigned int restart = 0, count = 0; 7325 unsigned long flags; 7326 7327 if (!has_addr_filter(event)) 7328 return; 7329 7330 raw_spin_lock_irqsave(&ifh->lock, flags); 7331 list_for_each_entry(filter, &ifh->list, entry) { 7332 if (filter->path.dentry) { 7333 event->addr_filter_ranges[count].start = 0; 7334 event->addr_filter_ranges[count].size = 0; 7335 restart++; 7336 } 7337 7338 count++; 7339 } 7340 7341 if (restart) 7342 event->addr_filters_gen++; 7343 raw_spin_unlock_irqrestore(&ifh->lock, flags); 7344 7345 if (restart) 7346 perf_event_stop(event, 1); 7347 } 7348 7349 void perf_event_exec(void) 7350 { 7351 struct perf_event_context *ctx; 7352 int ctxn; 7353 7354 rcu_read_lock(); 7355 for_each_task_context_nr(ctxn) { 7356 ctx = current->perf_event_ctxp[ctxn]; 7357 if (!ctx) 7358 continue; 7359 7360 perf_event_enable_on_exec(ctxn); 7361 7362 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, 7363 true); 7364 } 7365 rcu_read_unlock(); 7366 } 7367 7368 struct remote_output { 7369 struct perf_buffer *rb; 7370 int err; 7371 }; 7372 7373 static void __perf_event_output_stop(struct perf_event *event, void *data) 7374 { 7375 struct perf_event *parent = event->parent; 7376 struct remote_output *ro = data; 7377 struct perf_buffer *rb = ro->rb; 7378 struct stop_event_data sd = { 7379 .event = event, 7380 }; 7381 7382 if (!has_aux(event)) 7383 return; 7384 7385 if (!parent) 7386 parent = event; 7387 7388 /* 7389 * In case of inheritance, it will be the parent that links to the 7390 * ring-buffer, but it will be the child that's actually using it. 7391 * 7392 * We are using event::rb to determine if the event should be stopped, 7393 * however this may race with ring_buffer_attach() (through set_output), 7394 * which will make us skip the event that actually needs to be stopped. 7395 * So ring_buffer_attach() has to stop an aux event before re-assigning 7396 * its rb pointer. 7397 */ 7398 if (rcu_dereference(parent->rb) == rb) 7399 ro->err = __perf_event_stop(&sd); 7400 } 7401 7402 static int __perf_pmu_output_stop(void *info) 7403 { 7404 struct perf_event *event = info; 7405 struct pmu *pmu = event->ctx->pmu; 7406 struct perf_cpu_context *cpuctx = this_cpu_ptr(pmu->pmu_cpu_context); 7407 struct remote_output ro = { 7408 .rb = event->rb, 7409 }; 7410 7411 rcu_read_lock(); 7412 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false); 7413 if (cpuctx->task_ctx) 7414 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop, 7415 &ro, false); 7416 rcu_read_unlock(); 7417 7418 return ro.err; 7419 } 7420 7421 static void perf_pmu_output_stop(struct perf_event *event) 7422 { 7423 struct perf_event *iter; 7424 int err, cpu; 7425 7426 restart: 7427 rcu_read_lock(); 7428 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) { 7429 /* 7430 * For per-CPU events, we need to make sure that neither they 7431 * nor their children are running; for cpu==-1 events it's 7432 * sufficient to stop the event itself if it's active, since 7433 * it can't have children. 7434 */ 7435 cpu = iter->cpu; 7436 if (cpu == -1) 7437 cpu = READ_ONCE(iter->oncpu); 7438 7439 if (cpu == -1) 7440 continue; 7441 7442 err = cpu_function_call(cpu, __perf_pmu_output_stop, event); 7443 if (err == -EAGAIN) { 7444 rcu_read_unlock(); 7445 goto restart; 7446 } 7447 } 7448 rcu_read_unlock(); 7449 } 7450 7451 /* 7452 * task tracking -- fork/exit 7453 * 7454 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task 7455 */ 7456 7457 struct perf_task_event { 7458 struct task_struct *task; 7459 struct perf_event_context *task_ctx; 7460 7461 struct { 7462 struct perf_event_header header; 7463 7464 u32 pid; 7465 u32 ppid; 7466 u32 tid; 7467 u32 ptid; 7468 u64 time; 7469 } event_id; 7470 }; 7471 7472 static int perf_event_task_match(struct perf_event *event) 7473 { 7474 return event->attr.comm || event->attr.mmap || 7475 event->attr.mmap2 || event->attr.mmap_data || 7476 event->attr.task; 7477 } 7478 7479 static void perf_event_task_output(struct perf_event *event, 7480 void *data) 7481 { 7482 struct perf_task_event *task_event = data; 7483 struct perf_output_handle handle; 7484 struct perf_sample_data sample; 7485 struct task_struct *task = task_event->task; 7486 int ret, size = task_event->event_id.header.size; 7487 7488 if (!perf_event_task_match(event)) 7489 return; 7490 7491 perf_event_header__init_id(&task_event->event_id.header, &sample, event); 7492 7493 ret = perf_output_begin(&handle, event, 7494 task_event->event_id.header.size); 7495 if (ret) 7496 goto out; 7497 7498 task_event->event_id.pid = perf_event_pid(event, task); 7499 task_event->event_id.tid = perf_event_tid(event, task); 7500 7501 if (task_event->event_id.header.type == PERF_RECORD_EXIT) { 7502 task_event->event_id.ppid = perf_event_pid(event, 7503 task->real_parent); 7504 task_event->event_id.ptid = perf_event_pid(event, 7505 task->real_parent); 7506 } else { /* PERF_RECORD_FORK */ 7507 task_event->event_id.ppid = perf_event_pid(event, current); 7508 task_event->event_id.ptid = perf_event_tid(event, current); 7509 } 7510 7511 task_event->event_id.time = perf_event_clock(event); 7512 7513 perf_output_put(&handle, task_event->event_id); 7514 7515 perf_event__output_id_sample(event, &handle, &sample); 7516 7517 perf_output_end(&handle); 7518 out: 7519 task_event->event_id.header.size = size; 7520 } 7521 7522 static void perf_event_task(struct task_struct *task, 7523 struct perf_event_context *task_ctx, 7524 int new) 7525 { 7526 struct perf_task_event task_event; 7527 7528 if (!atomic_read(&nr_comm_events) && 7529 !atomic_read(&nr_mmap_events) && 7530 !atomic_read(&nr_task_events)) 7531 return; 7532 7533 task_event = (struct perf_task_event){ 7534 .task = task, 7535 .task_ctx = task_ctx, 7536 .event_id = { 7537 .header = { 7538 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT, 7539 .misc = 0, 7540 .size = sizeof(task_event.event_id), 7541 }, 7542 /* .pid */ 7543 /* .ppid */ 7544 /* .tid */ 7545 /* .ptid */ 7546 /* .time */ 7547 }, 7548 }; 7549 7550 perf_iterate_sb(perf_event_task_output, 7551 &task_event, 7552 task_ctx); 7553 } 7554 7555 void perf_event_fork(struct task_struct *task) 7556 { 7557 perf_event_task(task, NULL, 1); 7558 perf_event_namespaces(task); 7559 } 7560 7561 /* 7562 * comm tracking 7563 */ 7564 7565 struct perf_comm_event { 7566 struct task_struct *task; 7567 char *comm; 7568 int comm_size; 7569 7570 struct { 7571 struct perf_event_header header; 7572 7573 u32 pid; 7574 u32 tid; 7575 } event_id; 7576 }; 7577 7578 static int perf_event_comm_match(struct perf_event *event) 7579 { 7580 return event->attr.comm; 7581 } 7582 7583 static void perf_event_comm_output(struct perf_event *event, 7584 void *data) 7585 { 7586 struct perf_comm_event *comm_event = data; 7587 struct perf_output_handle handle; 7588 struct perf_sample_data sample; 7589 int size = comm_event->event_id.header.size; 7590 int ret; 7591 7592 if (!perf_event_comm_match(event)) 7593 return; 7594 7595 perf_event_header__init_id(&comm_event->event_id.header, &sample, event); 7596 ret = perf_output_begin(&handle, event, 7597 comm_event->event_id.header.size); 7598 7599 if (ret) 7600 goto out; 7601 7602 comm_event->event_id.pid = perf_event_pid(event, comm_event->task); 7603 comm_event->event_id.tid = perf_event_tid(event, comm_event->task); 7604 7605 perf_output_put(&handle, comm_event->event_id); 7606 __output_copy(&handle, comm_event->comm, 7607 comm_event->comm_size); 7608 7609 perf_event__output_id_sample(event, &handle, &sample); 7610 7611 perf_output_end(&handle); 7612 out: 7613 comm_event->event_id.header.size = size; 7614 } 7615 7616 static void perf_event_comm_event(struct perf_comm_event *comm_event) 7617 { 7618 char comm[TASK_COMM_LEN]; 7619 unsigned int size; 7620 7621 memset(comm, 0, sizeof(comm)); 7622 strlcpy(comm, comm_event->task->comm, sizeof(comm)); 7623 size = ALIGN(strlen(comm)+1, sizeof(u64)); 7624 7625 comm_event->comm = comm; 7626 comm_event->comm_size = size; 7627 7628 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size; 7629 7630 perf_iterate_sb(perf_event_comm_output, 7631 comm_event, 7632 NULL); 7633 } 7634 7635 void perf_event_comm(struct task_struct *task, bool exec) 7636 { 7637 struct perf_comm_event comm_event; 7638 7639 if (!atomic_read(&nr_comm_events)) 7640 return; 7641 7642 comm_event = (struct perf_comm_event){ 7643 .task = task, 7644 /* .comm */ 7645 /* .comm_size */ 7646 .event_id = { 7647 .header = { 7648 .type = PERF_RECORD_COMM, 7649 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0, 7650 /* .size */ 7651 }, 7652 /* .pid */ 7653 /* .tid */ 7654 }, 7655 }; 7656 7657 perf_event_comm_event(&comm_event); 7658 } 7659 7660 /* 7661 * namespaces tracking 7662 */ 7663 7664 struct perf_namespaces_event { 7665 struct task_struct *task; 7666 7667 struct { 7668 struct perf_event_header header; 7669 7670 u32 pid; 7671 u32 tid; 7672 u64 nr_namespaces; 7673 struct perf_ns_link_info link_info[NR_NAMESPACES]; 7674 } event_id; 7675 }; 7676 7677 static int perf_event_namespaces_match(struct perf_event *event) 7678 { 7679 return event->attr.namespaces; 7680 } 7681 7682 static void perf_event_namespaces_output(struct perf_event *event, 7683 void *data) 7684 { 7685 struct perf_namespaces_event *namespaces_event = data; 7686 struct perf_output_handle handle; 7687 struct perf_sample_data sample; 7688 u16 header_size = namespaces_event->event_id.header.size; 7689 int ret; 7690 7691 if (!perf_event_namespaces_match(event)) 7692 return; 7693 7694 perf_event_header__init_id(&namespaces_event->event_id.header, 7695 &sample, event); 7696 ret = perf_output_begin(&handle, event, 7697 namespaces_event->event_id.header.size); 7698 if (ret) 7699 goto out; 7700 7701 namespaces_event->event_id.pid = perf_event_pid(event, 7702 namespaces_event->task); 7703 namespaces_event->event_id.tid = perf_event_tid(event, 7704 namespaces_event->task); 7705 7706 perf_output_put(&handle, namespaces_event->event_id); 7707 7708 perf_event__output_id_sample(event, &handle, &sample); 7709 7710 perf_output_end(&handle); 7711 out: 7712 namespaces_event->event_id.header.size = header_size; 7713 } 7714 7715 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info, 7716 struct task_struct *task, 7717 const struct proc_ns_operations *ns_ops) 7718 { 7719 struct path ns_path; 7720 struct inode *ns_inode; 7721 int error; 7722 7723 error = ns_get_path(&ns_path, task, ns_ops); 7724 if (!error) { 7725 ns_inode = ns_path.dentry->d_inode; 7726 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev); 7727 ns_link_info->ino = ns_inode->i_ino; 7728 path_put(&ns_path); 7729 } 7730 } 7731 7732 void perf_event_namespaces(struct task_struct *task) 7733 { 7734 struct perf_namespaces_event namespaces_event; 7735 struct perf_ns_link_info *ns_link_info; 7736 7737 if (!atomic_read(&nr_namespaces_events)) 7738 return; 7739 7740 namespaces_event = (struct perf_namespaces_event){ 7741 .task = task, 7742 .event_id = { 7743 .header = { 7744 .type = PERF_RECORD_NAMESPACES, 7745 .misc = 0, 7746 .size = sizeof(namespaces_event.event_id), 7747 }, 7748 /* .pid */ 7749 /* .tid */ 7750 .nr_namespaces = NR_NAMESPACES, 7751 /* .link_info[NR_NAMESPACES] */ 7752 }, 7753 }; 7754 7755 ns_link_info = namespaces_event.event_id.link_info; 7756 7757 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX], 7758 task, &mntns_operations); 7759 7760 #ifdef CONFIG_USER_NS 7761 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX], 7762 task, &userns_operations); 7763 #endif 7764 #ifdef CONFIG_NET_NS 7765 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX], 7766 task, &netns_operations); 7767 #endif 7768 #ifdef CONFIG_UTS_NS 7769 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX], 7770 task, &utsns_operations); 7771 #endif 7772 #ifdef CONFIG_IPC_NS 7773 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX], 7774 task, &ipcns_operations); 7775 #endif 7776 #ifdef CONFIG_PID_NS 7777 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX], 7778 task, &pidns_operations); 7779 #endif 7780 #ifdef CONFIG_CGROUPS 7781 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX], 7782 task, &cgroupns_operations); 7783 #endif 7784 7785 perf_iterate_sb(perf_event_namespaces_output, 7786 &namespaces_event, 7787 NULL); 7788 } 7789 7790 /* 7791 * cgroup tracking 7792 */ 7793 #ifdef CONFIG_CGROUP_PERF 7794 7795 struct perf_cgroup_event { 7796 char *path; 7797 int path_size; 7798 struct { 7799 struct perf_event_header header; 7800 u64 id; 7801 char path[]; 7802 } event_id; 7803 }; 7804 7805 static int perf_event_cgroup_match(struct perf_event *event) 7806 { 7807 return event->attr.cgroup; 7808 } 7809 7810 static void perf_event_cgroup_output(struct perf_event *event, void *data) 7811 { 7812 struct perf_cgroup_event *cgroup_event = data; 7813 struct perf_output_handle handle; 7814 struct perf_sample_data sample; 7815 u16 header_size = cgroup_event->event_id.header.size; 7816 int ret; 7817 7818 if (!perf_event_cgroup_match(event)) 7819 return; 7820 7821 perf_event_header__init_id(&cgroup_event->event_id.header, 7822 &sample, event); 7823 ret = perf_output_begin(&handle, event, 7824 cgroup_event->event_id.header.size); 7825 if (ret) 7826 goto out; 7827 7828 perf_output_put(&handle, cgroup_event->event_id); 7829 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size); 7830 7831 perf_event__output_id_sample(event, &handle, &sample); 7832 7833 perf_output_end(&handle); 7834 out: 7835 cgroup_event->event_id.header.size = header_size; 7836 } 7837 7838 static void perf_event_cgroup(struct cgroup *cgrp) 7839 { 7840 struct perf_cgroup_event cgroup_event; 7841 char path_enomem[16] = "//enomem"; 7842 char *pathname; 7843 size_t size; 7844 7845 if (!atomic_read(&nr_cgroup_events)) 7846 return; 7847 7848 cgroup_event = (struct perf_cgroup_event){ 7849 .event_id = { 7850 .header = { 7851 .type = PERF_RECORD_CGROUP, 7852 .misc = 0, 7853 .size = sizeof(cgroup_event.event_id), 7854 }, 7855 .id = cgroup_id(cgrp), 7856 }, 7857 }; 7858 7859 pathname = kmalloc(PATH_MAX, GFP_KERNEL); 7860 if (pathname == NULL) { 7861 cgroup_event.path = path_enomem; 7862 } else { 7863 /* just to be sure to have enough space for alignment */ 7864 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64)); 7865 cgroup_event.path = pathname; 7866 } 7867 7868 /* 7869 * Since our buffer works in 8 byte units we need to align our string 7870 * size to a multiple of 8. However, we must guarantee the tail end is 7871 * zero'd out to avoid leaking random bits to userspace. 7872 */ 7873 size = strlen(cgroup_event.path) + 1; 7874 while (!IS_ALIGNED(size, sizeof(u64))) 7875 cgroup_event.path[size++] = '\0'; 7876 7877 cgroup_event.event_id.header.size += size; 7878 cgroup_event.path_size = size; 7879 7880 perf_iterate_sb(perf_event_cgroup_output, 7881 &cgroup_event, 7882 NULL); 7883 7884 kfree(pathname); 7885 } 7886 7887 #endif 7888 7889 /* 7890 * mmap tracking 7891 */ 7892 7893 struct perf_mmap_event { 7894 struct vm_area_struct *vma; 7895 7896 const char *file_name; 7897 int file_size; 7898 int maj, min; 7899 u64 ino; 7900 u64 ino_generation; 7901 u32 prot, flags; 7902 7903 struct { 7904 struct perf_event_header header; 7905 7906 u32 pid; 7907 u32 tid; 7908 u64 start; 7909 u64 len; 7910 u64 pgoff; 7911 } event_id; 7912 }; 7913 7914 static int perf_event_mmap_match(struct perf_event *event, 7915 void *data) 7916 { 7917 struct perf_mmap_event *mmap_event = data; 7918 struct vm_area_struct *vma = mmap_event->vma; 7919 int executable = vma->vm_flags & VM_EXEC; 7920 7921 return (!executable && event->attr.mmap_data) || 7922 (executable && (event->attr.mmap || event->attr.mmap2)); 7923 } 7924 7925 static void perf_event_mmap_output(struct perf_event *event, 7926 void *data) 7927 { 7928 struct perf_mmap_event *mmap_event = data; 7929 struct perf_output_handle handle; 7930 struct perf_sample_data sample; 7931 int size = mmap_event->event_id.header.size; 7932 u32 type = mmap_event->event_id.header.type; 7933 int ret; 7934 7935 if (!perf_event_mmap_match(event, data)) 7936 return; 7937 7938 if (event->attr.mmap2) { 7939 mmap_event->event_id.header.type = PERF_RECORD_MMAP2; 7940 mmap_event->event_id.header.size += sizeof(mmap_event->maj); 7941 mmap_event->event_id.header.size += sizeof(mmap_event->min); 7942 mmap_event->event_id.header.size += sizeof(mmap_event->ino); 7943 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation); 7944 mmap_event->event_id.header.size += sizeof(mmap_event->prot); 7945 mmap_event->event_id.header.size += sizeof(mmap_event->flags); 7946 } 7947 7948 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event); 7949 ret = perf_output_begin(&handle, event, 7950 mmap_event->event_id.header.size); 7951 if (ret) 7952 goto out; 7953 7954 mmap_event->event_id.pid = perf_event_pid(event, current); 7955 mmap_event->event_id.tid = perf_event_tid(event, current); 7956 7957 perf_output_put(&handle, mmap_event->event_id); 7958 7959 if (event->attr.mmap2) { 7960 perf_output_put(&handle, mmap_event->maj); 7961 perf_output_put(&handle, mmap_event->min); 7962 perf_output_put(&handle, mmap_event->ino); 7963 perf_output_put(&handle, mmap_event->ino_generation); 7964 perf_output_put(&handle, mmap_event->prot); 7965 perf_output_put(&handle, mmap_event->flags); 7966 } 7967 7968 __output_copy(&handle, mmap_event->file_name, 7969 mmap_event->file_size); 7970 7971 perf_event__output_id_sample(event, &handle, &sample); 7972 7973 perf_output_end(&handle); 7974 out: 7975 mmap_event->event_id.header.size = size; 7976 mmap_event->event_id.header.type = type; 7977 } 7978 7979 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event) 7980 { 7981 struct vm_area_struct *vma = mmap_event->vma; 7982 struct file *file = vma->vm_file; 7983 int maj = 0, min = 0; 7984 u64 ino = 0, gen = 0; 7985 u32 prot = 0, flags = 0; 7986 unsigned int size; 7987 char tmp[16]; 7988 char *buf = NULL; 7989 char *name; 7990 7991 if (vma->vm_flags & VM_READ) 7992 prot |= PROT_READ; 7993 if (vma->vm_flags & VM_WRITE) 7994 prot |= PROT_WRITE; 7995 if (vma->vm_flags & VM_EXEC) 7996 prot |= PROT_EXEC; 7997 7998 if (vma->vm_flags & VM_MAYSHARE) 7999 flags = MAP_SHARED; 8000 else 8001 flags = MAP_PRIVATE; 8002 8003 if (vma->vm_flags & VM_DENYWRITE) 8004 flags |= MAP_DENYWRITE; 8005 if (vma->vm_flags & VM_MAYEXEC) 8006 flags |= MAP_EXECUTABLE; 8007 if (vma->vm_flags & VM_LOCKED) 8008 flags |= MAP_LOCKED; 8009 if (is_vm_hugetlb_page(vma)) 8010 flags |= MAP_HUGETLB; 8011 8012 if (file) { 8013 struct inode *inode; 8014 dev_t dev; 8015 8016 buf = kmalloc(PATH_MAX, GFP_KERNEL); 8017 if (!buf) { 8018 name = "//enomem"; 8019 goto cpy_name; 8020 } 8021 /* 8022 * d_path() works from the end of the rb backwards, so we 8023 * need to add enough zero bytes after the string to handle 8024 * the 64bit alignment we do later. 8025 */ 8026 name = file_path(file, buf, PATH_MAX - sizeof(u64)); 8027 if (IS_ERR(name)) { 8028 name = "//toolong"; 8029 goto cpy_name; 8030 } 8031 inode = file_inode(vma->vm_file); 8032 dev = inode->i_sb->s_dev; 8033 ino = inode->i_ino; 8034 gen = inode->i_generation; 8035 maj = MAJOR(dev); 8036 min = MINOR(dev); 8037 8038 goto got_name; 8039 } else { 8040 if (vma->vm_ops && vma->vm_ops->name) { 8041 name = (char *) vma->vm_ops->name(vma); 8042 if (name) 8043 goto cpy_name; 8044 } 8045 8046 name = (char *)arch_vma_name(vma); 8047 if (name) 8048 goto cpy_name; 8049 8050 if (vma->vm_start <= vma->vm_mm->start_brk && 8051 vma->vm_end >= vma->vm_mm->brk) { 8052 name = "[heap]"; 8053 goto cpy_name; 8054 } 8055 if (vma->vm_start <= vma->vm_mm->start_stack && 8056 vma->vm_end >= vma->vm_mm->start_stack) { 8057 name = "[stack]"; 8058 goto cpy_name; 8059 } 8060 8061 name = "//anon"; 8062 goto cpy_name; 8063 } 8064 8065 cpy_name: 8066 strlcpy(tmp, name, sizeof(tmp)); 8067 name = tmp; 8068 got_name: 8069 /* 8070 * Since our buffer works in 8 byte units we need to align our string 8071 * size to a multiple of 8. However, we must guarantee the tail end is 8072 * zero'd out to avoid leaking random bits to userspace. 8073 */ 8074 size = strlen(name)+1; 8075 while (!IS_ALIGNED(size, sizeof(u64))) 8076 name[size++] = '\0'; 8077 8078 mmap_event->file_name = name; 8079 mmap_event->file_size = size; 8080 mmap_event->maj = maj; 8081 mmap_event->min = min; 8082 mmap_event->ino = ino; 8083 mmap_event->ino_generation = gen; 8084 mmap_event->prot = prot; 8085 mmap_event->flags = flags; 8086 8087 if (!(vma->vm_flags & VM_EXEC)) 8088 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA; 8089 8090 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size; 8091 8092 perf_iterate_sb(perf_event_mmap_output, 8093 mmap_event, 8094 NULL); 8095 8096 kfree(buf); 8097 } 8098 8099 /* 8100 * Check whether inode and address range match filter criteria. 8101 */ 8102 static bool perf_addr_filter_match(struct perf_addr_filter *filter, 8103 struct file *file, unsigned long offset, 8104 unsigned long size) 8105 { 8106 /* d_inode(NULL) won't be equal to any mapped user-space file */ 8107 if (!filter->path.dentry) 8108 return false; 8109 8110 if (d_inode(filter->path.dentry) != file_inode(file)) 8111 return false; 8112 8113 if (filter->offset > offset + size) 8114 return false; 8115 8116 if (filter->offset + filter->size < offset) 8117 return false; 8118 8119 return true; 8120 } 8121 8122 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter, 8123 struct vm_area_struct *vma, 8124 struct perf_addr_filter_range *fr) 8125 { 8126 unsigned long vma_size = vma->vm_end - vma->vm_start; 8127 unsigned long off = vma->vm_pgoff << PAGE_SHIFT; 8128 struct file *file = vma->vm_file; 8129 8130 if (!perf_addr_filter_match(filter, file, off, vma_size)) 8131 return false; 8132 8133 if (filter->offset < off) { 8134 fr->start = vma->vm_start; 8135 fr->size = min(vma_size, filter->size - (off - filter->offset)); 8136 } else { 8137 fr->start = vma->vm_start + filter->offset - off; 8138 fr->size = min(vma->vm_end - fr->start, filter->size); 8139 } 8140 8141 return true; 8142 } 8143 8144 static void __perf_addr_filters_adjust(struct perf_event *event, void *data) 8145 { 8146 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 8147 struct vm_area_struct *vma = data; 8148 struct perf_addr_filter *filter; 8149 unsigned int restart = 0, count = 0; 8150 unsigned long flags; 8151 8152 if (!has_addr_filter(event)) 8153 return; 8154 8155 if (!vma->vm_file) 8156 return; 8157 8158 raw_spin_lock_irqsave(&ifh->lock, flags); 8159 list_for_each_entry(filter, &ifh->list, entry) { 8160 if (perf_addr_filter_vma_adjust(filter, vma, 8161 &event->addr_filter_ranges[count])) 8162 restart++; 8163 8164 count++; 8165 } 8166 8167 if (restart) 8168 event->addr_filters_gen++; 8169 raw_spin_unlock_irqrestore(&ifh->lock, flags); 8170 8171 if (restart) 8172 perf_event_stop(event, 1); 8173 } 8174 8175 /* 8176 * Adjust all task's events' filters to the new vma 8177 */ 8178 static void perf_addr_filters_adjust(struct vm_area_struct *vma) 8179 { 8180 struct perf_event_context *ctx; 8181 int ctxn; 8182 8183 /* 8184 * Data tracing isn't supported yet and as such there is no need 8185 * to keep track of anything that isn't related to executable code: 8186 */ 8187 if (!(vma->vm_flags & VM_EXEC)) 8188 return; 8189 8190 rcu_read_lock(); 8191 for_each_task_context_nr(ctxn) { 8192 ctx = rcu_dereference(current->perf_event_ctxp[ctxn]); 8193 if (!ctx) 8194 continue; 8195 8196 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true); 8197 } 8198 rcu_read_unlock(); 8199 } 8200 8201 void perf_event_mmap(struct vm_area_struct *vma) 8202 { 8203 struct perf_mmap_event mmap_event; 8204 8205 if (!atomic_read(&nr_mmap_events)) 8206 return; 8207 8208 mmap_event = (struct perf_mmap_event){ 8209 .vma = vma, 8210 /* .file_name */ 8211 /* .file_size */ 8212 .event_id = { 8213 .header = { 8214 .type = PERF_RECORD_MMAP, 8215 .misc = PERF_RECORD_MISC_USER, 8216 /* .size */ 8217 }, 8218 /* .pid */ 8219 /* .tid */ 8220 .start = vma->vm_start, 8221 .len = vma->vm_end - vma->vm_start, 8222 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT, 8223 }, 8224 /* .maj (attr_mmap2 only) */ 8225 /* .min (attr_mmap2 only) */ 8226 /* .ino (attr_mmap2 only) */ 8227 /* .ino_generation (attr_mmap2 only) */ 8228 /* .prot (attr_mmap2 only) */ 8229 /* .flags (attr_mmap2 only) */ 8230 }; 8231 8232 perf_addr_filters_adjust(vma); 8233 perf_event_mmap_event(&mmap_event); 8234 } 8235 8236 void perf_event_aux_event(struct perf_event *event, unsigned long head, 8237 unsigned long size, u64 flags) 8238 { 8239 struct perf_output_handle handle; 8240 struct perf_sample_data sample; 8241 struct perf_aux_event { 8242 struct perf_event_header header; 8243 u64 offset; 8244 u64 size; 8245 u64 flags; 8246 } rec = { 8247 .header = { 8248 .type = PERF_RECORD_AUX, 8249 .misc = 0, 8250 .size = sizeof(rec), 8251 }, 8252 .offset = head, 8253 .size = size, 8254 .flags = flags, 8255 }; 8256 int ret; 8257 8258 perf_event_header__init_id(&rec.header, &sample, event); 8259 ret = perf_output_begin(&handle, event, rec.header.size); 8260 8261 if (ret) 8262 return; 8263 8264 perf_output_put(&handle, rec); 8265 perf_event__output_id_sample(event, &handle, &sample); 8266 8267 perf_output_end(&handle); 8268 } 8269 8270 /* 8271 * Lost/dropped samples logging 8272 */ 8273 void perf_log_lost_samples(struct perf_event *event, u64 lost) 8274 { 8275 struct perf_output_handle handle; 8276 struct perf_sample_data sample; 8277 int ret; 8278 8279 struct { 8280 struct perf_event_header header; 8281 u64 lost; 8282 } lost_samples_event = { 8283 .header = { 8284 .type = PERF_RECORD_LOST_SAMPLES, 8285 .misc = 0, 8286 .size = sizeof(lost_samples_event), 8287 }, 8288 .lost = lost, 8289 }; 8290 8291 perf_event_header__init_id(&lost_samples_event.header, &sample, event); 8292 8293 ret = perf_output_begin(&handle, event, 8294 lost_samples_event.header.size); 8295 if (ret) 8296 return; 8297 8298 perf_output_put(&handle, lost_samples_event); 8299 perf_event__output_id_sample(event, &handle, &sample); 8300 perf_output_end(&handle); 8301 } 8302 8303 /* 8304 * context_switch tracking 8305 */ 8306 8307 struct perf_switch_event { 8308 struct task_struct *task; 8309 struct task_struct *next_prev; 8310 8311 struct { 8312 struct perf_event_header header; 8313 u32 next_prev_pid; 8314 u32 next_prev_tid; 8315 } event_id; 8316 }; 8317 8318 static int perf_event_switch_match(struct perf_event *event) 8319 { 8320 return event->attr.context_switch; 8321 } 8322 8323 static void perf_event_switch_output(struct perf_event *event, void *data) 8324 { 8325 struct perf_switch_event *se = data; 8326 struct perf_output_handle handle; 8327 struct perf_sample_data sample; 8328 int ret; 8329 8330 if (!perf_event_switch_match(event)) 8331 return; 8332 8333 /* Only CPU-wide events are allowed to see next/prev pid/tid */ 8334 if (event->ctx->task) { 8335 se->event_id.header.type = PERF_RECORD_SWITCH; 8336 se->event_id.header.size = sizeof(se->event_id.header); 8337 } else { 8338 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE; 8339 se->event_id.header.size = sizeof(se->event_id); 8340 se->event_id.next_prev_pid = 8341 perf_event_pid(event, se->next_prev); 8342 se->event_id.next_prev_tid = 8343 perf_event_tid(event, se->next_prev); 8344 } 8345 8346 perf_event_header__init_id(&se->event_id.header, &sample, event); 8347 8348 ret = perf_output_begin(&handle, event, se->event_id.header.size); 8349 if (ret) 8350 return; 8351 8352 if (event->ctx->task) 8353 perf_output_put(&handle, se->event_id.header); 8354 else 8355 perf_output_put(&handle, se->event_id); 8356 8357 perf_event__output_id_sample(event, &handle, &sample); 8358 8359 perf_output_end(&handle); 8360 } 8361 8362 static void perf_event_switch(struct task_struct *task, 8363 struct task_struct *next_prev, bool sched_in) 8364 { 8365 struct perf_switch_event switch_event; 8366 8367 /* N.B. caller checks nr_switch_events != 0 */ 8368 8369 switch_event = (struct perf_switch_event){ 8370 .task = task, 8371 .next_prev = next_prev, 8372 .event_id = { 8373 .header = { 8374 /* .type */ 8375 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT, 8376 /* .size */ 8377 }, 8378 /* .next_prev_pid */ 8379 /* .next_prev_tid */ 8380 }, 8381 }; 8382 8383 if (!sched_in && task->state == TASK_RUNNING) 8384 switch_event.event_id.header.misc |= 8385 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT; 8386 8387 perf_iterate_sb(perf_event_switch_output, 8388 &switch_event, 8389 NULL); 8390 } 8391 8392 /* 8393 * IRQ throttle logging 8394 */ 8395 8396 static void perf_log_throttle(struct perf_event *event, int enable) 8397 { 8398 struct perf_output_handle handle; 8399 struct perf_sample_data sample; 8400 int ret; 8401 8402 struct { 8403 struct perf_event_header header; 8404 u64 time; 8405 u64 id; 8406 u64 stream_id; 8407 } throttle_event = { 8408 .header = { 8409 .type = PERF_RECORD_THROTTLE, 8410 .misc = 0, 8411 .size = sizeof(throttle_event), 8412 }, 8413 .time = perf_event_clock(event), 8414 .id = primary_event_id(event), 8415 .stream_id = event->id, 8416 }; 8417 8418 if (enable) 8419 throttle_event.header.type = PERF_RECORD_UNTHROTTLE; 8420 8421 perf_event_header__init_id(&throttle_event.header, &sample, event); 8422 8423 ret = perf_output_begin(&handle, event, 8424 throttle_event.header.size); 8425 if (ret) 8426 return; 8427 8428 perf_output_put(&handle, throttle_event); 8429 perf_event__output_id_sample(event, &handle, &sample); 8430 perf_output_end(&handle); 8431 } 8432 8433 /* 8434 * ksymbol register/unregister tracking 8435 */ 8436 8437 struct perf_ksymbol_event { 8438 const char *name; 8439 int name_len; 8440 struct { 8441 struct perf_event_header header; 8442 u64 addr; 8443 u32 len; 8444 u16 ksym_type; 8445 u16 flags; 8446 } event_id; 8447 }; 8448 8449 static int perf_event_ksymbol_match(struct perf_event *event) 8450 { 8451 return event->attr.ksymbol; 8452 } 8453 8454 static void perf_event_ksymbol_output(struct perf_event *event, void *data) 8455 { 8456 struct perf_ksymbol_event *ksymbol_event = data; 8457 struct perf_output_handle handle; 8458 struct perf_sample_data sample; 8459 int ret; 8460 8461 if (!perf_event_ksymbol_match(event)) 8462 return; 8463 8464 perf_event_header__init_id(&ksymbol_event->event_id.header, 8465 &sample, event); 8466 ret = perf_output_begin(&handle, event, 8467 ksymbol_event->event_id.header.size); 8468 if (ret) 8469 return; 8470 8471 perf_output_put(&handle, ksymbol_event->event_id); 8472 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len); 8473 perf_event__output_id_sample(event, &handle, &sample); 8474 8475 perf_output_end(&handle); 8476 } 8477 8478 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister, 8479 const char *sym) 8480 { 8481 struct perf_ksymbol_event ksymbol_event; 8482 char name[KSYM_NAME_LEN]; 8483 u16 flags = 0; 8484 int name_len; 8485 8486 if (!atomic_read(&nr_ksymbol_events)) 8487 return; 8488 8489 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX || 8490 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN) 8491 goto err; 8492 8493 strlcpy(name, sym, KSYM_NAME_LEN); 8494 name_len = strlen(name) + 1; 8495 while (!IS_ALIGNED(name_len, sizeof(u64))) 8496 name[name_len++] = '\0'; 8497 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64)); 8498 8499 if (unregister) 8500 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER; 8501 8502 ksymbol_event = (struct perf_ksymbol_event){ 8503 .name = name, 8504 .name_len = name_len, 8505 .event_id = { 8506 .header = { 8507 .type = PERF_RECORD_KSYMBOL, 8508 .size = sizeof(ksymbol_event.event_id) + 8509 name_len, 8510 }, 8511 .addr = addr, 8512 .len = len, 8513 .ksym_type = ksym_type, 8514 .flags = flags, 8515 }, 8516 }; 8517 8518 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL); 8519 return; 8520 err: 8521 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type); 8522 } 8523 8524 /* 8525 * bpf program load/unload tracking 8526 */ 8527 8528 struct perf_bpf_event { 8529 struct bpf_prog *prog; 8530 struct { 8531 struct perf_event_header header; 8532 u16 type; 8533 u16 flags; 8534 u32 id; 8535 u8 tag[BPF_TAG_SIZE]; 8536 } event_id; 8537 }; 8538 8539 static int perf_event_bpf_match(struct perf_event *event) 8540 { 8541 return event->attr.bpf_event; 8542 } 8543 8544 static void perf_event_bpf_output(struct perf_event *event, void *data) 8545 { 8546 struct perf_bpf_event *bpf_event = data; 8547 struct perf_output_handle handle; 8548 struct perf_sample_data sample; 8549 int ret; 8550 8551 if (!perf_event_bpf_match(event)) 8552 return; 8553 8554 perf_event_header__init_id(&bpf_event->event_id.header, 8555 &sample, event); 8556 ret = perf_output_begin(&handle, event, 8557 bpf_event->event_id.header.size); 8558 if (ret) 8559 return; 8560 8561 perf_output_put(&handle, bpf_event->event_id); 8562 perf_event__output_id_sample(event, &handle, &sample); 8563 8564 perf_output_end(&handle); 8565 } 8566 8567 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog, 8568 enum perf_bpf_event_type type) 8569 { 8570 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD; 8571 int i; 8572 8573 if (prog->aux->func_cnt == 0) { 8574 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, 8575 (u64)(unsigned long)prog->bpf_func, 8576 prog->jited_len, unregister, 8577 prog->aux->ksym.name); 8578 } else { 8579 for (i = 0; i < prog->aux->func_cnt; i++) { 8580 struct bpf_prog *subprog = prog->aux->func[i]; 8581 8582 perf_event_ksymbol( 8583 PERF_RECORD_KSYMBOL_TYPE_BPF, 8584 (u64)(unsigned long)subprog->bpf_func, 8585 subprog->jited_len, unregister, 8586 prog->aux->ksym.name); 8587 } 8588 } 8589 } 8590 8591 void perf_event_bpf_event(struct bpf_prog *prog, 8592 enum perf_bpf_event_type type, 8593 u16 flags) 8594 { 8595 struct perf_bpf_event bpf_event; 8596 8597 if (type <= PERF_BPF_EVENT_UNKNOWN || 8598 type >= PERF_BPF_EVENT_MAX) 8599 return; 8600 8601 switch (type) { 8602 case PERF_BPF_EVENT_PROG_LOAD: 8603 case PERF_BPF_EVENT_PROG_UNLOAD: 8604 if (atomic_read(&nr_ksymbol_events)) 8605 perf_event_bpf_emit_ksymbols(prog, type); 8606 break; 8607 default: 8608 break; 8609 } 8610 8611 if (!atomic_read(&nr_bpf_events)) 8612 return; 8613 8614 bpf_event = (struct perf_bpf_event){ 8615 .prog = prog, 8616 .event_id = { 8617 .header = { 8618 .type = PERF_RECORD_BPF_EVENT, 8619 .size = sizeof(bpf_event.event_id), 8620 }, 8621 .type = type, 8622 .flags = flags, 8623 .id = prog->aux->id, 8624 }, 8625 }; 8626 8627 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64)); 8628 8629 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE); 8630 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL); 8631 } 8632 8633 void perf_event_itrace_started(struct perf_event *event) 8634 { 8635 event->attach_state |= PERF_ATTACH_ITRACE; 8636 } 8637 8638 static void perf_log_itrace_start(struct perf_event *event) 8639 { 8640 struct perf_output_handle handle; 8641 struct perf_sample_data sample; 8642 struct perf_aux_event { 8643 struct perf_event_header header; 8644 u32 pid; 8645 u32 tid; 8646 } rec; 8647 int ret; 8648 8649 if (event->parent) 8650 event = event->parent; 8651 8652 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) || 8653 event->attach_state & PERF_ATTACH_ITRACE) 8654 return; 8655 8656 rec.header.type = PERF_RECORD_ITRACE_START; 8657 rec.header.misc = 0; 8658 rec.header.size = sizeof(rec); 8659 rec.pid = perf_event_pid(event, current); 8660 rec.tid = perf_event_tid(event, current); 8661 8662 perf_event_header__init_id(&rec.header, &sample, event); 8663 ret = perf_output_begin(&handle, event, rec.header.size); 8664 8665 if (ret) 8666 return; 8667 8668 perf_output_put(&handle, rec); 8669 perf_event__output_id_sample(event, &handle, &sample); 8670 8671 perf_output_end(&handle); 8672 } 8673 8674 static int 8675 __perf_event_account_interrupt(struct perf_event *event, int throttle) 8676 { 8677 struct hw_perf_event *hwc = &event->hw; 8678 int ret = 0; 8679 u64 seq; 8680 8681 seq = __this_cpu_read(perf_throttled_seq); 8682 if (seq != hwc->interrupts_seq) { 8683 hwc->interrupts_seq = seq; 8684 hwc->interrupts = 1; 8685 } else { 8686 hwc->interrupts++; 8687 if (unlikely(throttle 8688 && hwc->interrupts >= max_samples_per_tick)) { 8689 __this_cpu_inc(perf_throttled_count); 8690 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 8691 hwc->interrupts = MAX_INTERRUPTS; 8692 perf_log_throttle(event, 0); 8693 ret = 1; 8694 } 8695 } 8696 8697 if (event->attr.freq) { 8698 u64 now = perf_clock(); 8699 s64 delta = now - hwc->freq_time_stamp; 8700 8701 hwc->freq_time_stamp = now; 8702 8703 if (delta > 0 && delta < 2*TICK_NSEC) 8704 perf_adjust_period(event, delta, hwc->last_period, true); 8705 } 8706 8707 return ret; 8708 } 8709 8710 int perf_event_account_interrupt(struct perf_event *event) 8711 { 8712 return __perf_event_account_interrupt(event, 1); 8713 } 8714 8715 /* 8716 * Generic event overflow handling, sampling. 8717 */ 8718 8719 static int __perf_event_overflow(struct perf_event *event, 8720 int throttle, struct perf_sample_data *data, 8721 struct pt_regs *regs) 8722 { 8723 int events = atomic_read(&event->event_limit); 8724 int ret = 0; 8725 8726 /* 8727 * Non-sampling counters might still use the PMI to fold short 8728 * hardware counters, ignore those. 8729 */ 8730 if (unlikely(!is_sampling_event(event))) 8731 return 0; 8732 8733 ret = __perf_event_account_interrupt(event, throttle); 8734 8735 /* 8736 * XXX event_limit might not quite work as expected on inherited 8737 * events 8738 */ 8739 8740 event->pending_kill = POLL_IN; 8741 if (events && atomic_dec_and_test(&event->event_limit)) { 8742 ret = 1; 8743 event->pending_kill = POLL_HUP; 8744 8745 perf_event_disable_inatomic(event); 8746 } 8747 8748 READ_ONCE(event->overflow_handler)(event, data, regs); 8749 8750 if (*perf_event_fasync(event) && event->pending_kill) { 8751 event->pending_wakeup = 1; 8752 irq_work_queue(&event->pending); 8753 } 8754 8755 return ret; 8756 } 8757 8758 int perf_event_overflow(struct perf_event *event, 8759 struct perf_sample_data *data, 8760 struct pt_regs *regs) 8761 { 8762 return __perf_event_overflow(event, 1, data, regs); 8763 } 8764 8765 /* 8766 * Generic software event infrastructure 8767 */ 8768 8769 struct swevent_htable { 8770 struct swevent_hlist *swevent_hlist; 8771 struct mutex hlist_mutex; 8772 int hlist_refcount; 8773 8774 /* Recursion avoidance in each contexts */ 8775 int recursion[PERF_NR_CONTEXTS]; 8776 }; 8777 8778 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable); 8779 8780 /* 8781 * We directly increment event->count and keep a second value in 8782 * event->hw.period_left to count intervals. This period event 8783 * is kept in the range [-sample_period, 0] so that we can use the 8784 * sign as trigger. 8785 */ 8786 8787 u64 perf_swevent_set_period(struct perf_event *event) 8788 { 8789 struct hw_perf_event *hwc = &event->hw; 8790 u64 period = hwc->last_period; 8791 u64 nr, offset; 8792 s64 old, val; 8793 8794 hwc->last_period = hwc->sample_period; 8795 8796 again: 8797 old = val = local64_read(&hwc->period_left); 8798 if (val < 0) 8799 return 0; 8800 8801 nr = div64_u64(period + val, period); 8802 offset = nr * period; 8803 val -= offset; 8804 if (local64_cmpxchg(&hwc->period_left, old, val) != old) 8805 goto again; 8806 8807 return nr; 8808 } 8809 8810 static void perf_swevent_overflow(struct perf_event *event, u64 overflow, 8811 struct perf_sample_data *data, 8812 struct pt_regs *regs) 8813 { 8814 struct hw_perf_event *hwc = &event->hw; 8815 int throttle = 0; 8816 8817 if (!overflow) 8818 overflow = perf_swevent_set_period(event); 8819 8820 if (hwc->interrupts == MAX_INTERRUPTS) 8821 return; 8822 8823 for (; overflow; overflow--) { 8824 if (__perf_event_overflow(event, throttle, 8825 data, regs)) { 8826 /* 8827 * We inhibit the overflow from happening when 8828 * hwc->interrupts == MAX_INTERRUPTS. 8829 */ 8830 break; 8831 } 8832 throttle = 1; 8833 } 8834 } 8835 8836 static void perf_swevent_event(struct perf_event *event, u64 nr, 8837 struct perf_sample_data *data, 8838 struct pt_regs *regs) 8839 { 8840 struct hw_perf_event *hwc = &event->hw; 8841 8842 local64_add(nr, &event->count); 8843 8844 if (!regs) 8845 return; 8846 8847 if (!is_sampling_event(event)) 8848 return; 8849 8850 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) { 8851 data->period = nr; 8852 return perf_swevent_overflow(event, 1, data, regs); 8853 } else 8854 data->period = event->hw.last_period; 8855 8856 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) 8857 return perf_swevent_overflow(event, 1, data, regs); 8858 8859 if (local64_add_negative(nr, &hwc->period_left)) 8860 return; 8861 8862 perf_swevent_overflow(event, 0, data, regs); 8863 } 8864 8865 static int perf_exclude_event(struct perf_event *event, 8866 struct pt_regs *regs) 8867 { 8868 if (event->hw.state & PERF_HES_STOPPED) 8869 return 1; 8870 8871 if (regs) { 8872 if (event->attr.exclude_user && user_mode(regs)) 8873 return 1; 8874 8875 if (event->attr.exclude_kernel && !user_mode(regs)) 8876 return 1; 8877 } 8878 8879 return 0; 8880 } 8881 8882 static int perf_swevent_match(struct perf_event *event, 8883 enum perf_type_id type, 8884 u32 event_id, 8885 struct perf_sample_data *data, 8886 struct pt_regs *regs) 8887 { 8888 if (event->attr.type != type) 8889 return 0; 8890 8891 if (event->attr.config != event_id) 8892 return 0; 8893 8894 if (perf_exclude_event(event, regs)) 8895 return 0; 8896 8897 return 1; 8898 } 8899 8900 static inline u64 swevent_hash(u64 type, u32 event_id) 8901 { 8902 u64 val = event_id | (type << 32); 8903 8904 return hash_64(val, SWEVENT_HLIST_BITS); 8905 } 8906 8907 static inline struct hlist_head * 8908 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id) 8909 { 8910 u64 hash = swevent_hash(type, event_id); 8911 8912 return &hlist->heads[hash]; 8913 } 8914 8915 /* For the read side: events when they trigger */ 8916 static inline struct hlist_head * 8917 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id) 8918 { 8919 struct swevent_hlist *hlist; 8920 8921 hlist = rcu_dereference(swhash->swevent_hlist); 8922 if (!hlist) 8923 return NULL; 8924 8925 return __find_swevent_head(hlist, type, event_id); 8926 } 8927 8928 /* For the event head insertion and removal in the hlist */ 8929 static inline struct hlist_head * 8930 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) 8931 { 8932 struct swevent_hlist *hlist; 8933 u32 event_id = event->attr.config; 8934 u64 type = event->attr.type; 8935 8936 /* 8937 * Event scheduling is always serialized against hlist allocation 8938 * and release. Which makes the protected version suitable here. 8939 * The context lock guarantees that. 8940 */ 8941 hlist = rcu_dereference_protected(swhash->swevent_hlist, 8942 lockdep_is_held(&event->ctx->lock)); 8943 if (!hlist) 8944 return NULL; 8945 8946 return __find_swevent_head(hlist, type, event_id); 8947 } 8948 8949 static void do_perf_sw_event(enum perf_type_id type, u32 event_id, 8950 u64 nr, 8951 struct perf_sample_data *data, 8952 struct pt_regs *regs) 8953 { 8954 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 8955 struct perf_event *event; 8956 struct hlist_head *head; 8957 8958 rcu_read_lock(); 8959 head = find_swevent_head_rcu(swhash, type, event_id); 8960 if (!head) 8961 goto end; 8962 8963 hlist_for_each_entry_rcu(event, head, hlist_entry) { 8964 if (perf_swevent_match(event, type, event_id, data, regs)) 8965 perf_swevent_event(event, nr, data, regs); 8966 } 8967 end: 8968 rcu_read_unlock(); 8969 } 8970 8971 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]); 8972 8973 int perf_swevent_get_recursion_context(void) 8974 { 8975 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 8976 8977 return get_recursion_context(swhash->recursion); 8978 } 8979 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context); 8980 8981 void perf_swevent_put_recursion_context(int rctx) 8982 { 8983 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 8984 8985 put_recursion_context(swhash->recursion, rctx); 8986 } 8987 8988 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 8989 { 8990 struct perf_sample_data data; 8991 8992 if (WARN_ON_ONCE(!regs)) 8993 return; 8994 8995 perf_sample_data_init(&data, addr, 0); 8996 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs); 8997 } 8998 8999 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 9000 { 9001 int rctx; 9002 9003 preempt_disable_notrace(); 9004 rctx = perf_swevent_get_recursion_context(); 9005 if (unlikely(rctx < 0)) 9006 goto fail; 9007 9008 ___perf_sw_event(event_id, nr, regs, addr); 9009 9010 perf_swevent_put_recursion_context(rctx); 9011 fail: 9012 preempt_enable_notrace(); 9013 } 9014 9015 static void perf_swevent_read(struct perf_event *event) 9016 { 9017 } 9018 9019 static int perf_swevent_add(struct perf_event *event, int flags) 9020 { 9021 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 9022 struct hw_perf_event *hwc = &event->hw; 9023 struct hlist_head *head; 9024 9025 if (is_sampling_event(event)) { 9026 hwc->last_period = hwc->sample_period; 9027 perf_swevent_set_period(event); 9028 } 9029 9030 hwc->state = !(flags & PERF_EF_START); 9031 9032 head = find_swevent_head(swhash, event); 9033 if (WARN_ON_ONCE(!head)) 9034 return -EINVAL; 9035 9036 hlist_add_head_rcu(&event->hlist_entry, head); 9037 perf_event_update_userpage(event); 9038 9039 return 0; 9040 } 9041 9042 static void perf_swevent_del(struct perf_event *event, int flags) 9043 { 9044 hlist_del_rcu(&event->hlist_entry); 9045 } 9046 9047 static void perf_swevent_start(struct perf_event *event, int flags) 9048 { 9049 event->hw.state = 0; 9050 } 9051 9052 static void perf_swevent_stop(struct perf_event *event, int flags) 9053 { 9054 event->hw.state = PERF_HES_STOPPED; 9055 } 9056 9057 /* Deref the hlist from the update side */ 9058 static inline struct swevent_hlist * 9059 swevent_hlist_deref(struct swevent_htable *swhash) 9060 { 9061 return rcu_dereference_protected(swhash->swevent_hlist, 9062 lockdep_is_held(&swhash->hlist_mutex)); 9063 } 9064 9065 static void swevent_hlist_release(struct swevent_htable *swhash) 9066 { 9067 struct swevent_hlist *hlist = swevent_hlist_deref(swhash); 9068 9069 if (!hlist) 9070 return; 9071 9072 RCU_INIT_POINTER(swhash->swevent_hlist, NULL); 9073 kfree_rcu(hlist, rcu_head); 9074 } 9075 9076 static void swevent_hlist_put_cpu(int cpu) 9077 { 9078 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 9079 9080 mutex_lock(&swhash->hlist_mutex); 9081 9082 if (!--swhash->hlist_refcount) 9083 swevent_hlist_release(swhash); 9084 9085 mutex_unlock(&swhash->hlist_mutex); 9086 } 9087 9088 static void swevent_hlist_put(void) 9089 { 9090 int cpu; 9091 9092 for_each_possible_cpu(cpu) 9093 swevent_hlist_put_cpu(cpu); 9094 } 9095 9096 static int swevent_hlist_get_cpu(int cpu) 9097 { 9098 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 9099 int err = 0; 9100 9101 mutex_lock(&swhash->hlist_mutex); 9102 if (!swevent_hlist_deref(swhash) && 9103 cpumask_test_cpu(cpu, perf_online_mask)) { 9104 struct swevent_hlist *hlist; 9105 9106 hlist = kzalloc(sizeof(*hlist), GFP_KERNEL); 9107 if (!hlist) { 9108 err = -ENOMEM; 9109 goto exit; 9110 } 9111 rcu_assign_pointer(swhash->swevent_hlist, hlist); 9112 } 9113 swhash->hlist_refcount++; 9114 exit: 9115 mutex_unlock(&swhash->hlist_mutex); 9116 9117 return err; 9118 } 9119 9120 static int swevent_hlist_get(void) 9121 { 9122 int err, cpu, failed_cpu; 9123 9124 mutex_lock(&pmus_lock); 9125 for_each_possible_cpu(cpu) { 9126 err = swevent_hlist_get_cpu(cpu); 9127 if (err) { 9128 failed_cpu = cpu; 9129 goto fail; 9130 } 9131 } 9132 mutex_unlock(&pmus_lock); 9133 return 0; 9134 fail: 9135 for_each_possible_cpu(cpu) { 9136 if (cpu == failed_cpu) 9137 break; 9138 swevent_hlist_put_cpu(cpu); 9139 } 9140 mutex_unlock(&pmus_lock); 9141 return err; 9142 } 9143 9144 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX]; 9145 9146 static void sw_perf_event_destroy(struct perf_event *event) 9147 { 9148 u64 event_id = event->attr.config; 9149 9150 WARN_ON(event->parent); 9151 9152 static_key_slow_dec(&perf_swevent_enabled[event_id]); 9153 swevent_hlist_put(); 9154 } 9155 9156 static int perf_swevent_init(struct perf_event *event) 9157 { 9158 u64 event_id = event->attr.config; 9159 9160 if (event->attr.type != PERF_TYPE_SOFTWARE) 9161 return -ENOENT; 9162 9163 /* 9164 * no branch sampling for software events 9165 */ 9166 if (has_branch_stack(event)) 9167 return -EOPNOTSUPP; 9168 9169 switch (event_id) { 9170 case PERF_COUNT_SW_CPU_CLOCK: 9171 case PERF_COUNT_SW_TASK_CLOCK: 9172 return -ENOENT; 9173 9174 default: 9175 break; 9176 } 9177 9178 if (event_id >= PERF_COUNT_SW_MAX) 9179 return -ENOENT; 9180 9181 if (!event->parent) { 9182 int err; 9183 9184 err = swevent_hlist_get(); 9185 if (err) 9186 return err; 9187 9188 static_key_slow_inc(&perf_swevent_enabled[event_id]); 9189 event->destroy = sw_perf_event_destroy; 9190 } 9191 9192 return 0; 9193 } 9194 9195 static struct pmu perf_swevent = { 9196 .task_ctx_nr = perf_sw_context, 9197 9198 .capabilities = PERF_PMU_CAP_NO_NMI, 9199 9200 .event_init = perf_swevent_init, 9201 .add = perf_swevent_add, 9202 .del = perf_swevent_del, 9203 .start = perf_swevent_start, 9204 .stop = perf_swevent_stop, 9205 .read = perf_swevent_read, 9206 }; 9207 9208 #ifdef CONFIG_EVENT_TRACING 9209 9210 static int perf_tp_filter_match(struct perf_event *event, 9211 struct perf_sample_data *data) 9212 { 9213 void *record = data->raw->frag.data; 9214 9215 /* only top level events have filters set */ 9216 if (event->parent) 9217 event = event->parent; 9218 9219 if (likely(!event->filter) || filter_match_preds(event->filter, record)) 9220 return 1; 9221 return 0; 9222 } 9223 9224 static int perf_tp_event_match(struct perf_event *event, 9225 struct perf_sample_data *data, 9226 struct pt_regs *regs) 9227 { 9228 if (event->hw.state & PERF_HES_STOPPED) 9229 return 0; 9230 /* 9231 * If exclude_kernel, only trace user-space tracepoints (uprobes) 9232 */ 9233 if (event->attr.exclude_kernel && !user_mode(regs)) 9234 return 0; 9235 9236 if (!perf_tp_filter_match(event, data)) 9237 return 0; 9238 9239 return 1; 9240 } 9241 9242 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx, 9243 struct trace_event_call *call, u64 count, 9244 struct pt_regs *regs, struct hlist_head *head, 9245 struct task_struct *task) 9246 { 9247 if (bpf_prog_array_valid(call)) { 9248 *(struct pt_regs **)raw_data = regs; 9249 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) { 9250 perf_swevent_put_recursion_context(rctx); 9251 return; 9252 } 9253 } 9254 perf_tp_event(call->event.type, count, raw_data, size, regs, head, 9255 rctx, task); 9256 } 9257 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit); 9258 9259 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size, 9260 struct pt_regs *regs, struct hlist_head *head, int rctx, 9261 struct task_struct *task) 9262 { 9263 struct perf_sample_data data; 9264 struct perf_event *event; 9265 9266 struct perf_raw_record raw = { 9267 .frag = { 9268 .size = entry_size, 9269 .data = record, 9270 }, 9271 }; 9272 9273 perf_sample_data_init(&data, 0, 0); 9274 data.raw = &raw; 9275 9276 perf_trace_buf_update(record, event_type); 9277 9278 hlist_for_each_entry_rcu(event, head, hlist_entry) { 9279 if (perf_tp_event_match(event, &data, regs)) 9280 perf_swevent_event(event, count, &data, regs); 9281 } 9282 9283 /* 9284 * If we got specified a target task, also iterate its context and 9285 * deliver this event there too. 9286 */ 9287 if (task && task != current) { 9288 struct perf_event_context *ctx; 9289 struct trace_entry *entry = record; 9290 9291 rcu_read_lock(); 9292 ctx = rcu_dereference(task->perf_event_ctxp[perf_sw_context]); 9293 if (!ctx) 9294 goto unlock; 9295 9296 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { 9297 if (event->cpu != smp_processor_id()) 9298 continue; 9299 if (event->attr.type != PERF_TYPE_TRACEPOINT) 9300 continue; 9301 if (event->attr.config != entry->type) 9302 continue; 9303 if (perf_tp_event_match(event, &data, regs)) 9304 perf_swevent_event(event, count, &data, regs); 9305 } 9306 unlock: 9307 rcu_read_unlock(); 9308 } 9309 9310 perf_swevent_put_recursion_context(rctx); 9311 } 9312 EXPORT_SYMBOL_GPL(perf_tp_event); 9313 9314 static void tp_perf_event_destroy(struct perf_event *event) 9315 { 9316 perf_trace_destroy(event); 9317 } 9318 9319 static int perf_tp_event_init(struct perf_event *event) 9320 { 9321 int err; 9322 9323 if (event->attr.type != PERF_TYPE_TRACEPOINT) 9324 return -ENOENT; 9325 9326 /* 9327 * no branch sampling for tracepoint events 9328 */ 9329 if (has_branch_stack(event)) 9330 return -EOPNOTSUPP; 9331 9332 err = perf_trace_init(event); 9333 if (err) 9334 return err; 9335 9336 event->destroy = tp_perf_event_destroy; 9337 9338 return 0; 9339 } 9340 9341 static struct pmu perf_tracepoint = { 9342 .task_ctx_nr = perf_sw_context, 9343 9344 .event_init = perf_tp_event_init, 9345 .add = perf_trace_add, 9346 .del = perf_trace_del, 9347 .start = perf_swevent_start, 9348 .stop = perf_swevent_stop, 9349 .read = perf_swevent_read, 9350 }; 9351 9352 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS) 9353 /* 9354 * Flags in config, used by dynamic PMU kprobe and uprobe 9355 * The flags should match following PMU_FORMAT_ATTR(). 9356 * 9357 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe 9358 * if not set, create kprobe/uprobe 9359 * 9360 * The following values specify a reference counter (or semaphore in the 9361 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically 9362 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset. 9363 * 9364 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset 9365 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left 9366 */ 9367 enum perf_probe_config { 9368 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */ 9369 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32, 9370 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS, 9371 }; 9372 9373 PMU_FORMAT_ATTR(retprobe, "config:0"); 9374 #endif 9375 9376 #ifdef CONFIG_KPROBE_EVENTS 9377 static struct attribute *kprobe_attrs[] = { 9378 &format_attr_retprobe.attr, 9379 NULL, 9380 }; 9381 9382 static struct attribute_group kprobe_format_group = { 9383 .name = "format", 9384 .attrs = kprobe_attrs, 9385 }; 9386 9387 static const struct attribute_group *kprobe_attr_groups[] = { 9388 &kprobe_format_group, 9389 NULL, 9390 }; 9391 9392 static int perf_kprobe_event_init(struct perf_event *event); 9393 static struct pmu perf_kprobe = { 9394 .task_ctx_nr = perf_sw_context, 9395 .event_init = perf_kprobe_event_init, 9396 .add = perf_trace_add, 9397 .del = perf_trace_del, 9398 .start = perf_swevent_start, 9399 .stop = perf_swevent_stop, 9400 .read = perf_swevent_read, 9401 .attr_groups = kprobe_attr_groups, 9402 }; 9403 9404 static int perf_kprobe_event_init(struct perf_event *event) 9405 { 9406 int err; 9407 bool is_retprobe; 9408 9409 if (event->attr.type != perf_kprobe.type) 9410 return -ENOENT; 9411 9412 if (!perfmon_capable()) 9413 return -EACCES; 9414 9415 /* 9416 * no branch sampling for probe events 9417 */ 9418 if (has_branch_stack(event)) 9419 return -EOPNOTSUPP; 9420 9421 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 9422 err = perf_kprobe_init(event, is_retprobe); 9423 if (err) 9424 return err; 9425 9426 event->destroy = perf_kprobe_destroy; 9427 9428 return 0; 9429 } 9430 #endif /* CONFIG_KPROBE_EVENTS */ 9431 9432 #ifdef CONFIG_UPROBE_EVENTS 9433 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63"); 9434 9435 static struct attribute *uprobe_attrs[] = { 9436 &format_attr_retprobe.attr, 9437 &format_attr_ref_ctr_offset.attr, 9438 NULL, 9439 }; 9440 9441 static struct attribute_group uprobe_format_group = { 9442 .name = "format", 9443 .attrs = uprobe_attrs, 9444 }; 9445 9446 static const struct attribute_group *uprobe_attr_groups[] = { 9447 &uprobe_format_group, 9448 NULL, 9449 }; 9450 9451 static int perf_uprobe_event_init(struct perf_event *event); 9452 static struct pmu perf_uprobe = { 9453 .task_ctx_nr = perf_sw_context, 9454 .event_init = perf_uprobe_event_init, 9455 .add = perf_trace_add, 9456 .del = perf_trace_del, 9457 .start = perf_swevent_start, 9458 .stop = perf_swevent_stop, 9459 .read = perf_swevent_read, 9460 .attr_groups = uprobe_attr_groups, 9461 }; 9462 9463 static int perf_uprobe_event_init(struct perf_event *event) 9464 { 9465 int err; 9466 unsigned long ref_ctr_offset; 9467 bool is_retprobe; 9468 9469 if (event->attr.type != perf_uprobe.type) 9470 return -ENOENT; 9471 9472 if (!perfmon_capable()) 9473 return -EACCES; 9474 9475 /* 9476 * no branch sampling for probe events 9477 */ 9478 if (has_branch_stack(event)) 9479 return -EOPNOTSUPP; 9480 9481 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 9482 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT; 9483 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe); 9484 if (err) 9485 return err; 9486 9487 event->destroy = perf_uprobe_destroy; 9488 9489 return 0; 9490 } 9491 #endif /* CONFIG_UPROBE_EVENTS */ 9492 9493 static inline void perf_tp_register(void) 9494 { 9495 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT); 9496 #ifdef CONFIG_KPROBE_EVENTS 9497 perf_pmu_register(&perf_kprobe, "kprobe", -1); 9498 #endif 9499 #ifdef CONFIG_UPROBE_EVENTS 9500 perf_pmu_register(&perf_uprobe, "uprobe", -1); 9501 #endif 9502 } 9503 9504 static void perf_event_free_filter(struct perf_event *event) 9505 { 9506 ftrace_profile_free_filter(event); 9507 } 9508 9509 #ifdef CONFIG_BPF_SYSCALL 9510 static void bpf_overflow_handler(struct perf_event *event, 9511 struct perf_sample_data *data, 9512 struct pt_regs *regs) 9513 { 9514 struct bpf_perf_event_data_kern ctx = { 9515 .data = data, 9516 .event = event, 9517 }; 9518 int ret = 0; 9519 9520 ctx.regs = perf_arch_bpf_user_pt_regs(regs); 9521 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) 9522 goto out; 9523 rcu_read_lock(); 9524 ret = BPF_PROG_RUN(event->prog, &ctx); 9525 rcu_read_unlock(); 9526 out: 9527 __this_cpu_dec(bpf_prog_active); 9528 if (!ret) 9529 return; 9530 9531 event->orig_overflow_handler(event, data, regs); 9532 } 9533 9534 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd) 9535 { 9536 struct bpf_prog *prog; 9537 9538 if (event->overflow_handler_context) 9539 /* hw breakpoint or kernel counter */ 9540 return -EINVAL; 9541 9542 if (event->prog) 9543 return -EEXIST; 9544 9545 prog = bpf_prog_get_type(prog_fd, BPF_PROG_TYPE_PERF_EVENT); 9546 if (IS_ERR(prog)) 9547 return PTR_ERR(prog); 9548 9549 event->prog = prog; 9550 event->orig_overflow_handler = READ_ONCE(event->overflow_handler); 9551 WRITE_ONCE(event->overflow_handler, bpf_overflow_handler); 9552 return 0; 9553 } 9554 9555 static void perf_event_free_bpf_handler(struct perf_event *event) 9556 { 9557 struct bpf_prog *prog = event->prog; 9558 9559 if (!prog) 9560 return; 9561 9562 WRITE_ONCE(event->overflow_handler, event->orig_overflow_handler); 9563 event->prog = NULL; 9564 bpf_prog_put(prog); 9565 } 9566 #else 9567 static int perf_event_set_bpf_handler(struct perf_event *event, u32 prog_fd) 9568 { 9569 return -EOPNOTSUPP; 9570 } 9571 static void perf_event_free_bpf_handler(struct perf_event *event) 9572 { 9573 } 9574 #endif 9575 9576 /* 9577 * returns true if the event is a tracepoint, or a kprobe/upprobe created 9578 * with perf_event_open() 9579 */ 9580 static inline bool perf_event_is_tracing(struct perf_event *event) 9581 { 9582 if (event->pmu == &perf_tracepoint) 9583 return true; 9584 #ifdef CONFIG_KPROBE_EVENTS 9585 if (event->pmu == &perf_kprobe) 9586 return true; 9587 #endif 9588 #ifdef CONFIG_UPROBE_EVENTS 9589 if (event->pmu == &perf_uprobe) 9590 return true; 9591 #endif 9592 return false; 9593 } 9594 9595 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd) 9596 { 9597 bool is_kprobe, is_tracepoint, is_syscall_tp; 9598 struct bpf_prog *prog; 9599 int ret; 9600 9601 if (!perf_event_is_tracing(event)) 9602 return perf_event_set_bpf_handler(event, prog_fd); 9603 9604 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_UKPROBE; 9605 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT; 9606 is_syscall_tp = is_syscall_trace_event(event->tp_event); 9607 if (!is_kprobe && !is_tracepoint && !is_syscall_tp) 9608 /* bpf programs can only be attached to u/kprobe or tracepoint */ 9609 return -EINVAL; 9610 9611 prog = bpf_prog_get(prog_fd); 9612 if (IS_ERR(prog)) 9613 return PTR_ERR(prog); 9614 9615 if ((is_kprobe && prog->type != BPF_PROG_TYPE_KPROBE) || 9616 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) || 9617 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) { 9618 /* valid fd, but invalid bpf program type */ 9619 bpf_prog_put(prog); 9620 return -EINVAL; 9621 } 9622 9623 /* Kprobe override only works for kprobes, not uprobes. */ 9624 if (prog->kprobe_override && 9625 !(event->tp_event->flags & TRACE_EVENT_FL_KPROBE)) { 9626 bpf_prog_put(prog); 9627 return -EINVAL; 9628 } 9629 9630 if (is_tracepoint || is_syscall_tp) { 9631 int off = trace_event_get_offsets(event->tp_event); 9632 9633 if (prog->aux->max_ctx_offset > off) { 9634 bpf_prog_put(prog); 9635 return -EACCES; 9636 } 9637 } 9638 9639 ret = perf_event_attach_bpf_prog(event, prog); 9640 if (ret) 9641 bpf_prog_put(prog); 9642 return ret; 9643 } 9644 9645 static void perf_event_free_bpf_prog(struct perf_event *event) 9646 { 9647 if (!perf_event_is_tracing(event)) { 9648 perf_event_free_bpf_handler(event); 9649 return; 9650 } 9651 perf_event_detach_bpf_prog(event); 9652 } 9653 9654 #else 9655 9656 static inline void perf_tp_register(void) 9657 { 9658 } 9659 9660 static void perf_event_free_filter(struct perf_event *event) 9661 { 9662 } 9663 9664 static int perf_event_set_bpf_prog(struct perf_event *event, u32 prog_fd) 9665 { 9666 return -ENOENT; 9667 } 9668 9669 static void perf_event_free_bpf_prog(struct perf_event *event) 9670 { 9671 } 9672 #endif /* CONFIG_EVENT_TRACING */ 9673 9674 #ifdef CONFIG_HAVE_HW_BREAKPOINT 9675 void perf_bp_event(struct perf_event *bp, void *data) 9676 { 9677 struct perf_sample_data sample; 9678 struct pt_regs *regs = data; 9679 9680 perf_sample_data_init(&sample, bp->attr.bp_addr, 0); 9681 9682 if (!bp->hw.state && !perf_exclude_event(bp, regs)) 9683 perf_swevent_event(bp, 1, &sample, regs); 9684 } 9685 #endif 9686 9687 /* 9688 * Allocate a new address filter 9689 */ 9690 static struct perf_addr_filter * 9691 perf_addr_filter_new(struct perf_event *event, struct list_head *filters) 9692 { 9693 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu); 9694 struct perf_addr_filter *filter; 9695 9696 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node); 9697 if (!filter) 9698 return NULL; 9699 9700 INIT_LIST_HEAD(&filter->entry); 9701 list_add_tail(&filter->entry, filters); 9702 9703 return filter; 9704 } 9705 9706 static void free_filters_list(struct list_head *filters) 9707 { 9708 struct perf_addr_filter *filter, *iter; 9709 9710 list_for_each_entry_safe(filter, iter, filters, entry) { 9711 path_put(&filter->path); 9712 list_del(&filter->entry); 9713 kfree(filter); 9714 } 9715 } 9716 9717 /* 9718 * Free existing address filters and optionally install new ones 9719 */ 9720 static void perf_addr_filters_splice(struct perf_event *event, 9721 struct list_head *head) 9722 { 9723 unsigned long flags; 9724 LIST_HEAD(list); 9725 9726 if (!has_addr_filter(event)) 9727 return; 9728 9729 /* don't bother with children, they don't have their own filters */ 9730 if (event->parent) 9731 return; 9732 9733 raw_spin_lock_irqsave(&event->addr_filters.lock, flags); 9734 9735 list_splice_init(&event->addr_filters.list, &list); 9736 if (head) 9737 list_splice(head, &event->addr_filters.list); 9738 9739 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags); 9740 9741 free_filters_list(&list); 9742 } 9743 9744 /* 9745 * Scan through mm's vmas and see if one of them matches the 9746 * @filter; if so, adjust filter's address range. 9747 * Called with mm::mmap_sem down for reading. 9748 */ 9749 static void perf_addr_filter_apply(struct perf_addr_filter *filter, 9750 struct mm_struct *mm, 9751 struct perf_addr_filter_range *fr) 9752 { 9753 struct vm_area_struct *vma; 9754 9755 for (vma = mm->mmap; vma; vma = vma->vm_next) { 9756 if (!vma->vm_file) 9757 continue; 9758 9759 if (perf_addr_filter_vma_adjust(filter, vma, fr)) 9760 return; 9761 } 9762 } 9763 9764 /* 9765 * Update event's address range filters based on the 9766 * task's existing mappings, if any. 9767 */ 9768 static void perf_event_addr_filters_apply(struct perf_event *event) 9769 { 9770 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 9771 struct task_struct *task = READ_ONCE(event->ctx->task); 9772 struct perf_addr_filter *filter; 9773 struct mm_struct *mm = NULL; 9774 unsigned int count = 0; 9775 unsigned long flags; 9776 9777 /* 9778 * We may observe TASK_TOMBSTONE, which means that the event tear-down 9779 * will stop on the parent's child_mutex that our caller is also holding 9780 */ 9781 if (task == TASK_TOMBSTONE) 9782 return; 9783 9784 if (ifh->nr_file_filters) { 9785 mm = get_task_mm(event->ctx->task); 9786 if (!mm) 9787 goto restart; 9788 9789 down_read(&mm->mmap_sem); 9790 } 9791 9792 raw_spin_lock_irqsave(&ifh->lock, flags); 9793 list_for_each_entry(filter, &ifh->list, entry) { 9794 if (filter->path.dentry) { 9795 /* 9796 * Adjust base offset if the filter is associated to a 9797 * binary that needs to be mapped: 9798 */ 9799 event->addr_filter_ranges[count].start = 0; 9800 event->addr_filter_ranges[count].size = 0; 9801 9802 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]); 9803 } else { 9804 event->addr_filter_ranges[count].start = filter->offset; 9805 event->addr_filter_ranges[count].size = filter->size; 9806 } 9807 9808 count++; 9809 } 9810 9811 event->addr_filters_gen++; 9812 raw_spin_unlock_irqrestore(&ifh->lock, flags); 9813 9814 if (ifh->nr_file_filters) { 9815 up_read(&mm->mmap_sem); 9816 9817 mmput(mm); 9818 } 9819 9820 restart: 9821 perf_event_stop(event, 1); 9822 } 9823 9824 /* 9825 * Address range filtering: limiting the data to certain 9826 * instruction address ranges. Filters are ioctl()ed to us from 9827 * userspace as ascii strings. 9828 * 9829 * Filter string format: 9830 * 9831 * ACTION RANGE_SPEC 9832 * where ACTION is one of the 9833 * * "filter": limit the trace to this region 9834 * * "start": start tracing from this address 9835 * * "stop": stop tracing at this address/region; 9836 * RANGE_SPEC is 9837 * * for kernel addresses: <start address>[/<size>] 9838 * * for object files: <start address>[/<size>]@</path/to/object/file> 9839 * 9840 * if <size> is not specified or is zero, the range is treated as a single 9841 * address; not valid for ACTION=="filter". 9842 */ 9843 enum { 9844 IF_ACT_NONE = -1, 9845 IF_ACT_FILTER, 9846 IF_ACT_START, 9847 IF_ACT_STOP, 9848 IF_SRC_FILE, 9849 IF_SRC_KERNEL, 9850 IF_SRC_FILEADDR, 9851 IF_SRC_KERNELADDR, 9852 }; 9853 9854 enum { 9855 IF_STATE_ACTION = 0, 9856 IF_STATE_SOURCE, 9857 IF_STATE_END, 9858 }; 9859 9860 static const match_table_t if_tokens = { 9861 { IF_ACT_FILTER, "filter" }, 9862 { IF_ACT_START, "start" }, 9863 { IF_ACT_STOP, "stop" }, 9864 { IF_SRC_FILE, "%u/%u@%s" }, 9865 { IF_SRC_KERNEL, "%u/%u" }, 9866 { IF_SRC_FILEADDR, "%u@%s" }, 9867 { IF_SRC_KERNELADDR, "%u" }, 9868 { IF_ACT_NONE, NULL }, 9869 }; 9870 9871 /* 9872 * Address filter string parser 9873 */ 9874 static int 9875 perf_event_parse_addr_filter(struct perf_event *event, char *fstr, 9876 struct list_head *filters) 9877 { 9878 struct perf_addr_filter *filter = NULL; 9879 char *start, *orig, *filename = NULL; 9880 substring_t args[MAX_OPT_ARGS]; 9881 int state = IF_STATE_ACTION, token; 9882 unsigned int kernel = 0; 9883 int ret = -EINVAL; 9884 9885 orig = fstr = kstrdup(fstr, GFP_KERNEL); 9886 if (!fstr) 9887 return -ENOMEM; 9888 9889 while ((start = strsep(&fstr, " ,\n")) != NULL) { 9890 static const enum perf_addr_filter_action_t actions[] = { 9891 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER, 9892 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START, 9893 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP, 9894 }; 9895 ret = -EINVAL; 9896 9897 if (!*start) 9898 continue; 9899 9900 /* filter definition begins */ 9901 if (state == IF_STATE_ACTION) { 9902 filter = perf_addr_filter_new(event, filters); 9903 if (!filter) 9904 goto fail; 9905 } 9906 9907 token = match_token(start, if_tokens, args); 9908 switch (token) { 9909 case IF_ACT_FILTER: 9910 case IF_ACT_START: 9911 case IF_ACT_STOP: 9912 if (state != IF_STATE_ACTION) 9913 goto fail; 9914 9915 filter->action = actions[token]; 9916 state = IF_STATE_SOURCE; 9917 break; 9918 9919 case IF_SRC_KERNELADDR: 9920 case IF_SRC_KERNEL: 9921 kernel = 1; 9922 /* fall through */ 9923 9924 case IF_SRC_FILEADDR: 9925 case IF_SRC_FILE: 9926 if (state != IF_STATE_SOURCE) 9927 goto fail; 9928 9929 *args[0].to = 0; 9930 ret = kstrtoul(args[0].from, 0, &filter->offset); 9931 if (ret) 9932 goto fail; 9933 9934 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) { 9935 *args[1].to = 0; 9936 ret = kstrtoul(args[1].from, 0, &filter->size); 9937 if (ret) 9938 goto fail; 9939 } 9940 9941 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) { 9942 int fpos = token == IF_SRC_FILE ? 2 : 1; 9943 9944 filename = match_strdup(&args[fpos]); 9945 if (!filename) { 9946 ret = -ENOMEM; 9947 goto fail; 9948 } 9949 } 9950 9951 state = IF_STATE_END; 9952 break; 9953 9954 default: 9955 goto fail; 9956 } 9957 9958 /* 9959 * Filter definition is fully parsed, validate and install it. 9960 * Make sure that it doesn't contradict itself or the event's 9961 * attribute. 9962 */ 9963 if (state == IF_STATE_END) { 9964 ret = -EINVAL; 9965 if (kernel && event->attr.exclude_kernel) 9966 goto fail; 9967 9968 /* 9969 * ACTION "filter" must have a non-zero length region 9970 * specified. 9971 */ 9972 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER && 9973 !filter->size) 9974 goto fail; 9975 9976 if (!kernel) { 9977 if (!filename) 9978 goto fail; 9979 9980 /* 9981 * For now, we only support file-based filters 9982 * in per-task events; doing so for CPU-wide 9983 * events requires additional context switching 9984 * trickery, since same object code will be 9985 * mapped at different virtual addresses in 9986 * different processes. 9987 */ 9988 ret = -EOPNOTSUPP; 9989 if (!event->ctx->task) 9990 goto fail_free_name; 9991 9992 /* look up the path and grab its inode */ 9993 ret = kern_path(filename, LOOKUP_FOLLOW, 9994 &filter->path); 9995 if (ret) 9996 goto fail_free_name; 9997 9998 kfree(filename); 9999 filename = NULL; 10000 10001 ret = -EINVAL; 10002 if (!filter->path.dentry || 10003 !S_ISREG(d_inode(filter->path.dentry) 10004 ->i_mode)) 10005 goto fail; 10006 10007 event->addr_filters.nr_file_filters++; 10008 } 10009 10010 /* ready to consume more filters */ 10011 state = IF_STATE_ACTION; 10012 filter = NULL; 10013 } 10014 } 10015 10016 if (state != IF_STATE_ACTION) 10017 goto fail; 10018 10019 kfree(orig); 10020 10021 return 0; 10022 10023 fail_free_name: 10024 kfree(filename); 10025 fail: 10026 free_filters_list(filters); 10027 kfree(orig); 10028 10029 return ret; 10030 } 10031 10032 static int 10033 perf_event_set_addr_filter(struct perf_event *event, char *filter_str) 10034 { 10035 LIST_HEAD(filters); 10036 int ret; 10037 10038 /* 10039 * Since this is called in perf_ioctl() path, we're already holding 10040 * ctx::mutex. 10041 */ 10042 lockdep_assert_held(&event->ctx->mutex); 10043 10044 if (WARN_ON_ONCE(event->parent)) 10045 return -EINVAL; 10046 10047 ret = perf_event_parse_addr_filter(event, filter_str, &filters); 10048 if (ret) 10049 goto fail_clear_files; 10050 10051 ret = event->pmu->addr_filters_validate(&filters); 10052 if (ret) 10053 goto fail_free_filters; 10054 10055 /* remove existing filters, if any */ 10056 perf_addr_filters_splice(event, &filters); 10057 10058 /* install new filters */ 10059 perf_event_for_each_child(event, perf_event_addr_filters_apply); 10060 10061 return ret; 10062 10063 fail_free_filters: 10064 free_filters_list(&filters); 10065 10066 fail_clear_files: 10067 event->addr_filters.nr_file_filters = 0; 10068 10069 return ret; 10070 } 10071 10072 static int perf_event_set_filter(struct perf_event *event, void __user *arg) 10073 { 10074 int ret = -EINVAL; 10075 char *filter_str; 10076 10077 filter_str = strndup_user(arg, PAGE_SIZE); 10078 if (IS_ERR(filter_str)) 10079 return PTR_ERR(filter_str); 10080 10081 #ifdef CONFIG_EVENT_TRACING 10082 if (perf_event_is_tracing(event)) { 10083 struct perf_event_context *ctx = event->ctx; 10084 10085 /* 10086 * Beware, here be dragons!! 10087 * 10088 * the tracepoint muck will deadlock against ctx->mutex, but 10089 * the tracepoint stuff does not actually need it. So 10090 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we 10091 * already have a reference on ctx. 10092 * 10093 * This can result in event getting moved to a different ctx, 10094 * but that does not affect the tracepoint state. 10095 */ 10096 mutex_unlock(&ctx->mutex); 10097 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str); 10098 mutex_lock(&ctx->mutex); 10099 } else 10100 #endif 10101 if (has_addr_filter(event)) 10102 ret = perf_event_set_addr_filter(event, filter_str); 10103 10104 kfree(filter_str); 10105 return ret; 10106 } 10107 10108 /* 10109 * hrtimer based swevent callback 10110 */ 10111 10112 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer) 10113 { 10114 enum hrtimer_restart ret = HRTIMER_RESTART; 10115 struct perf_sample_data data; 10116 struct pt_regs *regs; 10117 struct perf_event *event; 10118 u64 period; 10119 10120 event = container_of(hrtimer, struct perf_event, hw.hrtimer); 10121 10122 if (event->state != PERF_EVENT_STATE_ACTIVE) 10123 return HRTIMER_NORESTART; 10124 10125 event->pmu->read(event); 10126 10127 perf_sample_data_init(&data, 0, event->hw.last_period); 10128 regs = get_irq_regs(); 10129 10130 if (regs && !perf_exclude_event(event, regs)) { 10131 if (!(event->attr.exclude_idle && is_idle_task(current))) 10132 if (__perf_event_overflow(event, 1, &data, regs)) 10133 ret = HRTIMER_NORESTART; 10134 } 10135 10136 period = max_t(u64, 10000, event->hw.sample_period); 10137 hrtimer_forward_now(hrtimer, ns_to_ktime(period)); 10138 10139 return ret; 10140 } 10141 10142 static void perf_swevent_start_hrtimer(struct perf_event *event) 10143 { 10144 struct hw_perf_event *hwc = &event->hw; 10145 s64 period; 10146 10147 if (!is_sampling_event(event)) 10148 return; 10149 10150 period = local64_read(&hwc->period_left); 10151 if (period) { 10152 if (period < 0) 10153 period = 10000; 10154 10155 local64_set(&hwc->period_left, 0); 10156 } else { 10157 period = max_t(u64, 10000, hwc->sample_period); 10158 } 10159 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period), 10160 HRTIMER_MODE_REL_PINNED_HARD); 10161 } 10162 10163 static void perf_swevent_cancel_hrtimer(struct perf_event *event) 10164 { 10165 struct hw_perf_event *hwc = &event->hw; 10166 10167 if (is_sampling_event(event)) { 10168 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer); 10169 local64_set(&hwc->period_left, ktime_to_ns(remaining)); 10170 10171 hrtimer_cancel(&hwc->hrtimer); 10172 } 10173 } 10174 10175 static void perf_swevent_init_hrtimer(struct perf_event *event) 10176 { 10177 struct hw_perf_event *hwc = &event->hw; 10178 10179 if (!is_sampling_event(event)) 10180 return; 10181 10182 hrtimer_init(&hwc->hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD); 10183 hwc->hrtimer.function = perf_swevent_hrtimer; 10184 10185 /* 10186 * Since hrtimers have a fixed rate, we can do a static freq->period 10187 * mapping and avoid the whole period adjust feedback stuff. 10188 */ 10189 if (event->attr.freq) { 10190 long freq = event->attr.sample_freq; 10191 10192 event->attr.sample_period = NSEC_PER_SEC / freq; 10193 hwc->sample_period = event->attr.sample_period; 10194 local64_set(&hwc->period_left, hwc->sample_period); 10195 hwc->last_period = hwc->sample_period; 10196 event->attr.freq = 0; 10197 } 10198 } 10199 10200 /* 10201 * Software event: cpu wall time clock 10202 */ 10203 10204 static void cpu_clock_event_update(struct perf_event *event) 10205 { 10206 s64 prev; 10207 u64 now; 10208 10209 now = local_clock(); 10210 prev = local64_xchg(&event->hw.prev_count, now); 10211 local64_add(now - prev, &event->count); 10212 } 10213 10214 static void cpu_clock_event_start(struct perf_event *event, int flags) 10215 { 10216 local64_set(&event->hw.prev_count, local_clock()); 10217 perf_swevent_start_hrtimer(event); 10218 } 10219 10220 static void cpu_clock_event_stop(struct perf_event *event, int flags) 10221 { 10222 perf_swevent_cancel_hrtimer(event); 10223 cpu_clock_event_update(event); 10224 } 10225 10226 static int cpu_clock_event_add(struct perf_event *event, int flags) 10227 { 10228 if (flags & PERF_EF_START) 10229 cpu_clock_event_start(event, flags); 10230 perf_event_update_userpage(event); 10231 10232 return 0; 10233 } 10234 10235 static void cpu_clock_event_del(struct perf_event *event, int flags) 10236 { 10237 cpu_clock_event_stop(event, flags); 10238 } 10239 10240 static void cpu_clock_event_read(struct perf_event *event) 10241 { 10242 cpu_clock_event_update(event); 10243 } 10244 10245 static int cpu_clock_event_init(struct perf_event *event) 10246 { 10247 if (event->attr.type != PERF_TYPE_SOFTWARE) 10248 return -ENOENT; 10249 10250 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK) 10251 return -ENOENT; 10252 10253 /* 10254 * no branch sampling for software events 10255 */ 10256 if (has_branch_stack(event)) 10257 return -EOPNOTSUPP; 10258 10259 perf_swevent_init_hrtimer(event); 10260 10261 return 0; 10262 } 10263 10264 static struct pmu perf_cpu_clock = { 10265 .task_ctx_nr = perf_sw_context, 10266 10267 .capabilities = PERF_PMU_CAP_NO_NMI, 10268 10269 .event_init = cpu_clock_event_init, 10270 .add = cpu_clock_event_add, 10271 .del = cpu_clock_event_del, 10272 .start = cpu_clock_event_start, 10273 .stop = cpu_clock_event_stop, 10274 .read = cpu_clock_event_read, 10275 }; 10276 10277 /* 10278 * Software event: task time clock 10279 */ 10280 10281 static void task_clock_event_update(struct perf_event *event, u64 now) 10282 { 10283 u64 prev; 10284 s64 delta; 10285 10286 prev = local64_xchg(&event->hw.prev_count, now); 10287 delta = now - prev; 10288 local64_add(delta, &event->count); 10289 } 10290 10291 static void task_clock_event_start(struct perf_event *event, int flags) 10292 { 10293 local64_set(&event->hw.prev_count, event->ctx->time); 10294 perf_swevent_start_hrtimer(event); 10295 } 10296 10297 static void task_clock_event_stop(struct perf_event *event, int flags) 10298 { 10299 perf_swevent_cancel_hrtimer(event); 10300 task_clock_event_update(event, event->ctx->time); 10301 } 10302 10303 static int task_clock_event_add(struct perf_event *event, int flags) 10304 { 10305 if (flags & PERF_EF_START) 10306 task_clock_event_start(event, flags); 10307 perf_event_update_userpage(event); 10308 10309 return 0; 10310 } 10311 10312 static void task_clock_event_del(struct perf_event *event, int flags) 10313 { 10314 task_clock_event_stop(event, PERF_EF_UPDATE); 10315 } 10316 10317 static void task_clock_event_read(struct perf_event *event) 10318 { 10319 u64 now = perf_clock(); 10320 u64 delta = now - event->ctx->timestamp; 10321 u64 time = event->ctx->time + delta; 10322 10323 task_clock_event_update(event, time); 10324 } 10325 10326 static int task_clock_event_init(struct perf_event *event) 10327 { 10328 if (event->attr.type != PERF_TYPE_SOFTWARE) 10329 return -ENOENT; 10330 10331 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK) 10332 return -ENOENT; 10333 10334 /* 10335 * no branch sampling for software events 10336 */ 10337 if (has_branch_stack(event)) 10338 return -EOPNOTSUPP; 10339 10340 perf_swevent_init_hrtimer(event); 10341 10342 return 0; 10343 } 10344 10345 static struct pmu perf_task_clock = { 10346 .task_ctx_nr = perf_sw_context, 10347 10348 .capabilities = PERF_PMU_CAP_NO_NMI, 10349 10350 .event_init = task_clock_event_init, 10351 .add = task_clock_event_add, 10352 .del = task_clock_event_del, 10353 .start = task_clock_event_start, 10354 .stop = task_clock_event_stop, 10355 .read = task_clock_event_read, 10356 }; 10357 10358 static void perf_pmu_nop_void(struct pmu *pmu) 10359 { 10360 } 10361 10362 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags) 10363 { 10364 } 10365 10366 static int perf_pmu_nop_int(struct pmu *pmu) 10367 { 10368 return 0; 10369 } 10370 10371 static int perf_event_nop_int(struct perf_event *event, u64 value) 10372 { 10373 return 0; 10374 } 10375 10376 static DEFINE_PER_CPU(unsigned int, nop_txn_flags); 10377 10378 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags) 10379 { 10380 __this_cpu_write(nop_txn_flags, flags); 10381 10382 if (flags & ~PERF_PMU_TXN_ADD) 10383 return; 10384 10385 perf_pmu_disable(pmu); 10386 } 10387 10388 static int perf_pmu_commit_txn(struct pmu *pmu) 10389 { 10390 unsigned int flags = __this_cpu_read(nop_txn_flags); 10391 10392 __this_cpu_write(nop_txn_flags, 0); 10393 10394 if (flags & ~PERF_PMU_TXN_ADD) 10395 return 0; 10396 10397 perf_pmu_enable(pmu); 10398 return 0; 10399 } 10400 10401 static void perf_pmu_cancel_txn(struct pmu *pmu) 10402 { 10403 unsigned int flags = __this_cpu_read(nop_txn_flags); 10404 10405 __this_cpu_write(nop_txn_flags, 0); 10406 10407 if (flags & ~PERF_PMU_TXN_ADD) 10408 return; 10409 10410 perf_pmu_enable(pmu); 10411 } 10412 10413 static int perf_event_idx_default(struct perf_event *event) 10414 { 10415 return 0; 10416 } 10417 10418 /* 10419 * Ensures all contexts with the same task_ctx_nr have the same 10420 * pmu_cpu_context too. 10421 */ 10422 static struct perf_cpu_context __percpu *find_pmu_context(int ctxn) 10423 { 10424 struct pmu *pmu; 10425 10426 if (ctxn < 0) 10427 return NULL; 10428 10429 list_for_each_entry(pmu, &pmus, entry) { 10430 if (pmu->task_ctx_nr == ctxn) 10431 return pmu->pmu_cpu_context; 10432 } 10433 10434 return NULL; 10435 } 10436 10437 static void free_pmu_context(struct pmu *pmu) 10438 { 10439 /* 10440 * Static contexts such as perf_sw_context have a global lifetime 10441 * and may be shared between different PMUs. Avoid freeing them 10442 * when a single PMU is going away. 10443 */ 10444 if (pmu->task_ctx_nr > perf_invalid_context) 10445 return; 10446 10447 free_percpu(pmu->pmu_cpu_context); 10448 } 10449 10450 /* 10451 * Let userspace know that this PMU supports address range filtering: 10452 */ 10453 static ssize_t nr_addr_filters_show(struct device *dev, 10454 struct device_attribute *attr, 10455 char *page) 10456 { 10457 struct pmu *pmu = dev_get_drvdata(dev); 10458 10459 return snprintf(page, PAGE_SIZE - 1, "%d\n", pmu->nr_addr_filters); 10460 } 10461 DEVICE_ATTR_RO(nr_addr_filters); 10462 10463 static struct idr pmu_idr; 10464 10465 static ssize_t 10466 type_show(struct device *dev, struct device_attribute *attr, char *page) 10467 { 10468 struct pmu *pmu = dev_get_drvdata(dev); 10469 10470 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->type); 10471 } 10472 static DEVICE_ATTR_RO(type); 10473 10474 static ssize_t 10475 perf_event_mux_interval_ms_show(struct device *dev, 10476 struct device_attribute *attr, 10477 char *page) 10478 { 10479 struct pmu *pmu = dev_get_drvdata(dev); 10480 10481 return snprintf(page, PAGE_SIZE-1, "%d\n", pmu->hrtimer_interval_ms); 10482 } 10483 10484 static DEFINE_MUTEX(mux_interval_mutex); 10485 10486 static ssize_t 10487 perf_event_mux_interval_ms_store(struct device *dev, 10488 struct device_attribute *attr, 10489 const char *buf, size_t count) 10490 { 10491 struct pmu *pmu = dev_get_drvdata(dev); 10492 int timer, cpu, ret; 10493 10494 ret = kstrtoint(buf, 0, &timer); 10495 if (ret) 10496 return ret; 10497 10498 if (timer < 1) 10499 return -EINVAL; 10500 10501 /* same value, noting to do */ 10502 if (timer == pmu->hrtimer_interval_ms) 10503 return count; 10504 10505 mutex_lock(&mux_interval_mutex); 10506 pmu->hrtimer_interval_ms = timer; 10507 10508 /* update all cpuctx for this PMU */ 10509 cpus_read_lock(); 10510 for_each_online_cpu(cpu) { 10511 struct perf_cpu_context *cpuctx; 10512 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); 10513 cpuctx->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); 10514 10515 cpu_function_call(cpu, 10516 (remote_function_f)perf_mux_hrtimer_restart, cpuctx); 10517 } 10518 cpus_read_unlock(); 10519 mutex_unlock(&mux_interval_mutex); 10520 10521 return count; 10522 } 10523 static DEVICE_ATTR_RW(perf_event_mux_interval_ms); 10524 10525 static struct attribute *pmu_dev_attrs[] = { 10526 &dev_attr_type.attr, 10527 &dev_attr_perf_event_mux_interval_ms.attr, 10528 NULL, 10529 }; 10530 ATTRIBUTE_GROUPS(pmu_dev); 10531 10532 static int pmu_bus_running; 10533 static struct bus_type pmu_bus = { 10534 .name = "event_source", 10535 .dev_groups = pmu_dev_groups, 10536 }; 10537 10538 static void pmu_dev_release(struct device *dev) 10539 { 10540 kfree(dev); 10541 } 10542 10543 static int pmu_dev_alloc(struct pmu *pmu) 10544 { 10545 int ret = -ENOMEM; 10546 10547 pmu->dev = kzalloc(sizeof(struct device), GFP_KERNEL); 10548 if (!pmu->dev) 10549 goto out; 10550 10551 pmu->dev->groups = pmu->attr_groups; 10552 device_initialize(pmu->dev); 10553 ret = dev_set_name(pmu->dev, "%s", pmu->name); 10554 if (ret) 10555 goto free_dev; 10556 10557 dev_set_drvdata(pmu->dev, pmu); 10558 pmu->dev->bus = &pmu_bus; 10559 pmu->dev->release = pmu_dev_release; 10560 ret = device_add(pmu->dev); 10561 if (ret) 10562 goto free_dev; 10563 10564 /* For PMUs with address filters, throw in an extra attribute: */ 10565 if (pmu->nr_addr_filters) 10566 ret = device_create_file(pmu->dev, &dev_attr_nr_addr_filters); 10567 10568 if (ret) 10569 goto del_dev; 10570 10571 if (pmu->attr_update) 10572 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update); 10573 10574 if (ret) 10575 goto del_dev; 10576 10577 out: 10578 return ret; 10579 10580 del_dev: 10581 device_del(pmu->dev); 10582 10583 free_dev: 10584 put_device(pmu->dev); 10585 goto out; 10586 } 10587 10588 static struct lock_class_key cpuctx_mutex; 10589 static struct lock_class_key cpuctx_lock; 10590 10591 int perf_pmu_register(struct pmu *pmu, const char *name, int type) 10592 { 10593 int cpu, ret, max = PERF_TYPE_MAX; 10594 10595 mutex_lock(&pmus_lock); 10596 ret = -ENOMEM; 10597 pmu->pmu_disable_count = alloc_percpu(int); 10598 if (!pmu->pmu_disable_count) 10599 goto unlock; 10600 10601 pmu->type = -1; 10602 if (!name) 10603 goto skip_type; 10604 pmu->name = name; 10605 10606 if (type != PERF_TYPE_SOFTWARE) { 10607 if (type >= 0) 10608 max = type; 10609 10610 ret = idr_alloc(&pmu_idr, pmu, max, 0, GFP_KERNEL); 10611 if (ret < 0) 10612 goto free_pdc; 10613 10614 WARN_ON(type >= 0 && ret != type); 10615 10616 type = ret; 10617 } 10618 pmu->type = type; 10619 10620 if (pmu_bus_running) { 10621 ret = pmu_dev_alloc(pmu); 10622 if (ret) 10623 goto free_idr; 10624 } 10625 10626 skip_type: 10627 if (pmu->task_ctx_nr == perf_hw_context) { 10628 static int hw_context_taken = 0; 10629 10630 /* 10631 * Other than systems with heterogeneous CPUs, it never makes 10632 * sense for two PMUs to share perf_hw_context. PMUs which are 10633 * uncore must use perf_invalid_context. 10634 */ 10635 if (WARN_ON_ONCE(hw_context_taken && 10636 !(pmu->capabilities & PERF_PMU_CAP_HETEROGENEOUS_CPUS))) 10637 pmu->task_ctx_nr = perf_invalid_context; 10638 10639 hw_context_taken = 1; 10640 } 10641 10642 pmu->pmu_cpu_context = find_pmu_context(pmu->task_ctx_nr); 10643 if (pmu->pmu_cpu_context) 10644 goto got_cpu_context; 10645 10646 ret = -ENOMEM; 10647 pmu->pmu_cpu_context = alloc_percpu(struct perf_cpu_context); 10648 if (!pmu->pmu_cpu_context) 10649 goto free_dev; 10650 10651 for_each_possible_cpu(cpu) { 10652 struct perf_cpu_context *cpuctx; 10653 10654 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); 10655 __perf_event_init_context(&cpuctx->ctx); 10656 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); 10657 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); 10658 cpuctx->ctx.pmu = pmu; 10659 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask); 10660 10661 __perf_mux_hrtimer_init(cpuctx, cpu); 10662 10663 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default); 10664 cpuctx->heap = cpuctx->heap_default; 10665 } 10666 10667 got_cpu_context: 10668 if (!pmu->start_txn) { 10669 if (pmu->pmu_enable) { 10670 /* 10671 * If we have pmu_enable/pmu_disable calls, install 10672 * transaction stubs that use that to try and batch 10673 * hardware accesses. 10674 */ 10675 pmu->start_txn = perf_pmu_start_txn; 10676 pmu->commit_txn = perf_pmu_commit_txn; 10677 pmu->cancel_txn = perf_pmu_cancel_txn; 10678 } else { 10679 pmu->start_txn = perf_pmu_nop_txn; 10680 pmu->commit_txn = perf_pmu_nop_int; 10681 pmu->cancel_txn = perf_pmu_nop_void; 10682 } 10683 } 10684 10685 if (!pmu->pmu_enable) { 10686 pmu->pmu_enable = perf_pmu_nop_void; 10687 pmu->pmu_disable = perf_pmu_nop_void; 10688 } 10689 10690 if (!pmu->check_period) 10691 pmu->check_period = perf_event_nop_int; 10692 10693 if (!pmu->event_idx) 10694 pmu->event_idx = perf_event_idx_default; 10695 10696 /* 10697 * Ensure the TYPE_SOFTWARE PMUs are at the head of the list, 10698 * since these cannot be in the IDR. This way the linear search 10699 * is fast, provided a valid software event is provided. 10700 */ 10701 if (type == PERF_TYPE_SOFTWARE || !name) 10702 list_add_rcu(&pmu->entry, &pmus); 10703 else 10704 list_add_tail_rcu(&pmu->entry, &pmus); 10705 10706 atomic_set(&pmu->exclusive_cnt, 0); 10707 ret = 0; 10708 unlock: 10709 mutex_unlock(&pmus_lock); 10710 10711 return ret; 10712 10713 free_dev: 10714 device_del(pmu->dev); 10715 put_device(pmu->dev); 10716 10717 free_idr: 10718 if (pmu->type != PERF_TYPE_SOFTWARE) 10719 idr_remove(&pmu_idr, pmu->type); 10720 10721 free_pdc: 10722 free_percpu(pmu->pmu_disable_count); 10723 goto unlock; 10724 } 10725 EXPORT_SYMBOL_GPL(perf_pmu_register); 10726 10727 void perf_pmu_unregister(struct pmu *pmu) 10728 { 10729 mutex_lock(&pmus_lock); 10730 list_del_rcu(&pmu->entry); 10731 10732 /* 10733 * We dereference the pmu list under both SRCU and regular RCU, so 10734 * synchronize against both of those. 10735 */ 10736 synchronize_srcu(&pmus_srcu); 10737 synchronize_rcu(); 10738 10739 free_percpu(pmu->pmu_disable_count); 10740 if (pmu->type != PERF_TYPE_SOFTWARE) 10741 idr_remove(&pmu_idr, pmu->type); 10742 if (pmu_bus_running) { 10743 if (pmu->nr_addr_filters) 10744 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters); 10745 device_del(pmu->dev); 10746 put_device(pmu->dev); 10747 } 10748 free_pmu_context(pmu); 10749 mutex_unlock(&pmus_lock); 10750 } 10751 EXPORT_SYMBOL_GPL(perf_pmu_unregister); 10752 10753 static inline bool has_extended_regs(struct perf_event *event) 10754 { 10755 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) || 10756 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK); 10757 } 10758 10759 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) 10760 { 10761 struct perf_event_context *ctx = NULL; 10762 int ret; 10763 10764 if (!try_module_get(pmu->module)) 10765 return -ENODEV; 10766 10767 /* 10768 * A number of pmu->event_init() methods iterate the sibling_list to, 10769 * for example, validate if the group fits on the PMU. Therefore, 10770 * if this is a sibling event, acquire the ctx->mutex to protect 10771 * the sibling_list. 10772 */ 10773 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) { 10774 /* 10775 * This ctx->mutex can nest when we're called through 10776 * inheritance. See the perf_event_ctx_lock_nested() comment. 10777 */ 10778 ctx = perf_event_ctx_lock_nested(event->group_leader, 10779 SINGLE_DEPTH_NESTING); 10780 BUG_ON(!ctx); 10781 } 10782 10783 event->pmu = pmu; 10784 ret = pmu->event_init(event); 10785 10786 if (ctx) 10787 perf_event_ctx_unlock(event->group_leader, ctx); 10788 10789 if (!ret) { 10790 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) && 10791 has_extended_regs(event)) 10792 ret = -EOPNOTSUPP; 10793 10794 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE && 10795 event_has_any_exclude_flag(event)) 10796 ret = -EINVAL; 10797 10798 if (ret && event->destroy) 10799 event->destroy(event); 10800 } 10801 10802 if (ret) 10803 module_put(pmu->module); 10804 10805 return ret; 10806 } 10807 10808 static struct pmu *perf_init_event(struct perf_event *event) 10809 { 10810 int idx, type, ret; 10811 struct pmu *pmu; 10812 10813 idx = srcu_read_lock(&pmus_srcu); 10814 10815 /* Try parent's PMU first: */ 10816 if (event->parent && event->parent->pmu) { 10817 pmu = event->parent->pmu; 10818 ret = perf_try_init_event(pmu, event); 10819 if (!ret) 10820 goto unlock; 10821 } 10822 10823 /* 10824 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE 10825 * are often aliases for PERF_TYPE_RAW. 10826 */ 10827 type = event->attr.type; 10828 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) 10829 type = PERF_TYPE_RAW; 10830 10831 again: 10832 rcu_read_lock(); 10833 pmu = idr_find(&pmu_idr, type); 10834 rcu_read_unlock(); 10835 if (pmu) { 10836 ret = perf_try_init_event(pmu, event); 10837 if (ret == -ENOENT && event->attr.type != type) { 10838 type = event->attr.type; 10839 goto again; 10840 } 10841 10842 if (ret) 10843 pmu = ERR_PTR(ret); 10844 10845 goto unlock; 10846 } 10847 10848 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) { 10849 ret = perf_try_init_event(pmu, event); 10850 if (!ret) 10851 goto unlock; 10852 10853 if (ret != -ENOENT) { 10854 pmu = ERR_PTR(ret); 10855 goto unlock; 10856 } 10857 } 10858 pmu = ERR_PTR(-ENOENT); 10859 unlock: 10860 srcu_read_unlock(&pmus_srcu, idx); 10861 10862 return pmu; 10863 } 10864 10865 static void attach_sb_event(struct perf_event *event) 10866 { 10867 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 10868 10869 raw_spin_lock(&pel->lock); 10870 list_add_rcu(&event->sb_list, &pel->list); 10871 raw_spin_unlock(&pel->lock); 10872 } 10873 10874 /* 10875 * We keep a list of all !task (and therefore per-cpu) events 10876 * that need to receive side-band records. 10877 * 10878 * This avoids having to scan all the various PMU per-cpu contexts 10879 * looking for them. 10880 */ 10881 static void account_pmu_sb_event(struct perf_event *event) 10882 { 10883 if (is_sb_event(event)) 10884 attach_sb_event(event); 10885 } 10886 10887 static void account_event_cpu(struct perf_event *event, int cpu) 10888 { 10889 if (event->parent) 10890 return; 10891 10892 if (is_cgroup_event(event)) 10893 atomic_inc(&per_cpu(perf_cgroup_events, cpu)); 10894 } 10895 10896 /* Freq events need the tick to stay alive (see perf_event_task_tick). */ 10897 static void account_freq_event_nohz(void) 10898 { 10899 #ifdef CONFIG_NO_HZ_FULL 10900 /* Lock so we don't race with concurrent unaccount */ 10901 spin_lock(&nr_freq_lock); 10902 if (atomic_inc_return(&nr_freq_events) == 1) 10903 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS); 10904 spin_unlock(&nr_freq_lock); 10905 #endif 10906 } 10907 10908 static void account_freq_event(void) 10909 { 10910 if (tick_nohz_full_enabled()) 10911 account_freq_event_nohz(); 10912 else 10913 atomic_inc(&nr_freq_events); 10914 } 10915 10916 10917 static void account_event(struct perf_event *event) 10918 { 10919 bool inc = false; 10920 10921 if (event->parent) 10922 return; 10923 10924 if (event->attach_state & PERF_ATTACH_TASK) 10925 inc = true; 10926 if (event->attr.mmap || event->attr.mmap_data) 10927 atomic_inc(&nr_mmap_events); 10928 if (event->attr.comm) 10929 atomic_inc(&nr_comm_events); 10930 if (event->attr.namespaces) 10931 atomic_inc(&nr_namespaces_events); 10932 if (event->attr.cgroup) 10933 atomic_inc(&nr_cgroup_events); 10934 if (event->attr.task) 10935 atomic_inc(&nr_task_events); 10936 if (event->attr.freq) 10937 account_freq_event(); 10938 if (event->attr.context_switch) { 10939 atomic_inc(&nr_switch_events); 10940 inc = true; 10941 } 10942 if (has_branch_stack(event)) 10943 inc = true; 10944 if (is_cgroup_event(event)) 10945 inc = true; 10946 if (event->attr.ksymbol) 10947 atomic_inc(&nr_ksymbol_events); 10948 if (event->attr.bpf_event) 10949 atomic_inc(&nr_bpf_events); 10950 10951 if (inc) { 10952 /* 10953 * We need the mutex here because static_branch_enable() 10954 * must complete *before* the perf_sched_count increment 10955 * becomes visible. 10956 */ 10957 if (atomic_inc_not_zero(&perf_sched_count)) 10958 goto enabled; 10959 10960 mutex_lock(&perf_sched_mutex); 10961 if (!atomic_read(&perf_sched_count)) { 10962 static_branch_enable(&perf_sched_events); 10963 /* 10964 * Guarantee that all CPUs observe they key change and 10965 * call the perf scheduling hooks before proceeding to 10966 * install events that need them. 10967 */ 10968 synchronize_rcu(); 10969 } 10970 /* 10971 * Now that we have waited for the sync_sched(), allow further 10972 * increments to by-pass the mutex. 10973 */ 10974 atomic_inc(&perf_sched_count); 10975 mutex_unlock(&perf_sched_mutex); 10976 } 10977 enabled: 10978 10979 account_event_cpu(event, event->cpu); 10980 10981 account_pmu_sb_event(event); 10982 } 10983 10984 /* 10985 * Allocate and initialize an event structure 10986 */ 10987 static struct perf_event * 10988 perf_event_alloc(struct perf_event_attr *attr, int cpu, 10989 struct task_struct *task, 10990 struct perf_event *group_leader, 10991 struct perf_event *parent_event, 10992 perf_overflow_handler_t overflow_handler, 10993 void *context, int cgroup_fd) 10994 { 10995 struct pmu *pmu; 10996 struct perf_event *event; 10997 struct hw_perf_event *hwc; 10998 long err = -EINVAL; 10999 11000 if ((unsigned)cpu >= nr_cpu_ids) { 11001 if (!task || cpu != -1) 11002 return ERR_PTR(-EINVAL); 11003 } 11004 11005 event = kzalloc(sizeof(*event), GFP_KERNEL); 11006 if (!event) 11007 return ERR_PTR(-ENOMEM); 11008 11009 /* 11010 * Single events are their own group leaders, with an 11011 * empty sibling list: 11012 */ 11013 if (!group_leader) 11014 group_leader = event; 11015 11016 mutex_init(&event->child_mutex); 11017 INIT_LIST_HEAD(&event->child_list); 11018 11019 INIT_LIST_HEAD(&event->event_entry); 11020 INIT_LIST_HEAD(&event->sibling_list); 11021 INIT_LIST_HEAD(&event->active_list); 11022 init_event_group(event); 11023 INIT_LIST_HEAD(&event->rb_entry); 11024 INIT_LIST_HEAD(&event->active_entry); 11025 INIT_LIST_HEAD(&event->addr_filters.list); 11026 INIT_HLIST_NODE(&event->hlist_entry); 11027 11028 11029 init_waitqueue_head(&event->waitq); 11030 event->pending_disable = -1; 11031 init_irq_work(&event->pending, perf_pending_event); 11032 11033 mutex_init(&event->mmap_mutex); 11034 raw_spin_lock_init(&event->addr_filters.lock); 11035 11036 atomic_long_set(&event->refcount, 1); 11037 event->cpu = cpu; 11038 event->attr = *attr; 11039 event->group_leader = group_leader; 11040 event->pmu = NULL; 11041 event->oncpu = -1; 11042 11043 event->parent = parent_event; 11044 11045 event->ns = get_pid_ns(task_active_pid_ns(current)); 11046 event->id = atomic64_inc_return(&perf_event_id); 11047 11048 event->state = PERF_EVENT_STATE_INACTIVE; 11049 11050 if (task) { 11051 event->attach_state = PERF_ATTACH_TASK; 11052 /* 11053 * XXX pmu::event_init needs to know what task to account to 11054 * and we cannot use the ctx information because we need the 11055 * pmu before we get a ctx. 11056 */ 11057 event->hw.target = get_task_struct(task); 11058 } 11059 11060 event->clock = &local_clock; 11061 if (parent_event) 11062 event->clock = parent_event->clock; 11063 11064 if (!overflow_handler && parent_event) { 11065 overflow_handler = parent_event->overflow_handler; 11066 context = parent_event->overflow_handler_context; 11067 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING) 11068 if (overflow_handler == bpf_overflow_handler) { 11069 struct bpf_prog *prog = parent_event->prog; 11070 11071 bpf_prog_inc(prog); 11072 event->prog = prog; 11073 event->orig_overflow_handler = 11074 parent_event->orig_overflow_handler; 11075 } 11076 #endif 11077 } 11078 11079 if (overflow_handler) { 11080 event->overflow_handler = overflow_handler; 11081 event->overflow_handler_context = context; 11082 } else if (is_write_backward(event)){ 11083 event->overflow_handler = perf_event_output_backward; 11084 event->overflow_handler_context = NULL; 11085 } else { 11086 event->overflow_handler = perf_event_output_forward; 11087 event->overflow_handler_context = NULL; 11088 } 11089 11090 perf_event__state_init(event); 11091 11092 pmu = NULL; 11093 11094 hwc = &event->hw; 11095 hwc->sample_period = attr->sample_period; 11096 if (attr->freq && attr->sample_freq) 11097 hwc->sample_period = 1; 11098 hwc->last_period = hwc->sample_period; 11099 11100 local64_set(&hwc->period_left, hwc->sample_period); 11101 11102 /* 11103 * We currently do not support PERF_SAMPLE_READ on inherited events. 11104 * See perf_output_read(). 11105 */ 11106 if (attr->inherit && (attr->sample_type & PERF_SAMPLE_READ)) 11107 goto err_ns; 11108 11109 if (!has_branch_stack(event)) 11110 event->attr.branch_sample_type = 0; 11111 11112 pmu = perf_init_event(event); 11113 if (IS_ERR(pmu)) { 11114 err = PTR_ERR(pmu); 11115 goto err_ns; 11116 } 11117 11118 /* 11119 * Disallow uncore-cgroup events, they don't make sense as the cgroup will 11120 * be different on other CPUs in the uncore mask. 11121 */ 11122 if (pmu->task_ctx_nr == perf_invalid_context && cgroup_fd != -1) { 11123 err = -EINVAL; 11124 goto err_pmu; 11125 } 11126 11127 if (event->attr.aux_output && 11128 !(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT)) { 11129 err = -EOPNOTSUPP; 11130 goto err_pmu; 11131 } 11132 11133 if (cgroup_fd != -1) { 11134 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader); 11135 if (err) 11136 goto err_pmu; 11137 } 11138 11139 err = exclusive_event_init(event); 11140 if (err) 11141 goto err_pmu; 11142 11143 if (has_addr_filter(event)) { 11144 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters, 11145 sizeof(struct perf_addr_filter_range), 11146 GFP_KERNEL); 11147 if (!event->addr_filter_ranges) { 11148 err = -ENOMEM; 11149 goto err_per_task; 11150 } 11151 11152 /* 11153 * Clone the parent's vma offsets: they are valid until exec() 11154 * even if the mm is not shared with the parent. 11155 */ 11156 if (event->parent) { 11157 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 11158 11159 raw_spin_lock_irq(&ifh->lock); 11160 memcpy(event->addr_filter_ranges, 11161 event->parent->addr_filter_ranges, 11162 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range)); 11163 raw_spin_unlock_irq(&ifh->lock); 11164 } 11165 11166 /* force hw sync on the address filters */ 11167 event->addr_filters_gen = 1; 11168 } 11169 11170 if (!event->parent) { 11171 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) { 11172 err = get_callchain_buffers(attr->sample_max_stack); 11173 if (err) 11174 goto err_addr_filters; 11175 } 11176 } 11177 11178 err = security_perf_event_alloc(event); 11179 if (err) 11180 goto err_callchain_buffer; 11181 11182 /* symmetric to unaccount_event() in _free_event() */ 11183 account_event(event); 11184 11185 return event; 11186 11187 err_callchain_buffer: 11188 if (!event->parent) { 11189 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) 11190 put_callchain_buffers(); 11191 } 11192 err_addr_filters: 11193 kfree(event->addr_filter_ranges); 11194 11195 err_per_task: 11196 exclusive_event_destroy(event); 11197 11198 err_pmu: 11199 if (is_cgroup_event(event)) 11200 perf_detach_cgroup(event); 11201 if (event->destroy) 11202 event->destroy(event); 11203 module_put(pmu->module); 11204 err_ns: 11205 if (event->ns) 11206 put_pid_ns(event->ns); 11207 if (event->hw.target) 11208 put_task_struct(event->hw.target); 11209 kfree(event); 11210 11211 return ERR_PTR(err); 11212 } 11213 11214 static int perf_copy_attr(struct perf_event_attr __user *uattr, 11215 struct perf_event_attr *attr) 11216 { 11217 u32 size; 11218 int ret; 11219 11220 /* Zero the full structure, so that a short copy will be nice. */ 11221 memset(attr, 0, sizeof(*attr)); 11222 11223 ret = get_user(size, &uattr->size); 11224 if (ret) 11225 return ret; 11226 11227 /* ABI compatibility quirk: */ 11228 if (!size) 11229 size = PERF_ATTR_SIZE_VER0; 11230 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE) 11231 goto err_size; 11232 11233 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size); 11234 if (ret) { 11235 if (ret == -E2BIG) 11236 goto err_size; 11237 return ret; 11238 } 11239 11240 attr->size = size; 11241 11242 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3) 11243 return -EINVAL; 11244 11245 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) 11246 return -EINVAL; 11247 11248 if (attr->read_format & ~(PERF_FORMAT_MAX-1)) 11249 return -EINVAL; 11250 11251 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) { 11252 u64 mask = attr->branch_sample_type; 11253 11254 /* only using defined bits */ 11255 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1)) 11256 return -EINVAL; 11257 11258 /* at least one branch bit must be set */ 11259 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL)) 11260 return -EINVAL; 11261 11262 /* propagate priv level, when not set for branch */ 11263 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) { 11264 11265 /* exclude_kernel checked on syscall entry */ 11266 if (!attr->exclude_kernel) 11267 mask |= PERF_SAMPLE_BRANCH_KERNEL; 11268 11269 if (!attr->exclude_user) 11270 mask |= PERF_SAMPLE_BRANCH_USER; 11271 11272 if (!attr->exclude_hv) 11273 mask |= PERF_SAMPLE_BRANCH_HV; 11274 /* 11275 * adjust user setting (for HW filter setup) 11276 */ 11277 attr->branch_sample_type = mask; 11278 } 11279 /* privileged levels capture (kernel, hv): check permissions */ 11280 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) { 11281 ret = perf_allow_kernel(attr); 11282 if (ret) 11283 return ret; 11284 } 11285 } 11286 11287 if (attr->sample_type & PERF_SAMPLE_REGS_USER) { 11288 ret = perf_reg_validate(attr->sample_regs_user); 11289 if (ret) 11290 return ret; 11291 } 11292 11293 if (attr->sample_type & PERF_SAMPLE_STACK_USER) { 11294 if (!arch_perf_have_user_stack_dump()) 11295 return -ENOSYS; 11296 11297 /* 11298 * We have __u32 type for the size, but so far 11299 * we can only use __u16 as maximum due to the 11300 * __u16 sample size limit. 11301 */ 11302 if (attr->sample_stack_user >= USHRT_MAX) 11303 return -EINVAL; 11304 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64))) 11305 return -EINVAL; 11306 } 11307 11308 if (!attr->sample_max_stack) 11309 attr->sample_max_stack = sysctl_perf_event_max_stack; 11310 11311 if (attr->sample_type & PERF_SAMPLE_REGS_INTR) 11312 ret = perf_reg_validate(attr->sample_regs_intr); 11313 11314 #ifndef CONFIG_CGROUP_PERF 11315 if (attr->sample_type & PERF_SAMPLE_CGROUP) 11316 return -EINVAL; 11317 #endif 11318 11319 out: 11320 return ret; 11321 11322 err_size: 11323 put_user(sizeof(*attr), &uattr->size); 11324 ret = -E2BIG; 11325 goto out; 11326 } 11327 11328 static int 11329 perf_event_set_output(struct perf_event *event, struct perf_event *output_event) 11330 { 11331 struct perf_buffer *rb = NULL; 11332 int ret = -EINVAL; 11333 11334 if (!output_event) 11335 goto set; 11336 11337 /* don't allow circular references */ 11338 if (event == output_event) 11339 goto out; 11340 11341 /* 11342 * Don't allow cross-cpu buffers 11343 */ 11344 if (output_event->cpu != event->cpu) 11345 goto out; 11346 11347 /* 11348 * If its not a per-cpu rb, it must be the same task. 11349 */ 11350 if (output_event->cpu == -1 && output_event->ctx != event->ctx) 11351 goto out; 11352 11353 /* 11354 * Mixing clocks in the same buffer is trouble you don't need. 11355 */ 11356 if (output_event->clock != event->clock) 11357 goto out; 11358 11359 /* 11360 * Either writing ring buffer from beginning or from end. 11361 * Mixing is not allowed. 11362 */ 11363 if (is_write_backward(output_event) != is_write_backward(event)) 11364 goto out; 11365 11366 /* 11367 * If both events generate aux data, they must be on the same PMU 11368 */ 11369 if (has_aux(event) && has_aux(output_event) && 11370 event->pmu != output_event->pmu) 11371 goto out; 11372 11373 set: 11374 mutex_lock(&event->mmap_mutex); 11375 /* Can't redirect output if we've got an active mmap() */ 11376 if (atomic_read(&event->mmap_count)) 11377 goto unlock; 11378 11379 if (output_event) { 11380 /* get the rb we want to redirect to */ 11381 rb = ring_buffer_get(output_event); 11382 if (!rb) 11383 goto unlock; 11384 } 11385 11386 ring_buffer_attach(event, rb); 11387 11388 ret = 0; 11389 unlock: 11390 mutex_unlock(&event->mmap_mutex); 11391 11392 out: 11393 return ret; 11394 } 11395 11396 static void mutex_lock_double(struct mutex *a, struct mutex *b) 11397 { 11398 if (b < a) 11399 swap(a, b); 11400 11401 mutex_lock(a); 11402 mutex_lock_nested(b, SINGLE_DEPTH_NESTING); 11403 } 11404 11405 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id) 11406 { 11407 bool nmi_safe = false; 11408 11409 switch (clk_id) { 11410 case CLOCK_MONOTONIC: 11411 event->clock = &ktime_get_mono_fast_ns; 11412 nmi_safe = true; 11413 break; 11414 11415 case CLOCK_MONOTONIC_RAW: 11416 event->clock = &ktime_get_raw_fast_ns; 11417 nmi_safe = true; 11418 break; 11419 11420 case CLOCK_REALTIME: 11421 event->clock = &ktime_get_real_ns; 11422 break; 11423 11424 case CLOCK_BOOTTIME: 11425 event->clock = &ktime_get_boottime_ns; 11426 break; 11427 11428 case CLOCK_TAI: 11429 event->clock = &ktime_get_clocktai_ns; 11430 break; 11431 11432 default: 11433 return -EINVAL; 11434 } 11435 11436 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI)) 11437 return -EINVAL; 11438 11439 return 0; 11440 } 11441 11442 /* 11443 * Variation on perf_event_ctx_lock_nested(), except we take two context 11444 * mutexes. 11445 */ 11446 static struct perf_event_context * 11447 __perf_event_ctx_lock_double(struct perf_event *group_leader, 11448 struct perf_event_context *ctx) 11449 { 11450 struct perf_event_context *gctx; 11451 11452 again: 11453 rcu_read_lock(); 11454 gctx = READ_ONCE(group_leader->ctx); 11455 if (!refcount_inc_not_zero(&gctx->refcount)) { 11456 rcu_read_unlock(); 11457 goto again; 11458 } 11459 rcu_read_unlock(); 11460 11461 mutex_lock_double(&gctx->mutex, &ctx->mutex); 11462 11463 if (group_leader->ctx != gctx) { 11464 mutex_unlock(&ctx->mutex); 11465 mutex_unlock(&gctx->mutex); 11466 put_ctx(gctx); 11467 goto again; 11468 } 11469 11470 return gctx; 11471 } 11472 11473 /** 11474 * sys_perf_event_open - open a performance event, associate it to a task/cpu 11475 * 11476 * @attr_uptr: event_id type attributes for monitoring/sampling 11477 * @pid: target pid 11478 * @cpu: target cpu 11479 * @group_fd: group leader event fd 11480 */ 11481 SYSCALL_DEFINE5(perf_event_open, 11482 struct perf_event_attr __user *, attr_uptr, 11483 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) 11484 { 11485 struct perf_event *group_leader = NULL, *output_event = NULL; 11486 struct perf_event *event, *sibling; 11487 struct perf_event_attr attr; 11488 struct perf_event_context *ctx, *uninitialized_var(gctx); 11489 struct file *event_file = NULL; 11490 struct fd group = {NULL, 0}; 11491 struct task_struct *task = NULL; 11492 struct pmu *pmu; 11493 int event_fd; 11494 int move_group = 0; 11495 int err; 11496 int f_flags = O_RDWR; 11497 int cgroup_fd = -1; 11498 11499 /* for future expandability... */ 11500 if (flags & ~PERF_FLAG_ALL) 11501 return -EINVAL; 11502 11503 /* Do we allow access to perf_event_open(2) ? */ 11504 err = security_perf_event_open(&attr, PERF_SECURITY_OPEN); 11505 if (err) 11506 return err; 11507 11508 err = perf_copy_attr(attr_uptr, &attr); 11509 if (err) 11510 return err; 11511 11512 if (!attr.exclude_kernel) { 11513 err = perf_allow_kernel(&attr); 11514 if (err) 11515 return err; 11516 } 11517 11518 if (attr.namespaces) { 11519 if (!perfmon_capable()) 11520 return -EACCES; 11521 } 11522 11523 if (attr.freq) { 11524 if (attr.sample_freq > sysctl_perf_event_sample_rate) 11525 return -EINVAL; 11526 } else { 11527 if (attr.sample_period & (1ULL << 63)) 11528 return -EINVAL; 11529 } 11530 11531 /* Only privileged users can get physical addresses */ 11532 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) { 11533 err = perf_allow_kernel(&attr); 11534 if (err) 11535 return err; 11536 } 11537 11538 err = security_locked_down(LOCKDOWN_PERF); 11539 if (err && (attr.sample_type & PERF_SAMPLE_REGS_INTR)) 11540 /* REGS_INTR can leak data, lockdown must prevent this */ 11541 return err; 11542 11543 err = 0; 11544 11545 /* 11546 * In cgroup mode, the pid argument is used to pass the fd 11547 * opened to the cgroup directory in cgroupfs. The cpu argument 11548 * designates the cpu on which to monitor threads from that 11549 * cgroup. 11550 */ 11551 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) 11552 return -EINVAL; 11553 11554 if (flags & PERF_FLAG_FD_CLOEXEC) 11555 f_flags |= O_CLOEXEC; 11556 11557 event_fd = get_unused_fd_flags(f_flags); 11558 if (event_fd < 0) 11559 return event_fd; 11560 11561 if (group_fd != -1) { 11562 err = perf_fget_light(group_fd, &group); 11563 if (err) 11564 goto err_fd; 11565 group_leader = group.file->private_data; 11566 if (flags & PERF_FLAG_FD_OUTPUT) 11567 output_event = group_leader; 11568 if (flags & PERF_FLAG_FD_NO_GROUP) 11569 group_leader = NULL; 11570 } 11571 11572 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { 11573 task = find_lively_task_by_vpid(pid); 11574 if (IS_ERR(task)) { 11575 err = PTR_ERR(task); 11576 goto err_group_fd; 11577 } 11578 } 11579 11580 if (task && group_leader && 11581 group_leader->attr.inherit != attr.inherit) { 11582 err = -EINVAL; 11583 goto err_task; 11584 } 11585 11586 if (task) { 11587 err = mutex_lock_interruptible(&task->signal->exec_update_mutex); 11588 if (err) 11589 goto err_task; 11590 11591 /* 11592 * Reuse ptrace permission checks for now. 11593 * 11594 * We must hold exec_update_mutex across this and any potential 11595 * perf_install_in_context() call for this new event to 11596 * serialize against exec() altering our credentials (and the 11597 * perf_event_exit_task() that could imply). 11598 */ 11599 err = -EACCES; 11600 if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) 11601 goto err_cred; 11602 } 11603 11604 if (flags & PERF_FLAG_PID_CGROUP) 11605 cgroup_fd = pid; 11606 11607 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, 11608 NULL, NULL, cgroup_fd); 11609 if (IS_ERR(event)) { 11610 err = PTR_ERR(event); 11611 goto err_cred; 11612 } 11613 11614 if (is_sampling_event(event)) { 11615 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { 11616 err = -EOPNOTSUPP; 11617 goto err_alloc; 11618 } 11619 } 11620 11621 /* 11622 * Special case software events and allow them to be part of 11623 * any hardware group. 11624 */ 11625 pmu = event->pmu; 11626 11627 if (attr.use_clockid) { 11628 err = perf_event_set_clock(event, attr.clockid); 11629 if (err) 11630 goto err_alloc; 11631 } 11632 11633 if (pmu->task_ctx_nr == perf_sw_context) 11634 event->event_caps |= PERF_EV_CAP_SOFTWARE; 11635 11636 if (group_leader) { 11637 if (is_software_event(event) && 11638 !in_software_context(group_leader)) { 11639 /* 11640 * If the event is a sw event, but the group_leader 11641 * is on hw context. 11642 * 11643 * Allow the addition of software events to hw 11644 * groups, this is safe because software events 11645 * never fail to schedule. 11646 */ 11647 pmu = group_leader->ctx->pmu; 11648 } else if (!is_software_event(event) && 11649 is_software_event(group_leader) && 11650 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { 11651 /* 11652 * In case the group is a pure software group, and we 11653 * try to add a hardware event, move the whole group to 11654 * the hardware context. 11655 */ 11656 move_group = 1; 11657 } 11658 } 11659 11660 /* 11661 * Get the target context (task or percpu): 11662 */ 11663 ctx = find_get_context(pmu, task, event); 11664 if (IS_ERR(ctx)) { 11665 err = PTR_ERR(ctx); 11666 goto err_alloc; 11667 } 11668 11669 /* 11670 * Look up the group leader (we will attach this event to it): 11671 */ 11672 if (group_leader) { 11673 err = -EINVAL; 11674 11675 /* 11676 * Do not allow a recursive hierarchy (this new sibling 11677 * becoming part of another group-sibling): 11678 */ 11679 if (group_leader->group_leader != group_leader) 11680 goto err_context; 11681 11682 /* All events in a group should have the same clock */ 11683 if (group_leader->clock != event->clock) 11684 goto err_context; 11685 11686 /* 11687 * Make sure we're both events for the same CPU; 11688 * grouping events for different CPUs is broken; since 11689 * you can never concurrently schedule them anyhow. 11690 */ 11691 if (group_leader->cpu != event->cpu) 11692 goto err_context; 11693 11694 /* 11695 * Make sure we're both on the same task, or both 11696 * per-CPU events. 11697 */ 11698 if (group_leader->ctx->task != ctx->task) 11699 goto err_context; 11700 11701 /* 11702 * Do not allow to attach to a group in a different task 11703 * or CPU context. If we're moving SW events, we'll fix 11704 * this up later, so allow that. 11705 */ 11706 if (!move_group && group_leader->ctx != ctx) 11707 goto err_context; 11708 11709 /* 11710 * Only a group leader can be exclusive or pinned 11711 */ 11712 if (attr.exclusive || attr.pinned) 11713 goto err_context; 11714 } 11715 11716 if (output_event) { 11717 err = perf_event_set_output(event, output_event); 11718 if (err) 11719 goto err_context; 11720 } 11721 11722 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, 11723 f_flags); 11724 if (IS_ERR(event_file)) { 11725 err = PTR_ERR(event_file); 11726 event_file = NULL; 11727 goto err_context; 11728 } 11729 11730 if (move_group) { 11731 gctx = __perf_event_ctx_lock_double(group_leader, ctx); 11732 11733 if (gctx->task == TASK_TOMBSTONE) { 11734 err = -ESRCH; 11735 goto err_locked; 11736 } 11737 11738 /* 11739 * Check if we raced against another sys_perf_event_open() call 11740 * moving the software group underneath us. 11741 */ 11742 if (!(group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { 11743 /* 11744 * If someone moved the group out from under us, check 11745 * if this new event wound up on the same ctx, if so 11746 * its the regular !move_group case, otherwise fail. 11747 */ 11748 if (gctx != ctx) { 11749 err = -EINVAL; 11750 goto err_locked; 11751 } else { 11752 perf_event_ctx_unlock(group_leader, gctx); 11753 move_group = 0; 11754 } 11755 } 11756 11757 /* 11758 * Failure to create exclusive events returns -EBUSY. 11759 */ 11760 err = -EBUSY; 11761 if (!exclusive_event_installable(group_leader, ctx)) 11762 goto err_locked; 11763 11764 for_each_sibling_event(sibling, group_leader) { 11765 if (!exclusive_event_installable(sibling, ctx)) 11766 goto err_locked; 11767 } 11768 } else { 11769 mutex_lock(&ctx->mutex); 11770 } 11771 11772 if (ctx->task == TASK_TOMBSTONE) { 11773 err = -ESRCH; 11774 goto err_locked; 11775 } 11776 11777 if (!perf_event_validate_size(event)) { 11778 err = -E2BIG; 11779 goto err_locked; 11780 } 11781 11782 if (!task) { 11783 /* 11784 * Check if the @cpu we're creating an event for is online. 11785 * 11786 * We use the perf_cpu_context::ctx::mutex to serialize against 11787 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 11788 */ 11789 struct perf_cpu_context *cpuctx = 11790 container_of(ctx, struct perf_cpu_context, ctx); 11791 11792 if (!cpuctx->online) { 11793 err = -ENODEV; 11794 goto err_locked; 11795 } 11796 } 11797 11798 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) { 11799 err = -EINVAL; 11800 goto err_locked; 11801 } 11802 11803 /* 11804 * Must be under the same ctx::mutex as perf_install_in_context(), 11805 * because we need to serialize with concurrent event creation. 11806 */ 11807 if (!exclusive_event_installable(event, ctx)) { 11808 err = -EBUSY; 11809 goto err_locked; 11810 } 11811 11812 WARN_ON_ONCE(ctx->parent_ctx); 11813 11814 /* 11815 * This is the point on no return; we cannot fail hereafter. This is 11816 * where we start modifying current state. 11817 */ 11818 11819 if (move_group) { 11820 /* 11821 * See perf_event_ctx_lock() for comments on the details 11822 * of swizzling perf_event::ctx. 11823 */ 11824 perf_remove_from_context(group_leader, 0); 11825 put_ctx(gctx); 11826 11827 for_each_sibling_event(sibling, group_leader) { 11828 perf_remove_from_context(sibling, 0); 11829 put_ctx(gctx); 11830 } 11831 11832 /* 11833 * Wait for everybody to stop referencing the events through 11834 * the old lists, before installing it on new lists. 11835 */ 11836 synchronize_rcu(); 11837 11838 /* 11839 * Install the group siblings before the group leader. 11840 * 11841 * Because a group leader will try and install the entire group 11842 * (through the sibling list, which is still in-tact), we can 11843 * end up with siblings installed in the wrong context. 11844 * 11845 * By installing siblings first we NO-OP because they're not 11846 * reachable through the group lists. 11847 */ 11848 for_each_sibling_event(sibling, group_leader) { 11849 perf_event__state_init(sibling); 11850 perf_install_in_context(ctx, sibling, sibling->cpu); 11851 get_ctx(ctx); 11852 } 11853 11854 /* 11855 * Removing from the context ends up with disabled 11856 * event. What we want here is event in the initial 11857 * startup state, ready to be add into new context. 11858 */ 11859 perf_event__state_init(group_leader); 11860 perf_install_in_context(ctx, group_leader, group_leader->cpu); 11861 get_ctx(ctx); 11862 } 11863 11864 /* 11865 * Precalculate sample_data sizes; do while holding ctx::mutex such 11866 * that we're serialized against further additions and before 11867 * perf_install_in_context() which is the point the event is active and 11868 * can use these values. 11869 */ 11870 perf_event__header_size(event); 11871 perf_event__id_header_size(event); 11872 11873 event->owner = current; 11874 11875 perf_install_in_context(ctx, event, event->cpu); 11876 perf_unpin_context(ctx); 11877 11878 if (move_group) 11879 perf_event_ctx_unlock(group_leader, gctx); 11880 mutex_unlock(&ctx->mutex); 11881 11882 if (task) { 11883 mutex_unlock(&task->signal->exec_update_mutex); 11884 put_task_struct(task); 11885 } 11886 11887 mutex_lock(¤t->perf_event_mutex); 11888 list_add_tail(&event->owner_entry, ¤t->perf_event_list); 11889 mutex_unlock(¤t->perf_event_mutex); 11890 11891 /* 11892 * Drop the reference on the group_event after placing the 11893 * new event on the sibling_list. This ensures destruction 11894 * of the group leader will find the pointer to itself in 11895 * perf_group_detach(). 11896 */ 11897 fdput(group); 11898 fd_install(event_fd, event_file); 11899 return event_fd; 11900 11901 err_locked: 11902 if (move_group) 11903 perf_event_ctx_unlock(group_leader, gctx); 11904 mutex_unlock(&ctx->mutex); 11905 /* err_file: */ 11906 fput(event_file); 11907 err_context: 11908 perf_unpin_context(ctx); 11909 put_ctx(ctx); 11910 err_alloc: 11911 /* 11912 * If event_file is set, the fput() above will have called ->release() 11913 * and that will take care of freeing the event. 11914 */ 11915 if (!event_file) 11916 free_event(event); 11917 err_cred: 11918 if (task) 11919 mutex_unlock(&task->signal->exec_update_mutex); 11920 err_task: 11921 if (task) 11922 put_task_struct(task); 11923 err_group_fd: 11924 fdput(group); 11925 err_fd: 11926 put_unused_fd(event_fd); 11927 return err; 11928 } 11929 11930 /** 11931 * perf_event_create_kernel_counter 11932 * 11933 * @attr: attributes of the counter to create 11934 * @cpu: cpu in which the counter is bound 11935 * @task: task to profile (NULL for percpu) 11936 */ 11937 struct perf_event * 11938 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu, 11939 struct task_struct *task, 11940 perf_overflow_handler_t overflow_handler, 11941 void *context) 11942 { 11943 struct perf_event_context *ctx; 11944 struct perf_event *event; 11945 int err; 11946 11947 /* 11948 * Grouping is not supported for kernel events, neither is 'AUX', 11949 * make sure the caller's intentions are adjusted. 11950 */ 11951 if (attr->aux_output) 11952 return ERR_PTR(-EINVAL); 11953 11954 event = perf_event_alloc(attr, cpu, task, NULL, NULL, 11955 overflow_handler, context, -1); 11956 if (IS_ERR(event)) { 11957 err = PTR_ERR(event); 11958 goto err; 11959 } 11960 11961 /* Mark owner so we could distinguish it from user events. */ 11962 event->owner = TASK_TOMBSTONE; 11963 11964 /* 11965 * Get the target context (task or percpu): 11966 */ 11967 ctx = find_get_context(event->pmu, task, event); 11968 if (IS_ERR(ctx)) { 11969 err = PTR_ERR(ctx); 11970 goto err_free; 11971 } 11972 11973 WARN_ON_ONCE(ctx->parent_ctx); 11974 mutex_lock(&ctx->mutex); 11975 if (ctx->task == TASK_TOMBSTONE) { 11976 err = -ESRCH; 11977 goto err_unlock; 11978 } 11979 11980 if (!task) { 11981 /* 11982 * Check if the @cpu we're creating an event for is online. 11983 * 11984 * We use the perf_cpu_context::ctx::mutex to serialize against 11985 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 11986 */ 11987 struct perf_cpu_context *cpuctx = 11988 container_of(ctx, struct perf_cpu_context, ctx); 11989 if (!cpuctx->online) { 11990 err = -ENODEV; 11991 goto err_unlock; 11992 } 11993 } 11994 11995 if (!exclusive_event_installable(event, ctx)) { 11996 err = -EBUSY; 11997 goto err_unlock; 11998 } 11999 12000 perf_install_in_context(ctx, event, event->cpu); 12001 perf_unpin_context(ctx); 12002 mutex_unlock(&ctx->mutex); 12003 12004 return event; 12005 12006 err_unlock: 12007 mutex_unlock(&ctx->mutex); 12008 perf_unpin_context(ctx); 12009 put_ctx(ctx); 12010 err_free: 12011 free_event(event); 12012 err: 12013 return ERR_PTR(err); 12014 } 12015 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter); 12016 12017 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu) 12018 { 12019 struct perf_event_context *src_ctx; 12020 struct perf_event_context *dst_ctx; 12021 struct perf_event *event, *tmp; 12022 LIST_HEAD(events); 12023 12024 src_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, src_cpu)->ctx; 12025 dst_ctx = &per_cpu_ptr(pmu->pmu_cpu_context, dst_cpu)->ctx; 12026 12027 /* 12028 * See perf_event_ctx_lock() for comments on the details 12029 * of swizzling perf_event::ctx. 12030 */ 12031 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex); 12032 list_for_each_entry_safe(event, tmp, &src_ctx->event_list, 12033 event_entry) { 12034 perf_remove_from_context(event, 0); 12035 unaccount_event_cpu(event, src_cpu); 12036 put_ctx(src_ctx); 12037 list_add(&event->migrate_entry, &events); 12038 } 12039 12040 /* 12041 * Wait for the events to quiesce before re-instating them. 12042 */ 12043 synchronize_rcu(); 12044 12045 /* 12046 * Re-instate events in 2 passes. 12047 * 12048 * Skip over group leaders and only install siblings on this first 12049 * pass, siblings will not get enabled without a leader, however a 12050 * leader will enable its siblings, even if those are still on the old 12051 * context. 12052 */ 12053 list_for_each_entry_safe(event, tmp, &events, migrate_entry) { 12054 if (event->group_leader == event) 12055 continue; 12056 12057 list_del(&event->migrate_entry); 12058 if (event->state >= PERF_EVENT_STATE_OFF) 12059 event->state = PERF_EVENT_STATE_INACTIVE; 12060 account_event_cpu(event, dst_cpu); 12061 perf_install_in_context(dst_ctx, event, dst_cpu); 12062 get_ctx(dst_ctx); 12063 } 12064 12065 /* 12066 * Once all the siblings are setup properly, install the group leaders 12067 * to make it go. 12068 */ 12069 list_for_each_entry_safe(event, tmp, &events, migrate_entry) { 12070 list_del(&event->migrate_entry); 12071 if (event->state >= PERF_EVENT_STATE_OFF) 12072 event->state = PERF_EVENT_STATE_INACTIVE; 12073 account_event_cpu(event, dst_cpu); 12074 perf_install_in_context(dst_ctx, event, dst_cpu); 12075 get_ctx(dst_ctx); 12076 } 12077 mutex_unlock(&dst_ctx->mutex); 12078 mutex_unlock(&src_ctx->mutex); 12079 } 12080 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context); 12081 12082 static void sync_child_event(struct perf_event *child_event, 12083 struct task_struct *child) 12084 { 12085 struct perf_event *parent_event = child_event->parent; 12086 u64 child_val; 12087 12088 if (child_event->attr.inherit_stat) 12089 perf_event_read_event(child_event, child); 12090 12091 child_val = perf_event_count(child_event); 12092 12093 /* 12094 * Add back the child's count to the parent's count: 12095 */ 12096 atomic64_add(child_val, &parent_event->child_count); 12097 atomic64_add(child_event->total_time_enabled, 12098 &parent_event->child_total_time_enabled); 12099 atomic64_add(child_event->total_time_running, 12100 &parent_event->child_total_time_running); 12101 } 12102 12103 static void 12104 perf_event_exit_event(struct perf_event *child_event, 12105 struct perf_event_context *child_ctx, 12106 struct task_struct *child) 12107 { 12108 struct perf_event *parent_event = child_event->parent; 12109 12110 /* 12111 * Do not destroy the 'original' grouping; because of the context 12112 * switch optimization the original events could've ended up in a 12113 * random child task. 12114 * 12115 * If we were to destroy the original group, all group related 12116 * operations would cease to function properly after this random 12117 * child dies. 12118 * 12119 * Do destroy all inherited groups, we don't care about those 12120 * and being thorough is better. 12121 */ 12122 raw_spin_lock_irq(&child_ctx->lock); 12123 WARN_ON_ONCE(child_ctx->is_active); 12124 12125 if (parent_event) 12126 perf_group_detach(child_event); 12127 list_del_event(child_event, child_ctx); 12128 perf_event_set_state(child_event, PERF_EVENT_STATE_EXIT); /* is_event_hup() */ 12129 raw_spin_unlock_irq(&child_ctx->lock); 12130 12131 /* 12132 * Parent events are governed by their filedesc, retain them. 12133 */ 12134 if (!parent_event) { 12135 perf_event_wakeup(child_event); 12136 return; 12137 } 12138 /* 12139 * Child events can be cleaned up. 12140 */ 12141 12142 sync_child_event(child_event, child); 12143 12144 /* 12145 * Remove this event from the parent's list 12146 */ 12147 WARN_ON_ONCE(parent_event->ctx->parent_ctx); 12148 mutex_lock(&parent_event->child_mutex); 12149 list_del_init(&child_event->child_list); 12150 mutex_unlock(&parent_event->child_mutex); 12151 12152 /* 12153 * Kick perf_poll() for is_event_hup(). 12154 */ 12155 perf_event_wakeup(parent_event); 12156 free_event(child_event); 12157 put_event(parent_event); 12158 } 12159 12160 static void perf_event_exit_task_context(struct task_struct *child, int ctxn) 12161 { 12162 struct perf_event_context *child_ctx, *clone_ctx = NULL; 12163 struct perf_event *child_event, *next; 12164 12165 WARN_ON_ONCE(child != current); 12166 12167 child_ctx = perf_pin_task_context(child, ctxn); 12168 if (!child_ctx) 12169 return; 12170 12171 /* 12172 * In order to reduce the amount of tricky in ctx tear-down, we hold 12173 * ctx::mutex over the entire thing. This serializes against almost 12174 * everything that wants to access the ctx. 12175 * 12176 * The exception is sys_perf_event_open() / 12177 * perf_event_create_kernel_count() which does find_get_context() 12178 * without ctx::mutex (it cannot because of the move_group double mutex 12179 * lock thing). See the comments in perf_install_in_context(). 12180 */ 12181 mutex_lock(&child_ctx->mutex); 12182 12183 /* 12184 * In a single ctx::lock section, de-schedule the events and detach the 12185 * context from the task such that we cannot ever get it scheduled back 12186 * in. 12187 */ 12188 raw_spin_lock_irq(&child_ctx->lock); 12189 task_ctx_sched_out(__get_cpu_context(child_ctx), child_ctx, EVENT_ALL); 12190 12191 /* 12192 * Now that the context is inactive, destroy the task <-> ctx relation 12193 * and mark the context dead. 12194 */ 12195 RCU_INIT_POINTER(child->perf_event_ctxp[ctxn], NULL); 12196 put_ctx(child_ctx); /* cannot be last */ 12197 WRITE_ONCE(child_ctx->task, TASK_TOMBSTONE); 12198 put_task_struct(current); /* cannot be last */ 12199 12200 clone_ctx = unclone_ctx(child_ctx); 12201 raw_spin_unlock_irq(&child_ctx->lock); 12202 12203 if (clone_ctx) 12204 put_ctx(clone_ctx); 12205 12206 /* 12207 * Report the task dead after unscheduling the events so that we 12208 * won't get any samples after PERF_RECORD_EXIT. We can however still 12209 * get a few PERF_RECORD_READ events. 12210 */ 12211 perf_event_task(child, child_ctx, 0); 12212 12213 list_for_each_entry_safe(child_event, next, &child_ctx->event_list, event_entry) 12214 perf_event_exit_event(child_event, child_ctx, child); 12215 12216 mutex_unlock(&child_ctx->mutex); 12217 12218 put_ctx(child_ctx); 12219 } 12220 12221 /* 12222 * When a child task exits, feed back event values to parent events. 12223 * 12224 * Can be called with exec_update_mutex held when called from 12225 * install_exec_creds(). 12226 */ 12227 void perf_event_exit_task(struct task_struct *child) 12228 { 12229 struct perf_event *event, *tmp; 12230 int ctxn; 12231 12232 mutex_lock(&child->perf_event_mutex); 12233 list_for_each_entry_safe(event, tmp, &child->perf_event_list, 12234 owner_entry) { 12235 list_del_init(&event->owner_entry); 12236 12237 /* 12238 * Ensure the list deletion is visible before we clear 12239 * the owner, closes a race against perf_release() where 12240 * we need to serialize on the owner->perf_event_mutex. 12241 */ 12242 smp_store_release(&event->owner, NULL); 12243 } 12244 mutex_unlock(&child->perf_event_mutex); 12245 12246 for_each_task_context_nr(ctxn) 12247 perf_event_exit_task_context(child, ctxn); 12248 12249 /* 12250 * The perf_event_exit_task_context calls perf_event_task 12251 * with child's task_ctx, which generates EXIT events for 12252 * child contexts and sets child->perf_event_ctxp[] to NULL. 12253 * At this point we need to send EXIT events to cpu contexts. 12254 */ 12255 perf_event_task(child, NULL, 0); 12256 } 12257 12258 static void perf_free_event(struct perf_event *event, 12259 struct perf_event_context *ctx) 12260 { 12261 struct perf_event *parent = event->parent; 12262 12263 if (WARN_ON_ONCE(!parent)) 12264 return; 12265 12266 mutex_lock(&parent->child_mutex); 12267 list_del_init(&event->child_list); 12268 mutex_unlock(&parent->child_mutex); 12269 12270 put_event(parent); 12271 12272 raw_spin_lock_irq(&ctx->lock); 12273 perf_group_detach(event); 12274 list_del_event(event, ctx); 12275 raw_spin_unlock_irq(&ctx->lock); 12276 free_event(event); 12277 } 12278 12279 /* 12280 * Free a context as created by inheritance by perf_event_init_task() below, 12281 * used by fork() in case of fail. 12282 * 12283 * Even though the task has never lived, the context and events have been 12284 * exposed through the child_list, so we must take care tearing it all down. 12285 */ 12286 void perf_event_free_task(struct task_struct *task) 12287 { 12288 struct perf_event_context *ctx; 12289 struct perf_event *event, *tmp; 12290 int ctxn; 12291 12292 for_each_task_context_nr(ctxn) { 12293 ctx = task->perf_event_ctxp[ctxn]; 12294 if (!ctx) 12295 continue; 12296 12297 mutex_lock(&ctx->mutex); 12298 raw_spin_lock_irq(&ctx->lock); 12299 /* 12300 * Destroy the task <-> ctx relation and mark the context dead. 12301 * 12302 * This is important because even though the task hasn't been 12303 * exposed yet the context has been (through child_list). 12304 */ 12305 RCU_INIT_POINTER(task->perf_event_ctxp[ctxn], NULL); 12306 WRITE_ONCE(ctx->task, TASK_TOMBSTONE); 12307 put_task_struct(task); /* cannot be last */ 12308 raw_spin_unlock_irq(&ctx->lock); 12309 12310 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) 12311 perf_free_event(event, ctx); 12312 12313 mutex_unlock(&ctx->mutex); 12314 12315 /* 12316 * perf_event_release_kernel() could've stolen some of our 12317 * child events and still have them on its free_list. In that 12318 * case we must wait for these events to have been freed (in 12319 * particular all their references to this task must've been 12320 * dropped). 12321 * 12322 * Without this copy_process() will unconditionally free this 12323 * task (irrespective of its reference count) and 12324 * _free_event()'s put_task_struct(event->hw.target) will be a 12325 * use-after-free. 12326 * 12327 * Wait for all events to drop their context reference. 12328 */ 12329 wait_var_event(&ctx->refcount, refcount_read(&ctx->refcount) == 1); 12330 put_ctx(ctx); /* must be last */ 12331 } 12332 } 12333 12334 void perf_event_delayed_put(struct task_struct *task) 12335 { 12336 int ctxn; 12337 12338 for_each_task_context_nr(ctxn) 12339 WARN_ON_ONCE(task->perf_event_ctxp[ctxn]); 12340 } 12341 12342 struct file *perf_event_get(unsigned int fd) 12343 { 12344 struct file *file = fget(fd); 12345 if (!file) 12346 return ERR_PTR(-EBADF); 12347 12348 if (file->f_op != &perf_fops) { 12349 fput(file); 12350 return ERR_PTR(-EBADF); 12351 } 12352 12353 return file; 12354 } 12355 12356 const struct perf_event *perf_get_event(struct file *file) 12357 { 12358 if (file->f_op != &perf_fops) 12359 return ERR_PTR(-EINVAL); 12360 12361 return file->private_data; 12362 } 12363 12364 const struct perf_event_attr *perf_event_attrs(struct perf_event *event) 12365 { 12366 if (!event) 12367 return ERR_PTR(-EINVAL); 12368 12369 return &event->attr; 12370 } 12371 12372 /* 12373 * Inherit an event from parent task to child task. 12374 * 12375 * Returns: 12376 * - valid pointer on success 12377 * - NULL for orphaned events 12378 * - IS_ERR() on error 12379 */ 12380 static struct perf_event * 12381 inherit_event(struct perf_event *parent_event, 12382 struct task_struct *parent, 12383 struct perf_event_context *parent_ctx, 12384 struct task_struct *child, 12385 struct perf_event *group_leader, 12386 struct perf_event_context *child_ctx) 12387 { 12388 enum perf_event_state parent_state = parent_event->state; 12389 struct perf_event *child_event; 12390 unsigned long flags; 12391 12392 /* 12393 * Instead of creating recursive hierarchies of events, 12394 * we link inherited events back to the original parent, 12395 * which has a filp for sure, which we use as the reference 12396 * count: 12397 */ 12398 if (parent_event->parent) 12399 parent_event = parent_event->parent; 12400 12401 child_event = perf_event_alloc(&parent_event->attr, 12402 parent_event->cpu, 12403 child, 12404 group_leader, parent_event, 12405 NULL, NULL, -1); 12406 if (IS_ERR(child_event)) 12407 return child_event; 12408 12409 12410 if ((child_event->attach_state & PERF_ATTACH_TASK_DATA) && 12411 !child_ctx->task_ctx_data) { 12412 struct pmu *pmu = child_event->pmu; 12413 12414 child_ctx->task_ctx_data = kzalloc(pmu->task_ctx_size, 12415 GFP_KERNEL); 12416 if (!child_ctx->task_ctx_data) { 12417 free_event(child_event); 12418 return ERR_PTR(-ENOMEM); 12419 } 12420 } 12421 12422 /* 12423 * is_orphaned_event() and list_add_tail(&parent_event->child_list) 12424 * must be under the same lock in order to serialize against 12425 * perf_event_release_kernel(), such that either we must observe 12426 * is_orphaned_event() or they will observe us on the child_list. 12427 */ 12428 mutex_lock(&parent_event->child_mutex); 12429 if (is_orphaned_event(parent_event) || 12430 !atomic_long_inc_not_zero(&parent_event->refcount)) { 12431 mutex_unlock(&parent_event->child_mutex); 12432 /* task_ctx_data is freed with child_ctx */ 12433 free_event(child_event); 12434 return NULL; 12435 } 12436 12437 get_ctx(child_ctx); 12438 12439 /* 12440 * Make the child state follow the state of the parent event, 12441 * not its attr.disabled bit. We hold the parent's mutex, 12442 * so we won't race with perf_event_{en, dis}able_family. 12443 */ 12444 if (parent_state >= PERF_EVENT_STATE_INACTIVE) 12445 child_event->state = PERF_EVENT_STATE_INACTIVE; 12446 else 12447 child_event->state = PERF_EVENT_STATE_OFF; 12448 12449 if (parent_event->attr.freq) { 12450 u64 sample_period = parent_event->hw.sample_period; 12451 struct hw_perf_event *hwc = &child_event->hw; 12452 12453 hwc->sample_period = sample_period; 12454 hwc->last_period = sample_period; 12455 12456 local64_set(&hwc->period_left, sample_period); 12457 } 12458 12459 child_event->ctx = child_ctx; 12460 child_event->overflow_handler = parent_event->overflow_handler; 12461 child_event->overflow_handler_context 12462 = parent_event->overflow_handler_context; 12463 12464 /* 12465 * Precalculate sample_data sizes 12466 */ 12467 perf_event__header_size(child_event); 12468 perf_event__id_header_size(child_event); 12469 12470 /* 12471 * Link it up in the child's context: 12472 */ 12473 raw_spin_lock_irqsave(&child_ctx->lock, flags); 12474 add_event_to_ctx(child_event, child_ctx); 12475 raw_spin_unlock_irqrestore(&child_ctx->lock, flags); 12476 12477 /* 12478 * Link this into the parent event's child list 12479 */ 12480 list_add_tail(&child_event->child_list, &parent_event->child_list); 12481 mutex_unlock(&parent_event->child_mutex); 12482 12483 return child_event; 12484 } 12485 12486 /* 12487 * Inherits an event group. 12488 * 12489 * This will quietly suppress orphaned events; !inherit_event() is not an error. 12490 * This matches with perf_event_release_kernel() removing all child events. 12491 * 12492 * Returns: 12493 * - 0 on success 12494 * - <0 on error 12495 */ 12496 static int inherit_group(struct perf_event *parent_event, 12497 struct task_struct *parent, 12498 struct perf_event_context *parent_ctx, 12499 struct task_struct *child, 12500 struct perf_event_context *child_ctx) 12501 { 12502 struct perf_event *leader; 12503 struct perf_event *sub; 12504 struct perf_event *child_ctr; 12505 12506 leader = inherit_event(parent_event, parent, parent_ctx, 12507 child, NULL, child_ctx); 12508 if (IS_ERR(leader)) 12509 return PTR_ERR(leader); 12510 /* 12511 * @leader can be NULL here because of is_orphaned_event(). In this 12512 * case inherit_event() will create individual events, similar to what 12513 * perf_group_detach() would do anyway. 12514 */ 12515 for_each_sibling_event(sub, parent_event) { 12516 child_ctr = inherit_event(sub, parent, parent_ctx, 12517 child, leader, child_ctx); 12518 if (IS_ERR(child_ctr)) 12519 return PTR_ERR(child_ctr); 12520 12521 if (sub->aux_event == parent_event && child_ctr && 12522 !perf_get_aux_event(child_ctr, leader)) 12523 return -EINVAL; 12524 } 12525 return 0; 12526 } 12527 12528 /* 12529 * Creates the child task context and tries to inherit the event-group. 12530 * 12531 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave 12532 * inherited_all set when we 'fail' to inherit an orphaned event; this is 12533 * consistent with perf_event_release_kernel() removing all child events. 12534 * 12535 * Returns: 12536 * - 0 on success 12537 * - <0 on error 12538 */ 12539 static int 12540 inherit_task_group(struct perf_event *event, struct task_struct *parent, 12541 struct perf_event_context *parent_ctx, 12542 struct task_struct *child, int ctxn, 12543 int *inherited_all) 12544 { 12545 int ret; 12546 struct perf_event_context *child_ctx; 12547 12548 if (!event->attr.inherit) { 12549 *inherited_all = 0; 12550 return 0; 12551 } 12552 12553 child_ctx = child->perf_event_ctxp[ctxn]; 12554 if (!child_ctx) { 12555 /* 12556 * This is executed from the parent task context, so 12557 * inherit events that have been marked for cloning. 12558 * First allocate and initialize a context for the 12559 * child. 12560 */ 12561 child_ctx = alloc_perf_context(parent_ctx->pmu, child); 12562 if (!child_ctx) 12563 return -ENOMEM; 12564 12565 child->perf_event_ctxp[ctxn] = child_ctx; 12566 } 12567 12568 ret = inherit_group(event, parent, parent_ctx, 12569 child, child_ctx); 12570 12571 if (ret) 12572 *inherited_all = 0; 12573 12574 return ret; 12575 } 12576 12577 /* 12578 * Initialize the perf_event context in task_struct 12579 */ 12580 static int perf_event_init_context(struct task_struct *child, int ctxn) 12581 { 12582 struct perf_event_context *child_ctx, *parent_ctx; 12583 struct perf_event_context *cloned_ctx; 12584 struct perf_event *event; 12585 struct task_struct *parent = current; 12586 int inherited_all = 1; 12587 unsigned long flags; 12588 int ret = 0; 12589 12590 if (likely(!parent->perf_event_ctxp[ctxn])) 12591 return 0; 12592 12593 /* 12594 * If the parent's context is a clone, pin it so it won't get 12595 * swapped under us. 12596 */ 12597 parent_ctx = perf_pin_task_context(parent, ctxn); 12598 if (!parent_ctx) 12599 return 0; 12600 12601 /* 12602 * No need to check if parent_ctx != NULL here; since we saw 12603 * it non-NULL earlier, the only reason for it to become NULL 12604 * is if we exit, and since we're currently in the middle of 12605 * a fork we can't be exiting at the same time. 12606 */ 12607 12608 /* 12609 * Lock the parent list. No need to lock the child - not PID 12610 * hashed yet and not running, so nobody can access it. 12611 */ 12612 mutex_lock(&parent_ctx->mutex); 12613 12614 /* 12615 * We dont have to disable NMIs - we are only looking at 12616 * the list, not manipulating it: 12617 */ 12618 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) { 12619 ret = inherit_task_group(event, parent, parent_ctx, 12620 child, ctxn, &inherited_all); 12621 if (ret) 12622 goto out_unlock; 12623 } 12624 12625 /* 12626 * We can't hold ctx->lock when iterating the ->flexible_group list due 12627 * to allocations, but we need to prevent rotation because 12628 * rotate_ctx() will change the list from interrupt context. 12629 */ 12630 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 12631 parent_ctx->rotate_disable = 1; 12632 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 12633 12634 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) { 12635 ret = inherit_task_group(event, parent, parent_ctx, 12636 child, ctxn, &inherited_all); 12637 if (ret) 12638 goto out_unlock; 12639 } 12640 12641 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 12642 parent_ctx->rotate_disable = 0; 12643 12644 child_ctx = child->perf_event_ctxp[ctxn]; 12645 12646 if (child_ctx && inherited_all) { 12647 /* 12648 * Mark the child context as a clone of the parent 12649 * context, or of whatever the parent is a clone of. 12650 * 12651 * Note that if the parent is a clone, the holding of 12652 * parent_ctx->lock avoids it from being uncloned. 12653 */ 12654 cloned_ctx = parent_ctx->parent_ctx; 12655 if (cloned_ctx) { 12656 child_ctx->parent_ctx = cloned_ctx; 12657 child_ctx->parent_gen = parent_ctx->parent_gen; 12658 } else { 12659 child_ctx->parent_ctx = parent_ctx; 12660 child_ctx->parent_gen = parent_ctx->generation; 12661 } 12662 get_ctx(child_ctx->parent_ctx); 12663 } 12664 12665 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 12666 out_unlock: 12667 mutex_unlock(&parent_ctx->mutex); 12668 12669 perf_unpin_context(parent_ctx); 12670 put_ctx(parent_ctx); 12671 12672 return ret; 12673 } 12674 12675 /* 12676 * Initialize the perf_event context in task_struct 12677 */ 12678 int perf_event_init_task(struct task_struct *child) 12679 { 12680 int ctxn, ret; 12681 12682 memset(child->perf_event_ctxp, 0, sizeof(child->perf_event_ctxp)); 12683 mutex_init(&child->perf_event_mutex); 12684 INIT_LIST_HEAD(&child->perf_event_list); 12685 12686 for_each_task_context_nr(ctxn) { 12687 ret = perf_event_init_context(child, ctxn); 12688 if (ret) { 12689 perf_event_free_task(child); 12690 return ret; 12691 } 12692 } 12693 12694 return 0; 12695 } 12696 12697 static void __init perf_event_init_all_cpus(void) 12698 { 12699 struct swevent_htable *swhash; 12700 int cpu; 12701 12702 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL); 12703 12704 for_each_possible_cpu(cpu) { 12705 swhash = &per_cpu(swevent_htable, cpu); 12706 mutex_init(&swhash->hlist_mutex); 12707 INIT_LIST_HEAD(&per_cpu(active_ctx_list, cpu)); 12708 12709 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu)); 12710 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu)); 12711 12712 #ifdef CONFIG_CGROUP_PERF 12713 INIT_LIST_HEAD(&per_cpu(cgrp_cpuctx_list, cpu)); 12714 #endif 12715 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu)); 12716 } 12717 } 12718 12719 static void perf_swevent_init_cpu(unsigned int cpu) 12720 { 12721 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 12722 12723 mutex_lock(&swhash->hlist_mutex); 12724 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) { 12725 struct swevent_hlist *hlist; 12726 12727 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); 12728 WARN_ON(!hlist); 12729 rcu_assign_pointer(swhash->swevent_hlist, hlist); 12730 } 12731 mutex_unlock(&swhash->hlist_mutex); 12732 } 12733 12734 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE 12735 static void __perf_event_exit_context(void *__info) 12736 { 12737 struct perf_event_context *ctx = __info; 12738 struct perf_cpu_context *cpuctx = __get_cpu_context(ctx); 12739 struct perf_event *event; 12740 12741 raw_spin_lock(&ctx->lock); 12742 ctx_sched_out(ctx, cpuctx, EVENT_TIME); 12743 list_for_each_entry(event, &ctx->event_list, event_entry) 12744 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP); 12745 raw_spin_unlock(&ctx->lock); 12746 } 12747 12748 static void perf_event_exit_cpu_context(int cpu) 12749 { 12750 struct perf_cpu_context *cpuctx; 12751 struct perf_event_context *ctx; 12752 struct pmu *pmu; 12753 12754 mutex_lock(&pmus_lock); 12755 list_for_each_entry(pmu, &pmus, entry) { 12756 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); 12757 ctx = &cpuctx->ctx; 12758 12759 mutex_lock(&ctx->mutex); 12760 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1); 12761 cpuctx->online = 0; 12762 mutex_unlock(&ctx->mutex); 12763 } 12764 cpumask_clear_cpu(cpu, perf_online_mask); 12765 mutex_unlock(&pmus_lock); 12766 } 12767 #else 12768 12769 static void perf_event_exit_cpu_context(int cpu) { } 12770 12771 #endif 12772 12773 int perf_event_init_cpu(unsigned int cpu) 12774 { 12775 struct perf_cpu_context *cpuctx; 12776 struct perf_event_context *ctx; 12777 struct pmu *pmu; 12778 12779 perf_swevent_init_cpu(cpu); 12780 12781 mutex_lock(&pmus_lock); 12782 cpumask_set_cpu(cpu, perf_online_mask); 12783 list_for_each_entry(pmu, &pmus, entry) { 12784 cpuctx = per_cpu_ptr(pmu->pmu_cpu_context, cpu); 12785 ctx = &cpuctx->ctx; 12786 12787 mutex_lock(&ctx->mutex); 12788 cpuctx->online = 1; 12789 mutex_unlock(&ctx->mutex); 12790 } 12791 mutex_unlock(&pmus_lock); 12792 12793 return 0; 12794 } 12795 12796 int perf_event_exit_cpu(unsigned int cpu) 12797 { 12798 perf_event_exit_cpu_context(cpu); 12799 return 0; 12800 } 12801 12802 static int 12803 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v) 12804 { 12805 int cpu; 12806 12807 for_each_online_cpu(cpu) 12808 perf_event_exit_cpu(cpu); 12809 12810 return NOTIFY_OK; 12811 } 12812 12813 /* 12814 * Run the perf reboot notifier at the very last possible moment so that 12815 * the generic watchdog code runs as long as possible. 12816 */ 12817 static struct notifier_block perf_reboot_notifier = { 12818 .notifier_call = perf_reboot, 12819 .priority = INT_MIN, 12820 }; 12821 12822 void __init perf_event_init(void) 12823 { 12824 int ret; 12825 12826 idr_init(&pmu_idr); 12827 12828 perf_event_init_all_cpus(); 12829 init_srcu_struct(&pmus_srcu); 12830 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE); 12831 perf_pmu_register(&perf_cpu_clock, NULL, -1); 12832 perf_pmu_register(&perf_task_clock, NULL, -1); 12833 perf_tp_register(); 12834 perf_event_init_cpu(smp_processor_id()); 12835 register_reboot_notifier(&perf_reboot_notifier); 12836 12837 ret = init_hw_breakpoint(); 12838 WARN(ret, "hw_breakpoint initialization failed with: %d", ret); 12839 12840 /* 12841 * Build time assertion that we keep the data_head at the intended 12842 * location. IOW, validation we got the __reserved[] size right. 12843 */ 12844 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head)) 12845 != 1024); 12846 } 12847 12848 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr, 12849 char *page) 12850 { 12851 struct perf_pmu_events_attr *pmu_attr = 12852 container_of(attr, struct perf_pmu_events_attr, attr); 12853 12854 if (pmu_attr->event_str) 12855 return sprintf(page, "%s\n", pmu_attr->event_str); 12856 12857 return 0; 12858 } 12859 EXPORT_SYMBOL_GPL(perf_event_sysfs_show); 12860 12861 static int __init perf_event_sysfs_init(void) 12862 { 12863 struct pmu *pmu; 12864 int ret; 12865 12866 mutex_lock(&pmus_lock); 12867 12868 ret = bus_register(&pmu_bus); 12869 if (ret) 12870 goto unlock; 12871 12872 list_for_each_entry(pmu, &pmus, entry) { 12873 if (!pmu->name || pmu->type < 0) 12874 continue; 12875 12876 ret = pmu_dev_alloc(pmu); 12877 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret); 12878 } 12879 pmu_bus_running = 1; 12880 ret = 0; 12881 12882 unlock: 12883 mutex_unlock(&pmus_lock); 12884 12885 return ret; 12886 } 12887 device_initcall(perf_event_sysfs_init); 12888 12889 #ifdef CONFIG_CGROUP_PERF 12890 static struct cgroup_subsys_state * 12891 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 12892 { 12893 struct perf_cgroup *jc; 12894 12895 jc = kzalloc(sizeof(*jc), GFP_KERNEL); 12896 if (!jc) 12897 return ERR_PTR(-ENOMEM); 12898 12899 jc->info = alloc_percpu(struct perf_cgroup_info); 12900 if (!jc->info) { 12901 kfree(jc); 12902 return ERR_PTR(-ENOMEM); 12903 } 12904 12905 return &jc->css; 12906 } 12907 12908 static void perf_cgroup_css_free(struct cgroup_subsys_state *css) 12909 { 12910 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css); 12911 12912 free_percpu(jc->info); 12913 kfree(jc); 12914 } 12915 12916 static int perf_cgroup_css_online(struct cgroup_subsys_state *css) 12917 { 12918 perf_event_cgroup(css->cgroup); 12919 return 0; 12920 } 12921 12922 static int __perf_cgroup_move(void *info) 12923 { 12924 struct task_struct *task = info; 12925 rcu_read_lock(); 12926 perf_cgroup_switch(task, PERF_CGROUP_SWOUT | PERF_CGROUP_SWIN); 12927 rcu_read_unlock(); 12928 return 0; 12929 } 12930 12931 static void perf_cgroup_attach(struct cgroup_taskset *tset) 12932 { 12933 struct task_struct *task; 12934 struct cgroup_subsys_state *css; 12935 12936 cgroup_taskset_for_each(task, css, tset) 12937 task_function_call(task, __perf_cgroup_move, task); 12938 } 12939 12940 struct cgroup_subsys perf_event_cgrp_subsys = { 12941 .css_alloc = perf_cgroup_css_alloc, 12942 .css_free = perf_cgroup_css_free, 12943 .css_online = perf_cgroup_css_online, 12944 .attach = perf_cgroup_attach, 12945 /* 12946 * Implicitly enable on dfl hierarchy so that perf events can 12947 * always be filtered by cgroup2 path as long as perf_event 12948 * controller is not mounted on a legacy hierarchy. 12949 */ 12950 .implicit_on_dfl = true, 12951 .threaded = true, 12952 }; 12953 #endif /* CONFIG_CGROUP_PERF */ 12954