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