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