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