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