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