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