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 bool revoke); 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, false); 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 kmem_cache_free(perf_event_cache, event); 5308 } 5309 5310 static void ring_buffer_attach(struct perf_event *event, 5311 struct perf_buffer *rb); 5312 5313 static void detach_sb_event(struct perf_event *event) 5314 { 5315 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 5316 5317 raw_spin_lock(&pel->lock); 5318 list_del_rcu(&event->sb_list); 5319 raw_spin_unlock(&pel->lock); 5320 } 5321 5322 static bool is_sb_event(struct perf_event *event) 5323 { 5324 struct perf_event_attr *attr = &event->attr; 5325 5326 if (event->parent) 5327 return false; 5328 5329 if (event->attach_state & PERF_ATTACH_TASK) 5330 return false; 5331 5332 if (attr->mmap || attr->mmap_data || attr->mmap2 || 5333 attr->comm || attr->comm_exec || 5334 attr->task || attr->ksymbol || 5335 attr->context_switch || attr->text_poke || 5336 attr->bpf_event) 5337 return true; 5338 5339 return false; 5340 } 5341 5342 static void unaccount_pmu_sb_event(struct perf_event *event) 5343 { 5344 if (is_sb_event(event)) 5345 detach_sb_event(event); 5346 } 5347 5348 #ifdef CONFIG_NO_HZ_FULL 5349 static DEFINE_SPINLOCK(nr_freq_lock); 5350 #endif 5351 5352 static void unaccount_freq_event_nohz(void) 5353 { 5354 #ifdef CONFIG_NO_HZ_FULL 5355 spin_lock(&nr_freq_lock); 5356 if (atomic_dec_and_test(&nr_freq_events)) 5357 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS); 5358 spin_unlock(&nr_freq_lock); 5359 #endif 5360 } 5361 5362 static void unaccount_freq_event(void) 5363 { 5364 if (tick_nohz_full_enabled()) 5365 unaccount_freq_event_nohz(); 5366 else 5367 atomic_dec(&nr_freq_events); 5368 } 5369 5370 5371 static struct perf_ctx_data * 5372 alloc_perf_ctx_data(struct kmem_cache *ctx_cache, bool global, gfp_t gfp_flags) 5373 { 5374 struct perf_ctx_data *cd; 5375 5376 cd = kzalloc_obj(*cd, gfp_flags); 5377 if (!cd) 5378 return NULL; 5379 5380 cd->data = kmem_cache_zalloc(ctx_cache, gfp_flags); 5381 if (!cd->data) { 5382 kfree(cd); 5383 return NULL; 5384 } 5385 5386 cd->global = global; 5387 cd->ctx_cache = ctx_cache; 5388 refcount_set(&cd->refcount, 1); 5389 5390 return cd; 5391 } 5392 5393 static void free_perf_ctx_data(struct perf_ctx_data *cd) 5394 { 5395 kmem_cache_free(cd->ctx_cache, cd->data); 5396 kfree(cd); 5397 } 5398 5399 static void __free_perf_ctx_data_rcu(struct rcu_head *rcu_head) 5400 { 5401 struct perf_ctx_data *cd; 5402 5403 cd = container_of(rcu_head, struct perf_ctx_data, rcu_head); 5404 free_perf_ctx_data(cd); 5405 } 5406 5407 static inline void perf_free_ctx_data_rcu(struct perf_ctx_data *cd) 5408 { 5409 call_rcu(&cd->rcu_head, __free_perf_ctx_data_rcu); 5410 } 5411 5412 static int 5413 attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache, 5414 bool global, gfp_t gfp_flags) 5415 { 5416 struct perf_ctx_data *cd, *old = NULL; 5417 5418 cd = alloc_perf_ctx_data(ctx_cache, global, gfp_flags); 5419 if (!cd) 5420 return -ENOMEM; 5421 5422 for (;;) { 5423 if (try_cmpxchg(&task->perf_ctx_data, &old, cd)) { 5424 if (old) 5425 perf_free_ctx_data_rcu(old); 5426 /* 5427 * Above try_cmpxchg() pairs with try_cmpxchg() from 5428 * detach_task_ctx_data() such that 5429 * if we race with perf_event_exit_task(), we must 5430 * observe PF_EXITING. 5431 */ 5432 if (task->flags & PF_EXITING) { 5433 /* detach_task_ctx_data() may free it already */ 5434 if (try_cmpxchg(&task->perf_ctx_data, &cd, NULL)) 5435 perf_free_ctx_data_rcu(cd); 5436 } 5437 return 0; 5438 } 5439 5440 if (!old) { 5441 /* 5442 * After seeing a dead @old, we raced with 5443 * removal and lost, try again to install @cd. 5444 */ 5445 continue; 5446 } 5447 5448 if (refcount_inc_not_zero(&old->refcount)) { 5449 free_perf_ctx_data(cd); /* unused */ 5450 return 0; 5451 } 5452 5453 /* 5454 * @old is a dead object, refcount==0 is stable, try and 5455 * replace it with @cd. 5456 */ 5457 } 5458 return 0; 5459 } 5460 5461 static void __detach_global_ctx_data(void); 5462 DEFINE_STATIC_PERCPU_RWSEM(global_ctx_data_rwsem); 5463 static refcount_t global_ctx_data_ref; 5464 5465 static int 5466 attach_global_ctx_data(struct kmem_cache *ctx_cache) 5467 { 5468 struct task_struct *g, *p; 5469 struct perf_ctx_data *cd; 5470 int ret; 5471 5472 if (refcount_inc_not_zero(&global_ctx_data_ref)) 5473 return 0; 5474 5475 guard(percpu_write)(&global_ctx_data_rwsem); 5476 if (refcount_inc_not_zero(&global_ctx_data_ref)) 5477 return 0; 5478 again: 5479 /* Allocate everything */ 5480 scoped_guard (rcu) { 5481 for_each_process_thread(g, p) { 5482 if (p->flags & PF_EXITING) 5483 continue; 5484 cd = rcu_dereference(p->perf_ctx_data); 5485 if (cd && !cd->global) { 5486 cd->global = 1; 5487 if (!refcount_inc_not_zero(&cd->refcount)) 5488 cd = NULL; 5489 } 5490 if (!cd) { 5491 /* 5492 * Try to allocate context quickly before 5493 * traversing the whole thread list again. 5494 */ 5495 if (!attach_task_ctx_data(p, ctx_cache, true, GFP_NOWAIT)) 5496 continue; 5497 get_task_struct(p); 5498 goto alloc; 5499 } 5500 } 5501 } 5502 5503 refcount_set(&global_ctx_data_ref, 1); 5504 5505 return 0; 5506 alloc: 5507 ret = attach_task_ctx_data(p, ctx_cache, true, GFP_KERNEL); 5508 put_task_struct(p); 5509 if (ret) { 5510 __detach_global_ctx_data(); 5511 return ret; 5512 } 5513 goto again; 5514 } 5515 5516 static int 5517 attach_perf_ctx_data(struct perf_event *event) 5518 { 5519 struct task_struct *task = event->hw.target; 5520 struct kmem_cache *ctx_cache = event->pmu->task_ctx_cache; 5521 int ret; 5522 5523 if (!ctx_cache) 5524 return -ENOMEM; 5525 5526 if (task) 5527 return attach_task_ctx_data(task, ctx_cache, false, GFP_KERNEL); 5528 5529 ret = attach_global_ctx_data(ctx_cache); 5530 if (ret) 5531 return ret; 5532 5533 event->attach_state |= PERF_ATTACH_GLOBAL_DATA; 5534 return 0; 5535 } 5536 5537 static void 5538 detach_task_ctx_data(struct task_struct *p) 5539 { 5540 struct perf_ctx_data *cd; 5541 5542 scoped_guard (rcu) { 5543 cd = rcu_dereference(p->perf_ctx_data); 5544 if (!cd || !refcount_dec_and_test(&cd->refcount)) 5545 return; 5546 } 5547 5548 /* 5549 * The old ctx_data may be lost because of the race. 5550 * Nothing is required to do for the case. 5551 * See attach_task_ctx_data(). 5552 */ 5553 if (try_cmpxchg((struct perf_ctx_data **)&p->perf_ctx_data, &cd, NULL)) 5554 perf_free_ctx_data_rcu(cd); 5555 } 5556 5557 static void __detach_global_ctx_data(void) 5558 { 5559 struct task_struct *g, *p; 5560 struct perf_ctx_data *cd; 5561 5562 scoped_guard (rcu) { 5563 for_each_process_thread(g, p) { 5564 cd = rcu_dereference(p->perf_ctx_data); 5565 if (cd && cd->global) { 5566 cd->global = 0; 5567 detach_task_ctx_data(p); 5568 } 5569 } 5570 } 5571 } 5572 5573 static void detach_global_ctx_data(void) 5574 { 5575 if (refcount_dec_not_one(&global_ctx_data_ref)) 5576 return; 5577 5578 guard(percpu_write)(&global_ctx_data_rwsem); 5579 if (!refcount_dec_and_test(&global_ctx_data_ref)) 5580 return; 5581 5582 /* remove everything */ 5583 __detach_global_ctx_data(); 5584 } 5585 5586 static void detach_perf_ctx_data(struct perf_event *event) 5587 { 5588 struct task_struct *task = event->hw.target; 5589 5590 event->attach_state &= ~PERF_ATTACH_TASK_DATA; 5591 5592 if (task) 5593 return detach_task_ctx_data(task); 5594 5595 if (event->attach_state & PERF_ATTACH_GLOBAL_DATA) { 5596 detach_global_ctx_data(); 5597 event->attach_state &= ~PERF_ATTACH_GLOBAL_DATA; 5598 } 5599 } 5600 5601 static void unaccount_event(struct perf_event *event) 5602 { 5603 bool dec = false; 5604 5605 if (event->parent) 5606 return; 5607 5608 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB)) 5609 dec = true; 5610 if (event->attr.mmap || event->attr.mmap_data) 5611 atomic_dec(&nr_mmap_events); 5612 if (event->attr.build_id) 5613 atomic_dec(&nr_build_id_events); 5614 if (event->attr.comm) 5615 atomic_dec(&nr_comm_events); 5616 if (event->attr.namespaces) 5617 atomic_dec(&nr_namespaces_events); 5618 if (event->attr.cgroup) 5619 atomic_dec(&nr_cgroup_events); 5620 if (event->attr.task) 5621 atomic_dec(&nr_task_events); 5622 if (event->attr.freq) 5623 unaccount_freq_event(); 5624 if (event->attr.context_switch) { 5625 dec = true; 5626 atomic_dec(&nr_switch_events); 5627 } 5628 if (is_cgroup_event(event)) 5629 dec = true; 5630 if (has_branch_stack(event)) 5631 dec = true; 5632 if (event->attr.ksymbol) 5633 atomic_dec(&nr_ksymbol_events); 5634 if (event->attr.bpf_event) 5635 atomic_dec(&nr_bpf_events); 5636 if (event->attr.text_poke) 5637 atomic_dec(&nr_text_poke_events); 5638 5639 if (dec) { 5640 if (!atomic_add_unless(&perf_sched_count, -1, 1)) 5641 schedule_delayed_work(&perf_sched_work, HZ); 5642 } 5643 5644 unaccount_pmu_sb_event(event); 5645 } 5646 5647 static void perf_sched_delayed(struct work_struct *work) 5648 { 5649 mutex_lock(&perf_sched_mutex); 5650 if (atomic_dec_and_test(&perf_sched_count)) 5651 static_branch_disable(&perf_sched_events); 5652 mutex_unlock(&perf_sched_mutex); 5653 } 5654 5655 /* 5656 * The following implement mutual exclusion of events on "exclusive" pmus 5657 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled 5658 * at a time, so we disallow creating events that might conflict, namely: 5659 * 5660 * 1) cpu-wide events in the presence of per-task events, 5661 * 2) per-task events in the presence of cpu-wide events, 5662 * 3) two matching events on the same perf_event_context. 5663 * 5664 * The former two cases are handled in the allocation path (perf_event_alloc(), 5665 * _free_event()), the latter -- before the first perf_install_in_context(). 5666 */ 5667 static int exclusive_event_init(struct perf_event *event) 5668 { 5669 struct pmu *pmu = event->pmu; 5670 5671 if (!is_exclusive_pmu(pmu)) 5672 return 0; 5673 5674 /* 5675 * Prevent co-existence of per-task and cpu-wide events on the 5676 * same exclusive pmu. 5677 * 5678 * Negative pmu::exclusive_cnt means there are cpu-wide 5679 * events on this "exclusive" pmu, positive means there are 5680 * per-task events. 5681 * 5682 * Since this is called in perf_event_alloc() path, event::ctx 5683 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK 5684 * to mean "per-task event", because unlike other attach states it 5685 * never gets cleared. 5686 */ 5687 if (event->attach_state & PERF_ATTACH_TASK) { 5688 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt)) 5689 return -EBUSY; 5690 } else { 5691 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt)) 5692 return -EBUSY; 5693 } 5694 5695 event->attach_state |= PERF_ATTACH_EXCLUSIVE; 5696 5697 return 0; 5698 } 5699 5700 static void exclusive_event_destroy(struct perf_event *event) 5701 { 5702 struct pmu *pmu = event->pmu; 5703 5704 /* see comment in exclusive_event_init() */ 5705 if (event->attach_state & PERF_ATTACH_TASK) 5706 atomic_dec(&pmu->exclusive_cnt); 5707 else 5708 atomic_inc(&pmu->exclusive_cnt); 5709 5710 event->attach_state &= ~PERF_ATTACH_EXCLUSIVE; 5711 } 5712 5713 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2) 5714 { 5715 if ((e1->pmu == e2->pmu) && 5716 (e1->cpu == e2->cpu || 5717 e1->cpu == -1 || 5718 e2->cpu == -1)) 5719 return true; 5720 return false; 5721 } 5722 5723 static bool exclusive_event_installable(struct perf_event *event, 5724 struct perf_event_context *ctx) 5725 { 5726 struct perf_event *iter_event; 5727 struct pmu *pmu = event->pmu; 5728 5729 lockdep_assert_held(&ctx->mutex); 5730 5731 if (!is_exclusive_pmu(pmu)) 5732 return true; 5733 5734 list_for_each_entry(iter_event, &ctx->event_list, event_entry) { 5735 if (exclusive_event_match(iter_event, event)) 5736 return false; 5737 } 5738 5739 return true; 5740 } 5741 5742 static void perf_free_addr_filters(struct perf_event *event); 5743 5744 /* vs perf_event_alloc() error */ 5745 static void __free_event(struct perf_event *event) 5746 { 5747 struct pmu *pmu = event->pmu; 5748 5749 security_perf_event_free(event); 5750 5751 if (event->attach_state & PERF_ATTACH_CALLCHAIN) 5752 put_callchain_buffers(); 5753 5754 kfree(event->addr_filter_ranges); 5755 5756 if (event->attach_state & PERF_ATTACH_EXCLUSIVE) 5757 exclusive_event_destroy(event); 5758 5759 if (is_cgroup_event(event)) 5760 perf_detach_cgroup(event); 5761 5762 if (event->attach_state & PERF_ATTACH_TASK_DATA) 5763 detach_perf_ctx_data(event); 5764 5765 if (event->destroy) 5766 event->destroy(event); 5767 5768 /* 5769 * Must be after ->destroy(), due to uprobe_perf_close() using 5770 * hw.target. 5771 */ 5772 if (event->hw.target) 5773 put_task_struct(event->hw.target); 5774 5775 if (event->pmu_ctx) { 5776 /* 5777 * put_pmu_ctx() needs an event->ctx reference, because of 5778 * epc->ctx. 5779 */ 5780 WARN_ON_ONCE(!pmu); 5781 WARN_ON_ONCE(!event->ctx); 5782 WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx); 5783 put_pmu_ctx(event->pmu_ctx); 5784 } 5785 5786 /* 5787 * perf_event_free_task() relies on put_ctx() being 'last', in 5788 * particular all task references must be cleaned up. 5789 */ 5790 if (event->ctx) 5791 put_ctx(event->ctx); 5792 5793 if (pmu) { 5794 module_put(pmu->module); 5795 scoped_guard (spinlock, &pmu->events_lock) { 5796 list_del(&event->pmu_list); 5797 wake_up_var(pmu); 5798 } 5799 } 5800 5801 call_rcu(&event->rcu_head, free_event_rcu); 5802 } 5803 5804 static void mediated_pmu_unaccount_event(struct perf_event *event); 5805 5806 DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T)) 5807 5808 /* vs perf_event_alloc() success */ 5809 static void _free_event(struct perf_event *event) 5810 { 5811 irq_work_sync(&event->pending_irq); 5812 irq_work_sync(&event->pending_disable_irq); 5813 5814 unaccount_event(event); 5815 mediated_pmu_unaccount_event(event); 5816 5817 if (event->rb) { 5818 /* 5819 * Can happen when we close an event with re-directed output. 5820 * 5821 * Since we have a 0 refcount, perf_mmap_close() will skip 5822 * over us; possibly making our ring_buffer_put() the last. 5823 */ 5824 mutex_lock(&event->mmap_mutex); 5825 ring_buffer_attach(event, NULL); 5826 mutex_unlock(&event->mmap_mutex); 5827 } 5828 5829 perf_event_free_bpf_prog(event); 5830 perf_free_addr_filters(event); 5831 5832 __free_event(event); 5833 } 5834 5835 /* 5836 * Used to free events which have a known refcount of 1, such as in error paths 5837 * of inherited events. 5838 */ 5839 static void free_event(struct perf_event *event) 5840 { 5841 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1, 5842 "unexpected event refcount: %ld; ptr=%p\n", 5843 atomic_long_read(&event->refcount), event)) { 5844 /* leak to avoid use-after-free */ 5845 return; 5846 } 5847 5848 _free_event(event); 5849 } 5850 5851 /* 5852 * Remove user event from the owner task. 5853 */ 5854 static void perf_remove_from_owner(struct perf_event *event) 5855 { 5856 struct task_struct *owner; 5857 5858 rcu_read_lock(); 5859 /* 5860 * Matches the smp_store_release() in perf_event_exit_task(). If we 5861 * observe !owner it means the list deletion is complete and we can 5862 * indeed free this event, otherwise we need to serialize on 5863 * owner->perf_event_mutex. 5864 */ 5865 owner = READ_ONCE(event->owner); 5866 if (owner) { 5867 /* 5868 * Since delayed_put_task_struct() also drops the last 5869 * task reference we can safely take a new reference 5870 * while holding the rcu_read_lock(). 5871 */ 5872 get_task_struct(owner); 5873 } 5874 rcu_read_unlock(); 5875 5876 if (owner) { 5877 /* 5878 * If we're here through perf_event_exit_task() we're already 5879 * holding ctx->mutex which would be an inversion wrt. the 5880 * normal lock order. 5881 * 5882 * However we can safely take this lock because its the child 5883 * ctx->mutex. 5884 */ 5885 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING); 5886 5887 /* 5888 * We have to re-check the event->owner field, if it is cleared 5889 * we raced with perf_event_exit_task(), acquiring the mutex 5890 * ensured they're done, and we can proceed with freeing the 5891 * event. 5892 */ 5893 if (event->owner) { 5894 list_del_init(&event->owner_entry); 5895 smp_store_release(&event->owner, NULL); 5896 } 5897 mutex_unlock(&owner->perf_event_mutex); 5898 put_task_struct(owner); 5899 } 5900 } 5901 5902 static void put_event(struct perf_event *event) 5903 { 5904 struct perf_event *parent; 5905 5906 if (!atomic_long_dec_and_test(&event->refcount)) 5907 return; 5908 5909 parent = event->parent; 5910 _free_event(event); 5911 5912 /* Matches the refcount bump in inherit_event() */ 5913 if (parent) 5914 put_event(parent); 5915 } 5916 5917 /* 5918 * Kill an event dead; while event:refcount will preserve the event 5919 * object, it will not preserve its functionality. Once the last 'user' 5920 * gives up the object, we'll destroy the thing. 5921 */ 5922 int perf_event_release_kernel(struct perf_event *event) 5923 { 5924 struct perf_event_context *ctx = event->ctx; 5925 struct perf_event *child, *tmp; 5926 5927 /* 5928 * If we got here through err_alloc: free_event(event); we will not 5929 * have attached to a context yet. 5930 */ 5931 if (!ctx) { 5932 WARN_ON_ONCE(event->attach_state & 5933 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP)); 5934 goto no_ctx; 5935 } 5936 5937 if (!is_kernel_event(event)) 5938 perf_remove_from_owner(event); 5939 5940 ctx = perf_event_ctx_lock(event); 5941 WARN_ON_ONCE(ctx->parent_ctx); 5942 5943 /* 5944 * Mark this event as STATE_DEAD, there is no external reference to it 5945 * anymore. 5946 * 5947 * Anybody acquiring event->child_mutex after the below loop _must_ 5948 * also see this, most importantly inherit_event() which will avoid 5949 * placing more children on the list. 5950 * 5951 * Thus this guarantees that we will in fact observe and kill _ALL_ 5952 * child events. 5953 */ 5954 if (event->state > PERF_EVENT_STATE_REVOKED) { 5955 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD); 5956 } else { 5957 event->state = PERF_EVENT_STATE_DEAD; 5958 } 5959 5960 perf_event_ctx_unlock(event, ctx); 5961 5962 again: 5963 mutex_lock(&event->child_mutex); 5964 list_for_each_entry(child, &event->child_list, child_list) { 5965 /* 5966 * Cannot change, child events are not migrated, see the 5967 * comment with perf_event_ctx_lock_nested(). 5968 */ 5969 ctx = READ_ONCE(child->ctx); 5970 /* 5971 * Since child_mutex nests inside ctx::mutex, we must jump 5972 * through hoops. We start by grabbing a reference on the ctx. 5973 * 5974 * Since the event cannot get freed while we hold the 5975 * child_mutex, the context must also exist and have a !0 5976 * reference count. 5977 */ 5978 get_ctx(ctx); 5979 5980 /* 5981 * Now that we have a ctx ref, we can drop child_mutex, and 5982 * acquire ctx::mutex without fear of it going away. Then we 5983 * can re-acquire child_mutex. 5984 */ 5985 mutex_unlock(&event->child_mutex); 5986 mutex_lock(&ctx->mutex); 5987 mutex_lock(&event->child_mutex); 5988 5989 /* 5990 * Now that we hold ctx::mutex and child_mutex, revalidate our 5991 * state, if child is still the first entry, it didn't get freed 5992 * and we can continue doing so. 5993 */ 5994 tmp = list_first_entry_or_null(&event->child_list, 5995 struct perf_event, child_list); 5996 if (tmp == child) { 5997 perf_remove_from_context(child, DETACH_GROUP | DETACH_CHILD); 5998 } else { 5999 child = NULL; 6000 } 6001 6002 mutex_unlock(&event->child_mutex); 6003 mutex_unlock(&ctx->mutex); 6004 6005 if (child) { 6006 /* Last reference unless ->pending_task work is pending */ 6007 put_event(child); 6008 } 6009 put_ctx(ctx); 6010 6011 goto again; 6012 } 6013 mutex_unlock(&event->child_mutex); 6014 6015 no_ctx: 6016 /* 6017 * Last reference unless ->pending_task work is pending on this event 6018 * or any of its children. 6019 */ 6020 put_event(event); 6021 return 0; 6022 } 6023 EXPORT_SYMBOL_GPL(perf_event_release_kernel); 6024 6025 /* 6026 * Called when the last reference to the file is gone. 6027 */ 6028 static int perf_release(struct inode *inode, struct file *file) 6029 { 6030 perf_event_release_kernel(file->private_data); 6031 return 0; 6032 } 6033 6034 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 6035 { 6036 struct perf_event *child; 6037 u64 total = 0; 6038 6039 *enabled = 0; 6040 *running = 0; 6041 6042 mutex_lock(&event->child_mutex); 6043 6044 (void)perf_event_read(event, false); 6045 total += perf_event_count(event, false); 6046 6047 *enabled += event->total_time_enabled + 6048 atomic64_read(&event->child_total_time_enabled); 6049 *running += event->total_time_running + 6050 atomic64_read(&event->child_total_time_running); 6051 6052 list_for_each_entry(child, &event->child_list, child_list) { 6053 (void)perf_event_read(child, false); 6054 total += perf_event_count(child, false); 6055 *enabled += child->total_time_enabled; 6056 *running += child->total_time_running; 6057 } 6058 mutex_unlock(&event->child_mutex); 6059 6060 return total; 6061 } 6062 6063 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 6064 { 6065 struct perf_event_context *ctx; 6066 u64 count; 6067 6068 ctx = perf_event_ctx_lock(event); 6069 count = __perf_event_read_value(event, enabled, running); 6070 perf_event_ctx_unlock(event, ctx); 6071 6072 return count; 6073 } 6074 EXPORT_SYMBOL_GPL(perf_event_read_value); 6075 6076 static int __perf_read_group_add(struct perf_event *leader, 6077 u64 read_format, u64 *values) 6078 { 6079 struct perf_event_context *ctx = leader->ctx; 6080 struct perf_event *sub, *parent; 6081 unsigned long flags; 6082 int n = 1; /* skip @nr */ 6083 int ret; 6084 6085 ret = perf_event_read(leader, true); 6086 if (ret) 6087 return ret; 6088 6089 raw_spin_lock_irqsave(&ctx->lock, flags); 6090 /* 6091 * Verify the grouping between the parent and child (inherited) 6092 * events is still in tact. 6093 * 6094 * Specifically: 6095 * - leader->ctx->lock pins leader->sibling_list 6096 * - parent->child_mutex pins parent->child_list 6097 * - parent->ctx->mutex pins parent->sibling_list 6098 * 6099 * Because parent->ctx != leader->ctx (and child_list nests inside 6100 * ctx->mutex), group destruction is not atomic between children, also 6101 * see perf_event_release_kernel(). Additionally, parent can grow the 6102 * group. 6103 * 6104 * Therefore it is possible to have parent and child groups in a 6105 * different configuration and summing over such a beast makes no sense 6106 * what so ever. 6107 * 6108 * Reject this. 6109 */ 6110 parent = leader->parent; 6111 if (parent && 6112 (parent->group_generation != leader->group_generation || 6113 parent->nr_siblings != leader->nr_siblings)) { 6114 ret = -ECHILD; 6115 goto unlock; 6116 } 6117 6118 /* 6119 * Since we co-schedule groups, {enabled,running} times of siblings 6120 * will be identical to those of the leader, so we only publish one 6121 * set. 6122 */ 6123 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 6124 values[n++] += leader->total_time_enabled + 6125 atomic64_read(&leader->child_total_time_enabled); 6126 } 6127 6128 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 6129 values[n++] += leader->total_time_running + 6130 atomic64_read(&leader->child_total_time_running); 6131 } 6132 6133 /* 6134 * Write {count,id} tuples for every sibling. 6135 */ 6136 values[n++] += perf_event_count(leader, false); 6137 if (read_format & PERF_FORMAT_ID) 6138 values[n++] = primary_event_id(leader); 6139 if (read_format & PERF_FORMAT_LOST) 6140 values[n++] = atomic64_read(&leader->lost_samples); 6141 6142 for_each_sibling_event(sub, leader) { 6143 values[n++] += perf_event_count(sub, false); 6144 if (read_format & PERF_FORMAT_ID) 6145 values[n++] = primary_event_id(sub); 6146 if (read_format & PERF_FORMAT_LOST) 6147 values[n++] = atomic64_read(&sub->lost_samples); 6148 } 6149 6150 unlock: 6151 raw_spin_unlock_irqrestore(&ctx->lock, flags); 6152 return ret; 6153 } 6154 6155 static int perf_read_group(struct perf_event *event, 6156 u64 read_format, char __user *buf) 6157 { 6158 struct perf_event *leader = event->group_leader, *child; 6159 struct perf_event_context *ctx = leader->ctx; 6160 int ret; 6161 u64 *values; 6162 6163 lockdep_assert_held(&ctx->mutex); 6164 6165 values = kzalloc(event->read_size, GFP_KERNEL); 6166 if (!values) 6167 return -ENOMEM; 6168 6169 values[0] = 1 + leader->nr_siblings; 6170 6171 mutex_lock(&leader->child_mutex); 6172 6173 ret = __perf_read_group_add(leader, read_format, values); 6174 if (ret) 6175 goto unlock; 6176 6177 list_for_each_entry(child, &leader->child_list, child_list) { 6178 ret = __perf_read_group_add(child, read_format, values); 6179 if (ret) 6180 goto unlock; 6181 } 6182 6183 mutex_unlock(&leader->child_mutex); 6184 6185 ret = event->read_size; 6186 if (copy_to_user(buf, values, event->read_size)) 6187 ret = -EFAULT; 6188 goto out; 6189 6190 unlock: 6191 mutex_unlock(&leader->child_mutex); 6192 out: 6193 kfree(values); 6194 return ret; 6195 } 6196 6197 static int perf_read_one(struct perf_event *event, 6198 u64 read_format, char __user *buf) 6199 { 6200 u64 enabled, running; 6201 u64 values[5]; 6202 int n = 0; 6203 6204 values[n++] = __perf_event_read_value(event, &enabled, &running); 6205 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 6206 values[n++] = enabled; 6207 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 6208 values[n++] = running; 6209 if (read_format & PERF_FORMAT_ID) 6210 values[n++] = primary_event_id(event); 6211 if (read_format & PERF_FORMAT_LOST) 6212 values[n++] = atomic64_read(&event->lost_samples); 6213 6214 if (copy_to_user(buf, values, n * sizeof(u64))) 6215 return -EFAULT; 6216 6217 return n * sizeof(u64); 6218 } 6219 6220 static bool is_event_hup(struct perf_event *event) 6221 { 6222 bool no_children; 6223 6224 if (event->state > PERF_EVENT_STATE_EXIT) 6225 return false; 6226 6227 mutex_lock(&event->child_mutex); 6228 no_children = list_empty(&event->child_list); 6229 mutex_unlock(&event->child_mutex); 6230 return no_children; 6231 } 6232 6233 /* 6234 * Read the performance event - simple non blocking version for now 6235 */ 6236 static ssize_t 6237 __perf_read(struct perf_event *event, char __user *buf, size_t count) 6238 { 6239 u64 read_format = event->attr.read_format; 6240 int ret; 6241 6242 /* 6243 * Return end-of-file for a read on an event that is in 6244 * error state (i.e. because it was pinned but it couldn't be 6245 * scheduled on to the CPU at some point). 6246 */ 6247 if (event->state == PERF_EVENT_STATE_ERROR) 6248 return 0; 6249 6250 if (count < event->read_size) 6251 return -ENOSPC; 6252 6253 WARN_ON_ONCE(event->ctx->parent_ctx); 6254 if (read_format & PERF_FORMAT_GROUP) 6255 ret = perf_read_group(event, read_format, buf); 6256 else 6257 ret = perf_read_one(event, read_format, buf); 6258 6259 return ret; 6260 } 6261 6262 static ssize_t 6263 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) 6264 { 6265 struct perf_event *event = file->private_data; 6266 struct perf_event_context *ctx; 6267 int ret; 6268 6269 ret = security_perf_event_read(event); 6270 if (ret) 6271 return ret; 6272 6273 ctx = perf_event_ctx_lock(event); 6274 ret = __perf_read(event, buf, count); 6275 perf_event_ctx_unlock(event, ctx); 6276 6277 return ret; 6278 } 6279 6280 static __poll_t perf_poll(struct file *file, poll_table *wait) 6281 { 6282 struct perf_event *event = file->private_data; 6283 struct perf_buffer *rb; 6284 __poll_t events = EPOLLHUP; 6285 6286 if (event->state <= PERF_EVENT_STATE_REVOKED) 6287 return EPOLLERR; 6288 6289 poll_wait(file, &event->waitq, wait); 6290 6291 if (event->state <= PERF_EVENT_STATE_REVOKED) 6292 return EPOLLERR; 6293 6294 if (is_event_hup(event)) 6295 return events; 6296 6297 if (unlikely(READ_ONCE(event->state) == PERF_EVENT_STATE_ERROR && 6298 event->attr.pinned)) 6299 return EPOLLERR; 6300 6301 /* 6302 * Pin the event->rb by taking event->mmap_mutex; otherwise 6303 * perf_event_set_output() can swizzle our rb and make us miss wakeups. 6304 */ 6305 mutex_lock(&event->mmap_mutex); 6306 rb = event->rb; 6307 if (rb) 6308 events = atomic_xchg(&rb->poll, 0); 6309 mutex_unlock(&event->mmap_mutex); 6310 return events; 6311 } 6312 6313 static void _perf_event_reset(struct perf_event *event) 6314 { 6315 (void)perf_event_read(event, false); 6316 local64_set(&event->count, 0); 6317 perf_event_update_userpage(event); 6318 } 6319 6320 /* Assume it's not an event with inherit set. */ 6321 u64 perf_event_pause(struct perf_event *event, bool reset) 6322 { 6323 struct perf_event_context *ctx; 6324 u64 count; 6325 6326 ctx = perf_event_ctx_lock(event); 6327 WARN_ON_ONCE(event->attr.inherit); 6328 _perf_event_disable(event); 6329 count = local64_read(&event->count); 6330 if (reset) 6331 local64_set(&event->count, 0); 6332 perf_event_ctx_unlock(event, ctx); 6333 6334 return count; 6335 } 6336 EXPORT_SYMBOL_GPL(perf_event_pause); 6337 6338 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU 6339 static atomic_t nr_include_guest_events __read_mostly; 6340 6341 static atomic_t nr_mediated_pmu_vms __read_mostly; 6342 static DEFINE_MUTEX(perf_mediated_pmu_mutex); 6343 6344 /* !exclude_guest event of PMU with PERF_PMU_CAP_MEDIATED_VPMU */ 6345 static inline bool is_include_guest_event(struct perf_event *event) 6346 { 6347 if ((event->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU) && 6348 !event->attr.exclude_guest) 6349 return true; 6350 6351 return false; 6352 } 6353 6354 static int mediated_pmu_account_event(struct perf_event *event) 6355 { 6356 if (!is_include_guest_event(event)) 6357 return 0; 6358 6359 if (atomic_inc_not_zero(&nr_include_guest_events)) 6360 return 0; 6361 6362 guard(mutex)(&perf_mediated_pmu_mutex); 6363 if (atomic_read(&nr_mediated_pmu_vms)) 6364 return -EOPNOTSUPP; 6365 6366 atomic_inc(&nr_include_guest_events); 6367 return 0; 6368 } 6369 6370 static void mediated_pmu_unaccount_event(struct perf_event *event) 6371 { 6372 if (!is_include_guest_event(event)) 6373 return; 6374 6375 if (WARN_ON_ONCE(!atomic_read(&nr_include_guest_events))) 6376 return; 6377 6378 atomic_dec(&nr_include_guest_events); 6379 } 6380 6381 /* 6382 * Currently invoked at VM creation to 6383 * - Check whether there are existing !exclude_guest events of PMU with 6384 * PERF_PMU_CAP_MEDIATED_VPMU 6385 * - Set nr_mediated_pmu_vms to prevent !exclude_guest event creation on 6386 * PMUs with PERF_PMU_CAP_MEDIATED_VPMU 6387 * 6388 * No impact for the PMU without PERF_PMU_CAP_MEDIATED_VPMU. The perf 6389 * still owns all the PMU resources. 6390 */ 6391 int perf_create_mediated_pmu(void) 6392 { 6393 if (atomic_inc_not_zero(&nr_mediated_pmu_vms)) 6394 return 0; 6395 6396 guard(mutex)(&perf_mediated_pmu_mutex); 6397 if (atomic_read(&nr_include_guest_events)) 6398 return -EBUSY; 6399 6400 atomic_inc(&nr_mediated_pmu_vms); 6401 return 0; 6402 } 6403 EXPORT_SYMBOL_FOR_KVM(perf_create_mediated_pmu); 6404 6405 void perf_release_mediated_pmu(void) 6406 { 6407 if (WARN_ON_ONCE(!atomic_read(&nr_mediated_pmu_vms))) 6408 return; 6409 6410 atomic_dec(&nr_mediated_pmu_vms); 6411 } 6412 EXPORT_SYMBOL_FOR_KVM(perf_release_mediated_pmu); 6413 6414 /* When loading a guest's mediated PMU, schedule out all exclude_guest events. */ 6415 void perf_load_guest_context(void) 6416 { 6417 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 6418 6419 lockdep_assert_irqs_disabled(); 6420 6421 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx); 6422 6423 if (WARN_ON_ONCE(__this_cpu_read(guest_ctx_loaded))) 6424 return; 6425 6426 perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST); 6427 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_GUEST); 6428 if (cpuctx->task_ctx) { 6429 perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST); 6430 task_ctx_sched_out(cpuctx->task_ctx, NULL, EVENT_GUEST); 6431 } 6432 6433 perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST); 6434 if (cpuctx->task_ctx) 6435 perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST); 6436 6437 __this_cpu_write(guest_ctx_loaded, true); 6438 } 6439 EXPORT_SYMBOL_GPL(perf_load_guest_context); 6440 6441 void perf_put_guest_context(void) 6442 { 6443 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 6444 6445 lockdep_assert_irqs_disabled(); 6446 6447 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx); 6448 6449 if (WARN_ON_ONCE(!__this_cpu_read(guest_ctx_loaded))) 6450 return; 6451 6452 perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST); 6453 if (cpuctx->task_ctx) 6454 perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST); 6455 6456 perf_event_sched_in(cpuctx, cpuctx->task_ctx, NULL, EVENT_GUEST); 6457 6458 if (cpuctx->task_ctx) 6459 perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST); 6460 perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST); 6461 6462 __this_cpu_write(guest_ctx_loaded, false); 6463 } 6464 EXPORT_SYMBOL_GPL(perf_put_guest_context); 6465 #else 6466 static int mediated_pmu_account_event(struct perf_event *event) { return 0; } 6467 static void mediated_pmu_unaccount_event(struct perf_event *event) {} 6468 #endif 6469 6470 /* 6471 * Holding the top-level event's child_mutex means that any 6472 * descendant process that has inherited this event will block 6473 * in perf_event_exit_event() if it goes to exit, thus satisfying the 6474 * task existence requirements of perf_event_enable/disable. 6475 */ 6476 static void perf_event_for_each_child(struct perf_event *event, 6477 void (*func)(struct perf_event *)) 6478 { 6479 struct perf_event *child; 6480 6481 WARN_ON_ONCE(event->ctx->parent_ctx); 6482 6483 mutex_lock(&event->child_mutex); 6484 func(event); 6485 list_for_each_entry(child, &event->child_list, child_list) 6486 func(child); 6487 mutex_unlock(&event->child_mutex); 6488 } 6489 6490 static void perf_event_for_each(struct perf_event *event, 6491 void (*func)(struct perf_event *)) 6492 { 6493 struct perf_event_context *ctx = event->ctx; 6494 struct perf_event *sibling; 6495 6496 lockdep_assert_held(&ctx->mutex); 6497 6498 event = event->group_leader; 6499 6500 perf_event_for_each_child(event, func); 6501 for_each_sibling_event(sibling, event) 6502 perf_event_for_each_child(sibling, func); 6503 } 6504 6505 static void __perf_event_period(struct perf_event *event, 6506 struct perf_cpu_context *cpuctx, 6507 struct perf_event_context *ctx, 6508 void *info) 6509 { 6510 u64 value = *((u64 *)info); 6511 bool active; 6512 6513 if (event->attr.freq) { 6514 event->attr.sample_freq = value; 6515 } else { 6516 event->attr.sample_period = value; 6517 event->hw.sample_period = value; 6518 } 6519 6520 active = (event->state == PERF_EVENT_STATE_ACTIVE); 6521 if (active) { 6522 perf_pmu_disable(event->pmu); 6523 event->pmu->stop(event, PERF_EF_UPDATE); 6524 } 6525 6526 local64_set(&event->hw.period_left, 0); 6527 6528 if (active) { 6529 event->pmu->start(event, PERF_EF_RELOAD); 6530 /* 6531 * Once the period is force-reset, the event starts immediately. 6532 * But the event/group could be throttled. Unthrottle the 6533 * event/group now to avoid the next tick trying to unthrottle 6534 * while we already re-started the event/group. 6535 */ 6536 if (event->hw.interrupts == MAX_INTERRUPTS) 6537 perf_event_unthrottle_group(event, true); 6538 perf_pmu_enable(event->pmu); 6539 } 6540 } 6541 6542 static int perf_event_check_period(struct perf_event *event, u64 value) 6543 { 6544 return event->pmu->check_period(event, value); 6545 } 6546 6547 static int _perf_event_period(struct perf_event *event, u64 value) 6548 { 6549 if (!is_sampling_event(event)) 6550 return -EINVAL; 6551 6552 if (!value) 6553 return -EINVAL; 6554 6555 if (event->attr.freq) { 6556 if (value > sysctl_perf_event_sample_rate) 6557 return -EINVAL; 6558 } else { 6559 if (perf_event_check_period(event, value)) 6560 return -EINVAL; 6561 if (value & (1ULL << 63)) 6562 return -EINVAL; 6563 } 6564 6565 event_function_call(event, __perf_event_period, &value); 6566 6567 return 0; 6568 } 6569 6570 int perf_event_period(struct perf_event *event, u64 value) 6571 { 6572 struct perf_event_context *ctx; 6573 int ret; 6574 6575 ctx = perf_event_ctx_lock(event); 6576 ret = _perf_event_period(event, value); 6577 perf_event_ctx_unlock(event, ctx); 6578 6579 return ret; 6580 } 6581 EXPORT_SYMBOL_GPL(perf_event_period); 6582 6583 static const struct file_operations perf_fops; 6584 6585 static inline bool is_perf_file(struct fd f) 6586 { 6587 return !fd_empty(f) && fd_file(f)->f_op == &perf_fops; 6588 } 6589 6590 static int perf_event_set_output(struct perf_event *event, 6591 struct perf_event *output_event); 6592 static int perf_event_set_filter(struct perf_event *event, void __user *arg); 6593 static int perf_copy_attr(struct perf_event_attr __user *uattr, 6594 struct perf_event_attr *attr); 6595 static int __perf_event_set_bpf_prog(struct perf_event *event, 6596 struct bpf_prog *prog, 6597 u64 bpf_cookie); 6598 6599 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg) 6600 { 6601 void (*func)(struct perf_event *); 6602 u32 flags = arg; 6603 6604 if (event->state <= PERF_EVENT_STATE_REVOKED) 6605 return -ENODEV; 6606 6607 switch (cmd) { 6608 case PERF_EVENT_IOC_ENABLE: 6609 func = _perf_event_enable; 6610 break; 6611 case PERF_EVENT_IOC_DISABLE: 6612 func = _perf_event_disable; 6613 break; 6614 case PERF_EVENT_IOC_RESET: 6615 func = _perf_event_reset; 6616 break; 6617 6618 case PERF_EVENT_IOC_REFRESH: 6619 return _perf_event_refresh(event, arg); 6620 6621 case PERF_EVENT_IOC_PERIOD: 6622 { 6623 u64 value; 6624 6625 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value))) 6626 return -EFAULT; 6627 6628 return _perf_event_period(event, value); 6629 } 6630 case PERF_EVENT_IOC_ID: 6631 { 6632 u64 id = primary_event_id(event); 6633 6634 if (copy_to_user((void __user *)arg, &id, sizeof(id))) 6635 return -EFAULT; 6636 return 0; 6637 } 6638 6639 case PERF_EVENT_IOC_SET_OUTPUT: 6640 { 6641 CLASS(fd, output)(arg); // arg == -1 => empty 6642 struct perf_event *output_event = NULL; 6643 if (arg != -1) { 6644 if (!is_perf_file(output)) 6645 return -EBADF; 6646 output_event = fd_file(output)->private_data; 6647 } 6648 return perf_event_set_output(event, output_event); 6649 } 6650 6651 case PERF_EVENT_IOC_SET_FILTER: 6652 return perf_event_set_filter(event, (void __user *)arg); 6653 6654 case PERF_EVENT_IOC_SET_BPF: 6655 { 6656 struct bpf_prog *prog; 6657 int err; 6658 6659 prog = bpf_prog_get(arg); 6660 if (IS_ERR(prog)) 6661 return PTR_ERR(prog); 6662 6663 err = __perf_event_set_bpf_prog(event, prog, 0); 6664 if (err) { 6665 bpf_prog_put(prog); 6666 return err; 6667 } 6668 6669 return 0; 6670 } 6671 6672 case PERF_EVENT_IOC_PAUSE_OUTPUT: { 6673 struct perf_buffer *rb; 6674 6675 rcu_read_lock(); 6676 rb = rcu_dereference(event->rb); 6677 if (!rb || !rb->nr_pages) { 6678 rcu_read_unlock(); 6679 return -EINVAL; 6680 } 6681 rb_toggle_paused(rb, !!arg); 6682 rcu_read_unlock(); 6683 return 0; 6684 } 6685 6686 case PERF_EVENT_IOC_QUERY_BPF: 6687 return perf_event_query_prog_array(event, (void __user *)arg); 6688 6689 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: { 6690 struct perf_event_attr new_attr; 6691 int err = perf_copy_attr((struct perf_event_attr __user *)arg, 6692 &new_attr); 6693 6694 if (err) 6695 return err; 6696 6697 return perf_event_modify_attr(event, &new_attr); 6698 } 6699 default: 6700 return -ENOTTY; 6701 } 6702 6703 if (flags & PERF_IOC_FLAG_GROUP) 6704 perf_event_for_each(event, func); 6705 else 6706 perf_event_for_each_child(event, func); 6707 6708 return 0; 6709 } 6710 6711 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg) 6712 { 6713 struct perf_event *event = file->private_data; 6714 struct perf_event_context *ctx; 6715 long ret; 6716 6717 /* Treat ioctl like writes as it is likely a mutating operation. */ 6718 ret = security_perf_event_write(event); 6719 if (ret) 6720 return ret; 6721 6722 ctx = perf_event_ctx_lock(event); 6723 ret = _perf_ioctl(event, cmd, arg); 6724 perf_event_ctx_unlock(event, ctx); 6725 6726 return ret; 6727 } 6728 6729 #ifdef CONFIG_COMPAT 6730 static long perf_compat_ioctl(struct file *file, unsigned int cmd, 6731 unsigned long arg) 6732 { 6733 switch (_IOC_NR(cmd)) { 6734 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER): 6735 case _IOC_NR(PERF_EVENT_IOC_ID): 6736 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF): 6737 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES): 6738 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */ 6739 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) { 6740 cmd &= ~IOCSIZE_MASK; 6741 cmd |= sizeof(void *) << IOCSIZE_SHIFT; 6742 } 6743 break; 6744 } 6745 return perf_ioctl(file, cmd, arg); 6746 } 6747 #else 6748 # define perf_compat_ioctl NULL 6749 #endif 6750 6751 int perf_event_task_enable(void) 6752 { 6753 struct perf_event_context *ctx; 6754 struct perf_event *event; 6755 6756 mutex_lock(¤t->perf_event_mutex); 6757 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) { 6758 ctx = perf_event_ctx_lock(event); 6759 perf_event_for_each_child(event, _perf_event_enable); 6760 perf_event_ctx_unlock(event, ctx); 6761 } 6762 mutex_unlock(¤t->perf_event_mutex); 6763 6764 return 0; 6765 } 6766 6767 int perf_event_task_disable(void) 6768 { 6769 struct perf_event_context *ctx; 6770 struct perf_event *event; 6771 6772 mutex_lock(¤t->perf_event_mutex); 6773 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) { 6774 ctx = perf_event_ctx_lock(event); 6775 perf_event_for_each_child(event, _perf_event_disable); 6776 perf_event_ctx_unlock(event, ctx); 6777 } 6778 mutex_unlock(¤t->perf_event_mutex); 6779 6780 return 0; 6781 } 6782 6783 static int perf_event_index(struct perf_event *event) 6784 { 6785 if (event->hw.state & PERF_HES_STOPPED) 6786 return 0; 6787 6788 if (event->state != PERF_EVENT_STATE_ACTIVE) 6789 return 0; 6790 6791 return event->pmu->event_idx(event); 6792 } 6793 6794 static void perf_event_init_userpage(struct perf_event *event) 6795 { 6796 struct perf_event_mmap_page *userpg; 6797 struct perf_buffer *rb; 6798 6799 rcu_read_lock(); 6800 rb = rcu_dereference(event->rb); 6801 if (!rb) 6802 goto unlock; 6803 6804 userpg = rb->user_page; 6805 6806 /* Allow new userspace to detect that bit 0 is deprecated */ 6807 userpg->cap_bit0_is_deprecated = 1; 6808 userpg->size = offsetof(struct perf_event_mmap_page, __reserved); 6809 userpg->data_offset = PAGE_SIZE; 6810 userpg->data_size = perf_data_size(rb); 6811 6812 unlock: 6813 rcu_read_unlock(); 6814 } 6815 6816 void __weak arch_perf_update_userpage( 6817 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now) 6818 { 6819 } 6820 6821 /* 6822 * Callers need to ensure there can be no nesting of this function, otherwise 6823 * the seqlock logic goes bad. We can not serialize this because the arch 6824 * code calls this from NMI context. 6825 */ 6826 void perf_event_update_userpage(struct perf_event *event) 6827 { 6828 struct perf_event_mmap_page *userpg; 6829 struct perf_buffer *rb; 6830 u64 enabled, running, now; 6831 6832 rcu_read_lock(); 6833 rb = rcu_dereference(event->rb); 6834 if (!rb) 6835 goto unlock; 6836 6837 /* 6838 * Disable preemption to guarantee consistent time stamps are stored to 6839 * the user page. 6840 */ 6841 preempt_disable(); 6842 6843 /* 6844 * Compute total_time_enabled, total_time_running based on snapshot 6845 * values taken when the event was last scheduled in. 6846 * 6847 * We cannot simply call update_context_time() because doing so would 6848 * lead to deadlock when called from NMI context. 6849 */ 6850 calc_timer_values(event, &now, &enabled, &running); 6851 6852 userpg = rb->user_page; 6853 6854 ++userpg->lock; 6855 barrier(); 6856 userpg->index = perf_event_index(event); 6857 userpg->offset = perf_event_count(event, false); 6858 if (userpg->index) 6859 userpg->offset -= local64_read(&event->hw.prev_count); 6860 6861 userpg->time_enabled = enabled + 6862 atomic64_read(&event->child_total_time_enabled); 6863 6864 userpg->time_running = running + 6865 atomic64_read(&event->child_total_time_running); 6866 6867 arch_perf_update_userpage(event, userpg, now); 6868 6869 barrier(); 6870 ++userpg->lock; 6871 preempt_enable(); 6872 unlock: 6873 rcu_read_unlock(); 6874 } 6875 EXPORT_SYMBOL_GPL(perf_event_update_userpage); 6876 6877 static void ring_buffer_attach(struct perf_event *event, 6878 struct perf_buffer *rb) 6879 { 6880 struct perf_buffer *old_rb = NULL; 6881 unsigned long flags; 6882 6883 WARN_ON_ONCE(event->parent); 6884 6885 if (event->rb) { 6886 /* 6887 * Should be impossible, we set this when removing 6888 * event->rb_entry and wait/clear when adding event->rb_entry. 6889 */ 6890 WARN_ON_ONCE(event->rcu_pending); 6891 6892 old_rb = event->rb; 6893 spin_lock_irqsave(&old_rb->event_lock, flags); 6894 list_del_rcu(&event->rb_entry); 6895 spin_unlock_irqrestore(&old_rb->event_lock, flags); 6896 6897 event->rcu_batches = get_state_synchronize_rcu(); 6898 event->rcu_pending = 1; 6899 } 6900 6901 if (rb) { 6902 if (event->rcu_pending) { 6903 cond_synchronize_rcu(event->rcu_batches); 6904 event->rcu_pending = 0; 6905 } 6906 6907 spin_lock_irqsave(&rb->event_lock, flags); 6908 list_add_rcu(&event->rb_entry, &rb->event_list); 6909 spin_unlock_irqrestore(&rb->event_lock, flags); 6910 } 6911 6912 /* 6913 * Avoid racing with perf_mmap_close(AUX): stop the event 6914 * before swizzling the event::rb pointer; if it's getting 6915 * unmapped, its aux_mmap_count will be 0 and it won't 6916 * restart. See the comment in __perf_pmu_output_stop(). 6917 * 6918 * Data will inevitably be lost when set_output is done in 6919 * mid-air, but then again, whoever does it like this is 6920 * not in for the data anyway. 6921 */ 6922 if (has_aux(event)) 6923 perf_event_stop(event, 0); 6924 6925 rcu_assign_pointer(event->rb, rb); 6926 6927 if (old_rb) { 6928 ring_buffer_put(old_rb); 6929 /* 6930 * Since we detached before setting the new rb, so that we 6931 * could attach the new rb, we could have missed a wakeup. 6932 * Provide it now. 6933 */ 6934 wake_up_all(&event->waitq); 6935 } 6936 } 6937 6938 static void ring_buffer_wakeup(struct perf_event *event) 6939 { 6940 struct perf_buffer *rb; 6941 6942 if (event->parent) 6943 event = event->parent; 6944 6945 rcu_read_lock(); 6946 rb = rcu_dereference(event->rb); 6947 if (rb) { 6948 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) 6949 wake_up_all(&event->waitq); 6950 } 6951 rcu_read_unlock(); 6952 } 6953 6954 struct perf_buffer *ring_buffer_get(struct perf_event *event) 6955 { 6956 struct perf_buffer *rb; 6957 6958 if (event->parent) 6959 event = event->parent; 6960 6961 rcu_read_lock(); 6962 rb = rcu_dereference(event->rb); 6963 if (rb) { 6964 if (!refcount_inc_not_zero(&rb->refcount)) 6965 rb = NULL; 6966 } 6967 rcu_read_unlock(); 6968 6969 return rb; 6970 } 6971 6972 void ring_buffer_put(struct perf_buffer *rb) 6973 { 6974 if (!refcount_dec_and_test(&rb->refcount)) 6975 return; 6976 6977 WARN_ON_ONCE(!list_empty(&rb->event_list)); 6978 6979 call_rcu(&rb->rcu_head, rb_free_rcu); 6980 } 6981 6982 typedef void (*mapped_f)(struct perf_event *event, struct mm_struct *mm); 6983 6984 #define get_mapped(event, func) \ 6985 ({ struct pmu *pmu; \ 6986 mapped_f f = NULL; \ 6987 guard(rcu)(); \ 6988 pmu = READ_ONCE(event->pmu); \ 6989 if (pmu) \ 6990 f = pmu->func; \ 6991 f; \ 6992 }) 6993 6994 static void perf_mmap_open(struct vm_area_struct *vma) 6995 { 6996 struct perf_event *event = vma->vm_file->private_data; 6997 mapped_f mapped = get_mapped(event, event_mapped); 6998 6999 refcount_inc(&event->mmap_count); 7000 refcount_inc(&event->rb->mmap_count); 7001 7002 if (vma->vm_pgoff) 7003 refcount_inc(&event->rb->aux_mmap_count); 7004 7005 if (mapped) 7006 mapped(event, vma->vm_mm); 7007 } 7008 7009 static void perf_pmu_output_stop(struct perf_event *event); 7010 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb); 7011 7012 /* 7013 * A buffer can be mmap()ed multiple times; either directly through the same 7014 * event, or through other events by use of perf_event_set_output(). 7015 * 7016 * In order to undo the VM accounting done by perf_mmap() we need to destroy 7017 * the buffer here, where we still have a VM context. This means we need 7018 * to detach all events redirecting to us. 7019 */ 7020 static void perf_mmap_close(struct vm_area_struct *vma) 7021 { 7022 struct perf_event *event = vma->vm_file->private_data; 7023 mapped_f unmapped = get_mapped(event, event_unmapped); 7024 struct perf_buffer *rb = ring_buffer_get(event); 7025 struct user_struct *mmap_user = rb->mmap_user; 7026 bool detach_rest = false; 7027 7028 /* FIXIES vs perf_pmu_unregister() */ 7029 if (unmapped) 7030 unmapped(event, vma->vm_mm); 7031 7032 /* 7033 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex 7034 * to avoid complications. 7035 */ 7036 if (rb_has_aux(rb) && vma->vm_pgoff == rb->aux_pgoff && 7037 refcount_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) { 7038 /* 7039 * Stop all AUX events that are writing to this buffer, 7040 * so that we can free its AUX pages and corresponding PMU 7041 * data. Note that after rb::aux_mmap_count dropped to zero, 7042 * they won't start any more (see perf_aux_output_begin()). 7043 */ 7044 perf_pmu_output_stop(event); 7045 7046 /* now it's safe to free the pages */ 7047 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->locked_vm); 7048 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm); 7049 7050 /* this has to be the last one */ 7051 rb_free_aux(rb); 7052 WARN_ON_ONCE(refcount_read(&rb->aux_refcount)); 7053 7054 mutex_unlock(&rb->aux_mutex); 7055 } 7056 7057 if (refcount_dec_and_test(&rb->mmap_count)) 7058 detach_rest = true; 7059 7060 if (!refcount_dec_and_mutex_lock(&event->mmap_count, &event->mmap_mutex)) 7061 goto out_put; 7062 7063 ring_buffer_attach(event, NULL); 7064 mutex_unlock(&event->mmap_mutex); 7065 7066 /* If there's still other mmap()s of this buffer, we're done. */ 7067 if (!detach_rest) 7068 goto out_put; 7069 7070 /* 7071 * No other mmap()s, detach from all other events that might redirect 7072 * into the now unreachable buffer. Somewhat complicated by the 7073 * fact that rb::event_lock otherwise nests inside mmap_mutex. 7074 */ 7075 again: 7076 rcu_read_lock(); 7077 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) { 7078 if (!atomic_long_inc_not_zero(&event->refcount)) { 7079 /* 7080 * This event is en-route to free_event() which will 7081 * detach it and remove it from the list. 7082 */ 7083 continue; 7084 } 7085 rcu_read_unlock(); 7086 7087 mutex_lock(&event->mmap_mutex); 7088 /* 7089 * Check we didn't race with perf_event_set_output() which can 7090 * swizzle the rb from under us while we were waiting to 7091 * acquire mmap_mutex. 7092 * 7093 * If we find a different rb; ignore this event, a next 7094 * iteration will no longer find it on the list. We have to 7095 * still restart the iteration to make sure we're not now 7096 * iterating the wrong list. 7097 */ 7098 if (event->rb == rb) 7099 ring_buffer_attach(event, NULL); 7100 7101 mutex_unlock(&event->mmap_mutex); 7102 put_event(event); 7103 7104 /* 7105 * Restart the iteration; either we're on the wrong list or 7106 * destroyed its integrity by doing a deletion. 7107 */ 7108 goto again; 7109 } 7110 rcu_read_unlock(); 7111 7112 /* 7113 * It could be there's still a few 0-ref events on the list; they'll 7114 * get cleaned up by free_event() -- they'll also still have their 7115 * ref on the rb and will free it whenever they are done with it. 7116 * 7117 * Aside from that, this buffer is 'fully' detached and unmapped, 7118 * undo the VM accounting. 7119 */ 7120 perf_mmap_unaccount(vma, rb); 7121 7122 out_put: 7123 ring_buffer_put(rb); /* could be last */ 7124 } 7125 7126 static vm_fault_t perf_mmap_pfn_mkwrite(struct vm_fault *vmf) 7127 { 7128 /* The first page is the user control page, others are read-only. */ 7129 return vmf->pgoff == 0 ? 0 : VM_FAULT_SIGBUS; 7130 } 7131 7132 static int perf_mmap_may_split(struct vm_area_struct *vma, unsigned long addr) 7133 { 7134 /* 7135 * Forbid splitting perf mappings to prevent refcount leaks due to 7136 * the resulting non-matching offsets and sizes. See open()/close(). 7137 */ 7138 return -EINVAL; 7139 } 7140 7141 static const struct vm_operations_struct perf_mmap_vmops = { 7142 .open = perf_mmap_open, 7143 .close = perf_mmap_close, /* non mergeable */ 7144 .pfn_mkwrite = perf_mmap_pfn_mkwrite, 7145 .may_split = perf_mmap_may_split, 7146 }; 7147 7148 static int map_range(struct perf_buffer *rb, struct vm_area_struct *vma) 7149 { 7150 unsigned long nr_pages = vma_pages(vma); 7151 int err = 0; 7152 unsigned long pagenum; 7153 7154 /* 7155 * We map this as a VM_PFNMAP VMA. 7156 * 7157 * This is not ideal as this is designed broadly for mappings of PFNs 7158 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which 7159 * !pfn_valid(pfn). 7160 * 7161 * We are mapping kernel-allocated memory (memory we manage ourselves) 7162 * which would more ideally be mapped using vm_insert_page() or a 7163 * similar mechanism, that is as a VM_MIXEDMAP mapping. 7164 * 7165 * However this won't work here, because: 7166 * 7167 * 1. It uses vma->vm_page_prot, but this field has not been completely 7168 * setup at the point of the f_op->mmp() hook, so we are unable to 7169 * indicate that this should be mapped CoW in order that the 7170 * mkwrite() hook can be invoked to make the first page R/W and the 7171 * rest R/O as desired. 7172 * 7173 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in 7174 * vm_normal_page() returning a struct page * pointer, which means 7175 * vm_ops->page_mkwrite() will be invoked rather than 7176 * vm_ops->pfn_mkwrite(), and this means we have to set page->mapping 7177 * to work around retry logic in the fault handler, however this 7178 * field is no longer allowed to be used within struct page. 7179 * 7180 * 3. Having a struct page * made available in the fault logic also 7181 * means that the page gets put on the rmap and becomes 7182 * inappropriately accessible and subject to map and ref counting. 7183 * 7184 * Ideally we would have a mechanism that could explicitly express our 7185 * desires, but this is not currently the case, so we instead use 7186 * VM_PFNMAP. 7187 * 7188 * We manage the lifetime of these mappings with internal refcounts (see 7189 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of 7190 * this mapping is maintained correctly. 7191 */ 7192 for (pagenum = 0; pagenum < nr_pages; pagenum++) { 7193 unsigned long va = vma->vm_start + PAGE_SIZE * pagenum; 7194 struct page *page = perf_mmap_to_page(rb, vma->vm_pgoff + pagenum); 7195 7196 if (page == NULL) { 7197 err = -EINVAL; 7198 break; 7199 } 7200 7201 /* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */ 7202 err = remap_pfn_range(vma, va, page_to_pfn(page), PAGE_SIZE, 7203 vm_get_page_prot(vma->vm_flags & ~VM_SHARED)); 7204 if (err) 7205 break; 7206 } 7207 7208 #ifdef CONFIG_MMU 7209 /* Clear any partial mappings on error. */ 7210 if (err) 7211 zap_vma_range(vma, vma->vm_start, nr_pages * PAGE_SIZE); 7212 #endif 7213 7214 return err; 7215 } 7216 7217 static bool perf_mmap_calc_limits(struct vm_area_struct *vma, long *user_extra, long *extra) 7218 { 7219 unsigned long user_locked, user_lock_limit, locked, lock_limit; 7220 struct user_struct *user = current_user(); 7221 7222 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10); 7223 /* Increase the limit linearly with more CPUs */ 7224 user_lock_limit *= num_online_cpus(); 7225 7226 user_locked = atomic_long_read(&user->locked_vm); 7227 7228 /* 7229 * sysctl_perf_event_mlock may have changed, so that 7230 * user->locked_vm > user_lock_limit 7231 */ 7232 if (user_locked > user_lock_limit) 7233 user_locked = user_lock_limit; 7234 user_locked += *user_extra; 7235 7236 if (user_locked > user_lock_limit) { 7237 /* 7238 * charge locked_vm until it hits user_lock_limit; 7239 * charge the rest from pinned_vm 7240 */ 7241 *extra = user_locked - user_lock_limit; 7242 *user_extra -= *extra; 7243 } 7244 7245 lock_limit = rlimit(RLIMIT_MEMLOCK); 7246 lock_limit >>= PAGE_SHIFT; 7247 locked = atomic64_read(&vma->vm_mm->pinned_vm) + *extra; 7248 7249 return locked <= lock_limit || !perf_is_paranoid() || capable(CAP_IPC_LOCK); 7250 } 7251 7252 static void perf_mmap_account(struct vm_area_struct *vma, long user_extra, long extra) 7253 { 7254 struct user_struct *user = current_user(); 7255 7256 atomic_long_add(user_extra, &user->locked_vm); 7257 atomic64_add(extra, &vma->vm_mm->pinned_vm); 7258 } 7259 7260 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb) 7261 { 7262 struct user_struct *user = rb->mmap_user; 7263 7264 atomic_long_sub((perf_data_size(rb) >> PAGE_SHIFT) + 1 - rb->mmap_locked, 7265 &user->locked_vm); 7266 atomic64_sub(rb->mmap_locked, &vma->vm_mm->pinned_vm); 7267 } 7268 7269 static int perf_mmap_rb(struct vm_area_struct *vma, struct perf_event *event, 7270 unsigned long nr_pages) 7271 { 7272 long extra = 0, user_extra = nr_pages; 7273 struct perf_buffer *rb; 7274 int rb_flags = 0; 7275 7276 nr_pages -= 1; 7277 7278 /* 7279 * If we have rb pages ensure they're a power-of-two number, so we 7280 * can do bitmasks instead of modulo. 7281 */ 7282 if (nr_pages != 0 && !is_power_of_2(nr_pages)) 7283 return -EINVAL; 7284 7285 WARN_ON_ONCE(event->ctx->parent_ctx); 7286 7287 if (event->rb) { 7288 if (data_page_nr(event->rb) != nr_pages) 7289 return -EINVAL; 7290 7291 /* 7292 * If this event doesn't have mmap_count, we're attempting to 7293 * create an alias of another event's mmap(); this would mean 7294 * both events will end up scribbling the same user_page; 7295 * which makes no sense. 7296 */ 7297 if (!refcount_read(&event->mmap_count)) 7298 return -EBUSY; 7299 7300 if (refcount_inc_not_zero(&event->rb->mmap_count)) { 7301 /* 7302 * Success -- managed to mmap() the same buffer 7303 * multiple times. 7304 */ 7305 perf_mmap_account(vma, user_extra, extra); 7306 refcount_inc(&event->mmap_count); 7307 return 0; 7308 } 7309 7310 /* 7311 * Raced against perf_mmap_close()'s 7312 * refcount_dec_and_mutex_lock() remove the 7313 * event and continue as if !event->rb 7314 */ 7315 ring_buffer_attach(event, NULL); 7316 } 7317 7318 if (!perf_mmap_calc_limits(vma, &user_extra, &extra)) 7319 return -EPERM; 7320 7321 if (vma->vm_flags & VM_WRITE) 7322 rb_flags |= RING_BUFFER_WRITABLE; 7323 7324 rb = rb_alloc(nr_pages, 7325 event->attr.watermark ? event->attr.wakeup_watermark : 0, 7326 event->cpu, rb_flags); 7327 7328 if (!rb) 7329 return -ENOMEM; 7330 7331 rb->mmap_locked = extra; 7332 7333 ring_buffer_attach(event, rb); 7334 7335 perf_event_update_time(event); 7336 perf_event_init_userpage(event); 7337 perf_event_update_userpage(event); 7338 7339 perf_mmap_account(vma, user_extra, extra); 7340 refcount_set(&event->mmap_count, 1); 7341 7342 return 0; 7343 } 7344 7345 static int perf_mmap_aux(struct vm_area_struct *vma, struct perf_event *event, 7346 unsigned long nr_pages) 7347 { 7348 long extra = 0, user_extra = nr_pages; 7349 u64 aux_offset, aux_size; 7350 struct perf_buffer *rb; 7351 int ret, rb_flags = 0; 7352 7353 rb = event->rb; 7354 if (!rb) 7355 return -EINVAL; 7356 7357 guard(mutex)(&rb->aux_mutex); 7358 7359 /* 7360 * AUX area mapping: if rb->aux_nr_pages != 0, it's already 7361 * mapped, all subsequent mappings should have the same size 7362 * and offset. Must be above the normal perf buffer. 7363 */ 7364 aux_offset = READ_ONCE(rb->user_page->aux_offset); 7365 aux_size = READ_ONCE(rb->user_page->aux_size); 7366 7367 if (aux_offset < perf_data_size(rb) + PAGE_SIZE) 7368 return -EINVAL; 7369 7370 if (aux_offset != vma->vm_pgoff << PAGE_SHIFT) 7371 return -EINVAL; 7372 7373 /* already mapped with a different offset */ 7374 if (rb_has_aux(rb) && rb->aux_pgoff != vma->vm_pgoff) 7375 return -EINVAL; 7376 7377 if (aux_size != nr_pages * PAGE_SIZE) 7378 return -EINVAL; 7379 7380 /* already mapped with a different size */ 7381 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages) 7382 return -EINVAL; 7383 7384 if (!is_power_of_2(nr_pages)) 7385 return -EINVAL; 7386 7387 if (!refcount_inc_not_zero(&rb->mmap_count)) 7388 return -EINVAL; 7389 7390 if (rb_has_aux(rb)) { 7391 refcount_inc(&rb->aux_mmap_count); 7392 7393 } else { 7394 if (!perf_mmap_calc_limits(vma, &user_extra, &extra)) { 7395 refcount_dec(&rb->mmap_count); 7396 return -EPERM; 7397 } 7398 7399 WARN_ON(!rb && event->rb); 7400 7401 if (vma->vm_flags & VM_WRITE) 7402 rb_flags |= RING_BUFFER_WRITABLE; 7403 7404 ret = rb_alloc_aux(rb, event, vma->vm_pgoff, nr_pages, 7405 event->attr.aux_watermark, rb_flags); 7406 if (ret) { 7407 refcount_dec(&rb->mmap_count); 7408 return ret; 7409 } 7410 7411 refcount_set(&rb->aux_mmap_count, 1); 7412 rb->aux_mmap_locked = extra; 7413 } 7414 7415 perf_mmap_account(vma, user_extra, extra); 7416 refcount_inc(&event->mmap_count); 7417 7418 return 0; 7419 } 7420 7421 static int perf_mmap(struct file *file, struct vm_area_struct *vma) 7422 { 7423 struct perf_event *event = file->private_data; 7424 unsigned long vma_size, nr_pages; 7425 mapped_f mapped; 7426 int ret; 7427 7428 /* 7429 * Don't allow mmap() of inherited per-task counters. This would 7430 * create a performance issue due to all children writing to the 7431 * same rb. 7432 */ 7433 if (event->cpu == -1 && event->attr.inherit) 7434 return -EINVAL; 7435 7436 if (!(vma->vm_flags & VM_SHARED)) 7437 return -EINVAL; 7438 7439 ret = security_perf_event_read(event); 7440 if (ret) 7441 return ret; 7442 7443 vma_size = vma->vm_end - vma->vm_start; 7444 nr_pages = vma_size / PAGE_SIZE; 7445 7446 if (nr_pages > INT_MAX) 7447 return -ENOMEM; 7448 7449 if (vma_size != PAGE_SIZE * nr_pages) 7450 return -EINVAL; 7451 7452 scoped_guard (mutex, &event->mmap_mutex) { 7453 /* 7454 * This relies on __pmu_detach_event() taking mmap_mutex after marking 7455 * the event REVOKED. Either we observe the state, or __pmu_detach_event() 7456 * will detach the rb created here. 7457 */ 7458 if (event->state <= PERF_EVENT_STATE_REVOKED) 7459 return -ENODEV; 7460 7461 if (vma->vm_pgoff == 0) 7462 ret = perf_mmap_rb(vma, event, nr_pages); 7463 else 7464 ret = perf_mmap_aux(vma, event, nr_pages); 7465 if (ret) 7466 return ret; 7467 7468 /* 7469 * Since pinned accounting is per vm we cannot allow fork() to copy our 7470 * vma. 7471 */ 7472 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP); 7473 vma->vm_ops = &perf_mmap_vmops; 7474 7475 mapped = get_mapped(event, event_mapped); 7476 if (mapped) 7477 mapped(event, vma->vm_mm); 7478 7479 /* 7480 * Try to map it into the page table. On fail undo the above, 7481 * as the callsite expects full cleanup in this case and 7482 * therefore does not invoke vmops::close(). 7483 */ 7484 ret = map_range(event->rb, vma); 7485 if (likely(!ret)) 7486 return 0; 7487 7488 /* Error path */ 7489 7490 /* 7491 * If this is the first mmap(), then event->mmap_count should 7492 * be stable at 1. It is only modified by: 7493 * perf_mmap_{open,close}() and perf_mmap(). 7494 * 7495 * The former are not possible because this mmap() hasn't been 7496 * successful yet, and the latter is serialized by 7497 * event->mmap_mutex which we still hold (note that mmap_lock 7498 * is not strictly sufficient here, because the event fd can 7499 * be passed to another process through trivial means like 7500 * fork(), leading to concurrent mmap() from different mm). 7501 * 7502 * Make sure to remove event->rb before releasing 7503 * event->mmap_mutex, such that any concurrent mmap() will not 7504 * attempt use this failed buffer. 7505 */ 7506 if (refcount_read(&event->mmap_count) == 1) { 7507 /* 7508 * Minimal perf_mmap_close(); there can't be AUX or 7509 * other events on account of this being the first. 7510 */ 7511 mapped = get_mapped(event, event_unmapped); 7512 if (mapped) 7513 mapped(event, vma->vm_mm); 7514 perf_mmap_unaccount(vma, event->rb); 7515 ring_buffer_attach(event, NULL); /* drops last rb->refcount */ 7516 refcount_set(&event->mmap_count, 0); 7517 return ret; 7518 } 7519 7520 /* 7521 * Otherwise this is an already existing buffer, and there is 7522 * no race vs first exposure, so fall-through and call 7523 * perf_mmap_close(). 7524 */ 7525 } 7526 7527 perf_mmap_close(vma); 7528 return ret; 7529 } 7530 7531 static int perf_fasync(int fd, struct file *filp, int on) 7532 { 7533 struct inode *inode = file_inode(filp); 7534 struct perf_event *event = filp->private_data; 7535 int retval; 7536 7537 if (event->state <= PERF_EVENT_STATE_REVOKED) 7538 return -ENODEV; 7539 7540 inode_lock(inode); 7541 retval = fasync_helper(fd, filp, on, &event->fasync); 7542 inode_unlock(inode); 7543 7544 if (retval < 0) 7545 return retval; 7546 7547 return 0; 7548 } 7549 7550 static void perf_show_fdinfo(struct seq_file *m, struct file *f) 7551 { 7552 struct perf_event *event = f->private_data; 7553 struct perf_event_context *ctx; 7554 struct mutex *child_mutex; 7555 7556 ctx = perf_event_ctx_lock(event); 7557 child_mutex = event->parent ? &event->parent->child_mutex : &event->child_mutex; 7558 mutex_lock(child_mutex); 7559 7560 seq_printf(m, "perf_event_attr.type:\t%u\n", event->orig_type); 7561 if (event->pmu) 7562 seq_printf(m, "pmu_type:\t%u\n", event->pmu->type); 7563 seq_printf(m, "perf_event_attr.config:\t0x%llx\n", (unsigned long long)event->attr.config); 7564 seq_printf(m, "perf_event_attr.config1:\t0x%llx\n", 7565 (unsigned long long)event->attr.config1); 7566 seq_printf(m, "perf_event_attr.config2:\t0x%llx\n", 7567 (unsigned long long)event->attr.config2); 7568 seq_printf(m, "perf_event_attr.config3:\t0x%llx\n", 7569 (unsigned long long)event->attr.config3); 7570 seq_printf(m, "perf_event_attr.config4:\t0x%llx\n", 7571 (unsigned long long)event->attr.config4); 7572 7573 mutex_unlock(child_mutex); 7574 perf_event_ctx_unlock(event, ctx); 7575 } 7576 7577 static const struct file_operations perf_fops = { 7578 .release = perf_release, 7579 .read = perf_read, 7580 .poll = perf_poll, 7581 .unlocked_ioctl = perf_ioctl, 7582 .compat_ioctl = perf_compat_ioctl, 7583 .mmap = perf_mmap, 7584 .fasync = perf_fasync, 7585 .show_fdinfo = perf_show_fdinfo, 7586 }; 7587 7588 /* 7589 * Perf event wakeup 7590 * 7591 * If there's data, ensure we set the poll() state and publish everything 7592 * to user-space before waking everybody up. 7593 */ 7594 7595 void perf_event_wakeup(struct perf_event *event) 7596 { 7597 ring_buffer_wakeup(event); 7598 7599 if (event->pending_kill) { 7600 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill); 7601 event->pending_kill = 0; 7602 } 7603 } 7604 7605 static void perf_sigtrap(struct perf_event *event) 7606 { 7607 /* 7608 * Both perf_pending_task() and perf_pending_irq() can race with the 7609 * task exiting. 7610 */ 7611 if (current->flags & PF_EXITING) 7612 return; 7613 7614 /* 7615 * We'd expect this to only occur if the irq_work is delayed and either 7616 * ctx->task or current has changed in the meantime. This can be the 7617 * case on architectures that do not implement arch_irq_work_raise(). 7618 */ 7619 if (WARN_ON_ONCE(event->ctx->task != current)) 7620 return; 7621 7622 send_sig_perf((void __user *)event->pending_addr, 7623 event->orig_type, event->attr.sig_data); 7624 } 7625 7626 /* 7627 * Deliver the pending work in-event-context or follow the context. 7628 */ 7629 static void __perf_pending_disable(struct perf_event *event) 7630 { 7631 int cpu = READ_ONCE(event->oncpu); 7632 7633 /* 7634 * If the event isn't running; we done. event_sched_out() will have 7635 * taken care of things. 7636 */ 7637 if (cpu < 0) 7638 return; 7639 7640 /* 7641 * Yay, we hit home and are in the context of the event. 7642 */ 7643 if (cpu == smp_processor_id()) { 7644 if (event->pending_disable) { 7645 event->pending_disable = 0; 7646 perf_event_disable_local(event); 7647 } 7648 return; 7649 } 7650 7651 /* 7652 * CPU-A CPU-B 7653 * 7654 * perf_event_disable_inatomic() 7655 * @pending_disable = 1; 7656 * irq_work_queue(); 7657 * 7658 * sched-out 7659 * @pending_disable = 0; 7660 * 7661 * sched-in 7662 * perf_event_disable_inatomic() 7663 * @pending_disable = 1; 7664 * irq_work_queue(); // FAILS 7665 * 7666 * irq_work_run() 7667 * perf_pending_disable() 7668 * 7669 * But the event runs on CPU-B and wants disabling there. 7670 */ 7671 irq_work_queue_on(&event->pending_disable_irq, cpu); 7672 } 7673 7674 static void perf_pending_disable(struct irq_work *entry) 7675 { 7676 struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq); 7677 int rctx; 7678 7679 /* 7680 * If we 'fail' here, that's OK, it means recursion is already disabled 7681 * and we won't recurse 'further'. 7682 */ 7683 rctx = perf_swevent_get_recursion_context(); 7684 __perf_pending_disable(event); 7685 if (rctx >= 0) 7686 perf_swevent_put_recursion_context(rctx); 7687 } 7688 7689 static void perf_pending_irq(struct irq_work *entry) 7690 { 7691 struct perf_event *event = container_of(entry, struct perf_event, pending_irq); 7692 int rctx; 7693 7694 /* 7695 * If we 'fail' here, that's OK, it means recursion is already disabled 7696 * and we won't recurse 'further'. 7697 */ 7698 rctx = perf_swevent_get_recursion_context(); 7699 7700 /* 7701 * The wakeup isn't bound to the context of the event -- it can happen 7702 * irrespective of where the event is. 7703 */ 7704 if (event->pending_wakeup) { 7705 event->pending_wakeup = 0; 7706 perf_event_wakeup(event); 7707 } 7708 7709 if (rctx >= 0) 7710 perf_swevent_put_recursion_context(rctx); 7711 } 7712 7713 static void perf_pending_task(struct callback_head *head) 7714 { 7715 struct perf_event *event = container_of(head, struct perf_event, pending_task); 7716 int rctx; 7717 7718 /* 7719 * If we 'fail' here, that's OK, it means recursion is already disabled 7720 * and we won't recurse 'further'. 7721 */ 7722 rctx = perf_swevent_get_recursion_context(); 7723 7724 if (event->pending_work) { 7725 event->pending_work = 0; 7726 perf_sigtrap(event); 7727 local_dec(&event->ctx->nr_no_switch_fast); 7728 } 7729 put_event(event); 7730 7731 if (rctx >= 0) 7732 perf_swevent_put_recursion_context(rctx); 7733 } 7734 7735 #ifdef CONFIG_GUEST_PERF_EVENTS 7736 struct perf_guest_info_callbacks __rcu *perf_guest_cbs; 7737 7738 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state); 7739 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip); 7740 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr); 7741 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi); 7742 7743 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7744 { 7745 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs))) 7746 return; 7747 7748 rcu_assign_pointer(perf_guest_cbs, cbs); 7749 static_call_update(__perf_guest_state, cbs->state); 7750 static_call_update(__perf_guest_get_ip, cbs->get_ip); 7751 7752 /* Implementing ->handle_intel_pt_intr is optional. */ 7753 if (cbs->handle_intel_pt_intr) 7754 static_call_update(__perf_guest_handle_intel_pt_intr, 7755 cbs->handle_intel_pt_intr); 7756 7757 if (cbs->handle_mediated_pmi) 7758 static_call_update(__perf_guest_handle_mediated_pmi, 7759 cbs->handle_mediated_pmi); 7760 } 7761 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks); 7762 7763 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7764 { 7765 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs)) 7766 return; 7767 7768 rcu_assign_pointer(perf_guest_cbs, NULL); 7769 static_call_update(__perf_guest_state, (void *)&__static_call_return0); 7770 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0); 7771 static_call_update(__perf_guest_handle_intel_pt_intr, (void *)&__static_call_return0); 7772 static_call_update(__perf_guest_handle_mediated_pmi, (void *)&__static_call_return0); 7773 synchronize_rcu(); 7774 } 7775 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks); 7776 #endif 7777 7778 static bool should_sample_guest(struct perf_event *event) 7779 { 7780 return !event->attr.exclude_guest && perf_guest_state(); 7781 } 7782 7783 unsigned long perf_misc_flags(struct perf_event *event, 7784 struct pt_regs *regs) 7785 { 7786 if (should_sample_guest(event)) 7787 return perf_arch_guest_misc_flags(regs); 7788 7789 return perf_arch_misc_flags(regs); 7790 } 7791 7792 unsigned long perf_instruction_pointer(struct perf_event *event, 7793 struct pt_regs *regs) 7794 { 7795 if (should_sample_guest(event)) 7796 return perf_guest_get_ip(); 7797 7798 return perf_arch_instruction_pointer(regs); 7799 } 7800 7801 static void 7802 perf_output_sample_regs(struct perf_output_handle *handle, 7803 struct pt_regs *regs, u64 mask) 7804 { 7805 int bit; 7806 DECLARE_BITMAP(_mask, 64); 7807 7808 bitmap_from_u64(_mask, mask); 7809 for_each_set_bit(bit, _mask, sizeof(mask) * BITS_PER_BYTE) { 7810 u64 val; 7811 7812 val = perf_reg_value(regs, bit); 7813 perf_output_put(handle, val); 7814 } 7815 } 7816 7817 static void perf_sample_regs_user(struct perf_regs *regs_user, 7818 struct pt_regs *regs) 7819 { 7820 if (user_mode(regs)) { 7821 regs_user->abi = perf_reg_abi(current); 7822 regs_user->regs = regs; 7823 } else if (is_user_task(current)) { 7824 perf_get_regs_user(regs_user, regs); 7825 } else { 7826 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE; 7827 regs_user->regs = NULL; 7828 } 7829 } 7830 7831 static void perf_sample_regs_intr(struct perf_regs *regs_intr, 7832 struct pt_regs *regs) 7833 { 7834 regs_intr->regs = regs; 7835 regs_intr->abi = perf_reg_abi(current); 7836 } 7837 7838 7839 /* 7840 * Get remaining task size from user stack pointer. 7841 * 7842 * It'd be better to take stack vma map and limit this more 7843 * precisely, but there's no way to get it safely under interrupt, 7844 * so using TASK_SIZE as limit. 7845 */ 7846 static u64 perf_ustack_task_size(struct pt_regs *regs) 7847 { 7848 unsigned long addr = perf_user_stack_pointer(regs); 7849 7850 if (!addr || addr >= TASK_SIZE) 7851 return 0; 7852 7853 return TASK_SIZE - addr; 7854 } 7855 7856 static u16 7857 perf_sample_ustack_size(u16 stack_size, u16 header_size, 7858 struct pt_regs *regs) 7859 { 7860 u64 task_size; 7861 7862 /* No regs, no stack pointer, no dump. */ 7863 if (!regs) 7864 return 0; 7865 7866 /* No mm, no stack, no dump. */ 7867 if (!current->mm) 7868 return 0; 7869 7870 /* 7871 * Check if we fit in with the requested stack size into the: 7872 * - TASK_SIZE 7873 * If we don't, we limit the size to the TASK_SIZE. 7874 * 7875 * - remaining sample size 7876 * If we don't, we customize the stack size to 7877 * fit in to the remaining sample size. 7878 */ 7879 7880 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs)); 7881 stack_size = min(stack_size, (u16) task_size); 7882 7883 /* Current header size plus static size and dynamic size. */ 7884 header_size += 2 * sizeof(u64); 7885 7886 /* Do we fit in with the current stack dump size? */ 7887 if ((u16) (header_size + stack_size) < header_size) { 7888 /* 7889 * If we overflow the maximum size for the sample, 7890 * we customize the stack dump size to fit in. 7891 */ 7892 stack_size = USHRT_MAX - header_size - sizeof(u64); 7893 stack_size = round_up(stack_size, sizeof(u64)); 7894 } 7895 7896 return stack_size; 7897 } 7898 7899 static void 7900 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size, 7901 struct pt_regs *regs) 7902 { 7903 /* Case of a kernel thread, nothing to dump */ 7904 if (!regs) { 7905 u64 size = 0; 7906 perf_output_put(handle, size); 7907 } else { 7908 unsigned long sp; 7909 unsigned int rem; 7910 u64 dyn_size; 7911 7912 /* 7913 * We dump: 7914 * static size 7915 * - the size requested by user or the best one we can fit 7916 * in to the sample max size 7917 * data 7918 * - user stack dump data 7919 * dynamic size 7920 * - the actual dumped size 7921 */ 7922 7923 /* Static size. */ 7924 perf_output_put(handle, dump_size); 7925 7926 /* Data. */ 7927 sp = perf_user_stack_pointer(regs); 7928 rem = __output_copy_user(handle, (void *) sp, dump_size); 7929 dyn_size = dump_size - rem; 7930 7931 perf_output_skip(handle, rem); 7932 7933 /* Dynamic size. */ 7934 perf_output_put(handle, dyn_size); 7935 } 7936 } 7937 7938 static unsigned long perf_prepare_sample_aux(struct perf_event *event, 7939 struct perf_sample_data *data, 7940 size_t size) 7941 { 7942 struct perf_event *sampler = event->aux_event; 7943 struct perf_buffer *rb; 7944 7945 data->aux_size = 0; 7946 7947 if (!sampler) 7948 goto out; 7949 7950 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE)) 7951 goto out; 7952 7953 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id())) 7954 goto out; 7955 7956 rb = ring_buffer_get(sampler); 7957 if (!rb) 7958 goto out; 7959 7960 /* 7961 * If this is an NMI hit inside sampling code, don't take 7962 * the sample. See also perf_aux_sample_output(). 7963 */ 7964 if (READ_ONCE(rb->aux_in_sampling)) { 7965 data->aux_size = 0; 7966 } else { 7967 size = min_t(size_t, size, perf_aux_size(rb)); 7968 data->aux_size = ALIGN(size, sizeof(u64)); 7969 } 7970 ring_buffer_put(rb); 7971 7972 out: 7973 return data->aux_size; 7974 } 7975 7976 static long perf_pmu_snapshot_aux(struct perf_buffer *rb, 7977 struct perf_event *event, 7978 struct perf_output_handle *handle, 7979 unsigned long size) 7980 { 7981 unsigned long flags; 7982 long ret; 7983 7984 /* 7985 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler 7986 * paths. If we start calling them in NMI context, they may race with 7987 * the IRQ ones, that is, for example, re-starting an event that's just 7988 * been stopped, which is why we're using a separate callback that 7989 * doesn't change the event state. 7990 * 7991 * IRQs need to be disabled to prevent IPIs from racing with us. 7992 */ 7993 local_irq_save(flags); 7994 /* 7995 * Guard against NMI hits inside the critical section; 7996 * see also perf_prepare_sample_aux(). 7997 */ 7998 WRITE_ONCE(rb->aux_in_sampling, 1); 7999 barrier(); 8000 8001 ret = event->pmu->snapshot_aux(event, handle, size); 8002 8003 barrier(); 8004 WRITE_ONCE(rb->aux_in_sampling, 0); 8005 local_irq_restore(flags); 8006 8007 return ret; 8008 } 8009 8010 static void perf_aux_sample_output(struct perf_event *event, 8011 struct perf_output_handle *handle, 8012 struct perf_sample_data *data) 8013 { 8014 struct perf_event *sampler = event->aux_event; 8015 struct perf_buffer *rb; 8016 unsigned long pad; 8017 long size; 8018 8019 if (WARN_ON_ONCE(!sampler || !data->aux_size)) 8020 return; 8021 8022 rb = ring_buffer_get(sampler); 8023 if (!rb) 8024 return; 8025 8026 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size); 8027 8028 /* 8029 * An error here means that perf_output_copy() failed (returned a 8030 * non-zero surplus that it didn't copy), which in its current 8031 * enlightened implementation is not possible. If that changes, we'd 8032 * like to know. 8033 */ 8034 if (WARN_ON_ONCE(size < 0)) 8035 goto out_put; 8036 8037 /* 8038 * The pad comes from ALIGN()ing data->aux_size up to u64 in 8039 * perf_prepare_sample_aux(), so should not be more than that. 8040 */ 8041 pad = data->aux_size - size; 8042 if (WARN_ON_ONCE(pad >= sizeof(u64))) 8043 pad = 8; 8044 8045 if (pad) { 8046 u64 zero = 0; 8047 perf_output_copy(handle, &zero, pad); 8048 } 8049 8050 out_put: 8051 ring_buffer_put(rb); 8052 } 8053 8054 /* 8055 * A set of common sample data types saved even for non-sample records 8056 * when event->attr.sample_id_all is set. 8057 */ 8058 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \ 8059 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \ 8060 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER) 8061 8062 static void __perf_event_header__init_id(struct perf_sample_data *data, 8063 struct perf_event *event, 8064 u64 sample_type) 8065 { 8066 data->type = event->attr.sample_type; 8067 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL; 8068 8069 if (sample_type & PERF_SAMPLE_TID) { 8070 /* namespace issues */ 8071 data->tid_entry.pid = perf_event_pid(event, current); 8072 data->tid_entry.tid = perf_event_tid(event, current); 8073 } 8074 8075 if (sample_type & PERF_SAMPLE_TIME) 8076 data->time = perf_event_clock(event); 8077 8078 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) 8079 data->id = primary_event_id(event); 8080 8081 if (sample_type & PERF_SAMPLE_STREAM_ID) 8082 data->stream_id = event->id; 8083 8084 if (sample_type & PERF_SAMPLE_CPU) { 8085 data->cpu_entry.cpu = raw_smp_processor_id(); 8086 data->cpu_entry.reserved = 0; 8087 } 8088 } 8089 8090 void perf_event_header__init_id(struct perf_event_header *header, 8091 struct perf_sample_data *data, 8092 struct perf_event *event) 8093 { 8094 if (event->attr.sample_id_all) { 8095 header->size += event->id_header_size; 8096 __perf_event_header__init_id(data, event, event->attr.sample_type); 8097 } 8098 } 8099 8100 static void __perf_event__output_id_sample(struct perf_output_handle *handle, 8101 struct perf_sample_data *data) 8102 { 8103 u64 sample_type = data->type; 8104 8105 if (sample_type & PERF_SAMPLE_TID) 8106 perf_output_put(handle, data->tid_entry); 8107 8108 if (sample_type & PERF_SAMPLE_TIME) 8109 perf_output_put(handle, data->time); 8110 8111 if (sample_type & PERF_SAMPLE_ID) 8112 perf_output_put(handle, data->id); 8113 8114 if (sample_type & PERF_SAMPLE_STREAM_ID) 8115 perf_output_put(handle, data->stream_id); 8116 8117 if (sample_type & PERF_SAMPLE_CPU) 8118 perf_output_put(handle, data->cpu_entry); 8119 8120 if (sample_type & PERF_SAMPLE_IDENTIFIER) 8121 perf_output_put(handle, data->id); 8122 } 8123 8124 void perf_event__output_id_sample(struct perf_event *event, 8125 struct perf_output_handle *handle, 8126 struct perf_sample_data *sample) 8127 { 8128 if (event->attr.sample_id_all) 8129 __perf_event__output_id_sample(handle, sample); 8130 } 8131 8132 static void perf_output_read_one(struct perf_output_handle *handle, 8133 struct perf_event *event, 8134 u64 enabled, u64 running) 8135 { 8136 u64 read_format = event->attr.read_format; 8137 u64 values[5]; 8138 int n = 0; 8139 8140 values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr)); 8141 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 8142 values[n++] = enabled + 8143 atomic64_read(&event->child_total_time_enabled); 8144 } 8145 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 8146 values[n++] = running + 8147 atomic64_read(&event->child_total_time_running); 8148 } 8149 if (read_format & PERF_FORMAT_ID) 8150 values[n++] = primary_event_id(event); 8151 if (read_format & PERF_FORMAT_LOST) 8152 values[n++] = atomic64_read(&event->lost_samples); 8153 8154 __output_copy(handle, values, n * sizeof(u64)); 8155 } 8156 8157 static void perf_output_read_group(struct perf_output_handle *handle, 8158 struct perf_event *event, 8159 u64 enabled, u64 running) 8160 { 8161 struct perf_event *leader = event->group_leader, *sub; 8162 u64 read_format = event->attr.read_format; 8163 unsigned long flags; 8164 u64 values[6]; 8165 int n = 0; 8166 bool self = has_inherit_and_sample_read(&event->attr); 8167 8168 /* 8169 * Disabling interrupts avoids all counter scheduling 8170 * (context switches, timer based rotation and IPIs). 8171 */ 8172 local_irq_save(flags); 8173 8174 values[n++] = 1 + leader->nr_siblings; 8175 8176 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 8177 values[n++] = enabled; 8178 8179 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 8180 values[n++] = running; 8181 8182 if ((leader != event) && !handle->skip_read) 8183 perf_pmu_read(leader); 8184 8185 values[n++] = perf_event_count(leader, self); 8186 if (read_format & PERF_FORMAT_ID) 8187 values[n++] = primary_event_id(leader); 8188 if (read_format & PERF_FORMAT_LOST) 8189 values[n++] = atomic64_read(&leader->lost_samples); 8190 8191 __output_copy(handle, values, n * sizeof(u64)); 8192 8193 for_each_sibling_event(sub, leader) { 8194 n = 0; 8195 8196 if ((sub != event) && !handle->skip_read) 8197 perf_pmu_read(sub); 8198 8199 values[n++] = perf_event_count(sub, self); 8200 if (read_format & PERF_FORMAT_ID) 8201 values[n++] = primary_event_id(sub); 8202 if (read_format & PERF_FORMAT_LOST) 8203 values[n++] = atomic64_read(&sub->lost_samples); 8204 8205 __output_copy(handle, values, n * sizeof(u64)); 8206 } 8207 8208 local_irq_restore(flags); 8209 } 8210 8211 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\ 8212 PERF_FORMAT_TOTAL_TIME_RUNNING) 8213 8214 /* 8215 * XXX PERF_SAMPLE_READ vs inherited events seems difficult. 8216 * 8217 * The problem is that its both hard and excessively expensive to iterate the 8218 * child list, not to mention that its impossible to IPI the children running 8219 * on another CPU, from interrupt/NMI context. 8220 * 8221 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread 8222 * counts rather than attempting to accumulate some value across all children on 8223 * all cores. 8224 */ 8225 static void perf_output_read(struct perf_output_handle *handle, 8226 struct perf_event *event) 8227 { 8228 u64 enabled = 0, running = 0, now; 8229 u64 read_format = event->attr.read_format; 8230 8231 /* 8232 * Compute total_time_enabled, total_time_running based on snapshot 8233 * values taken when the event was last scheduled in. 8234 * 8235 * We cannot simply call update_context_time() because doing so would 8236 * lead to deadlock when called from NMI context. 8237 */ 8238 if (read_format & PERF_FORMAT_TOTAL_TIMES) 8239 calc_timer_values(event, &now, &enabled, &running); 8240 8241 if (event->attr.read_format & PERF_FORMAT_GROUP) 8242 perf_output_read_group(handle, event, enabled, running); 8243 else 8244 perf_output_read_one(handle, event, enabled, running); 8245 } 8246 8247 void perf_output_sample(struct perf_output_handle *handle, 8248 struct perf_event_header *header, 8249 struct perf_sample_data *data, 8250 struct perf_event *event) 8251 { 8252 u64 sample_type = data->type; 8253 8254 if (data->sample_flags & PERF_SAMPLE_READ) 8255 handle->skip_read = 1; 8256 8257 perf_output_put(handle, *header); 8258 8259 if (sample_type & PERF_SAMPLE_IDENTIFIER) 8260 perf_output_put(handle, data->id); 8261 8262 if (sample_type & PERF_SAMPLE_IP) 8263 perf_output_put(handle, data->ip); 8264 8265 if (sample_type & PERF_SAMPLE_TID) 8266 perf_output_put(handle, data->tid_entry); 8267 8268 if (sample_type & PERF_SAMPLE_TIME) 8269 perf_output_put(handle, data->time); 8270 8271 if (sample_type & PERF_SAMPLE_ADDR) 8272 perf_output_put(handle, data->addr); 8273 8274 if (sample_type & PERF_SAMPLE_ID) 8275 perf_output_put(handle, data->id); 8276 8277 if (sample_type & PERF_SAMPLE_STREAM_ID) 8278 perf_output_put(handle, data->stream_id); 8279 8280 if (sample_type & PERF_SAMPLE_CPU) 8281 perf_output_put(handle, data->cpu_entry); 8282 8283 if (sample_type & PERF_SAMPLE_PERIOD) 8284 perf_output_put(handle, data->period); 8285 8286 if (sample_type & PERF_SAMPLE_READ) 8287 perf_output_read(handle, event); 8288 8289 if (sample_type & PERF_SAMPLE_CALLCHAIN) { 8290 int size = 1; 8291 8292 size += data->callchain->nr; 8293 size *= sizeof(u64); 8294 __output_copy(handle, data->callchain, size); 8295 } 8296 8297 if (sample_type & PERF_SAMPLE_RAW) { 8298 struct perf_raw_record *raw = data->raw; 8299 8300 if (raw) { 8301 struct perf_raw_frag *frag = &raw->frag; 8302 8303 perf_output_put(handle, raw->size); 8304 do { 8305 if (frag->copy) { 8306 __output_custom(handle, frag->copy, 8307 frag->data, frag->size); 8308 } else { 8309 __output_copy(handle, frag->data, 8310 frag->size); 8311 } 8312 if (perf_raw_frag_last(frag)) 8313 break; 8314 frag = frag->next; 8315 } while (1); 8316 if (frag->pad) 8317 __output_skip(handle, NULL, frag->pad); 8318 } else { 8319 struct { 8320 u32 size; 8321 u32 data; 8322 } raw = { 8323 .size = sizeof(u32), 8324 .data = 0, 8325 }; 8326 perf_output_put(handle, raw); 8327 } 8328 } 8329 8330 if (sample_type & PERF_SAMPLE_BRANCH_STACK) { 8331 if (data->br_stack) { 8332 size_t size; 8333 8334 size = data->br_stack->nr 8335 * sizeof(struct perf_branch_entry); 8336 8337 perf_output_put(handle, data->br_stack->nr); 8338 if (branch_sample_hw_index(event)) 8339 perf_output_put(handle, data->br_stack->hw_idx); 8340 perf_output_copy(handle, data->br_stack->entries, size); 8341 /* 8342 * Add the extension space which is appended 8343 * right after the struct perf_branch_stack. 8344 */ 8345 if (data->br_stack_cntr) { 8346 size = data->br_stack->nr * sizeof(u64); 8347 perf_output_copy(handle, data->br_stack_cntr, size); 8348 } 8349 } else { 8350 /* 8351 * we always store at least the value of nr 8352 */ 8353 u64 nr = 0; 8354 perf_output_put(handle, nr); 8355 } 8356 } 8357 8358 if (sample_type & PERF_SAMPLE_REGS_USER) { 8359 u64 abi = data->regs_user.abi; 8360 8361 /* 8362 * If there are no regs to dump, notice it through 8363 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 8364 */ 8365 perf_output_put(handle, abi); 8366 8367 if (abi) { 8368 u64 mask = event->attr.sample_regs_user; 8369 perf_output_sample_regs(handle, 8370 data->regs_user.regs, 8371 mask); 8372 } 8373 } 8374 8375 if (sample_type & PERF_SAMPLE_STACK_USER) { 8376 perf_output_sample_ustack(handle, 8377 data->stack_user_size, 8378 data->regs_user.regs); 8379 } 8380 8381 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) 8382 perf_output_put(handle, data->weight.full); 8383 8384 if (sample_type & PERF_SAMPLE_DATA_SRC) 8385 perf_output_put(handle, data->data_src.val); 8386 8387 if (sample_type & PERF_SAMPLE_TRANSACTION) 8388 perf_output_put(handle, data->txn); 8389 8390 if (sample_type & PERF_SAMPLE_REGS_INTR) { 8391 u64 abi = data->regs_intr.abi; 8392 /* 8393 * If there are no regs to dump, notice it through 8394 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 8395 */ 8396 perf_output_put(handle, abi); 8397 8398 if (abi) { 8399 u64 mask = event->attr.sample_regs_intr; 8400 8401 perf_output_sample_regs(handle, 8402 data->regs_intr.regs, 8403 mask); 8404 } 8405 } 8406 8407 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 8408 perf_output_put(handle, data->phys_addr); 8409 8410 if (sample_type & PERF_SAMPLE_CGROUP) 8411 perf_output_put(handle, data->cgroup); 8412 8413 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) 8414 perf_output_put(handle, data->data_page_size); 8415 8416 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) 8417 perf_output_put(handle, data->code_page_size); 8418 8419 if (sample_type & PERF_SAMPLE_AUX) { 8420 perf_output_put(handle, data->aux_size); 8421 8422 if (data->aux_size) 8423 perf_aux_sample_output(event, handle, data); 8424 } 8425 8426 if (!event->attr.watermark) { 8427 int wakeup_events = event->attr.wakeup_events; 8428 8429 if (wakeup_events) { 8430 struct perf_buffer *rb = handle->rb; 8431 int events = local_inc_return(&rb->events); 8432 8433 if (events >= wakeup_events) { 8434 local_sub(wakeup_events, &rb->events); 8435 local_inc(&rb->wakeup); 8436 } 8437 } 8438 } 8439 } 8440 8441 static u64 perf_virt_to_phys(u64 virt) 8442 { 8443 u64 phys_addr = 0; 8444 8445 if (!virt) 8446 return 0; 8447 8448 if (virt >= TASK_SIZE) { 8449 /* If it's vmalloc()d memory, leave phys_addr as 0 */ 8450 if (virt_addr_valid((void *)(uintptr_t)virt) && 8451 !(virt >= VMALLOC_START && virt < VMALLOC_END)) 8452 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt); 8453 } else { 8454 /* 8455 * Walking the pages tables for user address. 8456 * Interrupts are disabled, so it prevents any tear down 8457 * of the page tables. 8458 * Try IRQ-safe get_user_page_fast_only first. 8459 * If failed, leave phys_addr as 0. 8460 */ 8461 if (is_user_task(current)) { 8462 struct page *p; 8463 8464 pagefault_disable(); 8465 if (get_user_page_fast_only(virt, 0, &p)) { 8466 phys_addr = page_to_phys(p) + virt % PAGE_SIZE; 8467 put_page(p); 8468 } 8469 pagefault_enable(); 8470 } 8471 } 8472 8473 return phys_addr; 8474 } 8475 8476 /* 8477 * Return the pagetable size of a given virtual address. 8478 */ 8479 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr) 8480 { 8481 u64 size = 0; 8482 8483 #ifdef CONFIG_HAVE_GUP_FAST 8484 pgd_t *pgdp, pgd; 8485 p4d_t *p4dp, p4d; 8486 pud_t *pudp, pud; 8487 pmd_t *pmdp, pmd; 8488 pte_t *ptep, pte; 8489 8490 pgdp = pgd_offset(mm, addr); 8491 pgd = pgdp_get(pgdp); 8492 if (pgd_none(pgd)) 8493 return 0; 8494 8495 if (pgd_leaf(pgd)) 8496 return pgd_leaf_size(pgd); 8497 8498 p4dp = p4d_offset_lockless(pgdp, pgd, addr); 8499 p4d = p4dp_get(p4dp); 8500 if (!p4d_present(p4d)) 8501 return 0; 8502 8503 if (p4d_leaf(p4d)) 8504 return p4d_leaf_size(p4d); 8505 8506 pudp = pud_offset_lockless(p4dp, p4d, addr); 8507 pud = pudp_get(pudp); 8508 if (!pud_present(pud)) 8509 return 0; 8510 8511 if (pud_leaf(pud)) 8512 return pud_leaf_size(pud); 8513 8514 pmdp = pmd_offset_lockless(pudp, pud, addr); 8515 again: 8516 pmd = pmdp_get_lockless(pmdp); 8517 if (!pmd_present(pmd)) 8518 return 0; 8519 8520 if (pmd_leaf(pmd)) 8521 return pmd_leaf_size(pmd); 8522 8523 ptep = pte_offset_map(&pmd, addr); 8524 if (!ptep) 8525 goto again; 8526 8527 pte = ptep_get_lockless(ptep); 8528 if (pte_present(pte)) 8529 size = __pte_leaf_size(pmd, pte); 8530 pte_unmap(ptep); 8531 #endif /* CONFIG_HAVE_GUP_FAST */ 8532 8533 return size; 8534 } 8535 8536 static u64 perf_get_page_size(unsigned long addr) 8537 { 8538 struct mm_struct *mm; 8539 unsigned long flags; 8540 u64 size; 8541 8542 if (!addr) 8543 return 0; 8544 8545 /* 8546 * Software page-table walkers must disable IRQs, 8547 * which prevents any tear down of the page tables. 8548 */ 8549 local_irq_save(flags); 8550 8551 mm = current->mm; 8552 if (!mm) { 8553 /* 8554 * For kernel threads and the like, use init_mm so that 8555 * we can find kernel memory. 8556 */ 8557 mm = &init_mm; 8558 } 8559 8560 size = perf_get_pgtable_size(mm, addr); 8561 8562 local_irq_restore(flags); 8563 8564 return size; 8565 } 8566 8567 static struct perf_callchain_entry __empty_callchain = { .nr = 0, }; 8568 8569 static struct unwind_work perf_unwind_work; 8570 8571 struct perf_callchain_entry * 8572 perf_callchain(struct perf_event *event, struct pt_regs *regs) 8573 { 8574 bool kernel = !event->attr.exclude_callchain_kernel; 8575 bool user = !event->attr.exclude_callchain_user && 8576 is_user_task(current); 8577 /* Disallow cross-task user callchains. */ 8578 bool crosstask = event->ctx->task && event->ctx->task != current; 8579 bool defer_user = IS_ENABLED(CONFIG_UNWIND_USER) && user && 8580 event->attr.defer_callchain; 8581 const u32 max_stack = event->attr.sample_max_stack; 8582 struct perf_callchain_entry *callchain; 8583 u64 defer_cookie; 8584 8585 if (!current->mm) 8586 user = false; 8587 8588 if (!kernel && !user) 8589 return &__empty_callchain; 8590 8591 if (!(user && defer_user && !crosstask && 8592 unwind_deferred_request(&perf_unwind_work, &defer_cookie) >= 0)) 8593 defer_cookie = 0; 8594 8595 callchain = get_perf_callchain(regs, kernel, user, max_stack, 8596 crosstask, true, defer_cookie); 8597 8598 return callchain ?: &__empty_callchain; 8599 } 8600 8601 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d) 8602 { 8603 return d * !!(flags & s); 8604 } 8605 8606 void perf_prepare_sample(struct perf_sample_data *data, 8607 struct perf_event *event, 8608 struct pt_regs *regs) 8609 { 8610 u64 sample_type = event->attr.sample_type; 8611 u64 filtered_sample_type; 8612 8613 /* 8614 * Add the sample flags that are dependent to others. And clear the 8615 * sample flags that have already been done by the PMU driver. 8616 */ 8617 filtered_sample_type = sample_type; 8618 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE, 8619 PERF_SAMPLE_IP); 8620 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE | 8621 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR); 8622 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER, 8623 PERF_SAMPLE_REGS_USER); 8624 filtered_sample_type &= ~data->sample_flags; 8625 8626 if (filtered_sample_type == 0) { 8627 /* Make sure it has the correct data->type for output */ 8628 data->type = event->attr.sample_type; 8629 return; 8630 } 8631 8632 __perf_event_header__init_id(data, event, filtered_sample_type); 8633 8634 if (filtered_sample_type & PERF_SAMPLE_IP) { 8635 data->ip = perf_instruction_pointer(event, regs); 8636 data->sample_flags |= PERF_SAMPLE_IP; 8637 } 8638 8639 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN) 8640 perf_sample_save_callchain(data, event, regs); 8641 8642 if (filtered_sample_type & PERF_SAMPLE_RAW) { 8643 data->raw = NULL; 8644 data->dyn_size += sizeof(u64); 8645 data->sample_flags |= PERF_SAMPLE_RAW; 8646 } 8647 8648 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) { 8649 data->br_stack = NULL; 8650 data->dyn_size += sizeof(u64); 8651 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK; 8652 } 8653 8654 if (filtered_sample_type & PERF_SAMPLE_REGS_USER) 8655 perf_sample_regs_user(&data->regs_user, regs); 8656 8657 /* 8658 * It cannot use the filtered_sample_type here as REGS_USER can be set 8659 * by STACK_USER (using __cond_set() above) and we don't want to update 8660 * the dyn_size if it's not requested by users. 8661 */ 8662 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) { 8663 /* regs dump ABI info */ 8664 int size = sizeof(u64); 8665 8666 if (data->regs_user.regs) { 8667 u64 mask = event->attr.sample_regs_user; 8668 size += hweight64(mask) * sizeof(u64); 8669 } 8670 8671 data->dyn_size += size; 8672 data->sample_flags |= PERF_SAMPLE_REGS_USER; 8673 } 8674 8675 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) { 8676 /* 8677 * Either we need PERF_SAMPLE_STACK_USER bit to be always 8678 * processed as the last one or have additional check added 8679 * in case new sample type is added, because we could eat 8680 * up the rest of the sample size. 8681 */ 8682 u16 stack_size = event->attr.sample_stack_user; 8683 u16 header_size = perf_sample_data_size(data, event); 8684 u16 size = sizeof(u64); 8685 8686 stack_size = perf_sample_ustack_size(stack_size, header_size, 8687 data->regs_user.regs); 8688 8689 /* 8690 * If there is something to dump, add space for the dump 8691 * itself and for the field that tells the dynamic size, 8692 * which is how many have been actually dumped. 8693 */ 8694 if (stack_size) 8695 size += sizeof(u64) + stack_size; 8696 8697 data->stack_user_size = stack_size; 8698 data->dyn_size += size; 8699 data->sample_flags |= PERF_SAMPLE_STACK_USER; 8700 } 8701 8702 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) { 8703 data->weight.full = 0; 8704 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE; 8705 } 8706 8707 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) { 8708 data->data_src.val = PERF_MEM_NA; 8709 data->sample_flags |= PERF_SAMPLE_DATA_SRC; 8710 } 8711 8712 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) { 8713 data->txn = 0; 8714 data->sample_flags |= PERF_SAMPLE_TRANSACTION; 8715 } 8716 8717 if (filtered_sample_type & PERF_SAMPLE_ADDR) { 8718 data->addr = 0; 8719 data->sample_flags |= PERF_SAMPLE_ADDR; 8720 } 8721 8722 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) { 8723 /* regs dump ABI info */ 8724 int size = sizeof(u64); 8725 8726 perf_sample_regs_intr(&data->regs_intr, regs); 8727 8728 if (data->regs_intr.regs) { 8729 u64 mask = event->attr.sample_regs_intr; 8730 8731 size += hweight64(mask) * sizeof(u64); 8732 } 8733 8734 data->dyn_size += size; 8735 data->sample_flags |= PERF_SAMPLE_REGS_INTR; 8736 } 8737 8738 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) { 8739 data->phys_addr = perf_virt_to_phys(data->addr); 8740 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR; 8741 } 8742 8743 #ifdef CONFIG_CGROUP_PERF 8744 if (filtered_sample_type & PERF_SAMPLE_CGROUP) { 8745 struct cgroup *cgrp; 8746 8747 /* protected by RCU */ 8748 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup; 8749 data->cgroup = cgroup_id(cgrp); 8750 data->sample_flags |= PERF_SAMPLE_CGROUP; 8751 } 8752 #endif 8753 8754 /* 8755 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't 8756 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr, 8757 * but the value will not dump to the userspace. 8758 */ 8759 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) { 8760 data->data_page_size = perf_get_page_size(data->addr); 8761 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE; 8762 } 8763 8764 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) { 8765 data->code_page_size = perf_get_page_size(data->ip); 8766 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE; 8767 } 8768 8769 if (filtered_sample_type & PERF_SAMPLE_AUX) { 8770 u64 size; 8771 u16 header_size = perf_sample_data_size(data, event); 8772 8773 header_size += sizeof(u64); /* size */ 8774 8775 /* 8776 * Given the 16bit nature of header::size, an AUX sample can 8777 * easily overflow it, what with all the preceding sample bits. 8778 * Make sure this doesn't happen by using up to U16_MAX bytes 8779 * per sample in total (rounded down to 8 byte boundary). 8780 */ 8781 size = min_t(size_t, U16_MAX - header_size, 8782 event->attr.aux_sample_size); 8783 size = rounddown(size, 8); 8784 size = perf_prepare_sample_aux(event, data, size); 8785 8786 WARN_ON_ONCE(size + header_size > U16_MAX); 8787 data->dyn_size += size + sizeof(u64); /* size above */ 8788 data->sample_flags |= PERF_SAMPLE_AUX; 8789 } 8790 } 8791 8792 void perf_prepare_header(struct perf_event_header *header, 8793 struct perf_sample_data *data, 8794 struct perf_event *event, 8795 struct pt_regs *regs) 8796 { 8797 header->type = PERF_RECORD_SAMPLE; 8798 header->size = perf_sample_data_size(data, event); 8799 header->misc = perf_misc_flags(event, regs); 8800 8801 /* 8802 * If you're adding more sample types here, you likely need to do 8803 * something about the overflowing header::size, like repurpose the 8804 * lowest 3 bits of size, which should be always zero at the moment. 8805 * This raises a more important question, do we really need 512k sized 8806 * samples and why, so good argumentation is in order for whatever you 8807 * do here next. 8808 */ 8809 WARN_ON_ONCE(header->size & 7); 8810 } 8811 8812 static void __perf_event_aux_pause(struct perf_event *event, bool pause) 8813 { 8814 if (pause) { 8815 if (!event->hw.aux_paused) { 8816 event->hw.aux_paused = 1; 8817 event->pmu->stop(event, PERF_EF_PAUSE); 8818 } 8819 } else { 8820 if (event->hw.aux_paused) { 8821 event->hw.aux_paused = 0; 8822 event->pmu->start(event, PERF_EF_RESUME); 8823 } 8824 } 8825 } 8826 8827 static void perf_event_aux_pause(struct perf_event *event, bool pause) 8828 { 8829 struct perf_buffer *rb; 8830 8831 if (WARN_ON_ONCE(!event)) 8832 return; 8833 8834 rb = ring_buffer_get(event); 8835 if (!rb) 8836 return; 8837 8838 scoped_guard (irqsave) { 8839 /* 8840 * Guard against self-recursion here. Another event could trip 8841 * this same from NMI context. 8842 */ 8843 if (READ_ONCE(rb->aux_in_pause_resume)) 8844 break; 8845 8846 WRITE_ONCE(rb->aux_in_pause_resume, 1); 8847 barrier(); 8848 __perf_event_aux_pause(event, pause); 8849 barrier(); 8850 WRITE_ONCE(rb->aux_in_pause_resume, 0); 8851 } 8852 ring_buffer_put(rb); 8853 } 8854 8855 static __always_inline int 8856 __perf_event_output(struct perf_event *event, 8857 struct perf_sample_data *data, 8858 struct pt_regs *regs, 8859 int (*output_begin)(struct perf_output_handle *, 8860 struct perf_sample_data *, 8861 struct perf_event *, 8862 unsigned int)) 8863 { 8864 struct perf_output_handle handle; 8865 struct perf_event_header header; 8866 int err; 8867 8868 /* protect the callchain buffers */ 8869 rcu_read_lock(); 8870 8871 perf_prepare_sample(data, event, regs); 8872 perf_prepare_header(&header, data, event, regs); 8873 8874 err = output_begin(&handle, data, event, header.size); 8875 if (err) 8876 goto exit; 8877 8878 perf_output_sample(&handle, &header, data, event); 8879 8880 perf_output_end(&handle); 8881 8882 exit: 8883 rcu_read_unlock(); 8884 return err; 8885 } 8886 8887 void 8888 perf_event_output_forward(struct perf_event *event, 8889 struct perf_sample_data *data, 8890 struct pt_regs *regs) 8891 { 8892 __perf_event_output(event, data, regs, perf_output_begin_forward); 8893 } 8894 8895 void 8896 perf_event_output_backward(struct perf_event *event, 8897 struct perf_sample_data *data, 8898 struct pt_regs *regs) 8899 { 8900 __perf_event_output(event, data, regs, perf_output_begin_backward); 8901 } 8902 8903 int 8904 perf_event_output(struct perf_event *event, 8905 struct perf_sample_data *data, 8906 struct pt_regs *regs) 8907 { 8908 return __perf_event_output(event, data, regs, perf_output_begin); 8909 } 8910 8911 /* 8912 * read event_id 8913 */ 8914 8915 struct perf_read_event { 8916 struct perf_event_header header; 8917 8918 u32 pid; 8919 u32 tid; 8920 }; 8921 8922 static void 8923 perf_event_read_event(struct perf_event *event, 8924 struct task_struct *task) 8925 { 8926 struct perf_output_handle handle; 8927 struct perf_sample_data sample; 8928 struct perf_read_event read_event = { 8929 .header = { 8930 .type = PERF_RECORD_READ, 8931 .misc = 0, 8932 .size = sizeof(read_event) + event->read_size, 8933 }, 8934 .pid = perf_event_pid(event, task), 8935 .tid = perf_event_tid(event, task), 8936 }; 8937 int ret; 8938 8939 perf_event_header__init_id(&read_event.header, &sample, event); 8940 ret = perf_output_begin(&handle, &sample, event, read_event.header.size); 8941 if (ret) 8942 return; 8943 8944 perf_output_put(&handle, read_event); 8945 perf_output_read(&handle, event); 8946 perf_event__output_id_sample(event, &handle, &sample); 8947 8948 perf_output_end(&handle); 8949 } 8950 8951 typedef void (perf_iterate_f)(struct perf_event *event, void *data); 8952 8953 static void 8954 perf_iterate_ctx(struct perf_event_context *ctx, 8955 perf_iterate_f output, 8956 void *data, bool all) 8957 { 8958 struct perf_event *event; 8959 8960 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { 8961 if (!all) { 8962 if (event->state < PERF_EVENT_STATE_INACTIVE) 8963 continue; 8964 if (!event_filter_match(event)) 8965 continue; 8966 } 8967 8968 output(event, data); 8969 } 8970 } 8971 8972 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data) 8973 { 8974 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events); 8975 struct perf_event *event; 8976 8977 list_for_each_entry_rcu(event, &pel->list, sb_list) { 8978 /* 8979 * Skip events that are not fully formed yet; ensure that 8980 * if we observe event->ctx, both event and ctx will be 8981 * complete enough. See perf_install_in_context(). 8982 */ 8983 if (!smp_load_acquire(&event->ctx)) 8984 continue; 8985 8986 if (event->state < PERF_EVENT_STATE_INACTIVE) 8987 continue; 8988 if (!event_filter_match(event)) 8989 continue; 8990 output(event, data); 8991 } 8992 } 8993 8994 /* 8995 * Iterate all events that need to receive side-band events. 8996 * 8997 * For new callers; ensure that account_pmu_sb_event() includes 8998 * your event, otherwise it might not get delivered. 8999 */ 9000 static void 9001 perf_iterate_sb(perf_iterate_f output, void *data, 9002 struct perf_event_context *task_ctx) 9003 { 9004 struct perf_event_context *ctx; 9005 9006 rcu_read_lock(); 9007 preempt_disable(); 9008 9009 /* 9010 * If we have task_ctx != NULL we only notify the task context itself. 9011 * The task_ctx is set only for EXIT events before releasing task 9012 * context. 9013 */ 9014 if (task_ctx) { 9015 perf_iterate_ctx(task_ctx, output, data, false); 9016 goto done; 9017 } 9018 9019 perf_iterate_sb_cpu(output, data); 9020 9021 ctx = rcu_dereference(current->perf_event_ctxp); 9022 if (ctx) 9023 perf_iterate_ctx(ctx, output, data, false); 9024 done: 9025 preempt_enable(); 9026 rcu_read_unlock(); 9027 } 9028 9029 /* 9030 * Clear all file-based filters at exec, they'll have to be 9031 * re-instated when/if these objects are mmapped again. 9032 */ 9033 static void perf_event_addr_filters_exec(struct perf_event *event, void *data) 9034 { 9035 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 9036 struct perf_addr_filter *filter; 9037 unsigned int restart = 0, count = 0; 9038 unsigned long flags; 9039 9040 if (!has_addr_filter(event)) 9041 return; 9042 9043 raw_spin_lock_irqsave(&ifh->lock, flags); 9044 list_for_each_entry(filter, &ifh->list, entry) { 9045 if (filter->path.dentry) { 9046 event->addr_filter_ranges[count].start = 0; 9047 event->addr_filter_ranges[count].size = 0; 9048 restart++; 9049 } 9050 9051 count++; 9052 } 9053 9054 if (restart) 9055 event->addr_filters_gen++; 9056 raw_spin_unlock_irqrestore(&ifh->lock, flags); 9057 9058 if (restart) 9059 perf_event_stop(event, 1); 9060 } 9061 9062 void perf_event_exec(void) 9063 { 9064 struct perf_event_context *ctx; 9065 9066 ctx = perf_pin_task_context(current); 9067 if (!ctx) 9068 return; 9069 9070 perf_event_enable_on_exec(ctx); 9071 perf_event_remove_on_exec(ctx); 9072 scoped_guard(rcu) 9073 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true); 9074 9075 perf_unpin_context(ctx); 9076 put_ctx(ctx); 9077 } 9078 9079 struct remote_output { 9080 struct perf_buffer *rb; 9081 int err; 9082 }; 9083 9084 static void __perf_event_output_stop(struct perf_event *event, void *data) 9085 { 9086 struct perf_event *parent = event->parent; 9087 struct remote_output *ro = data; 9088 struct perf_buffer *rb = ro->rb; 9089 struct stop_event_data sd = { 9090 .event = event, 9091 }; 9092 9093 if (!has_aux(event)) 9094 return; 9095 9096 if (!parent) 9097 parent = event; 9098 9099 /* 9100 * In case of inheritance, it will be the parent that links to the 9101 * ring-buffer, but it will be the child that's actually using it. 9102 * 9103 * We are using event::rb to determine if the event should be stopped, 9104 * however this may race with ring_buffer_attach() (through set_output), 9105 * which will make us skip the event that actually needs to be stopped. 9106 * So ring_buffer_attach() has to stop an aux event before re-assigning 9107 * its rb pointer. 9108 */ 9109 if (rcu_dereference(parent->rb) == rb) 9110 ro->err = __perf_event_stop(&sd); 9111 } 9112 9113 static int __perf_pmu_output_stop(void *info) 9114 { 9115 struct perf_event *event = info; 9116 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 9117 struct remote_output ro = { 9118 .rb = event->rb, 9119 }; 9120 9121 rcu_read_lock(); 9122 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false); 9123 if (cpuctx->task_ctx) 9124 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop, 9125 &ro, false); 9126 rcu_read_unlock(); 9127 9128 return ro.err; 9129 } 9130 9131 static void perf_pmu_output_stop(struct perf_event *event) 9132 { 9133 struct perf_event *iter; 9134 int err, cpu; 9135 9136 restart: 9137 rcu_read_lock(); 9138 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) { 9139 /* 9140 * For per-CPU events, we need to make sure that neither they 9141 * nor their children are running; for cpu==-1 events it's 9142 * sufficient to stop the event itself if it's active, since 9143 * it can't have children. 9144 */ 9145 cpu = iter->cpu; 9146 if (cpu == -1) 9147 cpu = READ_ONCE(iter->oncpu); 9148 9149 if (cpu == -1) 9150 continue; 9151 9152 err = cpu_function_call(cpu, __perf_pmu_output_stop, event); 9153 if (err == -EAGAIN) { 9154 rcu_read_unlock(); 9155 goto restart; 9156 } 9157 } 9158 rcu_read_unlock(); 9159 } 9160 9161 /* 9162 * task tracking -- fork/exit 9163 * 9164 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task 9165 */ 9166 9167 struct perf_task_event { 9168 struct task_struct *task; 9169 struct perf_event_context *task_ctx; 9170 9171 struct { 9172 struct perf_event_header header; 9173 9174 u32 pid; 9175 u32 ppid; 9176 u32 tid; 9177 u32 ptid; 9178 u64 time; 9179 } event_id; 9180 }; 9181 9182 static int perf_event_task_match(struct perf_event *event) 9183 { 9184 return event->attr.comm || event->attr.mmap || 9185 event->attr.mmap2 || event->attr.mmap_data || 9186 event->attr.task; 9187 } 9188 9189 static void perf_event_task_output(struct perf_event *event, 9190 void *data) 9191 { 9192 struct perf_task_event *task_event = data; 9193 struct perf_output_handle handle; 9194 struct perf_sample_data sample; 9195 struct task_struct *task = task_event->task; 9196 int ret, size = task_event->event_id.header.size; 9197 9198 if (!perf_event_task_match(event)) 9199 return; 9200 9201 perf_event_header__init_id(&task_event->event_id.header, &sample, event); 9202 9203 ret = perf_output_begin(&handle, &sample, event, 9204 task_event->event_id.header.size); 9205 if (ret) 9206 goto out; 9207 9208 task_event->event_id.pid = perf_event_pid(event, task); 9209 task_event->event_id.tid = perf_event_tid(event, task); 9210 9211 if (task_event->event_id.header.type == PERF_RECORD_EXIT) { 9212 task_event->event_id.ppid = perf_event_pid(event, 9213 task->real_parent); 9214 task_event->event_id.ptid = perf_event_pid(event, 9215 task->real_parent); 9216 } else { /* PERF_RECORD_FORK */ 9217 task_event->event_id.ppid = perf_event_pid(event, current); 9218 task_event->event_id.ptid = perf_event_tid(event, current); 9219 } 9220 9221 task_event->event_id.time = perf_event_clock(event); 9222 9223 perf_output_put(&handle, task_event->event_id); 9224 9225 perf_event__output_id_sample(event, &handle, &sample); 9226 9227 perf_output_end(&handle); 9228 out: 9229 task_event->event_id.header.size = size; 9230 } 9231 9232 static void perf_event_task(struct task_struct *task, 9233 struct perf_event_context *task_ctx, 9234 int new) 9235 { 9236 struct perf_task_event task_event; 9237 9238 if (!atomic_read(&nr_comm_events) && 9239 !atomic_read(&nr_mmap_events) && 9240 !atomic_read(&nr_task_events)) 9241 return; 9242 9243 task_event = (struct perf_task_event){ 9244 .task = task, 9245 .task_ctx = task_ctx, 9246 .event_id = { 9247 .header = { 9248 .type = new ? PERF_RECORD_FORK : PERF_RECORD_EXIT, 9249 .misc = 0, 9250 .size = sizeof(task_event.event_id), 9251 }, 9252 /* .pid */ 9253 /* .ppid */ 9254 /* .tid */ 9255 /* .ptid */ 9256 /* .time */ 9257 }, 9258 }; 9259 9260 perf_iterate_sb(perf_event_task_output, 9261 &task_event, 9262 task_ctx); 9263 } 9264 9265 /* 9266 * Allocate data for a new task when profiling system-wide 9267 * events which require PMU specific data 9268 */ 9269 static void 9270 perf_event_alloc_task_data(struct task_struct *child, 9271 struct task_struct *parent) 9272 { 9273 struct kmem_cache *ctx_cache = NULL; 9274 struct perf_ctx_data *cd; 9275 9276 if (!refcount_read(&global_ctx_data_ref)) 9277 return; 9278 9279 scoped_guard (rcu) { 9280 cd = rcu_dereference(parent->perf_ctx_data); 9281 if (cd) 9282 ctx_cache = cd->ctx_cache; 9283 } 9284 9285 if (!ctx_cache) 9286 return; 9287 9288 guard(percpu_read)(&global_ctx_data_rwsem); 9289 scoped_guard (rcu) { 9290 cd = rcu_dereference(child->perf_ctx_data); 9291 if (!cd) { 9292 /* 9293 * A system-wide event may be unaccount, 9294 * when attaching the perf_ctx_data. 9295 */ 9296 if (!refcount_read(&global_ctx_data_ref)) 9297 return; 9298 goto attach; 9299 } 9300 9301 if (!cd->global) { 9302 cd->global = 1; 9303 refcount_inc(&cd->refcount); 9304 } 9305 } 9306 9307 return; 9308 attach: 9309 attach_task_ctx_data(child, ctx_cache, true, GFP_KERNEL); 9310 } 9311 9312 void perf_event_fork(struct task_struct *task) 9313 { 9314 perf_event_task(task, NULL, 1); 9315 perf_event_namespaces(task); 9316 perf_event_alloc_task_data(task, current); 9317 } 9318 9319 /* 9320 * comm tracking 9321 */ 9322 9323 struct perf_comm_event { 9324 struct task_struct *task; 9325 char *comm; 9326 int comm_size; 9327 9328 struct { 9329 struct perf_event_header header; 9330 9331 u32 pid; 9332 u32 tid; 9333 } event_id; 9334 }; 9335 9336 static int perf_event_comm_match(struct perf_event *event) 9337 { 9338 return event->attr.comm; 9339 } 9340 9341 static void perf_event_comm_output(struct perf_event *event, 9342 void *data) 9343 { 9344 struct perf_comm_event *comm_event = data; 9345 struct perf_output_handle handle; 9346 struct perf_sample_data sample; 9347 int size = comm_event->event_id.header.size; 9348 int ret; 9349 9350 if (!perf_event_comm_match(event)) 9351 return; 9352 9353 perf_event_header__init_id(&comm_event->event_id.header, &sample, event); 9354 ret = perf_output_begin(&handle, &sample, event, 9355 comm_event->event_id.header.size); 9356 9357 if (ret) 9358 goto out; 9359 9360 comm_event->event_id.pid = perf_event_pid(event, comm_event->task); 9361 comm_event->event_id.tid = perf_event_tid(event, comm_event->task); 9362 9363 perf_output_put(&handle, comm_event->event_id); 9364 __output_copy(&handle, comm_event->comm, 9365 comm_event->comm_size); 9366 9367 perf_event__output_id_sample(event, &handle, &sample); 9368 9369 perf_output_end(&handle); 9370 out: 9371 comm_event->event_id.header.size = size; 9372 } 9373 9374 static void perf_event_comm_event(struct perf_comm_event *comm_event) 9375 { 9376 char comm[TASK_COMM_LEN]; 9377 unsigned int size; 9378 9379 memset(comm, 0, sizeof(comm)); 9380 strscpy(comm, comm_event->task->comm); 9381 size = ALIGN(strlen(comm)+1, sizeof(u64)); 9382 9383 comm_event->comm = comm; 9384 comm_event->comm_size = size; 9385 9386 comm_event->event_id.header.size = sizeof(comm_event->event_id) + size; 9387 9388 perf_iterate_sb(perf_event_comm_output, 9389 comm_event, 9390 NULL); 9391 } 9392 9393 void perf_event_comm(struct task_struct *task, bool exec) 9394 { 9395 struct perf_comm_event comm_event; 9396 9397 if (!atomic_read(&nr_comm_events)) 9398 return; 9399 9400 comm_event = (struct perf_comm_event){ 9401 .task = task, 9402 /* .comm */ 9403 /* .comm_size */ 9404 .event_id = { 9405 .header = { 9406 .type = PERF_RECORD_COMM, 9407 .misc = exec ? PERF_RECORD_MISC_COMM_EXEC : 0, 9408 /* .size */ 9409 }, 9410 /* .pid */ 9411 /* .tid */ 9412 }, 9413 }; 9414 9415 perf_event_comm_event(&comm_event); 9416 } 9417 9418 /* 9419 * namespaces tracking 9420 */ 9421 9422 struct perf_namespaces_event { 9423 struct task_struct *task; 9424 9425 struct { 9426 struct perf_event_header header; 9427 9428 u32 pid; 9429 u32 tid; 9430 u64 nr_namespaces; 9431 struct perf_ns_link_info link_info[NR_NAMESPACES]; 9432 } event_id; 9433 }; 9434 9435 static int perf_event_namespaces_match(struct perf_event *event) 9436 { 9437 return event->attr.namespaces; 9438 } 9439 9440 static void perf_event_namespaces_output(struct perf_event *event, 9441 void *data) 9442 { 9443 struct perf_namespaces_event *namespaces_event = data; 9444 struct perf_output_handle handle; 9445 struct perf_sample_data sample; 9446 u16 header_size = namespaces_event->event_id.header.size; 9447 int ret; 9448 9449 if (!perf_event_namespaces_match(event)) 9450 return; 9451 9452 perf_event_header__init_id(&namespaces_event->event_id.header, 9453 &sample, event); 9454 ret = perf_output_begin(&handle, &sample, event, 9455 namespaces_event->event_id.header.size); 9456 if (ret) 9457 goto out; 9458 9459 namespaces_event->event_id.pid = perf_event_pid(event, 9460 namespaces_event->task); 9461 namespaces_event->event_id.tid = perf_event_tid(event, 9462 namespaces_event->task); 9463 9464 perf_output_put(&handle, namespaces_event->event_id); 9465 9466 perf_event__output_id_sample(event, &handle, &sample); 9467 9468 perf_output_end(&handle); 9469 out: 9470 namespaces_event->event_id.header.size = header_size; 9471 } 9472 9473 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info, 9474 struct task_struct *task, 9475 const struct proc_ns_operations *ns_ops) 9476 { 9477 struct path ns_path; 9478 struct inode *ns_inode; 9479 int error; 9480 9481 error = ns_get_path(&ns_path, task, ns_ops); 9482 if (!error) { 9483 ns_inode = ns_path.dentry->d_inode; 9484 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev); 9485 ns_link_info->ino = ns_inode->i_ino; 9486 path_put(&ns_path); 9487 } 9488 } 9489 9490 void perf_event_namespaces(struct task_struct *task) 9491 { 9492 struct perf_namespaces_event namespaces_event; 9493 struct perf_ns_link_info *ns_link_info; 9494 9495 if (!atomic_read(&nr_namespaces_events)) 9496 return; 9497 9498 namespaces_event = (struct perf_namespaces_event){ 9499 .task = task, 9500 .event_id = { 9501 .header = { 9502 .type = PERF_RECORD_NAMESPACES, 9503 .misc = 0, 9504 .size = sizeof(namespaces_event.event_id), 9505 }, 9506 /* .pid */ 9507 /* .tid */ 9508 .nr_namespaces = NR_NAMESPACES, 9509 /* .link_info[NR_NAMESPACES] */ 9510 }, 9511 }; 9512 9513 ns_link_info = namespaces_event.event_id.link_info; 9514 9515 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX], 9516 task, &mntns_operations); 9517 9518 #ifdef CONFIG_USER_NS 9519 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX], 9520 task, &userns_operations); 9521 #endif 9522 #ifdef CONFIG_NET_NS 9523 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX], 9524 task, &netns_operations); 9525 #endif 9526 #ifdef CONFIG_UTS_NS 9527 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX], 9528 task, &utsns_operations); 9529 #endif 9530 #ifdef CONFIG_IPC_NS 9531 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX], 9532 task, &ipcns_operations); 9533 #endif 9534 #ifdef CONFIG_PID_NS 9535 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX], 9536 task, &pidns_operations); 9537 #endif 9538 #ifdef CONFIG_CGROUPS 9539 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX], 9540 task, &cgroupns_operations); 9541 #endif 9542 9543 perf_iterate_sb(perf_event_namespaces_output, 9544 &namespaces_event, 9545 NULL); 9546 } 9547 9548 /* 9549 * cgroup tracking 9550 */ 9551 #ifdef CONFIG_CGROUP_PERF 9552 9553 struct perf_cgroup_event { 9554 char *path; 9555 int path_size; 9556 struct { 9557 struct perf_event_header header; 9558 u64 id; 9559 char path[]; 9560 } event_id; 9561 }; 9562 9563 static int perf_event_cgroup_match(struct perf_event *event) 9564 { 9565 return event->attr.cgroup; 9566 } 9567 9568 static void perf_event_cgroup_output(struct perf_event *event, void *data) 9569 { 9570 struct perf_cgroup_event *cgroup_event = data; 9571 struct perf_output_handle handle; 9572 struct perf_sample_data sample; 9573 u16 header_size = cgroup_event->event_id.header.size; 9574 int ret; 9575 9576 if (!perf_event_cgroup_match(event)) 9577 return; 9578 9579 perf_event_header__init_id(&cgroup_event->event_id.header, 9580 &sample, event); 9581 ret = perf_output_begin(&handle, &sample, event, 9582 cgroup_event->event_id.header.size); 9583 if (ret) 9584 goto out; 9585 9586 perf_output_put(&handle, cgroup_event->event_id); 9587 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size); 9588 9589 perf_event__output_id_sample(event, &handle, &sample); 9590 9591 perf_output_end(&handle); 9592 out: 9593 cgroup_event->event_id.header.size = header_size; 9594 } 9595 9596 static void perf_event_cgroup(struct cgroup *cgrp) 9597 { 9598 struct perf_cgroup_event cgroup_event; 9599 char path_enomem[16] = "//enomem"; 9600 char *pathname; 9601 size_t size; 9602 9603 if (!atomic_read(&nr_cgroup_events)) 9604 return; 9605 9606 cgroup_event = (struct perf_cgroup_event){ 9607 .event_id = { 9608 .header = { 9609 .type = PERF_RECORD_CGROUP, 9610 .misc = 0, 9611 .size = sizeof(cgroup_event.event_id), 9612 }, 9613 .id = cgroup_id(cgrp), 9614 }, 9615 }; 9616 9617 pathname = kmalloc(PATH_MAX, GFP_KERNEL); 9618 if (pathname == NULL) { 9619 cgroup_event.path = path_enomem; 9620 } else { 9621 /* just to be sure to have enough space for alignment */ 9622 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64)); 9623 cgroup_event.path = pathname; 9624 } 9625 9626 /* 9627 * Since our buffer works in 8 byte units we need to align our string 9628 * size to a multiple of 8. However, we must guarantee the tail end is 9629 * zero'd out to avoid leaking random bits to userspace. 9630 */ 9631 size = strlen(cgroup_event.path) + 1; 9632 while (!IS_ALIGNED(size, sizeof(u64))) 9633 cgroup_event.path[size++] = '\0'; 9634 9635 cgroup_event.event_id.header.size += size; 9636 cgroup_event.path_size = size; 9637 9638 perf_iterate_sb(perf_event_cgroup_output, 9639 &cgroup_event, 9640 NULL); 9641 9642 kfree(pathname); 9643 } 9644 9645 #endif 9646 9647 /* 9648 * mmap tracking 9649 */ 9650 9651 struct perf_mmap_event { 9652 struct vm_area_struct *vma; 9653 9654 const char *file_name; 9655 int file_size; 9656 int maj, min; 9657 u64 ino; 9658 u64 ino_generation; 9659 u32 prot, flags; 9660 u8 build_id[BUILD_ID_SIZE_MAX]; 9661 u32 build_id_size; 9662 9663 struct { 9664 struct perf_event_header header; 9665 9666 u32 pid; 9667 u32 tid; 9668 u64 start; 9669 u64 len; 9670 u64 pgoff; 9671 } event_id; 9672 }; 9673 9674 static int perf_event_mmap_match(struct perf_event *event, 9675 void *data) 9676 { 9677 struct perf_mmap_event *mmap_event = data; 9678 struct vm_area_struct *vma = mmap_event->vma; 9679 int executable = vma->vm_flags & VM_EXEC; 9680 9681 return (!executable && event->attr.mmap_data) || 9682 (executable && (event->attr.mmap || event->attr.mmap2)); 9683 } 9684 9685 static void perf_event_mmap_output(struct perf_event *event, 9686 void *data) 9687 { 9688 struct perf_mmap_event *mmap_event = data; 9689 struct perf_output_handle handle; 9690 struct perf_sample_data sample; 9691 int size = mmap_event->event_id.header.size; 9692 u32 type = mmap_event->event_id.header.type; 9693 bool use_build_id; 9694 int ret; 9695 9696 if (!perf_event_mmap_match(event, data)) 9697 return; 9698 9699 if (event->attr.mmap2) { 9700 mmap_event->event_id.header.type = PERF_RECORD_MMAP2; 9701 mmap_event->event_id.header.size += sizeof(mmap_event->maj); 9702 mmap_event->event_id.header.size += sizeof(mmap_event->min); 9703 mmap_event->event_id.header.size += sizeof(mmap_event->ino); 9704 mmap_event->event_id.header.size += sizeof(mmap_event->ino_generation); 9705 mmap_event->event_id.header.size += sizeof(mmap_event->prot); 9706 mmap_event->event_id.header.size += sizeof(mmap_event->flags); 9707 } 9708 9709 perf_event_header__init_id(&mmap_event->event_id.header, &sample, event); 9710 ret = perf_output_begin(&handle, &sample, event, 9711 mmap_event->event_id.header.size); 9712 if (ret) 9713 goto out; 9714 9715 mmap_event->event_id.pid = perf_event_pid(event, current); 9716 mmap_event->event_id.tid = perf_event_tid(event, current); 9717 9718 use_build_id = event->attr.build_id && mmap_event->build_id_size; 9719 9720 if (event->attr.mmap2 && use_build_id) 9721 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_BUILD_ID; 9722 9723 perf_output_put(&handle, mmap_event->event_id); 9724 9725 if (event->attr.mmap2) { 9726 if (use_build_id) { 9727 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 }; 9728 9729 __output_copy(&handle, size, 4); 9730 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX); 9731 } else { 9732 perf_output_put(&handle, mmap_event->maj); 9733 perf_output_put(&handle, mmap_event->min); 9734 perf_output_put(&handle, mmap_event->ino); 9735 perf_output_put(&handle, mmap_event->ino_generation); 9736 } 9737 perf_output_put(&handle, mmap_event->prot); 9738 perf_output_put(&handle, mmap_event->flags); 9739 } 9740 9741 __output_copy(&handle, mmap_event->file_name, 9742 mmap_event->file_size); 9743 9744 perf_event__output_id_sample(event, &handle, &sample); 9745 9746 perf_output_end(&handle); 9747 out: 9748 mmap_event->event_id.header.size = size; 9749 mmap_event->event_id.header.type = type; 9750 } 9751 9752 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event) 9753 { 9754 struct vm_area_struct *vma = mmap_event->vma; 9755 struct file *file = vma->vm_file; 9756 int maj = 0, min = 0; 9757 u64 ino = 0, gen = 0; 9758 u32 prot = 0, flags = 0; 9759 unsigned int size; 9760 char tmp[16]; 9761 char *buf = NULL; 9762 char *name = NULL; 9763 9764 if (vma->vm_flags & VM_READ) 9765 prot |= PROT_READ; 9766 if (vma->vm_flags & VM_WRITE) 9767 prot |= PROT_WRITE; 9768 if (vma->vm_flags & VM_EXEC) 9769 prot |= PROT_EXEC; 9770 9771 if (vma->vm_flags & VM_MAYSHARE) 9772 flags = MAP_SHARED; 9773 else 9774 flags = MAP_PRIVATE; 9775 9776 if (vma->vm_flags & VM_LOCKED) 9777 flags |= MAP_LOCKED; 9778 if (is_vm_hugetlb_page(vma)) 9779 flags |= MAP_HUGETLB; 9780 9781 if (file) { 9782 const struct inode *inode; 9783 dev_t dev; 9784 9785 buf = kmalloc(PATH_MAX, GFP_KERNEL); 9786 if (!buf) { 9787 name = "//enomem"; 9788 goto cpy_name; 9789 } 9790 /* 9791 * d_path() works from the end of the rb backwards, so we 9792 * need to add enough zero bytes after the string to handle 9793 * the 64bit alignment we do later. 9794 */ 9795 name = d_path(file_user_path(file), buf, PATH_MAX - sizeof(u64)); 9796 if (IS_ERR(name)) { 9797 name = "//toolong"; 9798 goto cpy_name; 9799 } 9800 inode = file_user_inode(vma->vm_file); 9801 dev = inode->i_sb->s_dev; 9802 ino = inode->i_ino; 9803 gen = inode->i_generation; 9804 maj = MAJOR(dev); 9805 min = MINOR(dev); 9806 9807 goto got_name; 9808 } else { 9809 if (vma->vm_ops && vma->vm_ops->name) 9810 name = (char *) vma->vm_ops->name(vma); 9811 if (!name) 9812 name = (char *)arch_vma_name(vma); 9813 if (!name) { 9814 if (vma_is_initial_heap(vma)) 9815 name = "[heap]"; 9816 else if (vma_is_initial_stack(vma)) 9817 name = "[stack]"; 9818 else 9819 name = "//anon"; 9820 } 9821 } 9822 9823 cpy_name: 9824 strscpy(tmp, name); 9825 name = tmp; 9826 got_name: 9827 /* 9828 * Since our buffer works in 8 byte units we need to align our string 9829 * size to a multiple of 8. However, we must guarantee the tail end is 9830 * zero'd out to avoid leaking random bits to userspace. 9831 */ 9832 size = strlen(name)+1; 9833 while (!IS_ALIGNED(size, sizeof(u64))) 9834 name[size++] = '\0'; 9835 9836 mmap_event->file_name = name; 9837 mmap_event->file_size = size; 9838 mmap_event->maj = maj; 9839 mmap_event->min = min; 9840 mmap_event->ino = ino; 9841 mmap_event->ino_generation = gen; 9842 mmap_event->prot = prot; 9843 mmap_event->flags = flags; 9844 9845 if (!(vma->vm_flags & VM_EXEC)) 9846 mmap_event->event_id.header.misc |= PERF_RECORD_MISC_MMAP_DATA; 9847 9848 mmap_event->event_id.header.size = sizeof(mmap_event->event_id) + size; 9849 9850 if (atomic_read(&nr_build_id_events)) 9851 build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size); 9852 9853 perf_iterate_sb(perf_event_mmap_output, 9854 mmap_event, 9855 NULL); 9856 9857 kfree(buf); 9858 } 9859 9860 /* 9861 * Check whether inode and address range match filter criteria. 9862 */ 9863 static bool perf_addr_filter_match(struct perf_addr_filter *filter, 9864 struct file *file, unsigned long offset, 9865 unsigned long size) 9866 { 9867 /* d_inode(NULL) won't be equal to any mapped user-space file */ 9868 if (!filter->path.dentry) 9869 return false; 9870 9871 if (d_inode(filter->path.dentry) != file_user_inode(file)) 9872 return false; 9873 9874 if (filter->offset > offset + size) 9875 return false; 9876 9877 if (filter->offset + filter->size < offset) 9878 return false; 9879 9880 return true; 9881 } 9882 9883 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter, 9884 struct vm_area_struct *vma, 9885 struct perf_addr_filter_range *fr) 9886 { 9887 unsigned long vma_size = vma->vm_end - vma->vm_start; 9888 unsigned long off = vma->vm_pgoff << PAGE_SHIFT; 9889 struct file *file = vma->vm_file; 9890 9891 if (!perf_addr_filter_match(filter, file, off, vma_size)) 9892 return false; 9893 9894 if (filter->offset < off) { 9895 fr->start = vma->vm_start; 9896 fr->size = min(vma_size, filter->size - (off - filter->offset)); 9897 } else { 9898 fr->start = vma->vm_start + filter->offset - off; 9899 fr->size = min(vma->vm_end - fr->start, filter->size); 9900 } 9901 9902 return true; 9903 } 9904 9905 static void __perf_addr_filters_adjust(struct perf_event *event, void *data) 9906 { 9907 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 9908 struct vm_area_struct *vma = data; 9909 struct perf_addr_filter *filter; 9910 unsigned int restart = 0, count = 0; 9911 unsigned long flags; 9912 9913 if (!has_addr_filter(event)) 9914 return; 9915 9916 if (!vma->vm_file) 9917 return; 9918 9919 raw_spin_lock_irqsave(&ifh->lock, flags); 9920 list_for_each_entry(filter, &ifh->list, entry) { 9921 if (perf_addr_filter_vma_adjust(filter, vma, 9922 &event->addr_filter_ranges[count])) 9923 restart++; 9924 9925 count++; 9926 } 9927 9928 if (restart) 9929 event->addr_filters_gen++; 9930 raw_spin_unlock_irqrestore(&ifh->lock, flags); 9931 9932 if (restart) 9933 perf_event_stop(event, 1); 9934 } 9935 9936 /* 9937 * Adjust all task's events' filters to the new vma 9938 */ 9939 static void perf_addr_filters_adjust(struct vm_area_struct *vma) 9940 { 9941 struct perf_event_context *ctx; 9942 9943 /* 9944 * Data tracing isn't supported yet and as such there is no need 9945 * to keep track of anything that isn't related to executable code: 9946 */ 9947 if (!(vma->vm_flags & VM_EXEC)) 9948 return; 9949 9950 rcu_read_lock(); 9951 ctx = rcu_dereference(current->perf_event_ctxp); 9952 if (ctx) 9953 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true); 9954 rcu_read_unlock(); 9955 } 9956 9957 void perf_event_mmap(struct vm_area_struct *vma) 9958 { 9959 struct perf_mmap_event mmap_event; 9960 9961 if (!atomic_read(&nr_mmap_events)) 9962 return; 9963 9964 mmap_event = (struct perf_mmap_event){ 9965 .vma = vma, 9966 /* .file_name */ 9967 /* .file_size */ 9968 .event_id = { 9969 .header = { 9970 .type = PERF_RECORD_MMAP, 9971 .misc = PERF_RECORD_MISC_USER, 9972 /* .size */ 9973 }, 9974 /* .pid */ 9975 /* .tid */ 9976 .start = vma->vm_start, 9977 .len = vma->vm_end - vma->vm_start, 9978 .pgoff = (u64)vma->vm_pgoff << PAGE_SHIFT, 9979 }, 9980 /* .maj (attr_mmap2 only) */ 9981 /* .min (attr_mmap2 only) */ 9982 /* .ino (attr_mmap2 only) */ 9983 /* .ino_generation (attr_mmap2 only) */ 9984 /* .prot (attr_mmap2 only) */ 9985 /* .flags (attr_mmap2 only) */ 9986 }; 9987 9988 perf_addr_filters_adjust(vma); 9989 perf_event_mmap_event(&mmap_event); 9990 } 9991 9992 void perf_event_aux_event(struct perf_event *event, unsigned long head, 9993 unsigned long size, u64 flags) 9994 { 9995 struct perf_output_handle handle; 9996 struct perf_sample_data sample; 9997 struct perf_aux_event { 9998 struct perf_event_header header; 9999 u64 offset; 10000 u64 size; 10001 u64 flags; 10002 } rec = { 10003 .header = { 10004 .type = PERF_RECORD_AUX, 10005 .misc = 0, 10006 .size = sizeof(rec), 10007 }, 10008 .offset = head, 10009 .size = size, 10010 .flags = flags, 10011 }; 10012 int ret; 10013 10014 perf_event_header__init_id(&rec.header, &sample, event); 10015 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10016 10017 if (ret) 10018 return; 10019 10020 perf_output_put(&handle, rec); 10021 perf_event__output_id_sample(event, &handle, &sample); 10022 10023 perf_output_end(&handle); 10024 } 10025 10026 /* 10027 * Lost/dropped samples logging 10028 */ 10029 void perf_log_lost_samples(struct perf_event *event, u64 lost) 10030 { 10031 struct perf_output_handle handle; 10032 struct perf_sample_data sample; 10033 int ret; 10034 10035 struct { 10036 struct perf_event_header header; 10037 u64 lost; 10038 } lost_samples_event = { 10039 .header = { 10040 .type = PERF_RECORD_LOST_SAMPLES, 10041 .misc = 0, 10042 .size = sizeof(lost_samples_event), 10043 }, 10044 .lost = lost, 10045 }; 10046 10047 perf_event_header__init_id(&lost_samples_event.header, &sample, event); 10048 10049 ret = perf_output_begin(&handle, &sample, event, 10050 lost_samples_event.header.size); 10051 if (ret) 10052 return; 10053 10054 perf_output_put(&handle, lost_samples_event); 10055 perf_event__output_id_sample(event, &handle, &sample); 10056 perf_output_end(&handle); 10057 } 10058 10059 /* 10060 * context_switch tracking 10061 */ 10062 10063 struct perf_switch_event { 10064 struct task_struct *task; 10065 struct task_struct *next_prev; 10066 10067 struct { 10068 struct perf_event_header header; 10069 u32 next_prev_pid; 10070 u32 next_prev_tid; 10071 } event_id; 10072 }; 10073 10074 static int perf_event_switch_match(struct perf_event *event) 10075 { 10076 return event->attr.context_switch; 10077 } 10078 10079 static void perf_event_switch_output(struct perf_event *event, void *data) 10080 { 10081 struct perf_switch_event *se = data; 10082 struct perf_output_handle handle; 10083 struct perf_sample_data sample; 10084 int ret; 10085 10086 if (!perf_event_switch_match(event)) 10087 return; 10088 10089 /* Only CPU-wide events are allowed to see next/prev pid/tid */ 10090 if (event->ctx->task) { 10091 se->event_id.header.type = PERF_RECORD_SWITCH; 10092 se->event_id.header.size = sizeof(se->event_id.header); 10093 } else { 10094 se->event_id.header.type = PERF_RECORD_SWITCH_CPU_WIDE; 10095 se->event_id.header.size = sizeof(se->event_id); 10096 se->event_id.next_prev_pid = 10097 perf_event_pid(event, se->next_prev); 10098 se->event_id.next_prev_tid = 10099 perf_event_tid(event, se->next_prev); 10100 } 10101 10102 perf_event_header__init_id(&se->event_id.header, &sample, event); 10103 10104 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size); 10105 if (ret) 10106 return; 10107 10108 if (event->ctx->task) 10109 perf_output_put(&handle, se->event_id.header); 10110 else 10111 perf_output_put(&handle, se->event_id); 10112 10113 perf_event__output_id_sample(event, &handle, &sample); 10114 10115 perf_output_end(&handle); 10116 } 10117 10118 static void perf_event_switch(struct task_struct *task, 10119 struct task_struct *next_prev, bool sched_in) 10120 { 10121 struct perf_switch_event switch_event; 10122 10123 /* N.B. caller checks nr_switch_events != 0 */ 10124 10125 switch_event = (struct perf_switch_event){ 10126 .task = task, 10127 .next_prev = next_prev, 10128 .event_id = { 10129 .header = { 10130 /* .type */ 10131 .misc = sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT, 10132 /* .size */ 10133 }, 10134 /* .next_prev_pid */ 10135 /* .next_prev_tid */ 10136 }, 10137 }; 10138 10139 if (!sched_in && task_is_runnable(task)) { 10140 switch_event.event_id.header.misc |= 10141 PERF_RECORD_MISC_SWITCH_OUT_PREEMPT; 10142 } 10143 10144 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL); 10145 } 10146 10147 /* 10148 * IRQ throttle logging 10149 */ 10150 10151 static void perf_log_throttle(struct perf_event *event, int enable) 10152 { 10153 struct perf_output_handle handle; 10154 struct perf_sample_data sample; 10155 int ret; 10156 10157 struct { 10158 struct perf_event_header header; 10159 u64 time; 10160 u64 id; 10161 u64 stream_id; 10162 } throttle_event = { 10163 .header = { 10164 .type = PERF_RECORD_THROTTLE, 10165 .misc = 0, 10166 .size = sizeof(throttle_event), 10167 }, 10168 .time = perf_event_clock(event), 10169 .id = primary_event_id(event), 10170 .stream_id = event->id, 10171 }; 10172 10173 if (enable) 10174 throttle_event.header.type = PERF_RECORD_UNTHROTTLE; 10175 10176 perf_event_header__init_id(&throttle_event.header, &sample, event); 10177 10178 ret = perf_output_begin(&handle, &sample, event, 10179 throttle_event.header.size); 10180 if (ret) 10181 return; 10182 10183 perf_output_put(&handle, throttle_event); 10184 perf_event__output_id_sample(event, &handle, &sample); 10185 perf_output_end(&handle); 10186 } 10187 10188 /* 10189 * ksymbol register/unregister tracking 10190 */ 10191 10192 struct perf_ksymbol_event { 10193 const char *name; 10194 int name_len; 10195 struct { 10196 struct perf_event_header header; 10197 u64 addr; 10198 u32 len; 10199 u16 ksym_type; 10200 u16 flags; 10201 } event_id; 10202 }; 10203 10204 static int perf_event_ksymbol_match(struct perf_event *event) 10205 { 10206 return event->attr.ksymbol; 10207 } 10208 10209 static void perf_event_ksymbol_output(struct perf_event *event, void *data) 10210 { 10211 struct perf_ksymbol_event *ksymbol_event = data; 10212 struct perf_output_handle handle; 10213 struct perf_sample_data sample; 10214 int ret; 10215 10216 if (!perf_event_ksymbol_match(event)) 10217 return; 10218 10219 perf_event_header__init_id(&ksymbol_event->event_id.header, 10220 &sample, event); 10221 ret = perf_output_begin(&handle, &sample, event, 10222 ksymbol_event->event_id.header.size); 10223 if (ret) 10224 return; 10225 10226 perf_output_put(&handle, ksymbol_event->event_id); 10227 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len); 10228 perf_event__output_id_sample(event, &handle, &sample); 10229 10230 perf_output_end(&handle); 10231 } 10232 10233 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister, 10234 const char *sym) 10235 { 10236 struct perf_ksymbol_event ksymbol_event; 10237 char name[KSYM_NAME_LEN]; 10238 u16 flags = 0; 10239 int name_len; 10240 10241 if (!atomic_read(&nr_ksymbol_events)) 10242 return; 10243 10244 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX || 10245 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN) 10246 goto err; 10247 10248 strscpy(name, sym); 10249 name_len = strlen(name) + 1; 10250 while (!IS_ALIGNED(name_len, sizeof(u64))) 10251 name[name_len++] = '\0'; 10252 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64)); 10253 10254 if (unregister) 10255 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER; 10256 10257 ksymbol_event = (struct perf_ksymbol_event){ 10258 .name = name, 10259 .name_len = name_len, 10260 .event_id = { 10261 .header = { 10262 .type = PERF_RECORD_KSYMBOL, 10263 .size = sizeof(ksymbol_event.event_id) + 10264 name_len, 10265 }, 10266 .addr = addr, 10267 .len = len, 10268 .ksym_type = ksym_type, 10269 .flags = flags, 10270 }, 10271 }; 10272 10273 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL); 10274 return; 10275 err: 10276 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type); 10277 } 10278 10279 /* 10280 * bpf program load/unload tracking 10281 */ 10282 10283 struct perf_bpf_event { 10284 struct bpf_prog *prog; 10285 struct { 10286 struct perf_event_header header; 10287 u16 type; 10288 u16 flags; 10289 u32 id; 10290 u8 tag[BPF_TAG_SIZE]; 10291 } event_id; 10292 }; 10293 10294 static int perf_event_bpf_match(struct perf_event *event) 10295 { 10296 return event->attr.bpf_event; 10297 } 10298 10299 static void perf_event_bpf_output(struct perf_event *event, void *data) 10300 { 10301 struct perf_bpf_event *bpf_event = data; 10302 struct perf_output_handle handle; 10303 struct perf_sample_data sample; 10304 int ret; 10305 10306 if (!perf_event_bpf_match(event)) 10307 return; 10308 10309 perf_event_header__init_id(&bpf_event->event_id.header, 10310 &sample, event); 10311 ret = perf_output_begin(&handle, &sample, event, 10312 bpf_event->event_id.header.size); 10313 if (ret) 10314 return; 10315 10316 perf_output_put(&handle, bpf_event->event_id); 10317 perf_event__output_id_sample(event, &handle, &sample); 10318 10319 perf_output_end(&handle); 10320 } 10321 10322 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog, 10323 enum perf_bpf_event_type type) 10324 { 10325 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD; 10326 int i; 10327 10328 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, 10329 (u64)(unsigned long)prog->bpf_func, 10330 prog->jited_len, unregister, 10331 prog->aux->ksym.name); 10332 10333 for (i = 1; i < prog->aux->func_cnt; i++) { 10334 struct bpf_prog *subprog = prog->aux->func[i]; 10335 10336 perf_event_ksymbol( 10337 PERF_RECORD_KSYMBOL_TYPE_BPF, 10338 (u64)(unsigned long)subprog->bpf_func, 10339 subprog->jited_len, unregister, 10340 subprog->aux->ksym.name); 10341 } 10342 } 10343 10344 void perf_event_bpf_event(struct bpf_prog *prog, 10345 enum perf_bpf_event_type type, 10346 u16 flags) 10347 { 10348 struct perf_bpf_event bpf_event; 10349 10350 switch (type) { 10351 case PERF_BPF_EVENT_PROG_LOAD: 10352 case PERF_BPF_EVENT_PROG_UNLOAD: 10353 if (atomic_read(&nr_ksymbol_events)) 10354 perf_event_bpf_emit_ksymbols(prog, type); 10355 break; 10356 default: 10357 return; 10358 } 10359 10360 if (!atomic_read(&nr_bpf_events)) 10361 return; 10362 10363 bpf_event = (struct perf_bpf_event){ 10364 .prog = prog, 10365 .event_id = { 10366 .header = { 10367 .type = PERF_RECORD_BPF_EVENT, 10368 .size = sizeof(bpf_event.event_id), 10369 }, 10370 .type = type, 10371 .flags = flags, 10372 .id = prog->aux->id, 10373 }, 10374 }; 10375 10376 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64)); 10377 10378 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE); 10379 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL); 10380 } 10381 10382 struct perf_callchain_deferred_event { 10383 struct unwind_stacktrace *trace; 10384 struct { 10385 struct perf_event_header header; 10386 u64 cookie; 10387 u64 nr; 10388 u64 ips[]; 10389 } event; 10390 }; 10391 10392 static void perf_callchain_deferred_output(struct perf_event *event, void *data) 10393 { 10394 struct perf_callchain_deferred_event *deferred_event = data; 10395 struct perf_output_handle handle; 10396 struct perf_sample_data sample; 10397 int ret, size = deferred_event->event.header.size; 10398 10399 if (!event->attr.defer_output) 10400 return; 10401 10402 /* XXX do we really need sample_id_all for this ??? */ 10403 perf_event_header__init_id(&deferred_event->event.header, &sample, event); 10404 10405 ret = perf_output_begin(&handle, &sample, event, 10406 deferred_event->event.header.size); 10407 if (ret) 10408 goto out; 10409 10410 perf_output_put(&handle, deferred_event->event); 10411 for (int i = 0; i < deferred_event->trace->nr; i++) { 10412 u64 entry = deferred_event->trace->entries[i]; 10413 perf_output_put(&handle, entry); 10414 } 10415 perf_event__output_id_sample(event, &handle, &sample); 10416 10417 perf_output_end(&handle); 10418 out: 10419 deferred_event->event.header.size = size; 10420 } 10421 10422 static void perf_unwind_deferred_callback(struct unwind_work *work, 10423 struct unwind_stacktrace *trace, u64 cookie) 10424 { 10425 struct perf_callchain_deferred_event deferred_event = { 10426 .trace = trace, 10427 .event = { 10428 .header = { 10429 .type = PERF_RECORD_CALLCHAIN_DEFERRED, 10430 .misc = PERF_RECORD_MISC_USER, 10431 .size = sizeof(deferred_event.event) + 10432 (trace->nr * sizeof(u64)), 10433 }, 10434 .cookie = cookie, 10435 .nr = trace->nr, 10436 }, 10437 }; 10438 10439 perf_iterate_sb(perf_callchain_deferred_output, &deferred_event, NULL); 10440 } 10441 10442 struct perf_text_poke_event { 10443 const void *old_bytes; 10444 const void *new_bytes; 10445 size_t pad; 10446 u16 old_len; 10447 u16 new_len; 10448 10449 struct { 10450 struct perf_event_header header; 10451 10452 u64 addr; 10453 } event_id; 10454 }; 10455 10456 static int perf_event_text_poke_match(struct perf_event *event) 10457 { 10458 return event->attr.text_poke; 10459 } 10460 10461 static void perf_event_text_poke_output(struct perf_event *event, void *data) 10462 { 10463 struct perf_text_poke_event *text_poke_event = data; 10464 struct perf_output_handle handle; 10465 struct perf_sample_data sample; 10466 u64 padding = 0; 10467 int ret; 10468 10469 if (!perf_event_text_poke_match(event)) 10470 return; 10471 10472 perf_event_header__init_id(&text_poke_event->event_id.header, &sample, event); 10473 10474 ret = perf_output_begin(&handle, &sample, event, 10475 text_poke_event->event_id.header.size); 10476 if (ret) 10477 return; 10478 10479 perf_output_put(&handle, text_poke_event->event_id); 10480 perf_output_put(&handle, text_poke_event->old_len); 10481 perf_output_put(&handle, text_poke_event->new_len); 10482 10483 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len); 10484 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len); 10485 10486 if (text_poke_event->pad) 10487 __output_copy(&handle, &padding, text_poke_event->pad); 10488 10489 perf_event__output_id_sample(event, &handle, &sample); 10490 10491 perf_output_end(&handle); 10492 } 10493 10494 void perf_event_text_poke(const void *addr, const void *old_bytes, 10495 size_t old_len, const void *new_bytes, size_t new_len) 10496 { 10497 struct perf_text_poke_event text_poke_event; 10498 size_t tot, pad; 10499 10500 if (!atomic_read(&nr_text_poke_events)) 10501 return; 10502 10503 tot = sizeof(text_poke_event.old_len) + old_len; 10504 tot += sizeof(text_poke_event.new_len) + new_len; 10505 pad = ALIGN(tot, sizeof(u64)) - tot; 10506 10507 text_poke_event = (struct perf_text_poke_event){ 10508 .old_bytes = old_bytes, 10509 .new_bytes = new_bytes, 10510 .pad = pad, 10511 .old_len = old_len, 10512 .new_len = new_len, 10513 .event_id = { 10514 .header = { 10515 .type = PERF_RECORD_TEXT_POKE, 10516 .misc = PERF_RECORD_MISC_KERNEL, 10517 .size = sizeof(text_poke_event.event_id) + tot + pad, 10518 }, 10519 .addr = (unsigned long)addr, 10520 }, 10521 }; 10522 10523 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL); 10524 } 10525 10526 void perf_event_itrace_started(struct perf_event *event) 10527 { 10528 WRITE_ONCE(event->attach_state, event->attach_state | PERF_ATTACH_ITRACE); 10529 } 10530 10531 static void perf_log_itrace_start(struct perf_event *event) 10532 { 10533 struct perf_output_handle handle; 10534 struct perf_sample_data sample; 10535 struct perf_aux_event { 10536 struct perf_event_header header; 10537 u32 pid; 10538 u32 tid; 10539 } rec; 10540 int ret; 10541 10542 if (event->parent) 10543 event = event->parent; 10544 10545 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) || 10546 event->attach_state & PERF_ATTACH_ITRACE) 10547 return; 10548 10549 rec.header.type = PERF_RECORD_ITRACE_START; 10550 rec.header.misc = 0; 10551 rec.header.size = sizeof(rec); 10552 rec.pid = perf_event_pid(event, current); 10553 rec.tid = perf_event_tid(event, current); 10554 10555 perf_event_header__init_id(&rec.header, &sample, event); 10556 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10557 10558 if (ret) 10559 return; 10560 10561 perf_output_put(&handle, rec); 10562 perf_event__output_id_sample(event, &handle, &sample); 10563 10564 perf_output_end(&handle); 10565 } 10566 10567 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id) 10568 { 10569 struct perf_output_handle handle; 10570 struct perf_sample_data sample; 10571 struct perf_aux_event { 10572 struct perf_event_header header; 10573 u64 hw_id; 10574 } rec; 10575 int ret; 10576 10577 if (event->parent) 10578 event = event->parent; 10579 10580 rec.header.type = PERF_RECORD_AUX_OUTPUT_HW_ID; 10581 rec.header.misc = 0; 10582 rec.header.size = sizeof(rec); 10583 rec.hw_id = hw_id; 10584 10585 perf_event_header__init_id(&rec.header, &sample, event); 10586 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10587 10588 if (ret) 10589 return; 10590 10591 perf_output_put(&handle, rec); 10592 perf_event__output_id_sample(event, &handle, &sample); 10593 10594 perf_output_end(&handle); 10595 } 10596 EXPORT_SYMBOL_GPL(perf_report_aux_output_id); 10597 10598 static int 10599 __perf_event_account_interrupt(struct perf_event *event, int throttle) 10600 { 10601 struct hw_perf_event *hwc = &event->hw; 10602 int ret = 0; 10603 u64 seq; 10604 10605 seq = __this_cpu_read(perf_throttled_seq); 10606 if (seq != hwc->interrupts_seq) { 10607 hwc->interrupts_seq = seq; 10608 hwc->interrupts = 1; 10609 } else { 10610 hwc->interrupts++; 10611 } 10612 10613 if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) { 10614 __this_cpu_inc(perf_throttled_count); 10615 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 10616 perf_event_throttle_group(event); 10617 ret = 1; 10618 } 10619 10620 if (event->attr.freq) { 10621 u64 now = perf_clock(); 10622 s64 delta = now - hwc->freq_time_stamp; 10623 10624 hwc->freq_time_stamp = now; 10625 10626 if (delta > 0 && delta < 2*TICK_NSEC) 10627 perf_adjust_period(event, delta, hwc->last_period, true); 10628 } 10629 10630 return ret; 10631 } 10632 10633 int perf_event_account_interrupt(struct perf_event *event) 10634 { 10635 return __perf_event_account_interrupt(event, 1); 10636 } 10637 10638 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs) 10639 { 10640 /* 10641 * Due to interrupt latency (AKA "skid"), we may enter the 10642 * kernel before taking an overflow, even if the PMU is only 10643 * counting user events. 10644 */ 10645 if (event->attr.exclude_kernel && !user_mode(regs)) 10646 return false; 10647 10648 return true; 10649 } 10650 10651 #ifdef CONFIG_BPF_SYSCALL 10652 static int bpf_overflow_handler(struct perf_event *event, 10653 struct perf_sample_data *data, 10654 struct pt_regs *regs) 10655 { 10656 struct bpf_perf_event_data_kern ctx = { 10657 .data = data, 10658 .event = event, 10659 }; 10660 struct bpf_prog *prog; 10661 int ret = 0; 10662 10663 ctx.regs = perf_arch_bpf_user_pt_regs(regs); 10664 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) 10665 goto out; 10666 rcu_read_lock(); 10667 prog = READ_ONCE(event->prog); 10668 if (prog) { 10669 perf_prepare_sample(data, event, regs); 10670 ret = bpf_prog_run(prog, &ctx); 10671 } 10672 rcu_read_unlock(); 10673 out: 10674 __this_cpu_dec(bpf_prog_active); 10675 10676 return ret; 10677 } 10678 10679 static inline int perf_event_set_bpf_handler(struct perf_event *event, 10680 struct bpf_prog *prog, 10681 u64 bpf_cookie) 10682 { 10683 if (event->overflow_handler_context) 10684 /* hw breakpoint or kernel counter */ 10685 return -EINVAL; 10686 10687 if (event->prog) 10688 return -EEXIST; 10689 10690 if (prog->type != BPF_PROG_TYPE_PERF_EVENT) 10691 return -EINVAL; 10692 10693 if (event->attr.precise_ip && 10694 prog->call_get_stack && 10695 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) || 10696 event->attr.exclude_callchain_kernel || 10697 event->attr.exclude_callchain_user)) { 10698 /* 10699 * On perf_event with precise_ip, calling bpf_get_stack() 10700 * may trigger unwinder warnings and occasional crashes. 10701 * bpf_get_[stack|stackid] works around this issue by using 10702 * callchain attached to perf_sample_data. If the 10703 * perf_event does not full (kernel and user) callchain 10704 * attached to perf_sample_data, do not allow attaching BPF 10705 * program that calls bpf_get_[stack|stackid]. 10706 */ 10707 return -EPROTO; 10708 } 10709 10710 event->prog = prog; 10711 event->bpf_cookie = bpf_cookie; 10712 return 0; 10713 } 10714 10715 static inline void perf_event_free_bpf_handler(struct perf_event *event) 10716 { 10717 struct bpf_prog *prog = event->prog; 10718 10719 if (!prog) 10720 return; 10721 10722 event->prog = NULL; 10723 bpf_prog_put(prog); 10724 } 10725 #else 10726 static inline int bpf_overflow_handler(struct perf_event *event, 10727 struct perf_sample_data *data, 10728 struct pt_regs *regs) 10729 { 10730 return 1; 10731 } 10732 10733 static inline int perf_event_set_bpf_handler(struct perf_event *event, 10734 struct bpf_prog *prog, 10735 u64 bpf_cookie) 10736 { 10737 return -EOPNOTSUPP; 10738 } 10739 10740 static inline void perf_event_free_bpf_handler(struct perf_event *event) 10741 { 10742 } 10743 #endif 10744 10745 /* 10746 * Generic event overflow handling, sampling. 10747 */ 10748 10749 static int __perf_event_overflow(struct perf_event *event, 10750 int throttle, struct perf_sample_data *data, 10751 struct pt_regs *regs) 10752 { 10753 int events = atomic_read(&event->event_limit); 10754 int ret = 0; 10755 10756 /* 10757 * Non-sampling counters might still use the PMI to fold short 10758 * hardware counters, ignore those. 10759 */ 10760 if (unlikely(!is_sampling_event(event))) 10761 return 0; 10762 10763 ret = __perf_event_account_interrupt(event, throttle); 10764 10765 if (event->attr.aux_pause) 10766 perf_event_aux_pause(event->aux_event, true); 10767 10768 if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT && 10769 !bpf_overflow_handler(event, data, regs)) 10770 goto out; 10771 10772 /* 10773 * XXX event_limit might not quite work as expected on inherited 10774 * events 10775 */ 10776 10777 event->pending_kill = POLL_IN; 10778 if (events && atomic_dec_and_test(&event->event_limit)) { 10779 ret = 1; 10780 event->pending_kill = POLL_HUP; 10781 perf_event_disable_inatomic(event); 10782 event->pmu->stop(event, 0); 10783 } 10784 10785 if (event->attr.sigtrap) { 10786 /* 10787 * The desired behaviour of sigtrap vs invalid samples is a bit 10788 * tricky; on the one hand, one should not loose the SIGTRAP if 10789 * it is the first event, on the other hand, we should also not 10790 * trigger the WARN or override the data address. 10791 */ 10792 bool valid_sample = sample_is_allowed(event, regs); 10793 unsigned int pending_id = 1; 10794 enum task_work_notify_mode notify_mode; 10795 10796 if (regs) 10797 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1; 10798 10799 notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME; 10800 10801 if (!event->pending_work && 10802 !task_work_add(current, &event->pending_task, notify_mode)) { 10803 event->pending_work = pending_id; 10804 local_inc(&event->ctx->nr_no_switch_fast); 10805 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount)); 10806 10807 event->pending_addr = 0; 10808 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR)) 10809 event->pending_addr = data->addr; 10810 10811 } else if (event->attr.exclude_kernel && valid_sample) { 10812 /* 10813 * Should not be able to return to user space without 10814 * consuming pending_work; with exceptions: 10815 * 10816 * 1. Where !exclude_kernel, events can overflow again 10817 * in the kernel without returning to user space. 10818 * 10819 * 2. Events that can overflow again before the IRQ- 10820 * work without user space progress (e.g. hrtimer). 10821 * To approximate progress (with false negatives), 10822 * check 32-bit hash of the current IP. 10823 */ 10824 WARN_ON_ONCE(event->pending_work != pending_id); 10825 } 10826 } 10827 10828 READ_ONCE(event->overflow_handler)(event, data, regs); 10829 10830 if (*perf_event_fasync(event) && event->pending_kill) { 10831 event->pending_wakeup = 1; 10832 irq_work_queue(&event->pending_irq); 10833 } 10834 out: 10835 if (event->attr.aux_resume) 10836 perf_event_aux_pause(event->aux_event, false); 10837 10838 return ret; 10839 } 10840 10841 int perf_event_overflow(struct perf_event *event, 10842 struct perf_sample_data *data, 10843 struct pt_regs *regs) 10844 { 10845 /* 10846 * Entry point from hardware PMI, interrupts should be disabled here. 10847 * This serializes us against perf_event_remove_from_context() in 10848 * things like perf_event_release_kernel(). 10849 */ 10850 lockdep_assert_irqs_disabled(); 10851 10852 return __perf_event_overflow(event, 1, data, regs); 10853 } 10854 10855 /* 10856 * Generic software event infrastructure 10857 */ 10858 10859 struct swevent_htable { 10860 struct swevent_hlist *swevent_hlist; 10861 struct mutex hlist_mutex; 10862 int hlist_refcount; 10863 }; 10864 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable); 10865 10866 /* 10867 * We directly increment event->count and keep a second value in 10868 * event->hw.period_left to count intervals. This period event 10869 * is kept in the range [-sample_period, 0] so that we can use the 10870 * sign as trigger. 10871 */ 10872 10873 u64 perf_swevent_set_period(struct perf_event *event) 10874 { 10875 struct hw_perf_event *hwc = &event->hw; 10876 u64 period = hwc->last_period; 10877 u64 nr, offset; 10878 s64 old, val; 10879 10880 hwc->last_period = hwc->sample_period; 10881 10882 old = local64_read(&hwc->period_left); 10883 do { 10884 val = old; 10885 if (val < 0) 10886 return 0; 10887 10888 nr = div64_u64(period + val, period); 10889 offset = nr * period; 10890 val -= offset; 10891 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val)); 10892 10893 return nr; 10894 } 10895 10896 static void perf_swevent_overflow(struct perf_event *event, u64 overflow, 10897 struct perf_sample_data *data, 10898 struct pt_regs *regs) 10899 { 10900 struct hw_perf_event *hwc = &event->hw; 10901 int throttle = 0; 10902 10903 if (!overflow) 10904 overflow = perf_swevent_set_period(event); 10905 10906 if (hwc->interrupts == MAX_INTERRUPTS) 10907 return; 10908 10909 for (; overflow; overflow--) { 10910 if (__perf_event_overflow(event, throttle, 10911 data, regs)) { 10912 /* 10913 * We inhibit the overflow from happening when 10914 * hwc->interrupts == MAX_INTERRUPTS. 10915 */ 10916 break; 10917 } 10918 throttle = 1; 10919 } 10920 } 10921 10922 static void perf_swevent_event(struct perf_event *event, u64 nr, 10923 struct perf_sample_data *data, 10924 struct pt_regs *regs) 10925 { 10926 struct hw_perf_event *hwc = &event->hw; 10927 10928 /* 10929 * This is: 10930 * - software preempt 10931 * - tracepoint preempt 10932 * - tp_target_task irq (ctx->lock) 10933 * - uprobes preempt/irq 10934 * - kprobes preempt/irq 10935 * - hw_breakpoint irq 10936 * 10937 * Any of these are sufficient to hold off RCU and thus ensure @event 10938 * exists. 10939 */ 10940 lockdep_assert_preemption_disabled(); 10941 local64_add(nr, &event->count); 10942 10943 if (!regs) 10944 return; 10945 10946 if (!is_sampling_event(event)) 10947 return; 10948 10949 /* 10950 * Serialize against event_function_call() IPIs like normal overflow 10951 * event handling. Specifically, must not allow 10952 * perf_event_release_kernel() -> perf_remove_from_context() to make 10953 * progress and 'release' the event from under us. 10954 */ 10955 guard(irqsave)(); 10956 if (event->state != PERF_EVENT_STATE_ACTIVE) 10957 return; 10958 10959 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) { 10960 data->period = nr; 10961 return perf_swevent_overflow(event, 1, data, regs); 10962 } else 10963 data->period = event->hw.last_period; 10964 10965 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) 10966 return perf_swevent_overflow(event, 1, data, regs); 10967 10968 if (local64_add_negative(nr, &hwc->period_left)) 10969 return; 10970 10971 perf_swevent_overflow(event, 0, data, regs); 10972 } 10973 10974 int perf_exclude_event(struct perf_event *event, struct pt_regs *regs) 10975 { 10976 if (event->hw.state & PERF_HES_STOPPED) 10977 return 1; 10978 10979 if (regs) { 10980 if (event->attr.exclude_user && user_mode(regs)) 10981 return 1; 10982 10983 if (event->attr.exclude_kernel && !user_mode(regs)) 10984 return 1; 10985 } 10986 10987 return 0; 10988 } 10989 10990 static int perf_swevent_match(struct perf_event *event, 10991 enum perf_type_id type, 10992 u32 event_id, 10993 struct perf_sample_data *data, 10994 struct pt_regs *regs) 10995 { 10996 if (event->attr.type != type) 10997 return 0; 10998 10999 if (event->attr.config != event_id) 11000 return 0; 11001 11002 if (perf_exclude_event(event, regs)) 11003 return 0; 11004 11005 return 1; 11006 } 11007 11008 static inline u64 swevent_hash(u64 type, u32 event_id) 11009 { 11010 u64 val = event_id | (type << 32); 11011 11012 return hash_64(val, SWEVENT_HLIST_BITS); 11013 } 11014 11015 static inline struct hlist_head * 11016 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id) 11017 { 11018 u64 hash = swevent_hash(type, event_id); 11019 11020 return &hlist->heads[hash]; 11021 } 11022 11023 /* For the read side: events when they trigger */ 11024 static inline struct hlist_head * 11025 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id) 11026 { 11027 struct swevent_hlist *hlist; 11028 11029 hlist = rcu_dereference(swhash->swevent_hlist); 11030 if (!hlist) 11031 return NULL; 11032 11033 return __find_swevent_head(hlist, type, event_id); 11034 } 11035 11036 /* For the event head insertion and removal in the hlist */ 11037 static inline struct hlist_head * 11038 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) 11039 { 11040 struct swevent_hlist *hlist; 11041 u32 event_id = event->attr.config; 11042 u64 type = event->attr.type; 11043 11044 /* 11045 * Event scheduling is always serialized against hlist allocation 11046 * and release. Which makes the protected version suitable here. 11047 * The context lock guarantees that. 11048 */ 11049 hlist = rcu_dereference_protected(swhash->swevent_hlist, 11050 lockdep_is_held(&event->ctx->lock)); 11051 if (!hlist) 11052 return NULL; 11053 11054 return __find_swevent_head(hlist, type, event_id); 11055 } 11056 11057 static void do_perf_sw_event(enum perf_type_id type, u32 event_id, 11058 u64 nr, 11059 struct perf_sample_data *data, 11060 struct pt_regs *regs) 11061 { 11062 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 11063 struct perf_event *event; 11064 struct hlist_head *head; 11065 11066 rcu_read_lock(); 11067 head = find_swevent_head_rcu(swhash, type, event_id); 11068 if (!head) 11069 goto end; 11070 11071 hlist_for_each_entry_rcu(event, head, hlist_entry) { 11072 if (perf_swevent_match(event, type, event_id, data, regs)) 11073 perf_swevent_event(event, nr, data, regs); 11074 } 11075 end: 11076 rcu_read_unlock(); 11077 } 11078 11079 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]); 11080 11081 int perf_swevent_get_recursion_context(void) 11082 { 11083 return get_recursion_context(current->perf_recursion); 11084 } 11085 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context); 11086 11087 void perf_swevent_put_recursion_context(int rctx) 11088 { 11089 put_recursion_context(current->perf_recursion, rctx); 11090 } 11091 11092 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 11093 { 11094 struct perf_sample_data data; 11095 11096 if (WARN_ON_ONCE(!regs)) 11097 return; 11098 11099 perf_sample_data_init(&data, addr, 0); 11100 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs); 11101 } 11102 11103 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 11104 { 11105 int rctx; 11106 11107 preempt_disable_notrace(); 11108 rctx = perf_swevent_get_recursion_context(); 11109 if (unlikely(rctx < 0)) 11110 goto fail; 11111 11112 ___perf_sw_event(event_id, nr, regs, addr); 11113 11114 perf_swevent_put_recursion_context(rctx); 11115 fail: 11116 preempt_enable_notrace(); 11117 } 11118 11119 static void perf_swevent_read(struct perf_event *event) 11120 { 11121 } 11122 11123 static int perf_swevent_add(struct perf_event *event, int flags) 11124 { 11125 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 11126 struct hw_perf_event *hwc = &event->hw; 11127 struct hlist_head *head; 11128 11129 if (is_sampling_event(event)) { 11130 hwc->last_period = hwc->sample_period; 11131 perf_swevent_set_period(event); 11132 } 11133 11134 hwc->state = !(flags & PERF_EF_START); 11135 11136 head = find_swevent_head(swhash, event); 11137 if (WARN_ON_ONCE(!head)) 11138 return -EINVAL; 11139 11140 hlist_add_head_rcu(&event->hlist_entry, head); 11141 perf_event_update_userpage(event); 11142 11143 return 0; 11144 } 11145 11146 static void perf_swevent_del(struct perf_event *event, int flags) 11147 { 11148 hlist_del_rcu(&event->hlist_entry); 11149 } 11150 11151 static void perf_swevent_start(struct perf_event *event, int flags) 11152 { 11153 event->hw.state = 0; 11154 } 11155 11156 static void perf_swevent_stop(struct perf_event *event, int flags) 11157 { 11158 event->hw.state = PERF_HES_STOPPED; 11159 } 11160 11161 /* Deref the hlist from the update side */ 11162 static inline struct swevent_hlist * 11163 swevent_hlist_deref(struct swevent_htable *swhash) 11164 { 11165 return rcu_dereference_protected(swhash->swevent_hlist, 11166 lockdep_is_held(&swhash->hlist_mutex)); 11167 } 11168 11169 static void swevent_hlist_release(struct swevent_htable *swhash) 11170 { 11171 struct swevent_hlist *hlist = swevent_hlist_deref(swhash); 11172 11173 if (!hlist) 11174 return; 11175 11176 RCU_INIT_POINTER(swhash->swevent_hlist, NULL); 11177 kfree_rcu(hlist, rcu_head); 11178 } 11179 11180 static void swevent_hlist_put_cpu(int cpu) 11181 { 11182 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 11183 11184 mutex_lock(&swhash->hlist_mutex); 11185 11186 if (!--swhash->hlist_refcount) 11187 swevent_hlist_release(swhash); 11188 11189 mutex_unlock(&swhash->hlist_mutex); 11190 } 11191 11192 static void swevent_hlist_put(void) 11193 { 11194 int cpu; 11195 11196 for_each_possible_cpu(cpu) 11197 swevent_hlist_put_cpu(cpu); 11198 } 11199 11200 static int swevent_hlist_get_cpu(int cpu) 11201 { 11202 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 11203 int err = 0; 11204 11205 mutex_lock(&swhash->hlist_mutex); 11206 if (!swevent_hlist_deref(swhash) && 11207 cpumask_test_cpu(cpu, perf_online_mask)) { 11208 struct swevent_hlist *hlist; 11209 11210 hlist = kzalloc_obj(*hlist); 11211 if (!hlist) { 11212 err = -ENOMEM; 11213 goto exit; 11214 } 11215 rcu_assign_pointer(swhash->swevent_hlist, hlist); 11216 } 11217 swhash->hlist_refcount++; 11218 exit: 11219 mutex_unlock(&swhash->hlist_mutex); 11220 11221 return err; 11222 } 11223 11224 static int swevent_hlist_get(void) 11225 { 11226 int err, cpu, failed_cpu; 11227 11228 mutex_lock(&pmus_lock); 11229 for_each_possible_cpu(cpu) { 11230 err = swevent_hlist_get_cpu(cpu); 11231 if (err) { 11232 failed_cpu = cpu; 11233 goto fail; 11234 } 11235 } 11236 mutex_unlock(&pmus_lock); 11237 return 0; 11238 fail: 11239 for_each_possible_cpu(cpu) { 11240 if (cpu == failed_cpu) 11241 break; 11242 swevent_hlist_put_cpu(cpu); 11243 } 11244 mutex_unlock(&pmus_lock); 11245 return err; 11246 } 11247 11248 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX]; 11249 11250 static void sw_perf_event_destroy(struct perf_event *event) 11251 { 11252 u64 event_id = event->attr.config; 11253 11254 WARN_ON(event->parent); 11255 11256 static_key_slow_dec(&perf_swevent_enabled[event_id]); 11257 swevent_hlist_put(); 11258 } 11259 11260 static struct pmu perf_cpu_clock; /* fwd declaration */ 11261 static struct pmu perf_task_clock; 11262 11263 static int perf_swevent_init(struct perf_event *event) 11264 { 11265 u64 event_id = event->attr.config; 11266 11267 if (event->attr.type != PERF_TYPE_SOFTWARE) 11268 return -ENOENT; 11269 11270 /* 11271 * no branch sampling for software events 11272 */ 11273 if (has_branch_stack(event)) 11274 return -EOPNOTSUPP; 11275 11276 switch (event_id) { 11277 case PERF_COUNT_SW_CPU_CLOCK: 11278 event->attr.type = perf_cpu_clock.type; 11279 return -ENOENT; 11280 case PERF_COUNT_SW_TASK_CLOCK: 11281 event->attr.type = perf_task_clock.type; 11282 return -ENOENT; 11283 11284 default: 11285 break; 11286 } 11287 11288 if (event_id >= PERF_COUNT_SW_MAX) 11289 return -ENOENT; 11290 11291 if (!event->parent) { 11292 int err; 11293 11294 err = swevent_hlist_get(); 11295 if (err) 11296 return err; 11297 11298 static_key_slow_inc(&perf_swevent_enabled[event_id]); 11299 event->destroy = sw_perf_event_destroy; 11300 } 11301 11302 return 0; 11303 } 11304 11305 static struct pmu perf_swevent = { 11306 .task_ctx_nr = perf_sw_context, 11307 11308 .capabilities = PERF_PMU_CAP_NO_NMI, 11309 11310 .event_init = perf_swevent_init, 11311 .add = perf_swevent_add, 11312 .del = perf_swevent_del, 11313 .start = perf_swevent_start, 11314 .stop = perf_swevent_stop, 11315 .read = perf_swevent_read, 11316 }; 11317 11318 #ifdef CONFIG_EVENT_TRACING 11319 11320 static void tp_perf_event_destroy(struct perf_event *event) 11321 { 11322 perf_trace_destroy(event); 11323 } 11324 11325 static int perf_tp_event_init(struct perf_event *event) 11326 { 11327 int err; 11328 11329 if (event->attr.type != PERF_TYPE_TRACEPOINT) 11330 return -ENOENT; 11331 11332 /* 11333 * no branch sampling for tracepoint events 11334 */ 11335 if (has_branch_stack(event)) 11336 return -EOPNOTSUPP; 11337 11338 err = perf_trace_init(event); 11339 if (err) 11340 return err; 11341 11342 event->destroy = tp_perf_event_destroy; 11343 11344 return 0; 11345 } 11346 11347 static struct pmu perf_tracepoint = { 11348 .task_ctx_nr = perf_sw_context, 11349 11350 .event_init = perf_tp_event_init, 11351 .add = perf_trace_add, 11352 .del = perf_trace_del, 11353 .start = perf_swevent_start, 11354 .stop = perf_swevent_stop, 11355 .read = perf_swevent_read, 11356 }; 11357 11358 static int perf_tp_filter_match(struct perf_event *event, 11359 struct perf_raw_record *raw) 11360 { 11361 void *record = raw->frag.data; 11362 11363 /* only top level events have filters set */ 11364 if (event->parent) 11365 event = event->parent; 11366 11367 if (likely(!event->filter) || filter_match_preds(event->filter, record)) 11368 return 1; 11369 return 0; 11370 } 11371 11372 static int perf_tp_event_match(struct perf_event *event, 11373 struct perf_raw_record *raw, 11374 struct pt_regs *regs) 11375 { 11376 if (event->hw.state & PERF_HES_STOPPED) 11377 return 0; 11378 /* 11379 * If exclude_kernel, only trace user-space tracepoints (uprobes) 11380 */ 11381 if (event->attr.exclude_kernel && !user_mode(regs)) 11382 return 0; 11383 11384 if (!perf_tp_filter_match(event, raw)) 11385 return 0; 11386 11387 return 1; 11388 } 11389 11390 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx, 11391 struct trace_event_call *call, u64 count, 11392 struct pt_regs *regs, struct hlist_head *head, 11393 struct task_struct *task) 11394 { 11395 if (bpf_prog_array_valid(call)) { 11396 *(struct pt_regs **)raw_data = regs; 11397 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) { 11398 perf_swevent_put_recursion_context(rctx); 11399 return; 11400 } 11401 } 11402 perf_tp_event(call->event.type, count, raw_data, size, regs, head, 11403 rctx, task); 11404 } 11405 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit); 11406 11407 static void __perf_tp_event_target_task(u64 count, void *record, 11408 struct pt_regs *regs, 11409 struct perf_sample_data *data, 11410 struct perf_raw_record *raw, 11411 struct perf_event *event) 11412 { 11413 struct trace_entry *entry = record; 11414 11415 if (event->attr.config != entry->type) 11416 return; 11417 /* Cannot deliver synchronous signal to other task. */ 11418 if (event->attr.sigtrap) 11419 return; 11420 if (perf_tp_event_match(event, raw, regs)) { 11421 perf_sample_data_init(data, 0, 0); 11422 perf_sample_save_raw_data(data, event, raw); 11423 perf_swevent_event(event, count, data, regs); 11424 } 11425 } 11426 11427 static void perf_tp_event_target_task(u64 count, void *record, 11428 struct pt_regs *regs, 11429 struct perf_sample_data *data, 11430 struct perf_raw_record *raw, 11431 struct perf_event_context *ctx) 11432 { 11433 unsigned int cpu = smp_processor_id(); 11434 struct pmu *pmu = &perf_tracepoint; 11435 struct perf_event *event, *sibling; 11436 11437 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) { 11438 __perf_tp_event_target_task(count, record, regs, data, raw, event); 11439 for_each_sibling_event(sibling, event) 11440 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 11441 } 11442 11443 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) { 11444 __perf_tp_event_target_task(count, record, regs, data, raw, event); 11445 for_each_sibling_event(sibling, event) 11446 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 11447 } 11448 } 11449 11450 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size, 11451 struct pt_regs *regs, struct hlist_head *head, int rctx, 11452 struct task_struct *task) 11453 { 11454 struct perf_sample_data data; 11455 struct perf_event *event; 11456 11457 /* 11458 * Per being a tracepoint, this runs with preemption disabled. 11459 */ 11460 lockdep_assert_preemption_disabled(); 11461 11462 struct perf_raw_record raw = { 11463 .frag = { 11464 .size = entry_size, 11465 .data = record, 11466 }, 11467 }; 11468 11469 perf_trace_buf_update(record, event_type); 11470 11471 hlist_for_each_entry_rcu(event, head, hlist_entry) { 11472 if (perf_tp_event_match(event, &raw, regs)) { 11473 /* 11474 * Here use the same on-stack perf_sample_data, 11475 * some members in data are event-specific and 11476 * need to be re-computed for different sweveents. 11477 * Re-initialize data->sample_flags safely to avoid 11478 * the problem that next event skips preparing data 11479 * because data->sample_flags is set. 11480 */ 11481 perf_sample_data_init(&data, 0, 0); 11482 perf_sample_save_raw_data(&data, event, &raw); 11483 perf_swevent_event(event, count, &data, regs); 11484 } 11485 } 11486 11487 /* 11488 * If we got specified a target task, also iterate its context and 11489 * deliver this event there too. 11490 */ 11491 if (task && task != current) { 11492 struct perf_event_context *ctx; 11493 11494 rcu_read_lock(); 11495 ctx = rcu_dereference(task->perf_event_ctxp); 11496 if (!ctx) 11497 goto unlock; 11498 11499 raw_spin_lock(&ctx->lock); 11500 perf_tp_event_target_task(count, record, regs, &data, &raw, ctx); 11501 raw_spin_unlock(&ctx->lock); 11502 unlock: 11503 rcu_read_unlock(); 11504 } 11505 11506 perf_swevent_put_recursion_context(rctx); 11507 } 11508 EXPORT_SYMBOL_GPL(perf_tp_event); 11509 11510 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS) 11511 /* 11512 * Flags in config, used by dynamic PMU kprobe and uprobe 11513 * The flags should match following PMU_FORMAT_ATTR(). 11514 * 11515 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe 11516 * if not set, create kprobe/uprobe 11517 * 11518 * The following values specify a reference counter (or semaphore in the 11519 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically 11520 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset. 11521 * 11522 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset 11523 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left 11524 */ 11525 enum perf_probe_config { 11526 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */ 11527 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32, 11528 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS, 11529 }; 11530 11531 PMU_FORMAT_ATTR(retprobe, "config:0"); 11532 #endif 11533 11534 #ifdef CONFIG_KPROBE_EVENTS 11535 static struct attribute *kprobe_attrs[] = { 11536 &format_attr_retprobe.attr, 11537 NULL, 11538 }; 11539 11540 static struct attribute_group kprobe_format_group = { 11541 .name = "format", 11542 .attrs = kprobe_attrs, 11543 }; 11544 11545 static const struct attribute_group *kprobe_attr_groups[] = { 11546 &kprobe_format_group, 11547 NULL, 11548 }; 11549 11550 static int perf_kprobe_event_init(struct perf_event *event); 11551 static struct pmu perf_kprobe = { 11552 .task_ctx_nr = perf_sw_context, 11553 .event_init = perf_kprobe_event_init, 11554 .add = perf_trace_add, 11555 .del = perf_trace_del, 11556 .start = perf_swevent_start, 11557 .stop = perf_swevent_stop, 11558 .read = perf_swevent_read, 11559 .attr_groups = kprobe_attr_groups, 11560 }; 11561 11562 static int perf_kprobe_event_init(struct perf_event *event) 11563 { 11564 int err; 11565 bool is_retprobe; 11566 11567 if (event->attr.type != perf_kprobe.type) 11568 return -ENOENT; 11569 11570 if (!perfmon_capable()) 11571 return -EACCES; 11572 11573 /* 11574 * no branch sampling for probe events 11575 */ 11576 if (has_branch_stack(event)) 11577 return -EOPNOTSUPP; 11578 11579 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 11580 err = perf_kprobe_init(event, is_retprobe); 11581 if (err) 11582 return err; 11583 11584 event->destroy = perf_kprobe_destroy; 11585 11586 return 0; 11587 } 11588 #endif /* CONFIG_KPROBE_EVENTS */ 11589 11590 #ifdef CONFIG_UPROBE_EVENTS 11591 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63"); 11592 11593 static struct attribute *uprobe_attrs[] = { 11594 &format_attr_retprobe.attr, 11595 &format_attr_ref_ctr_offset.attr, 11596 NULL, 11597 }; 11598 11599 static struct attribute_group uprobe_format_group = { 11600 .name = "format", 11601 .attrs = uprobe_attrs, 11602 }; 11603 11604 static const struct attribute_group *uprobe_attr_groups[] = { 11605 &uprobe_format_group, 11606 NULL, 11607 }; 11608 11609 static int perf_uprobe_event_init(struct perf_event *event); 11610 static struct pmu perf_uprobe = { 11611 .task_ctx_nr = perf_sw_context, 11612 .event_init = perf_uprobe_event_init, 11613 .add = perf_trace_add, 11614 .del = perf_trace_del, 11615 .start = perf_swevent_start, 11616 .stop = perf_swevent_stop, 11617 .read = perf_swevent_read, 11618 .attr_groups = uprobe_attr_groups, 11619 }; 11620 11621 static int perf_uprobe_event_init(struct perf_event *event) 11622 { 11623 int err; 11624 unsigned long ref_ctr_offset; 11625 bool is_retprobe; 11626 11627 if (event->attr.type != perf_uprobe.type) 11628 return -ENOENT; 11629 11630 if (!capable(CAP_SYS_ADMIN)) 11631 return -EACCES; 11632 11633 /* 11634 * no branch sampling for probe events 11635 */ 11636 if (has_branch_stack(event)) 11637 return -EOPNOTSUPP; 11638 11639 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 11640 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT; 11641 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe); 11642 if (err) 11643 return err; 11644 11645 event->destroy = perf_uprobe_destroy; 11646 11647 return 0; 11648 } 11649 #endif /* CONFIG_UPROBE_EVENTS */ 11650 11651 static inline void perf_tp_register(void) 11652 { 11653 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT); 11654 #ifdef CONFIG_KPROBE_EVENTS 11655 perf_pmu_register(&perf_kprobe, "kprobe", -1); 11656 #endif 11657 #ifdef CONFIG_UPROBE_EVENTS 11658 perf_pmu_register(&perf_uprobe, "uprobe", -1); 11659 #endif 11660 } 11661 11662 static void perf_event_free_filter(struct perf_event *event) 11663 { 11664 ftrace_profile_free_filter(event); 11665 } 11666 11667 /* 11668 * returns true if the event is a tracepoint, or a kprobe/upprobe created 11669 * with perf_event_open() 11670 */ 11671 static inline bool perf_event_is_tracing(struct perf_event *event) 11672 { 11673 if (event->pmu == &perf_tracepoint) 11674 return true; 11675 #ifdef CONFIG_KPROBE_EVENTS 11676 if (event->pmu == &perf_kprobe) 11677 return true; 11678 #endif 11679 #ifdef CONFIG_UPROBE_EVENTS 11680 if (event->pmu == &perf_uprobe) 11681 return true; 11682 #endif 11683 return false; 11684 } 11685 11686 static int __perf_event_set_bpf_prog(struct perf_event *event, 11687 struct bpf_prog *prog, 11688 u64 bpf_cookie) 11689 { 11690 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp; 11691 11692 if (event->state <= PERF_EVENT_STATE_REVOKED) 11693 return -ENODEV; 11694 11695 if (!perf_event_is_tracing(event)) 11696 return perf_event_set_bpf_handler(event, prog, bpf_cookie); 11697 11698 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE; 11699 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE; 11700 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT; 11701 is_syscall_tp = is_syscall_trace_event(event->tp_event); 11702 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp) 11703 /* bpf programs can only be attached to u/kprobe or tracepoint */ 11704 return -EINVAL; 11705 11706 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) || 11707 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) || 11708 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) 11709 return -EINVAL; 11710 11711 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe) 11712 /* only uprobe programs are allowed to be sleepable */ 11713 return -EINVAL; 11714 11715 /* Kprobe override only works for kprobes, not uprobes. */ 11716 if (prog->kprobe_override && !is_kprobe) 11717 return -EINVAL; 11718 11719 /* Writing to context allowed only for uprobes. */ 11720 if (prog->aux->kprobe_write_ctx && !is_uprobe) 11721 return -EINVAL; 11722 11723 if (is_tracepoint || is_syscall_tp) { 11724 int off = trace_event_get_offsets(event->tp_event); 11725 11726 if (prog->aux->max_ctx_offset > off) 11727 return -EACCES; 11728 } 11729 11730 return perf_event_attach_bpf_prog(event, prog, bpf_cookie); 11731 } 11732 11733 int perf_event_set_bpf_prog(struct perf_event *event, 11734 struct bpf_prog *prog, 11735 u64 bpf_cookie) 11736 { 11737 struct perf_event_context *ctx; 11738 int ret; 11739 11740 ctx = perf_event_ctx_lock(event); 11741 ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie); 11742 perf_event_ctx_unlock(event, ctx); 11743 11744 return ret; 11745 } 11746 11747 void perf_event_free_bpf_prog(struct perf_event *event) 11748 { 11749 if (!event->prog) 11750 return; 11751 11752 if (!perf_event_is_tracing(event)) { 11753 perf_event_free_bpf_handler(event); 11754 return; 11755 } 11756 perf_event_detach_bpf_prog(event); 11757 } 11758 11759 #else 11760 11761 static inline void perf_tp_register(void) 11762 { 11763 } 11764 11765 static void perf_event_free_filter(struct perf_event *event) 11766 { 11767 } 11768 11769 static int __perf_event_set_bpf_prog(struct perf_event *event, 11770 struct bpf_prog *prog, 11771 u64 bpf_cookie) 11772 { 11773 return -ENOENT; 11774 } 11775 11776 int perf_event_set_bpf_prog(struct perf_event *event, 11777 struct bpf_prog *prog, 11778 u64 bpf_cookie) 11779 { 11780 return -ENOENT; 11781 } 11782 11783 void perf_event_free_bpf_prog(struct perf_event *event) 11784 { 11785 } 11786 #endif /* CONFIG_EVENT_TRACING */ 11787 11788 #ifdef CONFIG_HAVE_HW_BREAKPOINT 11789 void perf_bp_event(struct perf_event *bp, void *data) 11790 { 11791 struct perf_sample_data sample; 11792 struct pt_regs *regs = data; 11793 11794 /* 11795 * Exception context, will have interrupts disabled. 11796 */ 11797 lockdep_assert_irqs_disabled(); 11798 11799 perf_sample_data_init(&sample, bp->attr.bp_addr, 0); 11800 11801 if (!bp->hw.state && !perf_exclude_event(bp, regs)) 11802 perf_swevent_event(bp, 1, &sample, regs); 11803 } 11804 #endif 11805 11806 /* 11807 * Allocate a new address filter 11808 */ 11809 static struct perf_addr_filter * 11810 perf_addr_filter_new(struct perf_event *event, struct list_head *filters) 11811 { 11812 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu); 11813 struct perf_addr_filter *filter; 11814 11815 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node); 11816 if (!filter) 11817 return NULL; 11818 11819 INIT_LIST_HEAD(&filter->entry); 11820 list_add_tail(&filter->entry, filters); 11821 11822 return filter; 11823 } 11824 11825 static void free_filters_list(struct list_head *filters) 11826 { 11827 struct perf_addr_filter *filter, *iter; 11828 11829 list_for_each_entry_safe(filter, iter, filters, entry) { 11830 path_put(&filter->path); 11831 list_del(&filter->entry); 11832 kfree(filter); 11833 } 11834 } 11835 11836 /* 11837 * Free existing address filters and optionally install new ones 11838 */ 11839 static void perf_addr_filters_splice(struct perf_event *event, 11840 struct list_head *head) 11841 { 11842 unsigned long flags; 11843 LIST_HEAD(list); 11844 11845 if (!has_addr_filter(event)) 11846 return; 11847 11848 /* don't bother with children, they don't have their own filters */ 11849 if (event->parent) 11850 return; 11851 11852 raw_spin_lock_irqsave(&event->addr_filters.lock, flags); 11853 11854 list_splice_init(&event->addr_filters.list, &list); 11855 if (head) 11856 list_splice(head, &event->addr_filters.list); 11857 11858 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags); 11859 11860 free_filters_list(&list); 11861 } 11862 11863 static void perf_free_addr_filters(struct perf_event *event) 11864 { 11865 /* 11866 * Used during free paths, there is no concurrency. 11867 */ 11868 if (list_empty(&event->addr_filters.list)) 11869 return; 11870 11871 perf_addr_filters_splice(event, NULL); 11872 } 11873 11874 /* 11875 * Scan through mm's vmas and see if one of them matches the 11876 * @filter; if so, adjust filter's address range. 11877 * Called with mm::mmap_lock down for reading. 11878 */ 11879 static void perf_addr_filter_apply(struct perf_addr_filter *filter, 11880 struct mm_struct *mm, 11881 struct perf_addr_filter_range *fr) 11882 { 11883 struct vm_area_struct *vma; 11884 VMA_ITERATOR(vmi, mm, 0); 11885 11886 for_each_vma(vmi, vma) { 11887 if (!vma->vm_file) 11888 continue; 11889 11890 if (perf_addr_filter_vma_adjust(filter, vma, fr)) 11891 return; 11892 } 11893 } 11894 11895 /* 11896 * Update event's address range filters based on the 11897 * task's existing mappings, if any. 11898 */ 11899 static void perf_event_addr_filters_apply(struct perf_event *event) 11900 { 11901 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 11902 struct task_struct *task = READ_ONCE(event->ctx->task); 11903 struct perf_addr_filter *filter; 11904 struct mm_struct *mm = NULL; 11905 unsigned int count = 0; 11906 unsigned long flags; 11907 11908 /* 11909 * We may observe TASK_TOMBSTONE, which means that the event tear-down 11910 * will stop on the parent's child_mutex that our caller is also holding 11911 */ 11912 if (task == TASK_TOMBSTONE) 11913 return; 11914 11915 if (ifh->nr_file_filters) { 11916 mm = get_task_mm(task); 11917 if (!mm) 11918 goto restart; 11919 11920 mmap_read_lock(mm); 11921 } 11922 11923 raw_spin_lock_irqsave(&ifh->lock, flags); 11924 list_for_each_entry(filter, &ifh->list, entry) { 11925 if (filter->path.dentry) { 11926 /* 11927 * Adjust base offset if the filter is associated to a 11928 * binary that needs to be mapped: 11929 */ 11930 event->addr_filter_ranges[count].start = 0; 11931 event->addr_filter_ranges[count].size = 0; 11932 11933 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]); 11934 } else { 11935 event->addr_filter_ranges[count].start = filter->offset; 11936 event->addr_filter_ranges[count].size = filter->size; 11937 } 11938 11939 count++; 11940 } 11941 11942 event->addr_filters_gen++; 11943 raw_spin_unlock_irqrestore(&ifh->lock, flags); 11944 11945 if (ifh->nr_file_filters) { 11946 mmap_read_unlock(mm); 11947 11948 mmput(mm); 11949 } 11950 11951 restart: 11952 perf_event_stop(event, 1); 11953 } 11954 11955 /* 11956 * Address range filtering: limiting the data to certain 11957 * instruction address ranges. Filters are ioctl()ed to us from 11958 * userspace as ascii strings. 11959 * 11960 * Filter string format: 11961 * 11962 * ACTION RANGE_SPEC 11963 * where ACTION is one of the 11964 * * "filter": limit the trace to this region 11965 * * "start": start tracing from this address 11966 * * "stop": stop tracing at this address/region; 11967 * RANGE_SPEC is 11968 * * for kernel addresses: <start address>[/<size>] 11969 * * for object files: <start address>[/<size>]@</path/to/object/file> 11970 * 11971 * if <size> is not specified or is zero, the range is treated as a single 11972 * address; not valid for ACTION=="filter". 11973 */ 11974 enum { 11975 IF_ACT_NONE = -1, 11976 IF_ACT_FILTER, 11977 IF_ACT_START, 11978 IF_ACT_STOP, 11979 IF_SRC_FILE, 11980 IF_SRC_KERNEL, 11981 IF_SRC_FILEADDR, 11982 IF_SRC_KERNELADDR, 11983 }; 11984 11985 enum { 11986 IF_STATE_ACTION = 0, 11987 IF_STATE_SOURCE, 11988 IF_STATE_END, 11989 }; 11990 11991 static const match_table_t if_tokens = { 11992 { IF_ACT_FILTER, "filter" }, 11993 { IF_ACT_START, "start" }, 11994 { IF_ACT_STOP, "stop" }, 11995 { IF_SRC_FILE, "%u/%u@%s" }, 11996 { IF_SRC_KERNEL, "%u/%u" }, 11997 { IF_SRC_FILEADDR, "%u@%s" }, 11998 { IF_SRC_KERNELADDR, "%u" }, 11999 { IF_ACT_NONE, NULL }, 12000 }; 12001 12002 /* 12003 * Address filter string parser 12004 */ 12005 static int 12006 perf_event_parse_addr_filter(struct perf_event *event, char *fstr, 12007 struct list_head *filters) 12008 { 12009 struct perf_addr_filter *filter = NULL; 12010 char *start, *orig, *filename = NULL; 12011 substring_t args[MAX_OPT_ARGS]; 12012 int state = IF_STATE_ACTION, token; 12013 unsigned int kernel = 0; 12014 int ret = -EINVAL; 12015 12016 orig = fstr = kstrdup(fstr, GFP_KERNEL); 12017 if (!fstr) 12018 return -ENOMEM; 12019 12020 while ((start = strsep(&fstr, " ,\n")) != NULL) { 12021 static const enum perf_addr_filter_action_t actions[] = { 12022 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER, 12023 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START, 12024 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP, 12025 }; 12026 ret = -EINVAL; 12027 12028 if (!*start) 12029 continue; 12030 12031 /* filter definition begins */ 12032 if (state == IF_STATE_ACTION) { 12033 filter = perf_addr_filter_new(event, filters); 12034 if (!filter) 12035 goto fail; 12036 } 12037 12038 token = match_token(start, if_tokens, args); 12039 switch (token) { 12040 case IF_ACT_FILTER: 12041 case IF_ACT_START: 12042 case IF_ACT_STOP: 12043 if (state != IF_STATE_ACTION) 12044 goto fail; 12045 12046 filter->action = actions[token]; 12047 state = IF_STATE_SOURCE; 12048 break; 12049 12050 case IF_SRC_KERNELADDR: 12051 case IF_SRC_KERNEL: 12052 kernel = 1; 12053 fallthrough; 12054 12055 case IF_SRC_FILEADDR: 12056 case IF_SRC_FILE: 12057 if (state != IF_STATE_SOURCE) 12058 goto fail; 12059 12060 *args[0].to = 0; 12061 ret = kstrtoul(args[0].from, 0, &filter->offset); 12062 if (ret) 12063 goto fail; 12064 12065 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) { 12066 *args[1].to = 0; 12067 ret = kstrtoul(args[1].from, 0, &filter->size); 12068 if (ret) 12069 goto fail; 12070 } 12071 12072 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) { 12073 int fpos = token == IF_SRC_FILE ? 2 : 1; 12074 12075 kfree(filename); 12076 filename = match_strdup(&args[fpos]); 12077 if (!filename) { 12078 ret = -ENOMEM; 12079 goto fail; 12080 } 12081 } 12082 12083 state = IF_STATE_END; 12084 break; 12085 12086 default: 12087 goto fail; 12088 } 12089 12090 /* 12091 * Filter definition is fully parsed, validate and install it. 12092 * Make sure that it doesn't contradict itself or the event's 12093 * attribute. 12094 */ 12095 if (state == IF_STATE_END) { 12096 ret = -EINVAL; 12097 12098 /* 12099 * ACTION "filter" must have a non-zero length region 12100 * specified. 12101 */ 12102 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER && 12103 !filter->size) 12104 goto fail; 12105 12106 if (!kernel) { 12107 if (!filename) 12108 goto fail; 12109 12110 /* 12111 * For now, we only support file-based filters 12112 * in per-task events; doing so for CPU-wide 12113 * events requires additional context switching 12114 * trickery, since same object code will be 12115 * mapped at different virtual addresses in 12116 * different processes. 12117 */ 12118 ret = -EOPNOTSUPP; 12119 if (!event->ctx->task) 12120 goto fail; 12121 12122 /* look up the path and grab its inode */ 12123 ret = kern_path(filename, LOOKUP_FOLLOW, 12124 &filter->path); 12125 if (ret) 12126 goto fail; 12127 12128 ret = -EINVAL; 12129 if (!filter->path.dentry || 12130 !S_ISREG(d_inode(filter->path.dentry) 12131 ->i_mode)) 12132 goto fail; 12133 12134 event->addr_filters.nr_file_filters++; 12135 } 12136 12137 /* ready to consume more filters */ 12138 kfree(filename); 12139 filename = NULL; 12140 state = IF_STATE_ACTION; 12141 filter = NULL; 12142 kernel = 0; 12143 } 12144 } 12145 12146 if (state != IF_STATE_ACTION) 12147 goto fail; 12148 12149 kfree(filename); 12150 kfree(orig); 12151 12152 return 0; 12153 12154 fail: 12155 kfree(filename); 12156 free_filters_list(filters); 12157 kfree(orig); 12158 12159 return ret; 12160 } 12161 12162 static int 12163 perf_event_set_addr_filter(struct perf_event *event, char *filter_str) 12164 { 12165 LIST_HEAD(filters); 12166 int ret; 12167 12168 /* 12169 * Since this is called in perf_ioctl() path, we're already holding 12170 * ctx::mutex. 12171 */ 12172 lockdep_assert_held(&event->ctx->mutex); 12173 12174 if (WARN_ON_ONCE(event->parent)) 12175 return -EINVAL; 12176 12177 ret = perf_event_parse_addr_filter(event, filter_str, &filters); 12178 if (ret) 12179 goto fail_clear_files; 12180 12181 ret = event->pmu->addr_filters_validate(&filters); 12182 if (ret) 12183 goto fail_free_filters; 12184 12185 /* remove existing filters, if any */ 12186 perf_addr_filters_splice(event, &filters); 12187 12188 /* install new filters */ 12189 perf_event_for_each_child(event, perf_event_addr_filters_apply); 12190 12191 return ret; 12192 12193 fail_free_filters: 12194 free_filters_list(&filters); 12195 12196 fail_clear_files: 12197 event->addr_filters.nr_file_filters = 0; 12198 12199 return ret; 12200 } 12201 12202 static int perf_event_set_filter(struct perf_event *event, void __user *arg) 12203 { 12204 int ret = -EINVAL; 12205 char *filter_str; 12206 12207 filter_str = strndup_user(arg, PAGE_SIZE); 12208 if (IS_ERR(filter_str)) 12209 return PTR_ERR(filter_str); 12210 12211 #ifdef CONFIG_EVENT_TRACING 12212 if (perf_event_is_tracing(event)) { 12213 struct perf_event_context *ctx = event->ctx; 12214 12215 /* 12216 * Beware, here be dragons!! 12217 * 12218 * the tracepoint muck will deadlock against ctx->mutex, but 12219 * the tracepoint stuff does not actually need it. So 12220 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we 12221 * already have a reference on ctx. 12222 * 12223 * This can result in event getting moved to a different ctx, 12224 * but that does not affect the tracepoint state. 12225 */ 12226 mutex_unlock(&ctx->mutex); 12227 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str); 12228 mutex_lock(&ctx->mutex); 12229 } else 12230 #endif 12231 if (has_addr_filter(event)) 12232 ret = perf_event_set_addr_filter(event, filter_str); 12233 12234 kfree(filter_str); 12235 return ret; 12236 } 12237 12238 /* 12239 * hrtimer based swevent callback 12240 */ 12241 12242 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer) 12243 { 12244 enum hrtimer_restart ret = HRTIMER_RESTART; 12245 struct perf_sample_data data; 12246 struct pt_regs *regs; 12247 struct perf_event *event; 12248 u64 period; 12249 12250 event = container_of(hrtimer, struct perf_event, hw.hrtimer); 12251 12252 if (event->state != PERF_EVENT_STATE_ACTIVE || 12253 event->hw.state & PERF_HES_STOPPED) 12254 return HRTIMER_NORESTART; 12255 12256 event->pmu->read(event); 12257 12258 perf_sample_data_init(&data, 0, event->hw.last_period); 12259 regs = get_irq_regs(); 12260 12261 if (regs && !perf_exclude_event(event, regs)) { 12262 if (!(event->attr.exclude_idle && is_idle_task(current))) 12263 if (perf_event_overflow(event, &data, regs)) 12264 ret = HRTIMER_NORESTART; 12265 } 12266 12267 period = max_t(u64, 10000, event->hw.sample_period); 12268 hrtimer_forward_now(hrtimer, ns_to_ktime(period)); 12269 12270 return ret; 12271 } 12272 12273 static void perf_swevent_start_hrtimer(struct perf_event *event) 12274 { 12275 struct hw_perf_event *hwc = &event->hw; 12276 s64 period; 12277 12278 if (!is_sampling_event(event)) 12279 return; 12280 12281 period = local64_read(&hwc->period_left); 12282 if (period) { 12283 if (period < 0) 12284 period = 10000; 12285 12286 local64_set(&hwc->period_left, 0); 12287 } else { 12288 period = max_t(u64, 10000, hwc->sample_period); 12289 } 12290 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period), 12291 HRTIMER_MODE_REL_PINNED_HARD); 12292 } 12293 12294 static void perf_swevent_cancel_hrtimer(struct perf_event *event) 12295 { 12296 struct hw_perf_event *hwc = &event->hw; 12297 12298 /* 12299 * Careful: this function can be triggered in the hrtimer handler, 12300 * for cpu-clock events, so hrtimer_cancel() would cause a 12301 * deadlock. 12302 * 12303 * So use hrtimer_try_to_cancel() to try to stop the hrtimer, 12304 * and the cpu-clock handler also sets the PERF_HES_STOPPED flag, 12305 * which guarantees that perf_swevent_hrtimer() will stop the 12306 * hrtimer once it sees the PERF_HES_STOPPED flag. 12307 */ 12308 if (is_sampling_event(event) && (hwc->interrupts != MAX_INTERRUPTS)) { 12309 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer); 12310 local64_set(&hwc->period_left, ktime_to_ns(remaining)); 12311 12312 hrtimer_try_to_cancel(&hwc->hrtimer); 12313 } 12314 } 12315 12316 static void perf_swevent_destroy_hrtimer(struct perf_event *event) 12317 { 12318 hrtimer_cancel(&event->hw.hrtimer); 12319 } 12320 12321 static void perf_swevent_init_hrtimer(struct perf_event *event) 12322 { 12323 struct hw_perf_event *hwc = &event->hw; 12324 12325 if (!is_sampling_event(event)) 12326 return; 12327 12328 hrtimer_setup(&hwc->hrtimer, perf_swevent_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD); 12329 event->destroy = perf_swevent_destroy_hrtimer; 12330 12331 /* 12332 * Since hrtimers have a fixed rate, we can do a static freq->period 12333 * mapping and avoid the whole period adjust feedback stuff. 12334 */ 12335 if (event->attr.freq) { 12336 long freq = event->attr.sample_freq; 12337 12338 event->attr.sample_period = NSEC_PER_SEC / freq; 12339 hwc->sample_period = event->attr.sample_period; 12340 local64_set(&hwc->period_left, hwc->sample_period); 12341 hwc->last_period = hwc->sample_period; 12342 event->attr.freq = 0; 12343 } 12344 } 12345 12346 /* 12347 * Software event: cpu wall time clock 12348 */ 12349 12350 static void cpu_clock_event_update(struct perf_event *event) 12351 { 12352 s64 prev; 12353 u64 now; 12354 12355 now = local_clock(); 12356 prev = local64_xchg(&event->hw.prev_count, now); 12357 local64_add(now - prev, &event->count); 12358 } 12359 12360 static void cpu_clock_event_start(struct perf_event *event, int flags) 12361 { 12362 event->hw.state = 0; 12363 local64_set(&event->hw.prev_count, local_clock()); 12364 perf_swevent_start_hrtimer(event); 12365 } 12366 12367 static void cpu_clock_event_stop(struct perf_event *event, int flags) 12368 { 12369 event->hw.state = PERF_HES_STOPPED; 12370 perf_swevent_cancel_hrtimer(event); 12371 if (flags & PERF_EF_UPDATE) 12372 cpu_clock_event_update(event); 12373 } 12374 12375 static int cpu_clock_event_add(struct perf_event *event, int flags) 12376 { 12377 if (flags & PERF_EF_START) 12378 cpu_clock_event_start(event, flags); 12379 perf_event_update_userpage(event); 12380 12381 return 0; 12382 } 12383 12384 static void cpu_clock_event_del(struct perf_event *event, int flags) 12385 { 12386 cpu_clock_event_stop(event, PERF_EF_UPDATE); 12387 } 12388 12389 static void cpu_clock_event_read(struct perf_event *event) 12390 { 12391 cpu_clock_event_update(event); 12392 } 12393 12394 static int cpu_clock_event_init(struct perf_event *event) 12395 { 12396 if (event->attr.type != perf_cpu_clock.type) 12397 return -ENOENT; 12398 12399 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK) 12400 return -ENOENT; 12401 12402 /* 12403 * no branch sampling for software events 12404 */ 12405 if (has_branch_stack(event)) 12406 return -EOPNOTSUPP; 12407 12408 perf_swevent_init_hrtimer(event); 12409 12410 return 0; 12411 } 12412 12413 static struct pmu perf_cpu_clock = { 12414 .task_ctx_nr = perf_sw_context, 12415 12416 .capabilities = PERF_PMU_CAP_NO_NMI, 12417 .dev = PMU_NULL_DEV, 12418 12419 .event_init = cpu_clock_event_init, 12420 .add = cpu_clock_event_add, 12421 .del = cpu_clock_event_del, 12422 .start = cpu_clock_event_start, 12423 .stop = cpu_clock_event_stop, 12424 .read = cpu_clock_event_read, 12425 }; 12426 12427 /* 12428 * Software event: task time clock 12429 */ 12430 12431 static void task_clock_event_update(struct perf_event *event, u64 now) 12432 { 12433 u64 prev; 12434 s64 delta; 12435 12436 prev = local64_xchg(&event->hw.prev_count, now); 12437 delta = now - prev; 12438 local64_add(delta, &event->count); 12439 } 12440 12441 static void task_clock_event_start(struct perf_event *event, int flags) 12442 { 12443 event->hw.state = 0; 12444 local64_set(&event->hw.prev_count, event->ctx->time.time); 12445 perf_swevent_start_hrtimer(event); 12446 } 12447 12448 static void task_clock_event_stop(struct perf_event *event, int flags) 12449 { 12450 event->hw.state = PERF_HES_STOPPED; 12451 perf_swevent_cancel_hrtimer(event); 12452 if (flags & PERF_EF_UPDATE) 12453 task_clock_event_update(event, event->ctx->time.time); 12454 } 12455 12456 static int task_clock_event_add(struct perf_event *event, int flags) 12457 { 12458 if (flags & PERF_EF_START) 12459 task_clock_event_start(event, flags); 12460 perf_event_update_userpage(event); 12461 12462 return 0; 12463 } 12464 12465 static void task_clock_event_del(struct perf_event *event, int flags) 12466 { 12467 task_clock_event_stop(event, PERF_EF_UPDATE); 12468 } 12469 12470 static void task_clock_event_read(struct perf_event *event) 12471 { 12472 u64 now = perf_clock(); 12473 u64 delta = now - event->ctx->time.stamp; 12474 u64 time = event->ctx->time.time + delta; 12475 12476 task_clock_event_update(event, time); 12477 } 12478 12479 static int task_clock_event_init(struct perf_event *event) 12480 { 12481 if (event->attr.type != perf_task_clock.type) 12482 return -ENOENT; 12483 12484 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK) 12485 return -ENOENT; 12486 12487 /* 12488 * no branch sampling for software events 12489 */ 12490 if (has_branch_stack(event)) 12491 return -EOPNOTSUPP; 12492 12493 perf_swevent_init_hrtimer(event); 12494 12495 return 0; 12496 } 12497 12498 static struct pmu perf_task_clock = { 12499 .task_ctx_nr = perf_sw_context, 12500 12501 .capabilities = PERF_PMU_CAP_NO_NMI, 12502 .dev = PMU_NULL_DEV, 12503 12504 .event_init = task_clock_event_init, 12505 .add = task_clock_event_add, 12506 .del = task_clock_event_del, 12507 .start = task_clock_event_start, 12508 .stop = task_clock_event_stop, 12509 .read = task_clock_event_read, 12510 }; 12511 12512 static void perf_pmu_nop_void(struct pmu *pmu) 12513 { 12514 } 12515 12516 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags) 12517 { 12518 } 12519 12520 static int perf_pmu_nop_int(struct pmu *pmu) 12521 { 12522 return 0; 12523 } 12524 12525 static int perf_event_nop_int(struct perf_event *event, u64 value) 12526 { 12527 return 0; 12528 } 12529 12530 static DEFINE_PER_CPU(unsigned int, nop_txn_flags); 12531 12532 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags) 12533 { 12534 __this_cpu_write(nop_txn_flags, flags); 12535 12536 if (flags & ~PERF_PMU_TXN_ADD) 12537 return; 12538 12539 perf_pmu_disable(pmu); 12540 } 12541 12542 static int perf_pmu_commit_txn(struct pmu *pmu) 12543 { 12544 unsigned int flags = __this_cpu_read(nop_txn_flags); 12545 12546 __this_cpu_write(nop_txn_flags, 0); 12547 12548 if (flags & ~PERF_PMU_TXN_ADD) 12549 return 0; 12550 12551 perf_pmu_enable(pmu); 12552 return 0; 12553 } 12554 12555 static void perf_pmu_cancel_txn(struct pmu *pmu) 12556 { 12557 unsigned int flags = __this_cpu_read(nop_txn_flags); 12558 12559 __this_cpu_write(nop_txn_flags, 0); 12560 12561 if (flags & ~PERF_PMU_TXN_ADD) 12562 return; 12563 12564 perf_pmu_enable(pmu); 12565 } 12566 12567 static int perf_event_idx_default(struct perf_event *event) 12568 { 12569 return 0; 12570 } 12571 12572 /* 12573 * Let userspace know that this PMU supports address range filtering: 12574 */ 12575 static ssize_t nr_addr_filters_show(struct device *dev, 12576 struct device_attribute *attr, 12577 char *page) 12578 { 12579 struct pmu *pmu = dev_get_drvdata(dev); 12580 12581 return sysfs_emit(page, "%d\n", pmu->nr_addr_filters); 12582 } 12583 DEVICE_ATTR_RO(nr_addr_filters); 12584 12585 static struct idr pmu_idr; 12586 12587 static ssize_t 12588 type_show(struct device *dev, struct device_attribute *attr, char *page) 12589 { 12590 struct pmu *pmu = dev_get_drvdata(dev); 12591 12592 return sysfs_emit(page, "%d\n", pmu->type); 12593 } 12594 static DEVICE_ATTR_RO(type); 12595 12596 static ssize_t 12597 perf_event_mux_interval_ms_show(struct device *dev, 12598 struct device_attribute *attr, 12599 char *page) 12600 { 12601 struct pmu *pmu = dev_get_drvdata(dev); 12602 12603 return sysfs_emit(page, "%d\n", pmu->hrtimer_interval_ms); 12604 } 12605 12606 static DEFINE_MUTEX(mux_interval_mutex); 12607 12608 static ssize_t 12609 perf_event_mux_interval_ms_store(struct device *dev, 12610 struct device_attribute *attr, 12611 const char *buf, size_t count) 12612 { 12613 struct pmu *pmu = dev_get_drvdata(dev); 12614 int timer, cpu, ret; 12615 12616 ret = kstrtoint(buf, 0, &timer); 12617 if (ret) 12618 return ret; 12619 12620 if (timer < 1) 12621 return -EINVAL; 12622 12623 /* same value, noting to do */ 12624 if (timer == pmu->hrtimer_interval_ms) 12625 return count; 12626 12627 mutex_lock(&mux_interval_mutex); 12628 pmu->hrtimer_interval_ms = timer; 12629 12630 /* update all cpuctx for this PMU */ 12631 cpus_read_lock(); 12632 for_each_online_cpu(cpu) { 12633 struct perf_cpu_pmu_context *cpc; 12634 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); 12635 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); 12636 12637 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc); 12638 } 12639 cpus_read_unlock(); 12640 mutex_unlock(&mux_interval_mutex); 12641 12642 return count; 12643 } 12644 static DEVICE_ATTR_RW(perf_event_mux_interval_ms); 12645 12646 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu) 12647 { 12648 switch (scope) { 12649 case PERF_PMU_SCOPE_CORE: 12650 return topology_sibling_cpumask(cpu); 12651 case PERF_PMU_SCOPE_DIE: 12652 return topology_die_cpumask(cpu); 12653 case PERF_PMU_SCOPE_CLUSTER: 12654 return topology_cluster_cpumask(cpu); 12655 case PERF_PMU_SCOPE_PKG: 12656 return topology_core_cpumask(cpu); 12657 case PERF_PMU_SCOPE_SYS_WIDE: 12658 return cpu_online_mask; 12659 } 12660 12661 return NULL; 12662 } 12663 12664 static inline struct cpumask *perf_scope_cpumask(unsigned int scope) 12665 { 12666 switch (scope) { 12667 case PERF_PMU_SCOPE_CORE: 12668 return perf_online_core_mask; 12669 case PERF_PMU_SCOPE_DIE: 12670 return perf_online_die_mask; 12671 case PERF_PMU_SCOPE_CLUSTER: 12672 return perf_online_cluster_mask; 12673 case PERF_PMU_SCOPE_PKG: 12674 return perf_online_pkg_mask; 12675 case PERF_PMU_SCOPE_SYS_WIDE: 12676 return perf_online_sys_mask; 12677 } 12678 12679 return NULL; 12680 } 12681 12682 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr, 12683 char *buf) 12684 { 12685 struct pmu *pmu = dev_get_drvdata(dev); 12686 struct cpumask *mask = perf_scope_cpumask(pmu->scope); 12687 12688 if (mask) 12689 return cpumap_print_to_pagebuf(true, buf, mask); 12690 return 0; 12691 } 12692 12693 static DEVICE_ATTR_RO(cpumask); 12694 12695 static struct attribute *pmu_dev_attrs[] = { 12696 &dev_attr_type.attr, 12697 &dev_attr_perf_event_mux_interval_ms.attr, 12698 &dev_attr_nr_addr_filters.attr, 12699 &dev_attr_cpumask.attr, 12700 NULL, 12701 }; 12702 12703 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n) 12704 { 12705 struct device *dev = kobj_to_dev(kobj); 12706 struct pmu *pmu = dev_get_drvdata(dev); 12707 12708 if (n == 2 && !pmu->nr_addr_filters) 12709 return 0; 12710 12711 /* cpumask */ 12712 if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE) 12713 return 0; 12714 12715 return a->mode; 12716 } 12717 12718 static struct attribute_group pmu_dev_attr_group = { 12719 .is_visible = pmu_dev_is_visible, 12720 .attrs = pmu_dev_attrs, 12721 }; 12722 12723 static const struct attribute_group *pmu_dev_groups[] = { 12724 &pmu_dev_attr_group, 12725 NULL, 12726 }; 12727 12728 static int pmu_bus_running; 12729 static const struct bus_type pmu_bus = { 12730 .name = "event_source", 12731 .dev_groups = pmu_dev_groups, 12732 }; 12733 12734 static void pmu_dev_release(struct device *dev) 12735 { 12736 kfree(dev); 12737 } 12738 12739 static int pmu_dev_alloc(struct pmu *pmu) 12740 { 12741 int ret = -ENOMEM; 12742 12743 pmu->dev = kzalloc_obj(struct device); 12744 if (!pmu->dev) 12745 goto out; 12746 12747 pmu->dev->groups = pmu->attr_groups; 12748 device_initialize(pmu->dev); 12749 12750 dev_set_drvdata(pmu->dev, pmu); 12751 pmu->dev->bus = &pmu_bus; 12752 pmu->dev->parent = pmu->parent; 12753 pmu->dev->release = pmu_dev_release; 12754 12755 ret = dev_set_name(pmu->dev, "%s", pmu->name); 12756 if (ret) 12757 goto free_dev; 12758 12759 ret = device_add(pmu->dev); 12760 if (ret) 12761 goto free_dev; 12762 12763 if (pmu->attr_update) { 12764 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update); 12765 if (ret) 12766 goto del_dev; 12767 } 12768 12769 out: 12770 return ret; 12771 12772 del_dev: 12773 device_del(pmu->dev); 12774 12775 free_dev: 12776 put_device(pmu->dev); 12777 pmu->dev = NULL; 12778 goto out; 12779 } 12780 12781 static struct lock_class_key cpuctx_mutex; 12782 static struct lock_class_key cpuctx_lock; 12783 12784 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new) 12785 { 12786 void *tmp, *val = idr_find(idr, id); 12787 12788 if (val != old) 12789 return false; 12790 12791 tmp = idr_replace(idr, new, id); 12792 if (IS_ERR(tmp)) 12793 return false; 12794 12795 WARN_ON_ONCE(tmp != val); 12796 return true; 12797 } 12798 12799 static void perf_pmu_free(struct pmu *pmu) 12800 { 12801 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) { 12802 if (pmu->nr_addr_filters) 12803 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters); 12804 device_del(pmu->dev); 12805 put_device(pmu->dev); 12806 } 12807 12808 if (pmu->cpu_pmu_context) { 12809 int cpu; 12810 12811 for_each_possible_cpu(cpu) { 12812 struct perf_cpu_pmu_context *cpc; 12813 12814 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); 12815 if (!cpc) 12816 continue; 12817 if (cpc->epc.embedded) { 12818 /* refcount managed */ 12819 put_pmu_ctx(&cpc->epc); 12820 continue; 12821 } 12822 kfree(cpc); 12823 } 12824 free_percpu(pmu->cpu_pmu_context); 12825 } 12826 } 12827 12828 DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T)) 12829 12830 int perf_pmu_register(struct pmu *_pmu, const char *name, int type) 12831 { 12832 int cpu, max = PERF_TYPE_MAX; 12833 12834 struct pmu *pmu __free(pmu_unregister) = _pmu; 12835 guard(mutex)(&pmus_lock); 12836 12837 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n")) 12838 return -EINVAL; 12839 12840 if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE, 12841 "Can not register a pmu with an invalid scope.\n")) 12842 return -EINVAL; 12843 12844 pmu->name = name; 12845 12846 if (type >= 0) 12847 max = type; 12848 12849 CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL); 12850 if (pmu_type.id < 0) 12851 return pmu_type.id; 12852 12853 WARN_ON(type >= 0 && pmu_type.id != type); 12854 12855 pmu->type = pmu_type.id; 12856 atomic_set(&pmu->exclusive_cnt, 0); 12857 12858 if (pmu_bus_running && !pmu->dev) { 12859 int ret = pmu_dev_alloc(pmu); 12860 if (ret) 12861 return ret; 12862 } 12863 12864 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *); 12865 if (!pmu->cpu_pmu_context) 12866 return -ENOMEM; 12867 12868 for_each_possible_cpu(cpu) { 12869 struct perf_cpu_pmu_context *cpc = 12870 kmalloc_node(sizeof(struct perf_cpu_pmu_context), 12871 GFP_KERNEL | __GFP_ZERO, 12872 cpu_to_node(cpu)); 12873 12874 if (!cpc) 12875 return -ENOMEM; 12876 12877 *per_cpu_ptr(pmu->cpu_pmu_context, cpu) = cpc; 12878 __perf_init_event_pmu_context(&cpc->epc, pmu); 12879 __perf_mux_hrtimer_init(cpc, cpu); 12880 } 12881 12882 if (!pmu->start_txn) { 12883 if (pmu->pmu_enable) { 12884 /* 12885 * If we have pmu_enable/pmu_disable calls, install 12886 * transaction stubs that use that to try and batch 12887 * hardware accesses. 12888 */ 12889 pmu->start_txn = perf_pmu_start_txn; 12890 pmu->commit_txn = perf_pmu_commit_txn; 12891 pmu->cancel_txn = perf_pmu_cancel_txn; 12892 } else { 12893 pmu->start_txn = perf_pmu_nop_txn; 12894 pmu->commit_txn = perf_pmu_nop_int; 12895 pmu->cancel_txn = perf_pmu_nop_void; 12896 } 12897 } 12898 12899 if (!pmu->pmu_enable) { 12900 pmu->pmu_enable = perf_pmu_nop_void; 12901 pmu->pmu_disable = perf_pmu_nop_void; 12902 } 12903 12904 if (!pmu->check_period) 12905 pmu->check_period = perf_event_nop_int; 12906 12907 if (!pmu->event_idx) 12908 pmu->event_idx = perf_event_idx_default; 12909 12910 INIT_LIST_HEAD(&pmu->events); 12911 spin_lock_init(&pmu->events_lock); 12912 12913 /* 12914 * Now that the PMU is complete, make it visible to perf_try_init_event(). 12915 */ 12916 if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu)) 12917 return -EINVAL; 12918 list_add_rcu(&pmu->entry, &pmus); 12919 12920 take_idr_id(pmu_type); 12921 _pmu = no_free_ptr(pmu); // let it rip 12922 return 0; 12923 } 12924 EXPORT_SYMBOL_GPL(perf_pmu_register); 12925 12926 static void __pmu_detach_event(struct pmu *pmu, struct perf_event *event, 12927 struct perf_event_context *ctx) 12928 { 12929 /* 12930 * De-schedule the event and mark it REVOKED. 12931 */ 12932 perf_event_exit_event(event, ctx, ctx->task, true); 12933 12934 /* 12935 * All _free_event() bits that rely on event->pmu: 12936 * 12937 * Notably, perf_mmap() relies on the ordering here. 12938 */ 12939 scoped_guard (mutex, &event->mmap_mutex) { 12940 WARN_ON_ONCE(pmu->event_unmapped); 12941 /* 12942 * Mostly an empty lock sequence, such that perf_mmap(), which 12943 * relies on mmap_mutex, is sure to observe the state change. 12944 */ 12945 } 12946 12947 perf_event_free_bpf_prog(event); 12948 perf_free_addr_filters(event); 12949 12950 if (event->destroy) { 12951 event->destroy(event); 12952 event->destroy = NULL; 12953 } 12954 12955 if (event->pmu_ctx) { 12956 put_pmu_ctx(event->pmu_ctx); 12957 event->pmu_ctx = NULL; 12958 } 12959 12960 exclusive_event_destroy(event); 12961 module_put(pmu->module); 12962 12963 event->pmu = NULL; /* force fault instead of UAF */ 12964 } 12965 12966 static void pmu_detach_event(struct pmu *pmu, struct perf_event *event) 12967 { 12968 struct perf_event_context *ctx; 12969 12970 ctx = perf_event_ctx_lock(event); 12971 __pmu_detach_event(pmu, event, ctx); 12972 perf_event_ctx_unlock(event, ctx); 12973 12974 scoped_guard (spinlock, &pmu->events_lock) 12975 list_del(&event->pmu_list); 12976 } 12977 12978 static struct perf_event *pmu_get_event(struct pmu *pmu) 12979 { 12980 struct perf_event *event; 12981 12982 guard(spinlock)(&pmu->events_lock); 12983 list_for_each_entry(event, &pmu->events, pmu_list) { 12984 if (atomic_long_inc_not_zero(&event->refcount)) 12985 return event; 12986 } 12987 12988 return NULL; 12989 } 12990 12991 static bool pmu_empty(struct pmu *pmu) 12992 { 12993 guard(spinlock)(&pmu->events_lock); 12994 return list_empty(&pmu->events); 12995 } 12996 12997 static void pmu_detach_events(struct pmu *pmu) 12998 { 12999 struct perf_event *event; 13000 13001 for (;;) { 13002 event = pmu_get_event(pmu); 13003 if (!event) 13004 break; 13005 13006 pmu_detach_event(pmu, event); 13007 put_event(event); 13008 } 13009 13010 /* 13011 * wait for pending _free_event()s 13012 */ 13013 wait_var_event(pmu, pmu_empty(pmu)); 13014 } 13015 13016 int perf_pmu_unregister(struct pmu *pmu) 13017 { 13018 scoped_guard (mutex, &pmus_lock) { 13019 if (!idr_cmpxchg(&pmu_idr, pmu->type, pmu, NULL)) 13020 return -EINVAL; 13021 13022 list_del_rcu(&pmu->entry); 13023 } 13024 13025 /* 13026 * We dereference the pmu list under both SRCU and regular RCU, so 13027 * synchronize against both of those. 13028 * 13029 * Notably, the entirety of event creation, from perf_init_event() 13030 * (which will now fail, because of the above) until 13031 * perf_install_in_context() should be under SRCU such that 13032 * this synchronizes against event creation. This avoids trying to 13033 * detach events that are not fully formed. 13034 */ 13035 synchronize_srcu(&pmus_srcu); 13036 synchronize_rcu(); 13037 13038 if (pmu->event_unmapped && !pmu_empty(pmu)) { 13039 /* 13040 * Can't force remove events when pmu::event_unmapped() 13041 * is used in perf_mmap_close(). 13042 */ 13043 guard(mutex)(&pmus_lock); 13044 idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu); 13045 list_add_rcu(&pmu->entry, &pmus); 13046 return -EBUSY; 13047 } 13048 13049 scoped_guard (mutex, &pmus_lock) 13050 idr_remove(&pmu_idr, pmu->type); 13051 13052 /* 13053 * PMU is removed from the pmus list, so no new events will 13054 * be created, now take care of the existing ones. 13055 */ 13056 pmu_detach_events(pmu); 13057 13058 /* 13059 * PMU is unused, make it go away. 13060 */ 13061 perf_pmu_free(pmu); 13062 return 0; 13063 } 13064 EXPORT_SYMBOL_GPL(perf_pmu_unregister); 13065 13066 static inline bool has_extended_regs(struct perf_event *event) 13067 { 13068 return (event->attr.sample_regs_user & PERF_REG_EXTENDED_MASK) || 13069 (event->attr.sample_regs_intr & PERF_REG_EXTENDED_MASK); 13070 } 13071 13072 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) 13073 { 13074 struct perf_event_context *ctx = NULL; 13075 int ret; 13076 13077 if (!try_module_get(pmu->module)) 13078 return -ENODEV; 13079 13080 /* 13081 * A number of pmu->event_init() methods iterate the sibling_list to, 13082 * for example, validate if the group fits on the PMU. Therefore, 13083 * if this is a sibling event, acquire the ctx->mutex to protect 13084 * the sibling_list. 13085 */ 13086 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) { 13087 /* 13088 * This ctx->mutex can nest when we're called through 13089 * inheritance. See the perf_event_ctx_lock_nested() comment. 13090 */ 13091 ctx = perf_event_ctx_lock_nested(event->group_leader, 13092 SINGLE_DEPTH_NESTING); 13093 BUG_ON(!ctx); 13094 } 13095 13096 event->pmu = pmu; 13097 ret = pmu->event_init(event); 13098 13099 if (ctx) 13100 perf_event_ctx_unlock(event->group_leader, ctx); 13101 13102 if (ret) 13103 goto err_pmu; 13104 13105 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) && 13106 has_extended_regs(event)) { 13107 ret = -EOPNOTSUPP; 13108 goto err_destroy; 13109 } 13110 13111 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE && 13112 event_has_any_exclude_flag(event)) { 13113 ret = -EINVAL; 13114 goto err_destroy; 13115 } 13116 13117 if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) { 13118 const struct cpumask *cpumask; 13119 struct cpumask *pmu_cpumask; 13120 int cpu; 13121 13122 cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu); 13123 pmu_cpumask = perf_scope_cpumask(pmu->scope); 13124 13125 ret = -ENODEV; 13126 if (!pmu_cpumask || !cpumask) 13127 goto err_destroy; 13128 13129 cpu = cpumask_any_and(pmu_cpumask, cpumask); 13130 if (cpu >= nr_cpu_ids) 13131 goto err_destroy; 13132 13133 event->event_caps |= PERF_EV_CAP_READ_SCOPE; 13134 } 13135 13136 return 0; 13137 13138 err_destroy: 13139 if (event->destroy) { 13140 event->destroy(event); 13141 event->destroy = NULL; 13142 } 13143 13144 err_pmu: 13145 event->pmu = NULL; 13146 module_put(pmu->module); 13147 return ret; 13148 } 13149 13150 static struct pmu *perf_init_event(struct perf_event *event) 13151 { 13152 bool extended_type = false; 13153 struct pmu *pmu; 13154 int type, ret; 13155 13156 guard(srcu)(&pmus_srcu); /* pmu idr/list access */ 13157 13158 /* 13159 * Save original type before calling pmu->event_init() since certain 13160 * pmus overwrites event->attr.type to forward event to another pmu. 13161 */ 13162 event->orig_type = event->attr.type; 13163 13164 /* Try parent's PMU first: */ 13165 if (event->parent && event->parent->pmu) { 13166 pmu = event->parent->pmu; 13167 ret = perf_try_init_event(pmu, event); 13168 if (!ret) 13169 return pmu; 13170 } 13171 13172 /* 13173 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE 13174 * are often aliases for PERF_TYPE_RAW. 13175 */ 13176 type = event->attr.type; 13177 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) { 13178 type = event->attr.config >> PERF_PMU_TYPE_SHIFT; 13179 if (!type) { 13180 type = PERF_TYPE_RAW; 13181 } else { 13182 extended_type = true; 13183 event->attr.config &= PERF_HW_EVENT_MASK; 13184 } 13185 } 13186 13187 again: 13188 scoped_guard (rcu) 13189 pmu = idr_find(&pmu_idr, type); 13190 if (pmu) { 13191 if (event->attr.type != type && type != PERF_TYPE_RAW && 13192 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE)) 13193 return ERR_PTR(-ENOENT); 13194 13195 ret = perf_try_init_event(pmu, event); 13196 if (ret == -ENOENT && event->attr.type != type && !extended_type) { 13197 type = event->attr.type; 13198 goto again; 13199 } 13200 13201 if (ret) 13202 return ERR_PTR(ret); 13203 13204 return pmu; 13205 } 13206 13207 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) { 13208 ret = perf_try_init_event(pmu, event); 13209 if (!ret) 13210 return pmu; 13211 13212 if (ret != -ENOENT) 13213 return ERR_PTR(ret); 13214 } 13215 13216 return ERR_PTR(-ENOENT); 13217 } 13218 13219 static void attach_sb_event(struct perf_event *event) 13220 { 13221 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 13222 13223 raw_spin_lock(&pel->lock); 13224 list_add_rcu(&event->sb_list, &pel->list); 13225 raw_spin_unlock(&pel->lock); 13226 } 13227 13228 /* 13229 * We keep a list of all !task (and therefore per-cpu) events 13230 * that need to receive side-band records. 13231 * 13232 * This avoids having to scan all the various PMU per-cpu contexts 13233 * looking for them. 13234 */ 13235 static void account_pmu_sb_event(struct perf_event *event) 13236 { 13237 if (is_sb_event(event)) 13238 attach_sb_event(event); 13239 } 13240 13241 /* Freq events need the tick to stay alive (see perf_event_task_tick). */ 13242 static void account_freq_event_nohz(void) 13243 { 13244 #ifdef CONFIG_NO_HZ_FULL 13245 /* Lock so we don't race with concurrent unaccount */ 13246 spin_lock(&nr_freq_lock); 13247 if (atomic_inc_return(&nr_freq_events) == 1) 13248 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS); 13249 spin_unlock(&nr_freq_lock); 13250 #endif 13251 } 13252 13253 static void account_freq_event(void) 13254 { 13255 if (tick_nohz_full_enabled()) 13256 account_freq_event_nohz(); 13257 else 13258 atomic_inc(&nr_freq_events); 13259 } 13260 13261 13262 static void account_event(struct perf_event *event) 13263 { 13264 bool inc = false; 13265 13266 if (event->parent) 13267 return; 13268 13269 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB)) 13270 inc = true; 13271 if (event->attr.mmap || event->attr.mmap_data) 13272 atomic_inc(&nr_mmap_events); 13273 if (event->attr.build_id) 13274 atomic_inc(&nr_build_id_events); 13275 if (event->attr.comm) 13276 atomic_inc(&nr_comm_events); 13277 if (event->attr.namespaces) 13278 atomic_inc(&nr_namespaces_events); 13279 if (event->attr.cgroup) 13280 atomic_inc(&nr_cgroup_events); 13281 if (event->attr.task) 13282 atomic_inc(&nr_task_events); 13283 if (event->attr.freq) 13284 account_freq_event(); 13285 if (event->attr.context_switch) { 13286 atomic_inc(&nr_switch_events); 13287 inc = true; 13288 } 13289 if (has_branch_stack(event)) 13290 inc = true; 13291 if (is_cgroup_event(event)) 13292 inc = true; 13293 if (event->attr.ksymbol) 13294 atomic_inc(&nr_ksymbol_events); 13295 if (event->attr.bpf_event) 13296 atomic_inc(&nr_bpf_events); 13297 if (event->attr.text_poke) 13298 atomic_inc(&nr_text_poke_events); 13299 13300 if (inc) { 13301 /* 13302 * We need the mutex here because static_branch_enable() 13303 * must complete *before* the perf_sched_count increment 13304 * becomes visible. 13305 */ 13306 if (atomic_inc_not_zero(&perf_sched_count)) 13307 goto enabled; 13308 13309 mutex_lock(&perf_sched_mutex); 13310 if (!atomic_read(&perf_sched_count)) { 13311 static_branch_enable(&perf_sched_events); 13312 /* 13313 * Guarantee that all CPUs observe they key change and 13314 * call the perf scheduling hooks before proceeding to 13315 * install events that need them. 13316 */ 13317 synchronize_rcu(); 13318 } 13319 /* 13320 * Now that we have waited for the sync_sched(), allow further 13321 * increments to by-pass the mutex. 13322 */ 13323 atomic_inc(&perf_sched_count); 13324 mutex_unlock(&perf_sched_mutex); 13325 } 13326 enabled: 13327 13328 account_pmu_sb_event(event); 13329 } 13330 13331 /* 13332 * Allocate and initialize an event structure 13333 */ 13334 static struct perf_event * 13335 perf_event_alloc(struct perf_event_attr *attr, int cpu, 13336 struct task_struct *task, 13337 struct perf_event *group_leader, 13338 struct perf_event *parent_event, 13339 perf_overflow_handler_t overflow_handler, 13340 void *context, int cgroup_fd) 13341 { 13342 struct pmu *pmu; 13343 struct hw_perf_event *hwc; 13344 long err = -EINVAL; 13345 int node; 13346 13347 if ((unsigned)cpu >= nr_cpu_ids) { 13348 if (!task || cpu != -1) 13349 return ERR_PTR(-EINVAL); 13350 } 13351 if (attr->sigtrap && !task) { 13352 /* Requires a task: avoid signalling random tasks. */ 13353 return ERR_PTR(-EINVAL); 13354 } 13355 13356 node = (cpu >= 0) ? cpu_to_node(cpu) : -1; 13357 struct perf_event *event __free(__free_event) = 13358 kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node); 13359 if (!event) 13360 return ERR_PTR(-ENOMEM); 13361 13362 /* 13363 * Single events are their own group leaders, with an 13364 * empty sibling list: 13365 */ 13366 if (!group_leader) 13367 group_leader = event; 13368 13369 mutex_init(&event->child_mutex); 13370 INIT_LIST_HEAD(&event->child_list); 13371 13372 INIT_LIST_HEAD(&event->event_entry); 13373 INIT_LIST_HEAD(&event->sibling_list); 13374 INIT_LIST_HEAD(&event->active_list); 13375 init_event_group(event); 13376 INIT_LIST_HEAD(&event->rb_entry); 13377 INIT_LIST_HEAD(&event->active_entry); 13378 INIT_LIST_HEAD(&event->addr_filters.list); 13379 INIT_HLIST_NODE(&event->hlist_entry); 13380 INIT_LIST_HEAD(&event->pmu_list); 13381 13382 13383 init_waitqueue_head(&event->waitq); 13384 init_irq_work(&event->pending_irq, perf_pending_irq); 13385 event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable); 13386 init_task_work(&event->pending_task, perf_pending_task); 13387 13388 mutex_init(&event->mmap_mutex); 13389 raw_spin_lock_init(&event->addr_filters.lock); 13390 13391 atomic_long_set(&event->refcount, 1); 13392 event->cpu = cpu; 13393 event->attr = *attr; 13394 event->group_leader = group_leader; 13395 event->pmu = NULL; 13396 event->oncpu = -1; 13397 13398 event->parent = parent_event; 13399 13400 event->ns = get_pid_ns(task_active_pid_ns(current)); 13401 event->id = atomic64_inc_return(&perf_event_id); 13402 13403 event->state = PERF_EVENT_STATE_INACTIVE; 13404 13405 if (parent_event) 13406 event->event_caps = parent_event->event_caps; 13407 13408 if (task) { 13409 event->attach_state = PERF_ATTACH_TASK; 13410 /* 13411 * XXX pmu::event_init needs to know what task to account to 13412 * and we cannot use the ctx information because we need the 13413 * pmu before we get a ctx. 13414 */ 13415 event->hw.target = get_task_struct(task); 13416 } 13417 13418 event->clock = &local_clock; 13419 if (parent_event) 13420 event->clock = parent_event->clock; 13421 13422 if (!overflow_handler && parent_event) { 13423 overflow_handler = parent_event->overflow_handler; 13424 context = parent_event->overflow_handler_context; 13425 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING) 13426 if (parent_event->prog) { 13427 struct bpf_prog *prog = parent_event->prog; 13428 13429 bpf_prog_inc(prog); 13430 event->prog = prog; 13431 } 13432 #endif 13433 } 13434 13435 if (overflow_handler) { 13436 event->overflow_handler = overflow_handler; 13437 event->overflow_handler_context = context; 13438 } else if (is_write_backward(event)){ 13439 event->overflow_handler = perf_event_output_backward; 13440 event->overflow_handler_context = NULL; 13441 } else { 13442 event->overflow_handler = perf_event_output_forward; 13443 event->overflow_handler_context = NULL; 13444 } 13445 13446 perf_event__state_init(event); 13447 13448 pmu = NULL; 13449 13450 hwc = &event->hw; 13451 hwc->sample_period = attr->sample_period; 13452 if (is_event_in_freq_mode(event)) 13453 hwc->sample_period = 1; 13454 hwc->last_period = hwc->sample_period; 13455 13456 local64_set(&hwc->period_left, hwc->sample_period); 13457 13458 /* 13459 * We do not support PERF_SAMPLE_READ on inherited events unless 13460 * PERF_SAMPLE_TID is also selected, which allows inherited events to 13461 * collect per-thread samples. 13462 * See perf_output_read(). 13463 */ 13464 if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID)) 13465 return ERR_PTR(-EINVAL); 13466 13467 if (!has_branch_stack(event)) 13468 event->attr.branch_sample_type = 0; 13469 13470 pmu = perf_init_event(event); 13471 if (IS_ERR(pmu)) 13472 return (void*)pmu; 13473 13474 /* 13475 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config(). 13476 * The attach should be right after the perf_init_event(). 13477 * Otherwise, the __free_event() would mistakenly detach the non-exist 13478 * perf_ctx_data because of the other errors between them. 13479 */ 13480 if (event->attach_state & PERF_ATTACH_TASK_DATA) { 13481 err = attach_perf_ctx_data(event); 13482 if (err) 13483 return ERR_PTR(err); 13484 } 13485 13486 /* 13487 * Disallow uncore-task events. Similarly, disallow uncore-cgroup 13488 * events (they don't make sense as the cgroup will be different 13489 * on other CPUs in the uncore mask). 13490 */ 13491 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) 13492 return ERR_PTR(-EINVAL); 13493 13494 if (event->attr.aux_output && 13495 (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) || 13496 event->attr.aux_pause || event->attr.aux_resume)) 13497 return ERR_PTR(-EOPNOTSUPP); 13498 13499 if (event->attr.aux_pause && event->attr.aux_resume) 13500 return ERR_PTR(-EINVAL); 13501 13502 if (event->attr.aux_start_paused) { 13503 if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) 13504 return ERR_PTR(-EOPNOTSUPP); 13505 event->hw.aux_paused = 1; 13506 } 13507 13508 if (cgroup_fd != -1) { 13509 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader); 13510 if (err) 13511 return ERR_PTR(err); 13512 } 13513 13514 err = exclusive_event_init(event); 13515 if (err) 13516 return ERR_PTR(err); 13517 13518 if (has_addr_filter(event)) { 13519 event->addr_filter_ranges = kcalloc(pmu->nr_addr_filters, 13520 sizeof(struct perf_addr_filter_range), 13521 GFP_KERNEL); 13522 if (!event->addr_filter_ranges) 13523 return ERR_PTR(-ENOMEM); 13524 13525 /* 13526 * Clone the parent's vma offsets: they are valid until exec() 13527 * even if the mm is not shared with the parent. 13528 */ 13529 if (event->parent) { 13530 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 13531 13532 raw_spin_lock_irq(&ifh->lock); 13533 memcpy(event->addr_filter_ranges, 13534 event->parent->addr_filter_ranges, 13535 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range)); 13536 raw_spin_unlock_irq(&ifh->lock); 13537 } 13538 13539 /* force hw sync on the address filters */ 13540 event->addr_filters_gen = 1; 13541 } 13542 13543 if (!event->parent) { 13544 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) { 13545 err = get_callchain_buffers(attr->sample_max_stack); 13546 if (err) 13547 return ERR_PTR(err); 13548 event->attach_state |= PERF_ATTACH_CALLCHAIN; 13549 } 13550 } 13551 13552 err = security_perf_event_alloc(event); 13553 if (err) 13554 return ERR_PTR(err); 13555 13556 err = mediated_pmu_account_event(event); 13557 if (err) 13558 return ERR_PTR(err); 13559 13560 /* symmetric to unaccount_event() in _free_event() */ 13561 account_event(event); 13562 13563 /* 13564 * Event creation should be under SRCU, see perf_pmu_unregister(). 13565 */ 13566 lockdep_assert_held(&pmus_srcu); 13567 scoped_guard (spinlock, &pmu->events_lock) 13568 list_add(&event->pmu_list, &pmu->events); 13569 13570 return_ptr(event); 13571 } 13572 13573 static int perf_copy_attr(struct perf_event_attr __user *uattr, 13574 struct perf_event_attr *attr) 13575 { 13576 u32 size; 13577 int ret; 13578 13579 /* Zero the full structure, so that a short copy will be nice. */ 13580 memset(attr, 0, sizeof(*attr)); 13581 13582 ret = get_user(size, &uattr->size); 13583 if (ret) 13584 return ret; 13585 13586 /* ABI compatibility quirk: */ 13587 if (!size) 13588 size = PERF_ATTR_SIZE_VER0; 13589 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE) 13590 goto err_size; 13591 13592 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size); 13593 if (ret) { 13594 if (ret == -E2BIG) 13595 goto err_size; 13596 return ret; 13597 } 13598 13599 attr->size = size; 13600 13601 if (attr->__reserved_1 || attr->__reserved_2 || attr->__reserved_3) 13602 return -EINVAL; 13603 13604 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) 13605 return -EINVAL; 13606 13607 if (attr->read_format & ~(PERF_FORMAT_MAX-1)) 13608 return -EINVAL; 13609 13610 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) { 13611 u64 mask = attr->branch_sample_type; 13612 13613 /* only using defined bits */ 13614 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1)) 13615 return -EINVAL; 13616 13617 /* at least one branch bit must be set */ 13618 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL)) 13619 return -EINVAL; 13620 13621 /* propagate priv level, when not set for branch */ 13622 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) { 13623 13624 /* exclude_kernel checked on syscall entry */ 13625 if (!attr->exclude_kernel) 13626 mask |= PERF_SAMPLE_BRANCH_KERNEL; 13627 13628 if (!attr->exclude_user) 13629 mask |= PERF_SAMPLE_BRANCH_USER; 13630 13631 if (!attr->exclude_hv) 13632 mask |= PERF_SAMPLE_BRANCH_HV; 13633 /* 13634 * adjust user setting (for HW filter setup) 13635 */ 13636 attr->branch_sample_type = mask; 13637 } 13638 /* privileged levels capture (kernel, hv): check permissions */ 13639 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) { 13640 ret = perf_allow_kernel(); 13641 if (ret) 13642 return ret; 13643 } 13644 } 13645 13646 if (attr->sample_type & PERF_SAMPLE_REGS_USER) { 13647 ret = perf_reg_validate(attr->sample_regs_user); 13648 if (ret) 13649 return ret; 13650 } 13651 13652 if (attr->sample_type & PERF_SAMPLE_STACK_USER) { 13653 if (!arch_perf_have_user_stack_dump()) 13654 return -ENOSYS; 13655 13656 /* 13657 * We have __u32 type for the size, but so far 13658 * we can only use __u16 as maximum due to the 13659 * __u16 sample size limit. 13660 */ 13661 if (attr->sample_stack_user >= USHRT_MAX) 13662 return -EINVAL; 13663 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64))) 13664 return -EINVAL; 13665 } 13666 13667 if (!attr->sample_max_stack) 13668 attr->sample_max_stack = sysctl_perf_event_max_stack; 13669 13670 if (attr->sample_type & PERF_SAMPLE_REGS_INTR) 13671 ret = perf_reg_validate(attr->sample_regs_intr); 13672 13673 #ifndef CONFIG_CGROUP_PERF 13674 if (attr->sample_type & PERF_SAMPLE_CGROUP) 13675 return -EINVAL; 13676 #endif 13677 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) && 13678 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT)) 13679 return -EINVAL; 13680 13681 if (!attr->inherit && attr->inherit_thread) 13682 return -EINVAL; 13683 13684 if (attr->remove_on_exec && attr->enable_on_exec) 13685 return -EINVAL; 13686 13687 if (attr->sigtrap && !attr->remove_on_exec) 13688 return -EINVAL; 13689 13690 out: 13691 return ret; 13692 13693 err_size: 13694 put_user(sizeof(*attr), &uattr->size); 13695 ret = -E2BIG; 13696 goto out; 13697 } 13698 13699 static void mutex_lock_double(struct mutex *a, struct mutex *b) 13700 { 13701 if (b < a) 13702 swap(a, b); 13703 13704 mutex_lock(a); 13705 mutex_lock_nested(b, SINGLE_DEPTH_NESTING); 13706 } 13707 13708 static int 13709 perf_event_set_output(struct perf_event *event, struct perf_event *output_event) 13710 { 13711 struct perf_buffer *rb = NULL; 13712 int ret = -EINVAL; 13713 13714 if (!output_event) { 13715 mutex_lock(&event->mmap_mutex); 13716 goto set; 13717 } 13718 13719 /* don't allow circular references */ 13720 if (event == output_event) 13721 goto out; 13722 13723 /* 13724 * Don't allow cross-cpu buffers 13725 */ 13726 if (output_event->cpu != event->cpu) 13727 goto out; 13728 13729 /* 13730 * If its not a per-cpu rb, it must be the same task. 13731 */ 13732 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target) 13733 goto out; 13734 13735 /* 13736 * Mixing clocks in the same buffer is trouble you don't need. 13737 */ 13738 if (output_event->clock != event->clock) 13739 goto out; 13740 13741 /* 13742 * Either writing ring buffer from beginning or from end. 13743 * Mixing is not allowed. 13744 */ 13745 if (is_write_backward(output_event) != is_write_backward(event)) 13746 goto out; 13747 13748 /* 13749 * If both events generate aux data, they must be on the same PMU 13750 */ 13751 if (has_aux(event) && has_aux(output_event) && 13752 event->pmu != output_event->pmu) 13753 goto out; 13754 13755 /* 13756 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since 13757 * output_event is already on rb->event_list, and the list iteration 13758 * restarts after every removal, it is guaranteed this new event is 13759 * observed *OR* if output_event is already removed, it's guaranteed we 13760 * observe !rb->mmap_count. 13761 */ 13762 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex); 13763 set: 13764 /* Can't redirect output if we've got an active mmap() */ 13765 if (refcount_read(&event->mmap_count)) 13766 goto unlock; 13767 13768 if (output_event) { 13769 if (output_event->state <= PERF_EVENT_STATE_REVOKED) 13770 goto unlock; 13771 13772 /* get the rb we want to redirect to */ 13773 rb = ring_buffer_get(output_event); 13774 if (!rb) 13775 goto unlock; 13776 13777 /* did we race against perf_mmap_close() */ 13778 if (!refcount_read(&rb->mmap_count)) { 13779 ring_buffer_put(rb); 13780 goto unlock; 13781 } 13782 } 13783 13784 ring_buffer_attach(event, rb); 13785 13786 ret = 0; 13787 unlock: 13788 mutex_unlock(&event->mmap_mutex); 13789 if (output_event) 13790 mutex_unlock(&output_event->mmap_mutex); 13791 13792 out: 13793 return ret; 13794 } 13795 13796 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id) 13797 { 13798 bool nmi_safe = false; 13799 13800 switch (clk_id) { 13801 case CLOCK_MONOTONIC: 13802 event->clock = &ktime_get_mono_fast_ns; 13803 nmi_safe = true; 13804 break; 13805 13806 case CLOCK_MONOTONIC_RAW: 13807 event->clock = &ktime_get_raw_fast_ns; 13808 nmi_safe = true; 13809 break; 13810 13811 case CLOCK_REALTIME: 13812 event->clock = &ktime_get_real_ns; 13813 break; 13814 13815 case CLOCK_BOOTTIME: 13816 event->clock = &ktime_get_boottime_ns; 13817 break; 13818 13819 case CLOCK_TAI: 13820 event->clock = &ktime_get_clocktai_ns; 13821 break; 13822 13823 default: 13824 return -EINVAL; 13825 } 13826 13827 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI)) 13828 return -EINVAL; 13829 13830 return 0; 13831 } 13832 13833 static bool 13834 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task) 13835 { 13836 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS; 13837 bool is_capable = perfmon_capable(); 13838 13839 if (attr->sigtrap) { 13840 /* 13841 * perf_event_attr::sigtrap sends signals to the other task. 13842 * Require the current task to also have CAP_KILL. 13843 */ 13844 rcu_read_lock(); 13845 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL); 13846 rcu_read_unlock(); 13847 13848 /* 13849 * If the required capabilities aren't available, checks for 13850 * ptrace permissions: upgrade to ATTACH, since sending signals 13851 * can effectively change the target task. 13852 */ 13853 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS; 13854 } 13855 13856 /* 13857 * Preserve ptrace permission check for backwards compatibility. The 13858 * ptrace check also includes checks that the current task and other 13859 * task have matching uids, and is therefore not done here explicitly. 13860 */ 13861 return is_capable || ptrace_may_access(task, ptrace_mode); 13862 } 13863 13864 /** 13865 * sys_perf_event_open - open a performance event, associate it to a task/cpu 13866 * 13867 * @attr_uptr: event_id type attributes for monitoring/sampling 13868 * @pid: target pid 13869 * @cpu: target cpu 13870 * @group_fd: group leader event fd 13871 * @flags: perf event open flags 13872 */ 13873 SYSCALL_DEFINE5(perf_event_open, 13874 struct perf_event_attr __user *, attr_uptr, 13875 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) 13876 { 13877 struct perf_event *group_leader = NULL, *output_event = NULL; 13878 struct perf_event_pmu_context *pmu_ctx; 13879 struct perf_event *event, *sibling; 13880 struct perf_event_attr attr; 13881 struct perf_event_context *ctx; 13882 struct file *event_file = NULL; 13883 struct task_struct *task = NULL; 13884 struct pmu *pmu; 13885 int event_fd; 13886 int move_group = 0; 13887 int err; 13888 int f_flags = O_RDWR; 13889 int cgroup_fd = -1; 13890 13891 /* for future expandability... */ 13892 if (flags & ~PERF_FLAG_ALL) 13893 return -EINVAL; 13894 13895 err = perf_copy_attr(attr_uptr, &attr); 13896 if (err) 13897 return err; 13898 13899 /* Do we allow access to perf_event_open(2) ? */ 13900 err = security_perf_event_open(PERF_SECURITY_OPEN); 13901 if (err) 13902 return err; 13903 13904 if (!attr.exclude_kernel) { 13905 err = perf_allow_kernel(); 13906 if (err) 13907 return err; 13908 } 13909 13910 if (attr.namespaces) { 13911 if (!perfmon_capable()) 13912 return -EACCES; 13913 } 13914 13915 if (attr.freq) { 13916 if (attr.sample_freq > sysctl_perf_event_sample_rate) 13917 return -EINVAL; 13918 } else { 13919 if (attr.sample_period & (1ULL << 63)) 13920 return -EINVAL; 13921 } 13922 13923 /* Only privileged users can get physical addresses */ 13924 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) { 13925 err = perf_allow_kernel(); 13926 if (err) 13927 return err; 13928 } 13929 13930 /* REGS_INTR can leak data, lockdown must prevent this */ 13931 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) { 13932 err = security_locked_down(LOCKDOWN_PERF); 13933 if (err) 13934 return err; 13935 } 13936 13937 /* 13938 * In cgroup mode, the pid argument is used to pass the fd 13939 * opened to the cgroup directory in cgroupfs. The cpu argument 13940 * designates the cpu on which to monitor threads from that 13941 * cgroup. 13942 */ 13943 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) 13944 return -EINVAL; 13945 13946 if (flags & PERF_FLAG_FD_CLOEXEC) 13947 f_flags |= O_CLOEXEC; 13948 13949 event_fd = get_unused_fd_flags(f_flags); 13950 if (event_fd < 0) 13951 return event_fd; 13952 13953 /* 13954 * Event creation should be under SRCU, see perf_pmu_unregister(). 13955 */ 13956 guard(srcu)(&pmus_srcu); 13957 13958 CLASS(fd, group)(group_fd); // group_fd == -1 => empty 13959 if (group_fd != -1) { 13960 if (!is_perf_file(group)) { 13961 err = -EBADF; 13962 goto err_fd; 13963 } 13964 group_leader = fd_file(group)->private_data; 13965 if (group_leader->state <= PERF_EVENT_STATE_REVOKED) { 13966 err = -ENODEV; 13967 goto err_fd; 13968 } 13969 if (flags & PERF_FLAG_FD_OUTPUT) 13970 output_event = group_leader; 13971 if (flags & PERF_FLAG_FD_NO_GROUP) 13972 group_leader = NULL; 13973 } 13974 13975 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { 13976 task = find_lively_task_by_vpid(pid); 13977 if (IS_ERR(task)) { 13978 err = PTR_ERR(task); 13979 goto err_fd; 13980 } 13981 } 13982 13983 if (task && group_leader && 13984 group_leader->attr.inherit != attr.inherit) { 13985 err = -EINVAL; 13986 goto err_task; 13987 } 13988 13989 if (flags & PERF_FLAG_PID_CGROUP) 13990 cgroup_fd = pid; 13991 13992 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, 13993 NULL, NULL, cgroup_fd); 13994 if (IS_ERR(event)) { 13995 err = PTR_ERR(event); 13996 goto err_task; 13997 } 13998 13999 if (is_sampling_event(event)) { 14000 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { 14001 err = -EOPNOTSUPP; 14002 goto err_alloc; 14003 } 14004 } 14005 14006 /* 14007 * Special case software events and allow them to be part of 14008 * any hardware group. 14009 */ 14010 pmu = event->pmu; 14011 14012 if (attr.use_clockid) { 14013 err = perf_event_set_clock(event, attr.clockid); 14014 if (err) 14015 goto err_alloc; 14016 } 14017 14018 if (pmu->task_ctx_nr == perf_sw_context) 14019 event->event_caps |= PERF_EV_CAP_SOFTWARE; 14020 14021 if (task) { 14022 err = down_read_interruptible(&task->signal->exec_update_lock); 14023 if (err) 14024 goto err_alloc; 14025 14026 /* 14027 * We must hold exec_update_lock across this and any potential 14028 * perf_install_in_context() call for this new event to 14029 * serialize against exec() altering our credentials (and the 14030 * perf_event_exit_task() that could imply). 14031 */ 14032 err = -EACCES; 14033 if (!perf_check_permission(&attr, task)) 14034 goto err_cred; 14035 } 14036 14037 /* 14038 * Get the target context (task or percpu): 14039 */ 14040 ctx = find_get_context(task, event); 14041 if (IS_ERR(ctx)) { 14042 err = PTR_ERR(ctx); 14043 goto err_cred; 14044 } 14045 14046 mutex_lock(&ctx->mutex); 14047 14048 if (ctx->task == TASK_TOMBSTONE) { 14049 err = -ESRCH; 14050 goto err_locked; 14051 } 14052 14053 if (!task) { 14054 /* 14055 * Check if the @cpu we're creating an event for is online. 14056 * 14057 * We use the perf_cpu_context::ctx::mutex to serialize against 14058 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 14059 */ 14060 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu); 14061 14062 if (!cpuctx->online) { 14063 err = -ENODEV; 14064 goto err_locked; 14065 } 14066 } 14067 14068 if (group_leader) { 14069 err = -EINVAL; 14070 14071 /* 14072 * Do not allow a recursive hierarchy (this new sibling 14073 * becoming part of another group-sibling): 14074 */ 14075 if (group_leader->group_leader != group_leader) 14076 goto err_locked; 14077 14078 /* All events in a group should have the same clock */ 14079 if (group_leader->clock != event->clock) 14080 goto err_locked; 14081 14082 /* 14083 * Make sure we're both events for the same CPU; 14084 * grouping events for different CPUs is broken; since 14085 * you can never concurrently schedule them anyhow. 14086 */ 14087 if (group_leader->cpu != event->cpu) 14088 goto err_locked; 14089 14090 /* 14091 * Make sure we're both on the same context; either task or cpu. 14092 */ 14093 if (group_leader->ctx != ctx) 14094 goto err_locked; 14095 14096 /* 14097 * Only a group leader can be exclusive or pinned 14098 */ 14099 if (attr.exclusive || attr.pinned) 14100 goto err_locked; 14101 14102 if (is_software_event(event) && 14103 !in_software_context(group_leader)) { 14104 /* 14105 * If the event is a sw event, but the group_leader 14106 * is on hw context. 14107 * 14108 * Allow the addition of software events to hw 14109 * groups, this is safe because software events 14110 * never fail to schedule. 14111 * 14112 * Note the comment that goes with struct 14113 * perf_event_pmu_context. 14114 */ 14115 pmu = group_leader->pmu_ctx->pmu; 14116 } else if (!is_software_event(event)) { 14117 if (is_software_event(group_leader) && 14118 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { 14119 /* 14120 * In case the group is a pure software group, and we 14121 * try to add a hardware event, move the whole group to 14122 * the hardware context. 14123 */ 14124 move_group = 1; 14125 } 14126 14127 /* Don't allow group of multiple hw events from different pmus */ 14128 if (!in_software_context(group_leader) && 14129 group_leader->pmu_ctx->pmu != pmu) 14130 goto err_locked; 14131 } 14132 } 14133 14134 /* 14135 * Now that we're certain of the pmu; find the pmu_ctx. 14136 */ 14137 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 14138 if (IS_ERR(pmu_ctx)) { 14139 err = PTR_ERR(pmu_ctx); 14140 goto err_locked; 14141 } 14142 event->pmu_ctx = pmu_ctx; 14143 14144 if (output_event) { 14145 err = perf_event_set_output(event, output_event); 14146 if (err) 14147 goto err_context; 14148 } 14149 14150 if (!perf_event_validate_size(event)) { 14151 err = -E2BIG; 14152 goto err_context; 14153 } 14154 14155 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) { 14156 err = -EINVAL; 14157 goto err_context; 14158 } 14159 14160 /* 14161 * Must be under the same ctx::mutex as perf_install_in_context(), 14162 * because we need to serialize with concurrent event creation. 14163 */ 14164 if (!exclusive_event_installable(event, ctx)) { 14165 err = -EBUSY; 14166 goto err_context; 14167 } 14168 14169 WARN_ON_ONCE(ctx->parent_ctx); 14170 14171 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); 14172 if (IS_ERR(event_file)) { 14173 err = PTR_ERR(event_file); 14174 event_file = NULL; 14175 goto err_context; 14176 } 14177 14178 /* 14179 * This is the point on no return; we cannot fail hereafter. This is 14180 * where we start modifying current state. 14181 */ 14182 14183 if (move_group) { 14184 perf_remove_from_context(group_leader, 0); 14185 put_pmu_ctx(group_leader->pmu_ctx); 14186 14187 for_each_sibling_event(sibling, group_leader) { 14188 perf_remove_from_context(sibling, 0); 14189 put_pmu_ctx(sibling->pmu_ctx); 14190 } 14191 14192 /* 14193 * Install the group siblings before the group leader. 14194 * 14195 * Because a group leader will try and install the entire group 14196 * (through the sibling list, which is still in-tact), we can 14197 * end up with siblings installed in the wrong context. 14198 * 14199 * By installing siblings first we NO-OP because they're not 14200 * reachable through the group lists. 14201 */ 14202 for_each_sibling_event(sibling, group_leader) { 14203 sibling->pmu_ctx = pmu_ctx; 14204 get_pmu_ctx(pmu_ctx); 14205 perf_event__state_init(sibling); 14206 perf_install_in_context(ctx, sibling, sibling->cpu); 14207 } 14208 14209 /* 14210 * Removing from the context ends up with disabled 14211 * event. What we want here is event in the initial 14212 * startup state, ready to be add into new context. 14213 */ 14214 group_leader->pmu_ctx = pmu_ctx; 14215 get_pmu_ctx(pmu_ctx); 14216 perf_event__state_init(group_leader); 14217 perf_install_in_context(ctx, group_leader, group_leader->cpu); 14218 } 14219 14220 /* 14221 * Precalculate sample_data sizes; do while holding ctx::mutex such 14222 * that we're serialized against further additions and before 14223 * perf_install_in_context() which is the point the event is active and 14224 * can use these values. 14225 */ 14226 perf_event__header_size(event); 14227 perf_event__id_header_size(event); 14228 14229 event->owner = current; 14230 14231 perf_install_in_context(ctx, event, event->cpu); 14232 perf_unpin_context(ctx); 14233 14234 mutex_unlock(&ctx->mutex); 14235 14236 if (task) { 14237 up_read(&task->signal->exec_update_lock); 14238 put_task_struct(task); 14239 } 14240 14241 mutex_lock(¤t->perf_event_mutex); 14242 list_add_tail(&event->owner_entry, ¤t->perf_event_list); 14243 mutex_unlock(¤t->perf_event_mutex); 14244 14245 /* 14246 * File reference in group guarantees that group_leader has been 14247 * kept alive until we place the new event on the sibling_list. 14248 * This ensures destruction of the group leader will find 14249 * the pointer to itself in perf_group_detach(). 14250 */ 14251 fd_install(event_fd, event_file); 14252 return event_fd; 14253 14254 err_context: 14255 put_pmu_ctx(event->pmu_ctx); 14256 event->pmu_ctx = NULL; /* _free_event() */ 14257 err_locked: 14258 mutex_unlock(&ctx->mutex); 14259 perf_unpin_context(ctx); 14260 put_ctx(ctx); 14261 err_cred: 14262 if (task) 14263 up_read(&task->signal->exec_update_lock); 14264 err_alloc: 14265 put_event(event); 14266 err_task: 14267 if (task) 14268 put_task_struct(task); 14269 err_fd: 14270 put_unused_fd(event_fd); 14271 return err; 14272 } 14273 14274 /** 14275 * perf_event_create_kernel_counter 14276 * 14277 * @attr: attributes of the counter to create 14278 * @cpu: cpu in which the counter is bound 14279 * @task: task to profile (NULL for percpu) 14280 * @overflow_handler: callback to trigger when we hit the event 14281 * @context: context data could be used in overflow_handler callback 14282 */ 14283 struct perf_event * 14284 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu, 14285 struct task_struct *task, 14286 perf_overflow_handler_t overflow_handler, 14287 void *context) 14288 { 14289 struct perf_event_pmu_context *pmu_ctx; 14290 struct perf_event_context *ctx; 14291 struct perf_event *event; 14292 struct pmu *pmu; 14293 int err; 14294 14295 /* 14296 * Grouping is not supported for kernel events, neither is 'AUX', 14297 * make sure the caller's intentions are adjusted. 14298 */ 14299 if (attr->aux_output || attr->aux_action) 14300 return ERR_PTR(-EINVAL); 14301 14302 /* 14303 * Event creation should be under SRCU, see perf_pmu_unregister(). 14304 */ 14305 guard(srcu)(&pmus_srcu); 14306 14307 event = perf_event_alloc(attr, cpu, task, NULL, NULL, 14308 overflow_handler, context, -1); 14309 if (IS_ERR(event)) { 14310 err = PTR_ERR(event); 14311 goto err; 14312 } 14313 14314 /* Mark owner so we could distinguish it from user events. */ 14315 event->owner = TASK_TOMBSTONE; 14316 pmu = event->pmu; 14317 14318 if (pmu->task_ctx_nr == perf_sw_context) 14319 event->event_caps |= PERF_EV_CAP_SOFTWARE; 14320 14321 /* 14322 * Get the target context (task or percpu): 14323 */ 14324 ctx = find_get_context(task, event); 14325 if (IS_ERR(ctx)) { 14326 err = PTR_ERR(ctx); 14327 goto err_alloc; 14328 } 14329 14330 WARN_ON_ONCE(ctx->parent_ctx); 14331 mutex_lock(&ctx->mutex); 14332 if (ctx->task == TASK_TOMBSTONE) { 14333 err = -ESRCH; 14334 goto err_unlock; 14335 } 14336 14337 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 14338 if (IS_ERR(pmu_ctx)) { 14339 err = PTR_ERR(pmu_ctx); 14340 goto err_unlock; 14341 } 14342 event->pmu_ctx = pmu_ctx; 14343 14344 if (!task) { 14345 /* 14346 * Check if the @cpu we're creating an event for is online. 14347 * 14348 * We use the perf_cpu_context::ctx::mutex to serialize against 14349 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 14350 */ 14351 struct perf_cpu_context *cpuctx = 14352 container_of(ctx, struct perf_cpu_context, ctx); 14353 if (!cpuctx->online) { 14354 err = -ENODEV; 14355 goto err_pmu_ctx; 14356 } 14357 } 14358 14359 if (!exclusive_event_installable(event, ctx)) { 14360 err = -EBUSY; 14361 goto err_pmu_ctx; 14362 } 14363 14364 perf_install_in_context(ctx, event, event->cpu); 14365 perf_unpin_context(ctx); 14366 mutex_unlock(&ctx->mutex); 14367 14368 return event; 14369 14370 err_pmu_ctx: 14371 put_pmu_ctx(pmu_ctx); 14372 event->pmu_ctx = NULL; /* _free_event() */ 14373 err_unlock: 14374 mutex_unlock(&ctx->mutex); 14375 perf_unpin_context(ctx); 14376 put_ctx(ctx); 14377 err_alloc: 14378 put_event(event); 14379 err: 14380 return ERR_PTR(err); 14381 } 14382 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter); 14383 14384 static void __perf_pmu_remove(struct perf_event_context *ctx, 14385 int cpu, struct pmu *pmu, 14386 struct perf_event_groups *groups, 14387 struct list_head *events) 14388 { 14389 struct perf_event *event, *sibling; 14390 14391 perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) { 14392 perf_remove_from_context(event, 0); 14393 put_pmu_ctx(event->pmu_ctx); 14394 list_add(&event->migrate_entry, events); 14395 14396 for_each_sibling_event(sibling, event) { 14397 perf_remove_from_context(sibling, 0); 14398 put_pmu_ctx(sibling->pmu_ctx); 14399 list_add(&sibling->migrate_entry, events); 14400 } 14401 } 14402 } 14403 14404 static void __perf_pmu_install_event(struct pmu *pmu, 14405 struct perf_event_context *ctx, 14406 int cpu, struct perf_event *event) 14407 { 14408 struct perf_event_pmu_context *epc; 14409 struct perf_event_context *old_ctx = event->ctx; 14410 14411 get_ctx(ctx); /* normally find_get_context() */ 14412 14413 event->cpu = cpu; 14414 epc = find_get_pmu_context(pmu, ctx, event); 14415 event->pmu_ctx = epc; 14416 14417 if (event->state >= PERF_EVENT_STATE_OFF) 14418 event->state = PERF_EVENT_STATE_INACTIVE; 14419 perf_install_in_context(ctx, event, cpu); 14420 14421 /* 14422 * Now that event->ctx is updated and visible, put the old ctx. 14423 */ 14424 put_ctx(old_ctx); 14425 } 14426 14427 static void __perf_pmu_install(struct perf_event_context *ctx, 14428 int cpu, struct pmu *pmu, struct list_head *events) 14429 { 14430 struct perf_event *event, *tmp; 14431 14432 /* 14433 * Re-instate events in 2 passes. 14434 * 14435 * Skip over group leaders and only install siblings on this first 14436 * pass, siblings will not get enabled without a leader, however a 14437 * leader will enable its siblings, even if those are still on the old 14438 * context. 14439 */ 14440 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 14441 if (event->group_leader == event) 14442 continue; 14443 14444 list_del(&event->migrate_entry); 14445 __perf_pmu_install_event(pmu, ctx, cpu, event); 14446 } 14447 14448 /* 14449 * Once all the siblings are setup properly, install the group leaders 14450 * to make it go. 14451 */ 14452 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 14453 list_del(&event->migrate_entry); 14454 __perf_pmu_install_event(pmu, ctx, cpu, event); 14455 } 14456 } 14457 14458 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu) 14459 { 14460 struct perf_event_context *src_ctx, *dst_ctx; 14461 LIST_HEAD(events); 14462 14463 /* 14464 * Since per-cpu context is persistent, no need to grab an extra 14465 * reference. 14466 */ 14467 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx; 14468 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx; 14469 14470 /* 14471 * See perf_event_ctx_lock() for comments on the details 14472 * of swizzling perf_event::ctx. 14473 */ 14474 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex); 14475 14476 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->pinned_groups, &events); 14477 __perf_pmu_remove(src_ctx, src_cpu, pmu, &src_ctx->flexible_groups, &events); 14478 14479 if (!list_empty(&events)) { 14480 /* 14481 * Wait for the events to quiesce before re-instating them. 14482 */ 14483 synchronize_rcu(); 14484 14485 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events); 14486 } 14487 14488 mutex_unlock(&dst_ctx->mutex); 14489 mutex_unlock(&src_ctx->mutex); 14490 } 14491 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context); 14492 14493 static void sync_child_event(struct perf_event *child_event, 14494 struct task_struct *task) 14495 { 14496 struct perf_event *parent_event = child_event->parent; 14497 u64 child_val; 14498 14499 if (child_event->attr.inherit_stat) { 14500 if (task && task != TASK_TOMBSTONE) 14501 perf_event_read_event(child_event, task); 14502 } 14503 14504 child_val = perf_event_count(child_event, false); 14505 14506 /* 14507 * Add back the child's count to the parent's count: 14508 */ 14509 atomic64_add(child_val, &parent_event->child_count); 14510 atomic64_add(child_event->total_time_enabled, 14511 &parent_event->child_total_time_enabled); 14512 atomic64_add(child_event->total_time_running, 14513 &parent_event->child_total_time_running); 14514 } 14515 14516 static void 14517 perf_event_exit_event(struct perf_event *event, 14518 struct perf_event_context *ctx, 14519 struct task_struct *task, 14520 bool revoke) 14521 { 14522 struct perf_event *parent_event = event->parent; 14523 unsigned long detach_flags = DETACH_EXIT; 14524 unsigned int attach_state; 14525 14526 if (parent_event) { 14527 /* 14528 * Do not destroy the 'original' grouping; because of the 14529 * context switch optimization the original events could've 14530 * ended up in a random child task. 14531 * 14532 * If we were to destroy the original group, all group related 14533 * operations would cease to function properly after this 14534 * random child dies. 14535 * 14536 * Do destroy all inherited groups, we don't care about those 14537 * and being thorough is better. 14538 */ 14539 detach_flags |= DETACH_GROUP | DETACH_CHILD; 14540 mutex_lock(&parent_event->child_mutex); 14541 /* PERF_ATTACH_ITRACE might be set concurrently */ 14542 attach_state = READ_ONCE(event->attach_state); 14543 14544 if (attach_state & PERF_ATTACH_CHILD) 14545 sync_child_event(event, task); 14546 } 14547 14548 if (revoke) 14549 detach_flags |= DETACH_GROUP | DETACH_REVOKE; 14550 14551 perf_remove_from_context(event, detach_flags); 14552 /* 14553 * Child events can be freed. 14554 */ 14555 if (parent_event) { 14556 mutex_unlock(&parent_event->child_mutex); 14557 14558 /* 14559 * Match the refcount initialization. Make sure it doesn't happen 14560 * twice if pmu_detach_event() calls it on an already exited task. 14561 */ 14562 if (attach_state & PERF_ATTACH_CHILD) { 14563 /* 14564 * Kick perf_poll() for is_event_hup(); 14565 */ 14566 perf_event_wakeup(parent_event); 14567 /* 14568 * pmu_detach_event() will have an extra refcount. 14569 * perf_pending_task() might have one too. 14570 */ 14571 put_event(event); 14572 } 14573 14574 return; 14575 } 14576 14577 /* 14578 * Parent events are governed by their filedesc, retain them. 14579 */ 14580 perf_event_wakeup(event); 14581 } 14582 14583 static void perf_event_exit_task_context(struct task_struct *task, bool exit) 14584 { 14585 struct perf_event_context *ctx, *clone_ctx = NULL; 14586 struct perf_event *child_event, *next; 14587 14588 ctx = perf_pin_task_context(task); 14589 if (!ctx) 14590 return; 14591 14592 /* 14593 * In order to reduce the amount of tricky in ctx tear-down, we hold 14594 * ctx::mutex over the entire thing. This serializes against almost 14595 * everything that wants to access the ctx. 14596 * 14597 * The exception is sys_perf_event_open() / 14598 * perf_event_create_kernel_count() which does find_get_context() 14599 * without ctx::mutex (it cannot because of the move_group double mutex 14600 * lock thing). See the comments in perf_install_in_context(). 14601 */ 14602 mutex_lock(&ctx->mutex); 14603 14604 /* 14605 * In a single ctx::lock section, de-schedule the events and detach the 14606 * context from the task such that we cannot ever get it scheduled back 14607 * in. 14608 */ 14609 raw_spin_lock_irq(&ctx->lock); 14610 if (exit) 14611 task_ctx_sched_out(ctx, NULL, EVENT_ALL); 14612 14613 /* 14614 * Now that the context is inactive, destroy the task <-> ctx relation 14615 * and mark the context dead. 14616 */ 14617 RCU_INIT_POINTER(task->perf_event_ctxp, NULL); 14618 put_ctx(ctx); /* cannot be last */ 14619 WRITE_ONCE(ctx->task, TASK_TOMBSTONE); 14620 put_task_struct(task); /* cannot be last */ 14621 14622 clone_ctx = unclone_ctx(ctx); 14623 raw_spin_unlock_irq(&ctx->lock); 14624 14625 if (clone_ctx) 14626 put_ctx(clone_ctx); 14627 14628 /* 14629 * Report the task dead after unscheduling the events so that we 14630 * won't get any samples after PERF_RECORD_EXIT. We can however still 14631 * get a few PERF_RECORD_READ events. 14632 */ 14633 if (exit) 14634 perf_event_task(task, ctx, 0); 14635 14636 list_for_each_entry_safe(child_event, next, &ctx->event_list, event_entry) 14637 perf_event_exit_event(child_event, ctx, exit ? task : NULL, false); 14638 14639 mutex_unlock(&ctx->mutex); 14640 14641 if (!exit) { 14642 /* 14643 * perf_event_release_kernel() could still have a reference on 14644 * this context. In that case we must wait for these events to 14645 * have been freed (in particular all their references to this 14646 * task must've been dropped). 14647 * 14648 * Without this copy_process() will unconditionally free this 14649 * task (irrespective of its reference count) and 14650 * _free_event()'s put_task_struct(event->hw.target) will be a 14651 * use-after-free. 14652 * 14653 * Wait for all events to drop their context reference. 14654 */ 14655 wait_var_event(&ctx->refcount, 14656 refcount_read(&ctx->refcount) == 1); 14657 } 14658 put_ctx(ctx); 14659 } 14660 14661 /* 14662 * When a task exits, feed back event values to parent events. 14663 * 14664 * Can be called with exec_update_lock held when called from 14665 * setup_new_exec(). 14666 */ 14667 void perf_event_exit_task(struct task_struct *task) 14668 { 14669 struct perf_event *event, *tmp; 14670 14671 WARN_ON_ONCE(task != current); 14672 14673 mutex_lock(&task->perf_event_mutex); 14674 list_for_each_entry_safe(event, tmp, &task->perf_event_list, 14675 owner_entry) { 14676 list_del_init(&event->owner_entry); 14677 14678 /* 14679 * Ensure the list deletion is visible before we clear 14680 * the owner, closes a race against perf_release() where 14681 * we need to serialize on the owner->perf_event_mutex. 14682 */ 14683 smp_store_release(&event->owner, NULL); 14684 } 14685 mutex_unlock(&task->perf_event_mutex); 14686 14687 perf_event_exit_task_context(task, true); 14688 14689 /* 14690 * The perf_event_exit_task_context calls perf_event_task 14691 * with task's task_ctx, which generates EXIT events for 14692 * task contexts and sets task->perf_event_ctxp[] to NULL. 14693 * At this point we need to send EXIT events to cpu contexts. 14694 */ 14695 perf_event_task(task, NULL, 0); 14696 14697 /* 14698 * Detach the perf_ctx_data for the system-wide event. 14699 * 14700 * Done without holding global_ctx_data_rwsem; typically 14701 * attach_global_ctx_data() will skip over this task, but otherwise 14702 * attach_task_ctx_data() will observe PF_EXITING. 14703 */ 14704 detach_task_ctx_data(task); 14705 } 14706 14707 /* 14708 * Free a context as created by inheritance by perf_event_init_task() below, 14709 * used by fork() in case of fail. 14710 * 14711 * Even though the task has never lived, the context and events have been 14712 * exposed through the child_list, so we must take care tearing it all down. 14713 */ 14714 void perf_event_free_task(struct task_struct *task) 14715 { 14716 perf_event_exit_task_context(task, false); 14717 } 14718 14719 void perf_event_delayed_put(struct task_struct *task) 14720 { 14721 WARN_ON_ONCE(task->perf_event_ctxp); 14722 } 14723 14724 struct file *perf_event_get(unsigned int fd) 14725 { 14726 struct file *file = fget(fd); 14727 if (!file) 14728 return ERR_PTR(-EBADF); 14729 14730 if (file->f_op != &perf_fops) { 14731 fput(file); 14732 return ERR_PTR(-EBADF); 14733 } 14734 14735 return file; 14736 } 14737 14738 const struct perf_event *perf_get_event(struct file *file) 14739 { 14740 if (file->f_op != &perf_fops) 14741 return ERR_PTR(-EINVAL); 14742 14743 return file->private_data; 14744 } 14745 14746 const struct perf_event_attr *perf_event_attrs(struct perf_event *event) 14747 { 14748 if (!event) 14749 return ERR_PTR(-EINVAL); 14750 14751 return &event->attr; 14752 } 14753 14754 int perf_allow_kernel(void) 14755 { 14756 if (sysctl_perf_event_paranoid > 1 && !perfmon_capable()) 14757 return -EACCES; 14758 14759 return security_perf_event_open(PERF_SECURITY_KERNEL); 14760 } 14761 EXPORT_SYMBOL_GPL(perf_allow_kernel); 14762 14763 /* 14764 * Inherit an event from parent task to child task. 14765 * 14766 * Returns: 14767 * - valid pointer on success 14768 * - NULL for orphaned events 14769 * - IS_ERR() on error 14770 */ 14771 static struct perf_event * 14772 inherit_event(struct perf_event *parent_event, 14773 struct task_struct *parent, 14774 struct perf_event_context *parent_ctx, 14775 struct task_struct *child, 14776 struct perf_event *group_leader, 14777 struct perf_event_context *child_ctx) 14778 { 14779 enum perf_event_state parent_state = parent_event->state; 14780 struct perf_event_pmu_context *pmu_ctx; 14781 struct perf_event *child_event; 14782 unsigned long flags; 14783 14784 /* 14785 * Instead of creating recursive hierarchies of events, 14786 * we link inherited events back to the original parent, 14787 * which has a filp for sure, which we use as the reference 14788 * count: 14789 */ 14790 if (parent_event->parent) 14791 parent_event = parent_event->parent; 14792 14793 if (parent_event->state <= PERF_EVENT_STATE_REVOKED) 14794 return NULL; 14795 14796 /* 14797 * Event creation should be under SRCU, see perf_pmu_unregister(). 14798 */ 14799 guard(srcu)(&pmus_srcu); 14800 14801 child_event = perf_event_alloc(&parent_event->attr, 14802 parent_event->cpu, 14803 child, 14804 group_leader, parent_event, 14805 NULL, NULL, -1); 14806 if (IS_ERR(child_event)) 14807 return child_event; 14808 14809 get_ctx(child_ctx); 14810 child_event->ctx = child_ctx; 14811 14812 pmu_ctx = find_get_pmu_context(parent_event->pmu_ctx->pmu, child_ctx, child_event); 14813 if (IS_ERR(pmu_ctx)) { 14814 free_event(child_event); 14815 return ERR_CAST(pmu_ctx); 14816 } 14817 child_event->pmu_ctx = pmu_ctx; 14818 14819 /* 14820 * is_orphaned_event() and list_add_tail(&parent_event->child_list) 14821 * must be under the same lock in order to serialize against 14822 * perf_event_release_kernel(), such that either we must observe 14823 * is_orphaned_event() or they will observe us on the child_list. 14824 */ 14825 mutex_lock(&parent_event->child_mutex); 14826 if (is_orphaned_event(parent_event) || 14827 !atomic_long_inc_not_zero(&parent_event->refcount)) { 14828 mutex_unlock(&parent_event->child_mutex); 14829 free_event(child_event); 14830 return NULL; 14831 } 14832 14833 /* 14834 * Make the child state follow the state of the parent event, 14835 * not its attr.disabled bit. We hold the parent's mutex, 14836 * so we won't race with perf_event_{en, dis}able_family. 14837 */ 14838 if (parent_state >= PERF_EVENT_STATE_INACTIVE) 14839 child_event->state = PERF_EVENT_STATE_INACTIVE; 14840 else 14841 child_event->state = PERF_EVENT_STATE_OFF; 14842 14843 if (parent_event->attr.freq) { 14844 u64 sample_period = parent_event->hw.sample_period; 14845 struct hw_perf_event *hwc = &child_event->hw; 14846 14847 hwc->sample_period = sample_period; 14848 hwc->last_period = sample_period; 14849 14850 local64_set(&hwc->period_left, sample_period); 14851 } 14852 14853 child_event->overflow_handler = parent_event->overflow_handler; 14854 child_event->overflow_handler_context 14855 = parent_event->overflow_handler_context; 14856 14857 /* 14858 * Precalculate sample_data sizes 14859 */ 14860 perf_event__header_size(child_event); 14861 perf_event__id_header_size(child_event); 14862 14863 /* 14864 * Link it up in the child's context: 14865 */ 14866 raw_spin_lock_irqsave(&child_ctx->lock, flags); 14867 add_event_to_ctx(child_event, child_ctx); 14868 child_event->attach_state |= PERF_ATTACH_CHILD; 14869 raw_spin_unlock_irqrestore(&child_ctx->lock, flags); 14870 14871 /* 14872 * Link this into the parent event's child list 14873 */ 14874 list_add_tail(&child_event->child_list, &parent_event->child_list); 14875 mutex_unlock(&parent_event->child_mutex); 14876 14877 return child_event; 14878 } 14879 14880 /* 14881 * Inherits an event group. 14882 * 14883 * This will quietly suppress orphaned events; !inherit_event() is not an error. 14884 * This matches with perf_event_release_kernel() removing all child events. 14885 * 14886 * Returns: 14887 * - 0 on success 14888 * - <0 on error 14889 */ 14890 static int inherit_group(struct perf_event *parent_event, 14891 struct task_struct *parent, 14892 struct perf_event_context *parent_ctx, 14893 struct task_struct *child, 14894 struct perf_event_context *child_ctx) 14895 { 14896 struct perf_event *leader; 14897 struct perf_event *sub; 14898 struct perf_event *child_ctr; 14899 14900 leader = inherit_event(parent_event, parent, parent_ctx, 14901 child, NULL, child_ctx); 14902 if (IS_ERR(leader)) 14903 return PTR_ERR(leader); 14904 /* 14905 * @leader can be NULL here because of is_orphaned_event(). In this 14906 * case inherit_event() will create individual events, similar to what 14907 * perf_group_detach() would do anyway. 14908 */ 14909 for_each_sibling_event(sub, parent_event) { 14910 child_ctr = inherit_event(sub, parent, parent_ctx, 14911 child, leader, child_ctx); 14912 if (IS_ERR(child_ctr)) 14913 return PTR_ERR(child_ctr); 14914 14915 if (sub->aux_event == parent_event && child_ctr && 14916 !perf_get_aux_event(child_ctr, leader)) 14917 return -EINVAL; 14918 } 14919 if (leader) 14920 leader->group_generation = parent_event->group_generation; 14921 return 0; 14922 } 14923 14924 /* 14925 * Creates the child task context and tries to inherit the event-group. 14926 * 14927 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave 14928 * inherited_all set when we 'fail' to inherit an orphaned event; this is 14929 * consistent with perf_event_release_kernel() removing all child events. 14930 * 14931 * Returns: 14932 * - 0 on success 14933 * - <0 on error 14934 */ 14935 static int 14936 inherit_task_group(struct perf_event *event, struct task_struct *parent, 14937 struct perf_event_context *parent_ctx, 14938 struct task_struct *child, 14939 u64 clone_flags, int *inherited_all) 14940 { 14941 struct perf_event_context *child_ctx; 14942 int ret; 14943 14944 if (!event->attr.inherit || 14945 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) || 14946 /* Do not inherit if sigtrap and signal handlers were cleared. */ 14947 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) { 14948 *inherited_all = 0; 14949 return 0; 14950 } 14951 14952 child_ctx = child->perf_event_ctxp; 14953 if (!child_ctx) { 14954 /* 14955 * This is executed from the parent task context, so 14956 * inherit events that have been marked for cloning. 14957 * First allocate and initialize a context for the 14958 * child. 14959 */ 14960 child_ctx = alloc_perf_context(child); 14961 if (!child_ctx) 14962 return -ENOMEM; 14963 14964 child->perf_event_ctxp = child_ctx; 14965 } 14966 14967 ret = inherit_group(event, parent, parent_ctx, child, child_ctx); 14968 if (ret) 14969 *inherited_all = 0; 14970 14971 return ret; 14972 } 14973 14974 /* 14975 * Initialize the perf_event context in task_struct 14976 */ 14977 static int perf_event_init_context(struct task_struct *child, u64 clone_flags) 14978 { 14979 struct perf_event_context *child_ctx, *parent_ctx; 14980 struct perf_event_context *cloned_ctx; 14981 struct perf_event *event; 14982 struct task_struct *parent = current; 14983 int inherited_all = 1; 14984 unsigned long flags; 14985 int ret = 0; 14986 14987 if (likely(!parent->perf_event_ctxp)) 14988 return 0; 14989 14990 /* 14991 * If the parent's context is a clone, pin it so it won't get 14992 * swapped under us. 14993 */ 14994 parent_ctx = perf_pin_task_context(parent); 14995 if (!parent_ctx) 14996 return 0; 14997 14998 /* 14999 * No need to check if parent_ctx != NULL here; since we saw 15000 * it non-NULL earlier, the only reason for it to become NULL 15001 * is if we exit, and since we're currently in the middle of 15002 * a fork we can't be exiting at the same time. 15003 */ 15004 15005 /* 15006 * Lock the parent list. No need to lock the child - not PID 15007 * hashed yet and not running, so nobody can access it. 15008 */ 15009 mutex_lock(&parent_ctx->mutex); 15010 15011 /* 15012 * We dont have to disable NMIs - we are only looking at 15013 * the list, not manipulating it: 15014 */ 15015 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) { 15016 ret = inherit_task_group(event, parent, parent_ctx, 15017 child, clone_flags, &inherited_all); 15018 if (ret) 15019 goto out_unlock; 15020 } 15021 15022 /* 15023 * We can't hold ctx->lock when iterating the ->flexible_group list due 15024 * to allocations, but we need to prevent rotation because 15025 * rotate_ctx() will change the list from interrupt context. 15026 */ 15027 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 15028 parent_ctx->rotate_disable = 1; 15029 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 15030 15031 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) { 15032 ret = inherit_task_group(event, parent, parent_ctx, 15033 child, clone_flags, &inherited_all); 15034 if (ret) 15035 goto out_unlock; 15036 } 15037 15038 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 15039 parent_ctx->rotate_disable = 0; 15040 15041 child_ctx = child->perf_event_ctxp; 15042 15043 if (child_ctx && inherited_all) { 15044 /* 15045 * Mark the child context as a clone of the parent 15046 * context, or of whatever the parent is a clone of. 15047 * 15048 * Note that if the parent is a clone, the holding of 15049 * parent_ctx->lock avoids it from being uncloned. 15050 */ 15051 cloned_ctx = parent_ctx->parent_ctx; 15052 if (cloned_ctx) { 15053 child_ctx->parent_ctx = cloned_ctx; 15054 child_ctx->parent_gen = parent_ctx->parent_gen; 15055 } else { 15056 child_ctx->parent_ctx = parent_ctx; 15057 child_ctx->parent_gen = parent_ctx->generation; 15058 } 15059 get_ctx(child_ctx->parent_ctx); 15060 } 15061 15062 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 15063 out_unlock: 15064 mutex_unlock(&parent_ctx->mutex); 15065 15066 perf_unpin_context(parent_ctx); 15067 put_ctx(parent_ctx); 15068 15069 return ret; 15070 } 15071 15072 /* 15073 * Initialize the perf_event context in task_struct 15074 */ 15075 int perf_event_init_task(struct task_struct *child, u64 clone_flags) 15076 { 15077 int ret; 15078 15079 memset(child->perf_recursion, 0, sizeof(child->perf_recursion)); 15080 child->perf_event_ctxp = NULL; 15081 mutex_init(&child->perf_event_mutex); 15082 INIT_LIST_HEAD(&child->perf_event_list); 15083 child->perf_ctx_data = NULL; 15084 15085 ret = perf_event_init_context(child, clone_flags); 15086 if (ret) { 15087 perf_event_free_task(child); 15088 return ret; 15089 } 15090 15091 return 0; 15092 } 15093 15094 static void __init perf_event_init_all_cpus(void) 15095 { 15096 struct swevent_htable *swhash; 15097 struct perf_cpu_context *cpuctx; 15098 int cpu; 15099 15100 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL); 15101 zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL); 15102 zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL); 15103 zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL); 15104 zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL); 15105 zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL); 15106 15107 15108 for_each_possible_cpu(cpu) { 15109 swhash = &per_cpu(swevent_htable, cpu); 15110 mutex_init(&swhash->hlist_mutex); 15111 15112 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu)); 15113 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu)); 15114 15115 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu)); 15116 15117 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15118 __perf_event_init_context(&cpuctx->ctx); 15119 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); 15120 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); 15121 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask); 15122 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default); 15123 cpuctx->heap = cpuctx->heap_default; 15124 } 15125 } 15126 15127 static void perf_swevent_init_cpu(unsigned int cpu) 15128 { 15129 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 15130 15131 mutex_lock(&swhash->hlist_mutex); 15132 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) { 15133 struct swevent_hlist *hlist; 15134 15135 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); 15136 WARN_ON(!hlist); 15137 rcu_assign_pointer(swhash->swevent_hlist, hlist); 15138 } 15139 mutex_unlock(&swhash->hlist_mutex); 15140 } 15141 15142 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE 15143 static void __perf_event_exit_context(void *__info) 15144 { 15145 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 15146 struct perf_event_context *ctx = __info; 15147 struct perf_event *event; 15148 15149 raw_spin_lock(&ctx->lock); 15150 ctx_sched_out(ctx, NULL, EVENT_TIME); 15151 list_for_each_entry(event, &ctx->event_list, event_entry) 15152 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP); 15153 raw_spin_unlock(&ctx->lock); 15154 } 15155 15156 static void perf_event_clear_cpumask(unsigned int cpu) 15157 { 15158 int target[PERF_PMU_MAX_SCOPE]; 15159 unsigned int scope; 15160 struct pmu *pmu; 15161 15162 cpumask_clear_cpu(cpu, perf_online_mask); 15163 15164 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15165 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 15166 struct cpumask *pmu_cpumask = perf_scope_cpumask(scope); 15167 15168 target[scope] = -1; 15169 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 15170 continue; 15171 15172 if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask)) 15173 continue; 15174 target[scope] = cpumask_any_but(cpumask, cpu); 15175 if (target[scope] < nr_cpu_ids) 15176 cpumask_set_cpu(target[scope], pmu_cpumask); 15177 } 15178 15179 /* migrate */ 15180 list_for_each_entry(pmu, &pmus, entry) { 15181 if (pmu->scope == PERF_PMU_SCOPE_NONE || 15182 WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE)) 15183 continue; 15184 15185 if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids) 15186 perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]); 15187 } 15188 } 15189 15190 static void perf_event_exit_cpu_context(int cpu) 15191 { 15192 struct perf_cpu_context *cpuctx; 15193 struct perf_event_context *ctx; 15194 15195 // XXX simplify cpuctx->online 15196 mutex_lock(&pmus_lock); 15197 /* 15198 * Clear the cpumasks, and migrate to other CPUs if possible. 15199 * Must be invoked before the __perf_event_exit_context. 15200 */ 15201 perf_event_clear_cpumask(cpu); 15202 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15203 ctx = &cpuctx->ctx; 15204 15205 mutex_lock(&ctx->mutex); 15206 if (ctx->nr_events) 15207 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1); 15208 cpuctx->online = 0; 15209 mutex_unlock(&ctx->mutex); 15210 mutex_unlock(&pmus_lock); 15211 } 15212 #else 15213 15214 static void perf_event_exit_cpu_context(int cpu) { } 15215 15216 #endif 15217 15218 static void perf_event_setup_cpumask(unsigned int cpu) 15219 { 15220 struct cpumask *pmu_cpumask; 15221 unsigned int scope; 15222 15223 /* 15224 * Early boot stage, the cpumask hasn't been set yet. 15225 * The perf_online_<domain>_masks includes the first CPU of each domain. 15226 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks. 15227 */ 15228 if (cpumask_empty(perf_online_mask)) { 15229 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15230 pmu_cpumask = perf_scope_cpumask(scope); 15231 if (WARN_ON_ONCE(!pmu_cpumask)) 15232 continue; 15233 cpumask_set_cpu(cpu, pmu_cpumask); 15234 } 15235 goto end; 15236 } 15237 15238 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15239 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 15240 15241 pmu_cpumask = perf_scope_cpumask(scope); 15242 15243 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 15244 continue; 15245 15246 if (!cpumask_empty(cpumask) && 15247 cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids) 15248 cpumask_set_cpu(cpu, pmu_cpumask); 15249 } 15250 end: 15251 cpumask_set_cpu(cpu, perf_online_mask); 15252 } 15253 15254 int perf_event_init_cpu(unsigned int cpu) 15255 { 15256 struct perf_cpu_context *cpuctx; 15257 struct perf_event_context *ctx; 15258 15259 perf_swevent_init_cpu(cpu); 15260 15261 mutex_lock(&pmus_lock); 15262 perf_event_setup_cpumask(cpu); 15263 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15264 ctx = &cpuctx->ctx; 15265 15266 mutex_lock(&ctx->mutex); 15267 cpuctx->online = 1; 15268 mutex_unlock(&ctx->mutex); 15269 mutex_unlock(&pmus_lock); 15270 15271 return 0; 15272 } 15273 15274 int perf_event_exit_cpu(unsigned int cpu) 15275 { 15276 perf_event_exit_cpu_context(cpu); 15277 return 0; 15278 } 15279 15280 static int 15281 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v) 15282 { 15283 int cpu; 15284 15285 for_each_online_cpu(cpu) 15286 perf_event_exit_cpu(cpu); 15287 15288 return NOTIFY_OK; 15289 } 15290 15291 /* 15292 * Run the perf reboot notifier at the very last possible moment so that 15293 * the generic watchdog code runs as long as possible. 15294 */ 15295 static struct notifier_block perf_reboot_notifier = { 15296 .notifier_call = perf_reboot, 15297 .priority = INT_MIN, 15298 }; 15299 15300 void __init perf_event_init(void) 15301 { 15302 int ret; 15303 15304 idr_init(&pmu_idr); 15305 15306 unwind_deferred_init(&perf_unwind_work, 15307 perf_unwind_deferred_callback); 15308 15309 perf_event_init_all_cpus(); 15310 init_srcu_struct(&pmus_srcu); 15311 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE); 15312 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1); 15313 perf_pmu_register(&perf_task_clock, "task_clock", -1); 15314 perf_tp_register(); 15315 perf_event_init_cpu(smp_processor_id()); 15316 register_reboot_notifier(&perf_reboot_notifier); 15317 15318 ret = init_hw_breakpoint(); 15319 WARN(ret, "hw_breakpoint initialization failed with: %d", ret); 15320 15321 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC); 15322 15323 /* 15324 * Build time assertion that we keep the data_head at the intended 15325 * location. IOW, validation we got the __reserved[] size right. 15326 */ 15327 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head)) 15328 != 1024); 15329 } 15330 15331 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr, 15332 char *page) 15333 { 15334 struct perf_pmu_events_attr *pmu_attr = 15335 container_of(attr, struct perf_pmu_events_attr, attr); 15336 15337 if (pmu_attr->event_str) 15338 return sprintf(page, "%s\n", pmu_attr->event_str); 15339 15340 return 0; 15341 } 15342 EXPORT_SYMBOL_GPL(perf_event_sysfs_show); 15343 15344 static int __init perf_event_sysfs_init(void) 15345 { 15346 struct pmu *pmu; 15347 int ret; 15348 15349 mutex_lock(&pmus_lock); 15350 15351 ret = bus_register(&pmu_bus); 15352 if (ret) 15353 goto unlock; 15354 15355 list_for_each_entry(pmu, &pmus, entry) { 15356 if (pmu->dev) 15357 continue; 15358 15359 ret = pmu_dev_alloc(pmu); 15360 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret); 15361 } 15362 pmu_bus_running = 1; 15363 ret = 0; 15364 15365 unlock: 15366 mutex_unlock(&pmus_lock); 15367 15368 return ret; 15369 } 15370 device_initcall(perf_event_sysfs_init); 15371 15372 #ifdef CONFIG_CGROUP_PERF 15373 static struct cgroup_subsys_state * 15374 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 15375 { 15376 struct perf_cgroup *jc; 15377 15378 jc = kzalloc_obj(*jc); 15379 if (!jc) 15380 return ERR_PTR(-ENOMEM); 15381 15382 jc->info = alloc_percpu(struct perf_cgroup_info); 15383 if (!jc->info) { 15384 kfree(jc); 15385 return ERR_PTR(-ENOMEM); 15386 } 15387 15388 return &jc->css; 15389 } 15390 15391 static void perf_cgroup_css_free(struct cgroup_subsys_state *css) 15392 { 15393 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css); 15394 15395 free_percpu(jc->info); 15396 kfree(jc); 15397 } 15398 15399 static int perf_cgroup_css_online(struct cgroup_subsys_state *css) 15400 { 15401 perf_event_cgroup(css->cgroup); 15402 return 0; 15403 } 15404 15405 static int __perf_cgroup_move(void *info) 15406 { 15407 struct task_struct *task = info; 15408 15409 preempt_disable(); 15410 perf_cgroup_switch(task); 15411 preempt_enable(); 15412 15413 return 0; 15414 } 15415 15416 static void perf_cgroup_attach(struct cgroup_taskset *tset) 15417 { 15418 struct task_struct *task; 15419 struct cgroup_subsys_state *css; 15420 15421 cgroup_taskset_for_each(task, css, tset) 15422 task_function_call(task, __perf_cgroup_move, task); 15423 } 15424 15425 struct cgroup_subsys perf_event_cgrp_subsys = { 15426 .css_alloc = perf_cgroup_css_alloc, 15427 .css_free = perf_cgroup_css_free, 15428 .css_online = perf_cgroup_css_online, 15429 .attach = perf_cgroup_attach, 15430 /* 15431 * Implicitly enable on dfl hierarchy so that perf events can 15432 * always be filtered by cgroup2 path as long as perf_event 15433 * controller is not mounted on a legacy hierarchy. 15434 */ 15435 .implicit_on_dfl = true, 15436 .threaded = true, 15437 }; 15438 #endif /* CONFIG_CGROUP_PERF */ 15439 15440 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t); 15441