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