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