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