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