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