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