1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Performance events core code: 4 * 5 * Copyright (C) 2008 Linutronix GmbH, Thomas Gleixner <tglx@kernel.org> 6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar 7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra 8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com> 9 */ 10 11 #include <linux/fs.h> 12 #include <linux/mm.h> 13 #include <linux/cpu.h> 14 #include <linux/smp.h> 15 #include <linux/idr.h> 16 #include <linux/file.h> 17 #include <linux/poll.h> 18 #include <linux/slab.h> 19 #include <linux/hash.h> 20 #include <linux/tick.h> 21 #include <linux/sysfs.h> 22 #include <linux/dcache.h> 23 #include <linux/percpu.h> 24 #include <linux/ptrace.h> 25 #include <linux/reboot.h> 26 #include <linux/vmstat.h> 27 #include <linux/device.h> 28 #include <linux/export.h> 29 #include <linux/vmalloc.h> 30 #include <linux/hardirq.h> 31 #include <linux/hugetlb.h> 32 #include <linux/rculist.h> 33 #include <linux/uaccess.h> 34 #include <linux/syscalls.h> 35 #include <linux/anon_inodes.h> 36 #include <linux/kernel_stat.h> 37 #include <linux/cgroup.h> 38 #include <linux/perf_event.h> 39 #include <linux/trace_events.h> 40 #include <linux/hw_breakpoint.h> 41 #include <linux/mm_types.h> 42 #include <linux/module.h> 43 #include <linux/mman.h> 44 #include <linux/compat.h> 45 #include <linux/bpf.h> 46 #include <linux/filter.h> 47 #include <linux/namei.h> 48 #include <linux/parser.h> 49 #include <linux/sched/clock.h> 50 #include <linux/sched/mm.h> 51 #include <linux/proc_ns.h> 52 #include <linux/mount.h> 53 #include <linux/min_heap.h> 54 #include <linux/highmem.h> 55 #include <linux/pgtable.h> 56 #include <linux/buildid.h> 57 #include <linux/task_work.h> 58 #include <linux/percpu-rwsem.h> 59 #include <linux/unwind_deferred.h> 60 #include <linux/kvm_types.h> 61 #include <linux/seq_file.h> 62 63 #include "internal.h" 64 65 #include <asm/irq_regs.h> 66 67 typedef int (*remote_function_f)(void *); 68 69 struct remote_function_call { 70 struct task_struct *p; 71 remote_function_f func; 72 void *info; 73 int ret; 74 }; 75 76 static void remote_function(void *data) 77 { 78 struct remote_function_call *tfc = data; 79 struct task_struct *p = tfc->p; 80 81 if (p) { 82 /* -EAGAIN */ 83 if (task_cpu(p) != smp_processor_id()) 84 return; 85 86 /* 87 * Now that we're on right CPU with IRQs disabled, we can test 88 * if we hit the right task without races. 89 */ 90 91 tfc->ret = -ESRCH; /* No such (running) process */ 92 if (p != current) 93 return; 94 } 95 96 tfc->ret = tfc->func(tfc->info); 97 } 98 99 /** 100 * task_function_call - call a function on the cpu on which a task runs 101 * @p: the task to evaluate 102 * @func: the function to be called 103 * @info: the function call argument 104 * 105 * Calls the function @func when the task is currently running. This might 106 * be on the current CPU, which just calls the function directly. This will 107 * retry due to any failures in smp_call_function_single(), such as if the 108 * task_cpu() goes offline concurrently. 109 * 110 * returns @func return value or -ESRCH or -ENXIO when the process isn't running 111 */ 112 static int 113 task_function_call(struct task_struct *p, remote_function_f func, void *info) 114 { 115 struct remote_function_call data = { 116 .p = p, 117 .func = func, 118 .info = info, 119 .ret = -EAGAIN, 120 }; 121 int ret; 122 123 for (;;) { 124 ret = smp_call_function_single(task_cpu(p), remote_function, 125 &data, 1); 126 if (!ret) 127 ret = data.ret; 128 129 if (ret != -EAGAIN) 130 break; 131 132 cond_resched(); 133 } 134 135 return ret; 136 } 137 138 /** 139 * cpu_function_call - call a function on the cpu 140 * @cpu: target cpu to queue this function 141 * @func: the function to be called 142 * @info: the function call argument 143 * 144 * Calls the function @func on the remote cpu. 145 * 146 * returns: @func return value or -ENXIO when the cpu is offline 147 */ 148 static int cpu_function_call(int cpu, remote_function_f func, void *info) 149 { 150 struct remote_function_call data = { 151 .p = NULL, 152 .func = func, 153 .info = info, 154 .ret = -ENXIO, /* No such CPU */ 155 }; 156 157 smp_call_function_single(cpu, remote_function, &data, 1); 158 159 return data.ret; 160 } 161 162 enum event_type_t { 163 EVENT_FLEXIBLE = 0x01, 164 EVENT_PINNED = 0x02, 165 EVENT_TIME = 0x04, 166 EVENT_FROZEN = 0x08, 167 /* see ctx_resched() for details */ 168 EVENT_CPU = 0x10, 169 EVENT_CGROUP = 0x20, 170 171 /* 172 * EVENT_GUEST is set when scheduling in/out events between the host 173 * and a guest with a mediated vPMU. Among other things, EVENT_GUEST 174 * is used: 175 * 176 * - In for_each_epc() to skip PMUs that don't support events in a 177 * MEDIATED_VPMU guest, i.e. don't need to be context switched. 178 * - To indicate the start/end point of the events in a guest. Guest 179 * running time is deducted for host-only (exclude_guest) events. 180 */ 181 EVENT_GUEST = 0x40, 182 EVENT_FLAGS = EVENT_CGROUP | EVENT_GUEST, 183 /* compound helpers */ 184 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED, 185 EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN, 186 }; 187 188 static inline void __perf_ctx_lock(struct perf_event_context *ctx) 189 { 190 raw_spin_lock(&ctx->lock); 191 WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN); 192 } 193 194 static void perf_ctx_lock(struct perf_cpu_context *cpuctx, 195 struct perf_event_context *ctx) 196 { 197 __perf_ctx_lock(&cpuctx->ctx); 198 if (ctx) 199 __perf_ctx_lock(ctx); 200 } 201 202 static inline void __perf_ctx_unlock(struct perf_event_context *ctx) 203 { 204 /* 205 * If ctx_sched_in() didn't again set any ALL flags, clean up 206 * after ctx_sched_out() by clearing is_active. 207 */ 208 if (ctx->is_active & EVENT_FROZEN) { 209 if (!(ctx->is_active & EVENT_ALL)) 210 ctx->is_active = 0; 211 else 212 ctx->is_active &= ~EVENT_FROZEN; 213 } 214 raw_spin_unlock(&ctx->lock); 215 } 216 217 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx, 218 struct perf_event_context *ctx) 219 { 220 if (ctx) 221 __perf_ctx_unlock(ctx); 222 __perf_ctx_unlock(&cpuctx->ctx); 223 } 224 225 typedef struct { 226 struct perf_cpu_context *cpuctx; 227 struct perf_event_context *ctx; 228 } class_perf_ctx_lock_t; 229 230 static inline void class_perf_ctx_lock_destructor(class_perf_ctx_lock_t *_T) 231 { perf_ctx_unlock(_T->cpuctx, _T->ctx); } 232 233 static inline class_perf_ctx_lock_t 234 class_perf_ctx_lock_constructor(struct perf_cpu_context *cpuctx, 235 struct perf_event_context *ctx) 236 { perf_ctx_lock(cpuctx, ctx); return (class_perf_ctx_lock_t){ cpuctx, ctx }; } 237 238 #define TASK_TOMBSTONE ((void *)-1L) 239 240 static bool is_kernel_event(struct perf_event *event) 241 { 242 return READ_ONCE(event->owner) == TASK_TOMBSTONE; 243 } 244 245 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context); 246 247 struct perf_event_context *perf_cpu_task_ctx(void) 248 { 249 lockdep_assert_irqs_disabled(); 250 return this_cpu_ptr(&perf_cpu_context)->task_ctx; 251 } 252 253 /* 254 * On task ctx scheduling... 255 * 256 * When !ctx->nr_events a task context will not be scheduled. This means 257 * we can disable the scheduler hooks (for performance) without leaving 258 * pending task ctx state. 259 * 260 * This however results in two special cases: 261 * 262 * - removing the last event from a task ctx; this is relatively straight 263 * forward and is done in __perf_remove_from_context. 264 * 265 * - adding the first event to a task ctx; this is tricky because we cannot 266 * rely on ctx->is_active and therefore cannot use event_function_call(). 267 * See perf_install_in_context(). 268 * 269 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set. 270 */ 271 272 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *, 273 struct perf_event_context *, void *); 274 275 struct event_function_struct { 276 struct perf_event *event; 277 event_f func; 278 void *data; 279 }; 280 281 static int event_function(void *info) 282 { 283 struct event_function_struct *efs = info; 284 struct perf_event *event = efs->event; 285 struct perf_event_context *ctx = event->ctx; 286 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 287 struct perf_event_context *task_ctx = cpuctx->task_ctx; 288 int ret = 0; 289 290 lockdep_assert_irqs_disabled(); 291 292 perf_ctx_lock(cpuctx, task_ctx); 293 /* 294 * Since we do the IPI call without holding ctx->lock things can have 295 * changed, double check we hit the task we set out to hit. 296 */ 297 if (ctx->task) { 298 if (ctx->task != current) { 299 ret = -ESRCH; 300 goto unlock; 301 } 302 303 /* 304 * We only use event_function_call() on established contexts, 305 * and event_function() is only ever called when active (or 306 * rather, we'll have bailed in task_function_call() or the 307 * above ctx->task != current test), therefore we must have 308 * ctx->is_active here. 309 */ 310 WARN_ON_ONCE(!ctx->is_active); 311 /* 312 * And since we have ctx->is_active, cpuctx->task_ctx must 313 * match. 314 */ 315 WARN_ON_ONCE(task_ctx != ctx); 316 } else { 317 WARN_ON_ONCE(&cpuctx->ctx != ctx); 318 } 319 320 efs->func(event, cpuctx, ctx, efs->data); 321 unlock: 322 perf_ctx_unlock(cpuctx, task_ctx); 323 324 return ret; 325 } 326 327 static void event_function_call(struct perf_event *event, event_f func, void *data) 328 { 329 struct perf_event_context *ctx = event->ctx; 330 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */ 331 struct perf_cpu_context *cpuctx; 332 struct event_function_struct efs = { 333 .event = event, 334 .func = func, 335 .data = data, 336 }; 337 338 if (!event->parent) { 339 /* 340 * If this is a !child event, we must hold ctx::mutex to 341 * stabilize the event->ctx relation. See 342 * perf_event_ctx_lock(). 343 */ 344 lockdep_assert_held(&ctx->mutex); 345 } 346 347 if (!task) { 348 cpu_function_call(event->cpu, event_function, &efs); 349 return; 350 } 351 352 if (task == TASK_TOMBSTONE) 353 return; 354 355 again: 356 if (!task_function_call(task, event_function, &efs)) 357 return; 358 359 local_irq_disable(); 360 cpuctx = this_cpu_ptr(&perf_cpu_context); 361 perf_ctx_lock(cpuctx, ctx); 362 /* 363 * Reload the task pointer, it might have been changed by 364 * a concurrent perf_event_context_sched_out(). 365 */ 366 task = ctx->task; 367 if (task == TASK_TOMBSTONE) 368 goto unlock; 369 if (ctx->is_active) { 370 perf_ctx_unlock(cpuctx, ctx); 371 local_irq_enable(); 372 goto again; 373 } 374 func(event, NULL, ctx, data); 375 unlock: 376 perf_ctx_unlock(cpuctx, ctx); 377 local_irq_enable(); 378 } 379 380 /* 381 * Similar to event_function_call() + event_function(), but hard assumes IRQs 382 * are already disabled and we're on the right CPU. 383 */ 384 static void event_function_local(struct perf_event *event, event_f func, void *data) 385 { 386 struct perf_event_context *ctx = event->ctx; 387 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 388 struct task_struct *task = READ_ONCE(ctx->task); 389 struct perf_event_context *task_ctx = NULL; 390 391 lockdep_assert_irqs_disabled(); 392 393 if (task) { 394 if (task == TASK_TOMBSTONE) 395 return; 396 397 task_ctx = ctx; 398 } 399 400 perf_ctx_lock(cpuctx, task_ctx); 401 402 task = ctx->task; 403 if (task == TASK_TOMBSTONE) 404 goto unlock; 405 406 if (task) { 407 /* 408 * We must be either inactive or active and the right task, 409 * otherwise we're screwed, since we cannot IPI to somewhere 410 * else. 411 */ 412 if (ctx->is_active) { 413 if (WARN_ON_ONCE(task != current)) 414 goto unlock; 415 416 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx)) 417 goto unlock; 418 } 419 } else { 420 WARN_ON_ONCE(&cpuctx->ctx != ctx); 421 } 422 423 func(event, cpuctx, ctx, data); 424 unlock: 425 perf_ctx_unlock(cpuctx, task_ctx); 426 } 427 428 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\ 429 PERF_FLAG_FD_OUTPUT |\ 430 PERF_FLAG_PID_CGROUP |\ 431 PERF_FLAG_FD_CLOEXEC) 432 433 /* 434 * branch priv levels that need permission checks 435 */ 436 #define PERF_SAMPLE_BRANCH_PERM_PLM \ 437 (PERF_SAMPLE_BRANCH_KERNEL |\ 438 PERF_SAMPLE_BRANCH_HV) 439 440 /* 441 * perf_sched_events : >0 events exist 442 */ 443 444 static void perf_sched_delayed(struct work_struct *work); 445 DEFINE_STATIC_KEY_FALSE(perf_sched_events); 446 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed); 447 static DEFINE_MUTEX(perf_sched_mutex); 448 static atomic_t perf_sched_count; 449 450 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events); 451 452 static atomic_t nr_mmap_events __read_mostly; 453 static atomic_t nr_comm_events __read_mostly; 454 static atomic_t nr_namespaces_events __read_mostly; 455 static atomic_t nr_task_events __read_mostly; 456 static atomic_t nr_freq_events __read_mostly; 457 static atomic_t nr_switch_events __read_mostly; 458 static atomic_t nr_ksymbol_events __read_mostly; 459 static atomic_t nr_bpf_events __read_mostly; 460 static atomic_t nr_cgroup_events __read_mostly; 461 static atomic_t nr_text_poke_events __read_mostly; 462 static atomic_t nr_build_id_events __read_mostly; 463 464 static LIST_HEAD(pmus); 465 static DEFINE_MUTEX(pmus_lock); 466 static struct srcu_struct pmus_srcu; 467 static cpumask_var_t perf_online_mask; 468 static cpumask_var_t perf_online_core_mask; 469 static cpumask_var_t perf_online_die_mask; 470 static cpumask_var_t perf_online_cluster_mask; 471 static cpumask_var_t perf_online_pkg_mask; 472 static cpumask_var_t perf_online_sys_mask; 473 static struct kmem_cache *perf_event_cache; 474 475 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU 476 static DEFINE_PER_CPU(bool, guest_ctx_loaded); 477 478 static __always_inline bool is_guest_mediated_pmu_loaded(void) 479 { 480 return __this_cpu_read(guest_ctx_loaded); 481 } 482 #else 483 static __always_inline bool is_guest_mediated_pmu_loaded(void) 484 { 485 return false; 486 } 487 #endif 488 489 /* 490 * perf event paranoia level: 491 * -1 - not paranoid at all 492 * 0 - disallow raw tracepoint access for unpriv 493 * 1 - disallow cpu events for unpriv 494 * 2 - disallow kernel profiling for unpriv 495 */ 496 int sysctl_perf_event_paranoid __read_mostly = 2; 497 498 /* Minimum for 512 kiB + 1 user control page. 'free' kiB per user. */ 499 static int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); 500 501 /* 502 * max perf event sample rate 503 */ 504 #define DEFAULT_MAX_SAMPLE_RATE 100000 505 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE) 506 #define DEFAULT_CPU_TIME_MAX_PERCENT 25 507 508 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE; 509 static int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT; 510 511 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ); 512 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS; 513 514 static int perf_sample_allowed_ns __read_mostly = 515 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100; 516 517 static void update_perf_cpu_limits(void) 518 { 519 u64 tmp = perf_sample_period_ns; 520 521 tmp *= sysctl_perf_cpu_time_max_percent; 522 tmp = div_u64(tmp, 100); 523 if (!tmp) 524 tmp = 1; 525 526 WRITE_ONCE(perf_sample_allowed_ns, tmp); 527 } 528 529 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc); 530 531 static int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write, 532 void *buffer, size_t *lenp, loff_t *ppos) 533 { 534 int ret; 535 int perf_cpu = sysctl_perf_cpu_time_max_percent; 536 /* 537 * If throttling is disabled don't allow the write: 538 */ 539 if (write && (perf_cpu == 100 || perf_cpu == 0)) 540 return -EINVAL; 541 542 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 543 if (ret || !write) 544 return ret; 545 546 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ); 547 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; 548 update_perf_cpu_limits(); 549 550 return 0; 551 } 552 553 static int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write, 554 void *buffer, size_t *lenp, loff_t *ppos) 555 { 556 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 557 558 if (ret || !write) 559 return ret; 560 561 if (sysctl_perf_cpu_time_max_percent == 100 || 562 sysctl_perf_cpu_time_max_percent == 0) { 563 printk(KERN_WARNING 564 "perf: Dynamic interrupt throttling disabled, can hang your system!\n"); 565 WRITE_ONCE(perf_sample_allowed_ns, 0); 566 } else { 567 update_perf_cpu_limits(); 568 } 569 570 return 0; 571 } 572 573 static const struct ctl_table events_core_sysctl_table[] = { 574 /* 575 * User-space relies on this file as a feature check for 576 * perf_events being enabled. It's an ABI, do not remove! 577 */ 578 { 579 .procname = "perf_event_paranoid", 580 .data = &sysctl_perf_event_paranoid, 581 .maxlen = sizeof(sysctl_perf_event_paranoid), 582 .mode = 0644, 583 .proc_handler = proc_dointvec, 584 }, 585 { 586 .procname = "perf_event_mlock_kb", 587 .data = &sysctl_perf_event_mlock, 588 .maxlen = sizeof(sysctl_perf_event_mlock), 589 .mode = 0644, 590 .proc_handler = proc_dointvec, 591 }, 592 { 593 .procname = "perf_event_max_sample_rate", 594 .data = &sysctl_perf_event_sample_rate, 595 .maxlen = sizeof(sysctl_perf_event_sample_rate), 596 .mode = 0644, 597 .proc_handler = perf_event_max_sample_rate_handler, 598 .extra1 = SYSCTL_ONE, 599 }, 600 { 601 .procname = "perf_cpu_time_max_percent", 602 .data = &sysctl_perf_cpu_time_max_percent, 603 .maxlen = sizeof(sysctl_perf_cpu_time_max_percent), 604 .mode = 0644, 605 .proc_handler = perf_cpu_time_max_percent_handler, 606 .extra1 = SYSCTL_ZERO, 607 .extra2 = SYSCTL_ONE_HUNDRED, 608 }, 609 }; 610 611 static int __init init_events_core_sysctls(void) 612 { 613 register_sysctl_init("kernel", events_core_sysctl_table); 614 return 0; 615 } 616 core_initcall(init_events_core_sysctls); 617 618 619 /* 620 * perf samples are done in some very critical code paths (NMIs). 621 * If they take too much CPU time, the system can lock up and not 622 * get any real work done. This will drop the sample rate when 623 * we detect that events are taking too long. 624 */ 625 #define NR_ACCUMULATED_SAMPLES 128 626 static DEFINE_PER_CPU(u64, running_sample_length); 627 628 static u64 __report_avg; 629 static u64 __report_allowed; 630 631 static void perf_duration_warn(struct irq_work *w) 632 { 633 printk_ratelimited(KERN_INFO 634 "perf: interrupt took too long (%lld > %lld), lowering " 635 "kernel.perf_event_max_sample_rate to %d\n", 636 __report_avg, __report_allowed, 637 sysctl_perf_event_sample_rate); 638 } 639 640 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn); 641 642 void perf_sample_event_took(u64 sample_len_ns) 643 { 644 u64 max_len = READ_ONCE(perf_sample_allowed_ns); 645 u64 running_len; 646 u64 avg_len; 647 u32 max; 648 649 if (max_len == 0) 650 return; 651 652 /* Decay the counter by 1 average sample. */ 653 running_len = __this_cpu_read(running_sample_length); 654 running_len -= running_len/NR_ACCUMULATED_SAMPLES; 655 running_len += sample_len_ns; 656 __this_cpu_write(running_sample_length, running_len); 657 658 /* 659 * Note: this will be biased artificially low until we have 660 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us 661 * from having to maintain a count. 662 */ 663 avg_len = running_len/NR_ACCUMULATED_SAMPLES; 664 if (avg_len <= max_len) 665 return; 666 667 __report_avg = avg_len; 668 __report_allowed = max_len; 669 670 /* 671 * Compute a throttle threshold 25% below the current duration. 672 */ 673 avg_len += avg_len / 4; 674 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent; 675 if (avg_len < max) 676 max /= (u32)avg_len; 677 else 678 max = 1; 679 680 WRITE_ONCE(perf_sample_allowed_ns, avg_len); 681 WRITE_ONCE(max_samples_per_tick, max); 682 683 sysctl_perf_event_sample_rate = max * HZ; 684 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; 685 686 if (!irq_work_queue(&perf_duration_work)) { 687 early_printk("perf: interrupt took too long (%lld > %lld), lowering " 688 "kernel.perf_event_max_sample_rate to %d\n", 689 __report_avg, __report_allowed, 690 sysctl_perf_event_sample_rate); 691 } 692 } 693 694 static atomic64_t perf_event_id; 695 696 static void update_context_time(struct perf_event_context *ctx); 697 static u64 perf_event_time(struct perf_event *event); 698 699 void __weak perf_event_print_debug(void) { } 700 701 static inline u64 perf_clock(void) 702 { 703 return local_clock(); 704 } 705 706 static inline u64 perf_event_clock(struct perf_event *event) 707 { 708 return event->clock(); 709 } 710 711 /* 712 * State based event timekeeping... 713 * 714 * The basic idea is to use event->state to determine which (if any) time 715 * fields to increment with the current delta. This means we only need to 716 * update timestamps when we change state or when they are explicitly requested 717 * (read). 718 * 719 * Event groups make things a little more complicated, but not terribly so. The 720 * rules for a group are that if the group leader is OFF the entire group is 721 * OFF, irrespective of what the group member states are. This results in 722 * __perf_effective_state(). 723 * 724 * A further ramification is that when a group leader flips between OFF and 725 * !OFF, we need to update all group member times. 726 * 727 * 728 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we 729 * need to make sure the relevant context time is updated before we try and 730 * update our timestamps. 731 */ 732 733 static __always_inline enum perf_event_state 734 __perf_effective_state(struct perf_event *event) 735 { 736 struct perf_event *leader = event->group_leader; 737 738 if (leader->state <= PERF_EVENT_STATE_OFF) 739 return leader->state; 740 741 return event->state; 742 } 743 744 static __always_inline void 745 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running) 746 { 747 enum perf_event_state state = __perf_effective_state(event); 748 u64 delta = now - event->tstamp; 749 750 *enabled = event->total_time_enabled; 751 if (state >= PERF_EVENT_STATE_INACTIVE) 752 *enabled += delta; 753 754 *running = event->total_time_running; 755 if (state >= PERF_EVENT_STATE_ACTIVE) 756 *running += delta; 757 } 758 759 static void perf_event_update_time(struct perf_event *event) 760 { 761 u64 now = perf_event_time(event); 762 763 __perf_update_times(event, now, &event->total_time_enabled, 764 &event->total_time_running); 765 event->tstamp = now; 766 } 767 768 static void perf_event_update_sibling_time(struct perf_event *leader) 769 { 770 struct perf_event *sibling; 771 772 for_each_sibling_event(sibling, leader) 773 perf_event_update_time(sibling); 774 } 775 776 static void 777 perf_event_set_state(struct perf_event *event, enum perf_event_state state) 778 { 779 if (event->state == state) 780 return; 781 782 perf_event_update_time(event); 783 /* 784 * If a group leader gets enabled/disabled all its siblings 785 * are affected too. 786 */ 787 if ((event->state < 0) ^ (state < 0)) 788 perf_event_update_sibling_time(event); 789 790 WRITE_ONCE(event->state, state); 791 } 792 793 /* 794 * UP store-release, load-acquire 795 */ 796 797 #define __store_release(ptr, val) \ 798 do { \ 799 barrier(); \ 800 WRITE_ONCE(*(ptr), (val)); \ 801 } while (0) 802 803 #define __load_acquire(ptr) \ 804 ({ \ 805 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \ 806 barrier(); \ 807 ___p; \ 808 }) 809 810 static bool perf_skip_pmu_ctx(struct perf_event_pmu_context *pmu_ctx, 811 enum event_type_t event_type) 812 { 813 if ((event_type & EVENT_CGROUP) && !pmu_ctx->nr_cgroups) 814 return true; 815 if ((event_type & EVENT_GUEST) && 816 !(pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU)) 817 return true; 818 return false; 819 } 820 821 #define for_each_epc(_epc, _ctx, _pmu, _event_type) \ 822 list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \ 823 if (perf_skip_pmu_ctx(_epc, _event_type)) \ 824 continue; \ 825 else if (_pmu && _epc->pmu != _pmu) \ 826 continue; \ 827 else 828 829 static void perf_ctx_disable(struct perf_event_context *ctx, 830 enum event_type_t event_type) 831 { 832 struct perf_event_pmu_context *pmu_ctx; 833 834 for_each_epc(pmu_ctx, ctx, NULL, event_type) 835 perf_pmu_disable(pmu_ctx->pmu); 836 } 837 838 static void perf_ctx_enable(struct perf_event_context *ctx, 839 enum event_type_t event_type) 840 { 841 struct perf_event_pmu_context *pmu_ctx; 842 843 for_each_epc(pmu_ctx, ctx, NULL, event_type) 844 perf_pmu_enable(pmu_ctx->pmu); 845 } 846 847 static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type); 848 static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type); 849 850 static inline void update_perf_time_ctx(struct perf_time_ctx *time, u64 now, bool adv) 851 { 852 if (adv) 853 time->time += now - time->stamp; 854 time->stamp = now; 855 856 /* 857 * The above: time' = time + (now - timestamp), can be re-arranged 858 * into: time` = now + (time - timestamp), which gives a single value 859 * offset to compute future time without locks on. 860 * 861 * See perf_event_time_now(), which can be used from NMI context where 862 * it's (obviously) not possible to acquire ctx->lock in order to read 863 * both the above values in a consistent manner. 864 */ 865 WRITE_ONCE(time->offset, time->time - time->stamp); 866 } 867 868 static_assert(offsetof(struct perf_event_context, timeguest) - 869 offsetof(struct perf_event_context, time) == 870 sizeof(struct perf_time_ctx)); 871 872 #define T_TOTAL 0 873 #define T_GUEST 1 874 875 static inline u64 __perf_event_time_ctx(struct perf_event *event, 876 struct perf_time_ctx *times) 877 { 878 u64 time = times[T_TOTAL].time; 879 880 if (event->attr.exclude_guest) 881 time -= times[T_GUEST].time; 882 883 return time; 884 } 885 886 static inline u64 __perf_event_time_ctx_now(struct perf_event *event, 887 struct perf_time_ctx *times, 888 u64 now) 889 { 890 if (is_guest_mediated_pmu_loaded() && event->attr.exclude_guest) { 891 /* 892 * (now + times[total].offset) - (now + times[guest].offset) := 893 * times[total].offset - times[guest].offset 894 */ 895 return READ_ONCE(times[T_TOTAL].offset) - READ_ONCE(times[T_GUEST].offset); 896 } 897 898 return now + READ_ONCE(times[T_TOTAL].offset); 899 } 900 901 #ifdef CONFIG_CGROUP_PERF 902 903 static inline bool 904 perf_cgroup_match(struct perf_event *event) 905 { 906 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 907 908 /* @event doesn't care about cgroup */ 909 if (!event->cgrp) 910 return true; 911 912 /* wants specific cgroup scope but @cpuctx isn't associated with any */ 913 if (!cpuctx->cgrp) 914 return false; 915 916 /* 917 * Cgroup scoping is recursive. An event enabled for a cgroup is 918 * also enabled for all its descendant cgroups. If @cpuctx's 919 * cgroup is a descendant of @event's (the test covers identity 920 * case), it's a match. 921 */ 922 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup, 923 event->cgrp->css.cgroup); 924 } 925 926 static inline void perf_detach_cgroup(struct perf_event *event) 927 { 928 css_put(&event->cgrp->css); 929 event->cgrp = NULL; 930 } 931 932 static inline int is_cgroup_event(struct perf_event *event) 933 { 934 return event->cgrp != NULL; 935 } 936 937 static_assert(offsetof(struct perf_cgroup_info, timeguest) - 938 offsetof(struct perf_cgroup_info, time) == 939 sizeof(struct perf_time_ctx)); 940 941 static inline u64 perf_cgroup_event_time(struct perf_event *event) 942 { 943 struct perf_cgroup_info *t; 944 945 t = per_cpu_ptr(event->cgrp->info, event->cpu); 946 return __perf_event_time_ctx(event, &t->time); 947 } 948 949 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now) 950 { 951 struct perf_cgroup_info *t; 952 953 t = per_cpu_ptr(event->cgrp->info, event->cpu); 954 if (!__load_acquire(&t->active)) 955 return __perf_event_time_ctx(event, &t->time); 956 957 return __perf_event_time_ctx_now(event, &t->time, now); 958 } 959 960 static inline void __update_cgrp_guest_time(struct perf_cgroup_info *info, u64 now, bool adv) 961 { 962 update_perf_time_ctx(&info->timeguest, now, adv); 963 } 964 965 static inline void update_cgrp_time(struct perf_cgroup_info *info, u64 now) 966 { 967 update_perf_time_ctx(&info->time, now, true); 968 if (is_guest_mediated_pmu_loaded()) 969 __update_cgrp_guest_time(info, now, true); 970 } 971 972 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final) 973 { 974 struct perf_cgroup *cgrp = cpuctx->cgrp; 975 struct cgroup_subsys_state *css; 976 struct perf_cgroup_info *info; 977 978 if (cgrp) { 979 u64 now = perf_clock(); 980 981 for (css = &cgrp->css; css; css = css->parent) { 982 cgrp = container_of(css, struct perf_cgroup, css); 983 info = this_cpu_ptr(cgrp->info); 984 985 update_cgrp_time(info, now); 986 if (final) 987 __store_release(&info->active, 0); 988 } 989 } 990 } 991 992 static inline void update_cgrp_time_from_event(struct perf_event *event) 993 { 994 struct perf_cgroup_info *info; 995 996 /* 997 * ensure we access cgroup data only when needed and 998 * when we know the cgroup is pinned (css_get) 999 */ 1000 if (!is_cgroup_event(event)) 1001 return; 1002 1003 info = this_cpu_ptr(event->cgrp->info); 1004 /* 1005 * Do not update time when cgroup is not active 1006 */ 1007 if (info->active) 1008 update_cgrp_time(info, perf_clock()); 1009 } 1010 1011 static inline void 1012 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx, bool guest) 1013 { 1014 struct perf_event_context *ctx = &cpuctx->ctx; 1015 struct perf_cgroup *cgrp = cpuctx->cgrp; 1016 struct perf_cgroup_info *info; 1017 struct cgroup_subsys_state *css; 1018 1019 /* 1020 * ctx->lock held by caller 1021 * ensure we do not access cgroup data 1022 * unless we have the cgroup pinned (css_get) 1023 */ 1024 if (!cgrp) 1025 return; 1026 1027 WARN_ON_ONCE(!ctx->nr_cgroups); 1028 1029 for (css = &cgrp->css; css; css = css->parent) { 1030 cgrp = container_of(css, struct perf_cgroup, css); 1031 info = this_cpu_ptr(cgrp->info); 1032 if (guest) { 1033 __update_cgrp_guest_time(info, ctx->time.stamp, false); 1034 } else { 1035 update_perf_time_ctx(&info->time, ctx->time.stamp, false); 1036 __store_release(&info->active, 1); 1037 } 1038 } 1039 } 1040 1041 /* 1042 * reschedule events based on the cgroup constraint of task. 1043 */ 1044 static void perf_cgroup_switch(struct task_struct *task) 1045 { 1046 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 1047 struct perf_cgroup *cgrp; 1048 1049 /* 1050 * cpuctx->cgrp is set when the first cgroup event enabled, 1051 * and is cleared when the last cgroup event disabled. 1052 */ 1053 if (READ_ONCE(cpuctx->cgrp) == NULL) 1054 return; 1055 1056 cgrp = perf_cgroup_from_task(task, NULL); 1057 if (READ_ONCE(cpuctx->cgrp) == cgrp) 1058 return; 1059 1060 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx); 1061 /* 1062 * Re-check, could've raced vs perf_remove_from_context(). 1063 */ 1064 if (READ_ONCE(cpuctx->cgrp) == NULL) 1065 return; 1066 1067 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0); 1068 perf_ctx_disable(&cpuctx->ctx, EVENT_CGROUP); 1069 1070 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP); 1071 /* 1072 * must not be done before ctxswout due 1073 * to update_cgrp_time_from_cpuctx() in 1074 * ctx_sched_out() 1075 * 1076 * ctx_sched_out() can consume a pending disable and drop the last cgroup 1077 * event, which clear the cpuctx->cgrp. Cgroup tracking follow active cgroup 1078 * event, so do not resurrect it 1079 */ 1080 if (cpuctx->ctx.nr_cgroups) 1081 cpuctx->cgrp = cgrp; 1082 /* 1083 * set cgrp before ctxsw in to allow 1084 * perf_cgroup_set_timestamp() in ctx_sched_in() 1085 * to not have to pass task around 1086 */ 1087 ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP); 1088 1089 perf_ctx_enable(&cpuctx->ctx, EVENT_CGROUP); 1090 } 1091 1092 static int perf_cgroup_ensure_storage(struct perf_event *event, 1093 struct cgroup_subsys_state *css) 1094 { 1095 struct perf_cpu_context *cpuctx; 1096 struct perf_event **storage; 1097 int cpu, heap_size, ret = 0; 1098 1099 /* 1100 * Allow storage to have sufficient space for an iterator for each 1101 * possibly nested cgroup plus an iterator for events with no cgroup. 1102 */ 1103 for (heap_size = 1; css; css = css->parent) 1104 heap_size++; 1105 1106 for_each_possible_cpu(cpu) { 1107 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 1108 if (heap_size <= cpuctx->heap_size) 1109 continue; 1110 1111 storage = kmalloc_node(heap_size * sizeof(struct perf_event *), 1112 GFP_KERNEL, cpu_to_node(cpu)); 1113 if (!storage) { 1114 ret = -ENOMEM; 1115 break; 1116 } 1117 1118 raw_spin_lock_irq(&cpuctx->ctx.lock); 1119 if (cpuctx->heap_size < heap_size) { 1120 swap(cpuctx->heap, storage); 1121 if (storage == cpuctx->heap_default) 1122 storage = NULL; 1123 cpuctx->heap_size = heap_size; 1124 } 1125 raw_spin_unlock_irq(&cpuctx->ctx.lock); 1126 1127 kfree(storage); 1128 } 1129 1130 return ret; 1131 } 1132 1133 static inline int perf_cgroup_connect(int fd, struct perf_event *event, 1134 struct perf_event_attr *attr, 1135 struct perf_event *group_leader) 1136 { 1137 struct perf_cgroup *cgrp; 1138 struct cgroup_subsys_state *css; 1139 CLASS(fd, f)(fd); 1140 int ret = 0; 1141 1142 if (fd_empty(f)) 1143 return -EBADF; 1144 1145 css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry, 1146 &perf_event_cgrp_subsys); 1147 if (IS_ERR(css)) 1148 return PTR_ERR(css); 1149 1150 ret = perf_cgroup_ensure_storage(event, css); 1151 if (ret) 1152 return ret; 1153 1154 cgrp = container_of(css, struct perf_cgroup, css); 1155 event->cgrp = cgrp; 1156 1157 /* 1158 * all events in a group must monitor 1159 * the same cgroup because a task belongs 1160 * to only one perf cgroup at a time 1161 */ 1162 if (group_leader && group_leader->cgrp != cgrp) { 1163 perf_detach_cgroup(event); 1164 ret = -EINVAL; 1165 } 1166 return ret; 1167 } 1168 1169 static inline void 1170 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx) 1171 { 1172 struct perf_cpu_context *cpuctx; 1173 1174 if (!is_cgroup_event(event)) 1175 return; 1176 1177 event->pmu_ctx->nr_cgroups++; 1178 1179 /* 1180 * Because cgroup events are always per-cpu events, 1181 * @ctx == &cpuctx->ctx. 1182 */ 1183 cpuctx = container_of(ctx, struct perf_cpu_context, ctx); 1184 1185 if (ctx->nr_cgroups++) 1186 return; 1187 1188 cpuctx->cgrp = perf_cgroup_from_task(current, ctx); 1189 } 1190 1191 static inline void 1192 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx) 1193 { 1194 struct perf_cpu_context *cpuctx; 1195 1196 if (!is_cgroup_event(event)) 1197 return; 1198 1199 event->pmu_ctx->nr_cgroups--; 1200 1201 /* 1202 * Because cgroup events are always per-cpu events, 1203 * @ctx == &cpuctx->ctx. 1204 */ 1205 cpuctx = container_of(ctx, struct perf_cpu_context, ctx); 1206 1207 if (--ctx->nr_cgroups) 1208 return; 1209 1210 cpuctx->cgrp = NULL; 1211 } 1212 1213 #else /* !CONFIG_CGROUP_PERF */ 1214 1215 static inline bool 1216 perf_cgroup_match(struct perf_event *event) 1217 { 1218 return true; 1219 } 1220 1221 static inline void perf_detach_cgroup(struct perf_event *event) 1222 {} 1223 1224 static inline int is_cgroup_event(struct perf_event *event) 1225 { 1226 return 0; 1227 } 1228 1229 static inline void update_cgrp_time_from_event(struct perf_event *event) 1230 { 1231 } 1232 1233 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, 1234 bool final) 1235 { 1236 } 1237 1238 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event, 1239 struct perf_event_attr *attr, 1240 struct perf_event *group_leader) 1241 { 1242 return -EINVAL; 1243 } 1244 1245 static inline void 1246 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx, bool guest) 1247 { 1248 } 1249 1250 static inline u64 perf_cgroup_event_time(struct perf_event *event) 1251 { 1252 return 0; 1253 } 1254 1255 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now) 1256 { 1257 return 0; 1258 } 1259 1260 static inline void 1261 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx) 1262 { 1263 } 1264 1265 static inline void 1266 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx) 1267 { 1268 } 1269 1270 static void perf_cgroup_switch(struct task_struct *task) 1271 { 1272 } 1273 #endif 1274 1275 /* 1276 * set default to be dependent on timer tick just 1277 * like original code 1278 */ 1279 #define PERF_CPU_HRTIMER (1000 / HZ) 1280 /* 1281 * function must be called with interrupts disabled 1282 */ 1283 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr) 1284 { 1285 struct perf_cpu_pmu_context *cpc; 1286 bool rotations; 1287 1288 lockdep_assert_irqs_disabled(); 1289 1290 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer); 1291 rotations = perf_rotate_context(cpc); 1292 1293 raw_spin_lock(&cpc->hrtimer_lock); 1294 if (rotations) 1295 hrtimer_forward_now(hr, cpc->hrtimer_interval); 1296 else 1297 cpc->hrtimer_active = 0; 1298 raw_spin_unlock(&cpc->hrtimer_lock); 1299 1300 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART; 1301 } 1302 1303 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu) 1304 { 1305 struct hrtimer *timer = &cpc->hrtimer; 1306 struct pmu *pmu = cpc->epc.pmu; 1307 u64 interval; 1308 1309 /* 1310 * check default is sane, if not set then force to 1311 * default interval (1/tick) 1312 */ 1313 interval = pmu->hrtimer_interval_ms; 1314 if (interval < 1) 1315 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER; 1316 1317 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval); 1318 1319 raw_spin_lock_init(&cpc->hrtimer_lock); 1320 hrtimer_setup(timer, perf_mux_hrtimer_handler, CLOCK_MONOTONIC, 1321 HRTIMER_MODE_ABS_PINNED_HARD); 1322 } 1323 1324 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc) 1325 { 1326 struct hrtimer *timer = &cpc->hrtimer; 1327 unsigned long flags; 1328 1329 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags); 1330 if (!cpc->hrtimer_active) { 1331 cpc->hrtimer_active = 1; 1332 hrtimer_forward_now(timer, cpc->hrtimer_interval); 1333 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD); 1334 } 1335 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags); 1336 1337 return 0; 1338 } 1339 1340 static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu) 1341 { 1342 return *this_cpu_ptr(pmu->cpu_pmu_context); 1343 } 1344 1345 static int perf_mux_hrtimer_interval_ipi(void *arg) 1346 { 1347 struct pmu *pmu = arg; 1348 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 1349 int ms = pmu->hrtimer_interval_ms; 1350 1351 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * ms); 1352 return perf_mux_hrtimer_restart(cpc); 1353 } 1354 1355 void perf_pmu_disable(struct pmu *pmu) 1356 { 1357 int *count = &this_cpc(pmu)->pmu_disable_count; 1358 if (!(*count)++) 1359 pmu->pmu_disable(pmu); 1360 } 1361 1362 void perf_pmu_enable(struct pmu *pmu) 1363 { 1364 int *count = &this_cpc(pmu)->pmu_disable_count; 1365 if (!--(*count)) 1366 pmu->pmu_enable(pmu); 1367 } 1368 1369 bool perf_pmu_enabled(struct pmu *pmu) 1370 { 1371 int *count = &this_cpc(pmu)->pmu_disable_count; 1372 return *count == 0; 1373 } 1374 1375 static void perf_assert_pmu_disabled(struct pmu *pmu) 1376 { 1377 int *count = &this_cpc(pmu)->pmu_disable_count; 1378 WARN_ON_ONCE(*count == 0); 1379 } 1380 1381 static inline void perf_pmu_read(struct perf_event *event) 1382 { 1383 if (event->state == PERF_EVENT_STATE_ACTIVE) 1384 event->pmu->read(event); 1385 } 1386 1387 static void get_ctx(struct perf_event_context *ctx) 1388 { 1389 refcount_inc(&ctx->refcount); 1390 } 1391 1392 static void free_ctx(struct rcu_head *head) 1393 { 1394 struct perf_event_context *ctx; 1395 1396 ctx = container_of(head, struct perf_event_context, rcu_head); 1397 kfree(ctx); 1398 } 1399 1400 static void put_ctx(struct perf_event_context *ctx) 1401 { 1402 if (refcount_dec_and_test(&ctx->refcount)) { 1403 if (ctx->parent_ctx) 1404 put_ctx(ctx->parent_ctx); 1405 if (ctx->task && ctx->task != TASK_TOMBSTONE) 1406 put_task_struct(ctx->task); 1407 call_rcu(&ctx->rcu_head, free_ctx); 1408 } else { 1409 smp_mb__after_atomic(); /* pairs with wait_var_event() */ 1410 if (ctx->task == TASK_TOMBSTONE) 1411 wake_up_var(&ctx->refcount); 1412 } 1413 } 1414 1415 /* 1416 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and 1417 * perf_pmu_migrate_context() we need some magic. 1418 * 1419 * Those places that change perf_event::ctx will hold both 1420 * perf_event_ctx::mutex of the 'old' and 'new' ctx value. 1421 * 1422 * Lock ordering is by mutex address. There are two other sites where 1423 * perf_event_context::mutex nests and those are: 1424 * 1425 * - perf_event_exit_task_context() [ child , 0 ] 1426 * perf_event_exit_event() 1427 * put_event() [ parent, 1 ] 1428 * 1429 * - perf_event_init_context() [ parent, 0 ] 1430 * inherit_task_group() 1431 * inherit_group() 1432 * inherit_event() 1433 * perf_event_alloc() 1434 * perf_init_event() 1435 * perf_try_init_event() [ child , 1 ] 1436 * 1437 * While it appears there is an obvious deadlock here -- the parent and child 1438 * nesting levels are inverted between the two. This is in fact safe because 1439 * life-time rules separate them. That is an exiting task cannot fork, and a 1440 * spawning task cannot (yet) exit. 1441 * 1442 * But remember that these are parent<->child context relations, and 1443 * migration does not affect children, therefore these two orderings should not 1444 * interact. 1445 * 1446 * The change in perf_event::ctx does not affect children (as claimed above) 1447 * because the sys_perf_event_open() case will install a new event and break 1448 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only 1449 * concerned with cpuctx and that doesn't have children. 1450 * 1451 * The places that change perf_event::ctx will issue: 1452 * 1453 * perf_remove_from_context(); 1454 * synchronize_rcu(); 1455 * perf_install_in_context(); 1456 * 1457 * to affect the change. The remove_from_context() + synchronize_rcu() should 1458 * quiesce the event, after which we can install it in the new location. This 1459 * means that only external vectors (perf_fops, prctl) can perturb the event 1460 * while in transit. Therefore all such accessors should also acquire 1461 * perf_event_context::mutex to serialize against this. 1462 * 1463 * However; because event->ctx can change while we're waiting to acquire 1464 * ctx->mutex we must be careful and use the below perf_event_ctx_lock() 1465 * function. 1466 * 1467 * Lock order: 1468 * exec_update_lock 1469 * task_struct::perf_event_mutex 1470 * perf_event_context::mutex 1471 * perf_event::child_mutex; 1472 * perf_event_context::lock 1473 * mmap_lock 1474 * perf_event::mmap_mutex 1475 * perf_buffer::aux_mutex 1476 * perf_addr_filters_head::lock 1477 * 1478 * cpu_hotplug_lock 1479 * pmus_lock 1480 * cpuctx->mutex / perf_event_context::mutex 1481 */ 1482 static struct perf_event_context * 1483 perf_event_ctx_lock_nested(struct perf_event *event, int nesting) 1484 { 1485 struct perf_event_context *ctx; 1486 1487 again: 1488 rcu_read_lock(); 1489 ctx = READ_ONCE(event->ctx); 1490 if (!refcount_inc_not_zero(&ctx->refcount)) { 1491 rcu_read_unlock(); 1492 goto again; 1493 } 1494 rcu_read_unlock(); 1495 1496 mutex_lock_nested(&ctx->mutex, nesting); 1497 if (event->ctx != ctx) { 1498 mutex_unlock(&ctx->mutex); 1499 put_ctx(ctx); 1500 goto again; 1501 } 1502 1503 return ctx; 1504 } 1505 1506 static inline struct perf_event_context * 1507 perf_event_ctx_lock(struct perf_event *event) 1508 { 1509 return perf_event_ctx_lock_nested(event, 0); 1510 } 1511 1512 static void perf_event_ctx_unlock(struct perf_event *event, 1513 struct perf_event_context *ctx) 1514 { 1515 mutex_unlock(&ctx->mutex); 1516 put_ctx(ctx); 1517 } 1518 1519 /* 1520 * This must be done under the ctx->lock, such as to serialize against 1521 * context_equiv(), therefore we cannot call put_ctx() since that might end up 1522 * calling scheduler related locks and ctx->lock nests inside those. 1523 */ 1524 static __must_check struct perf_event_context * 1525 unclone_ctx(struct perf_event_context *ctx) 1526 { 1527 struct perf_event_context *parent_ctx = ctx->parent_ctx; 1528 1529 lockdep_assert_held(&ctx->lock); 1530 1531 if (parent_ctx) 1532 ctx->parent_ctx = NULL; 1533 ctx->generation++; 1534 1535 return parent_ctx; 1536 } 1537 1538 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p, 1539 enum pid_type type) 1540 { 1541 u32 nr; 1542 /* 1543 * only top level events have the pid namespace they were created in 1544 */ 1545 if (event->parent) 1546 event = event->parent; 1547 1548 nr = __task_pid_nr_ns(p, type, event->ns); 1549 /* avoid -1 if it is idle thread or runs in another ns */ 1550 if (!nr && !pid_alive(p)) 1551 nr = -1; 1552 return nr; 1553 } 1554 1555 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p) 1556 { 1557 return perf_event_pid_type(event, p, PIDTYPE_TGID); 1558 } 1559 1560 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p) 1561 { 1562 return perf_event_pid_type(event, p, PIDTYPE_PID); 1563 } 1564 1565 /* 1566 * If we inherit events we want to return the parent event id 1567 * to userspace. 1568 */ 1569 static u64 primary_event_id(struct perf_event *event) 1570 { 1571 u64 id = event->id; 1572 1573 if (event->parent) 1574 id = event->parent->id; 1575 1576 return id; 1577 } 1578 1579 /* 1580 * Get the perf_event_context for a task and lock it. 1581 * 1582 * This has to cope with the fact that until it is locked, 1583 * the context could get moved to another task. 1584 */ 1585 static struct perf_event_context * 1586 perf_lock_task_context(struct task_struct *task, unsigned long *flags) 1587 { 1588 struct perf_event_context *ctx; 1589 1590 retry: 1591 /* 1592 * One of the few rules of preemptible RCU is that one cannot do 1593 * rcu_read_unlock() while holding a scheduler (or nested) lock when 1594 * part of the read side critical section was irqs-enabled -- see 1595 * rcu_read_unlock_special(). 1596 * 1597 * Since ctx->lock nests under rq->lock we must ensure the entire read 1598 * side critical section has interrupts disabled. 1599 */ 1600 local_irq_save(*flags); 1601 rcu_read_lock(); 1602 ctx = rcu_dereference(task->perf_event_ctxp); 1603 if (ctx) { 1604 /* 1605 * If this context is a clone of another, it might 1606 * get swapped for another underneath us by 1607 * perf_event_task_sched_out, though the 1608 * rcu_read_lock() protects us from any context 1609 * getting freed. Lock the context and check if it 1610 * got swapped before we could get the lock, and retry 1611 * if so. If we locked the right context, then it 1612 * can't get swapped on us any more. 1613 */ 1614 raw_spin_lock(&ctx->lock); 1615 if (ctx != rcu_dereference(task->perf_event_ctxp)) { 1616 raw_spin_unlock(&ctx->lock); 1617 rcu_read_unlock(); 1618 local_irq_restore(*flags); 1619 goto retry; 1620 } 1621 1622 if (ctx->task == TASK_TOMBSTONE || 1623 !refcount_inc_not_zero(&ctx->refcount)) { 1624 raw_spin_unlock(&ctx->lock); 1625 ctx = NULL; 1626 } else { 1627 WARN_ON_ONCE(ctx->task != task); 1628 } 1629 } 1630 rcu_read_unlock(); 1631 if (!ctx) 1632 local_irq_restore(*flags); 1633 return ctx; 1634 } 1635 1636 /* 1637 * Get the context for a task and increment its pin_count so it 1638 * can't get swapped to another task. This also increments its 1639 * reference count so that the context can't get freed. 1640 */ 1641 static struct perf_event_context * 1642 perf_pin_task_context(struct task_struct *task) 1643 { 1644 struct perf_event_context *ctx; 1645 unsigned long flags; 1646 1647 ctx = perf_lock_task_context(task, &flags); 1648 if (ctx) { 1649 ++ctx->pin_count; 1650 raw_spin_unlock_irqrestore(&ctx->lock, flags); 1651 } 1652 return ctx; 1653 } 1654 1655 static void perf_unpin_context(struct perf_event_context *ctx) 1656 { 1657 unsigned long flags; 1658 1659 raw_spin_lock_irqsave(&ctx->lock, flags); 1660 --ctx->pin_count; 1661 raw_spin_unlock_irqrestore(&ctx->lock, flags); 1662 } 1663 1664 /* 1665 * Update the record of the current time in a context. 1666 */ 1667 static void __update_context_time(struct perf_event_context *ctx, bool adv) 1668 { 1669 lockdep_assert_held(&ctx->lock); 1670 1671 update_perf_time_ctx(&ctx->time, perf_clock(), adv); 1672 } 1673 1674 static void __update_context_guest_time(struct perf_event_context *ctx, bool adv) 1675 { 1676 lockdep_assert_held(&ctx->lock); 1677 1678 /* must be called after __update_context_time(); */ 1679 update_perf_time_ctx(&ctx->timeguest, ctx->time.stamp, adv); 1680 } 1681 1682 static void update_context_time(struct perf_event_context *ctx) 1683 { 1684 __update_context_time(ctx, true); 1685 if (is_guest_mediated_pmu_loaded()) 1686 __update_context_guest_time(ctx, true); 1687 } 1688 1689 static u64 perf_event_time(struct perf_event *event) 1690 { 1691 struct perf_event_context *ctx = event->ctx; 1692 1693 if (unlikely(!ctx)) 1694 return 0; 1695 1696 if (is_cgroup_event(event)) 1697 return perf_cgroup_event_time(event); 1698 1699 return __perf_event_time_ctx(event, &ctx->time); 1700 } 1701 1702 static u64 perf_event_time_now(struct perf_event *event, u64 now) 1703 { 1704 struct perf_event_context *ctx = event->ctx; 1705 1706 if (unlikely(!ctx)) 1707 return 0; 1708 1709 if (is_cgroup_event(event)) 1710 return perf_cgroup_event_time_now(event, now); 1711 1712 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME)) 1713 return __perf_event_time_ctx(event, &ctx->time); 1714 1715 return __perf_event_time_ctx_now(event, &ctx->time, now); 1716 } 1717 1718 static enum event_type_t get_event_type(struct perf_event *event) 1719 { 1720 struct perf_event_context *ctx = event->ctx; 1721 enum event_type_t event_type; 1722 1723 lockdep_assert_held(&ctx->lock); 1724 1725 /* 1726 * It's 'group type', really, because if our group leader is 1727 * pinned, so are we. 1728 */ 1729 if (event->group_leader != event) 1730 event = event->group_leader; 1731 1732 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE; 1733 if (!ctx->task) 1734 event_type |= EVENT_CPU; 1735 1736 return event_type; 1737 } 1738 1739 /* 1740 * Helper function to initialize event group nodes. 1741 */ 1742 static void init_event_group(struct perf_event *event) 1743 { 1744 RB_CLEAR_NODE(&event->group_node); 1745 event->group_index = 0; 1746 } 1747 1748 /* 1749 * Extract pinned or flexible groups from the context 1750 * based on event attrs bits. 1751 */ 1752 static struct perf_event_groups * 1753 get_event_groups(struct perf_event *event, struct perf_event_context *ctx) 1754 { 1755 if (event->attr.pinned) 1756 return &ctx->pinned_groups; 1757 else 1758 return &ctx->flexible_groups; 1759 } 1760 1761 /* 1762 * Helper function to initializes perf_event_group trees. 1763 */ 1764 static void perf_event_groups_init(struct perf_event_groups *groups) 1765 { 1766 groups->tree = RB_ROOT; 1767 groups->index = 0; 1768 } 1769 1770 static inline struct cgroup *event_cgroup(const struct perf_event *event) 1771 { 1772 struct cgroup *cgroup = NULL; 1773 1774 #ifdef CONFIG_CGROUP_PERF 1775 if (event->cgrp) 1776 cgroup = event->cgrp->css.cgroup; 1777 #endif 1778 1779 return cgroup; 1780 } 1781 1782 /* 1783 * Compare function for event groups; 1784 * 1785 * Implements complex key that first sorts by CPU and then by virtual index 1786 * which provides ordering when rotating groups for the same CPU. 1787 */ 1788 static __always_inline int 1789 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu, 1790 const struct cgroup *left_cgroup, const u64 left_group_index, 1791 const struct perf_event *right) 1792 { 1793 if (left_cpu < right->cpu) 1794 return -1; 1795 if (left_cpu > right->cpu) 1796 return 1; 1797 1798 if (left_pmu) { 1799 if (left_pmu < right->pmu_ctx->pmu) 1800 return -1; 1801 if (left_pmu > right->pmu_ctx->pmu) 1802 return 1; 1803 } 1804 1805 #ifdef CONFIG_CGROUP_PERF 1806 { 1807 const struct cgroup *right_cgroup = event_cgroup(right); 1808 1809 if (left_cgroup != right_cgroup) { 1810 if (!left_cgroup) { 1811 /* 1812 * Left has no cgroup but right does, no 1813 * cgroups come first. 1814 */ 1815 return -1; 1816 } 1817 if (!right_cgroup) { 1818 /* 1819 * Right has no cgroup but left does, no 1820 * cgroups come first. 1821 */ 1822 return 1; 1823 } 1824 /* Two dissimilar cgroups, order by id. */ 1825 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup)) 1826 return -1; 1827 1828 return 1; 1829 } 1830 } 1831 #endif 1832 1833 if (left_group_index < right->group_index) 1834 return -1; 1835 if (left_group_index > right->group_index) 1836 return 1; 1837 1838 return 0; 1839 } 1840 1841 #define __node_2_pe(node) \ 1842 rb_entry((node), struct perf_event, group_node) 1843 1844 static inline bool __group_less(struct rb_node *a, const struct rb_node *b) 1845 { 1846 struct perf_event *e = __node_2_pe(a); 1847 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e), 1848 e->group_index, __node_2_pe(b)) < 0; 1849 } 1850 1851 struct __group_key { 1852 int cpu; 1853 struct pmu *pmu; 1854 struct cgroup *cgroup; 1855 }; 1856 1857 static inline int __group_cmp(const void *key, const struct rb_node *node) 1858 { 1859 const struct __group_key *a = key; 1860 const struct perf_event *b = __node_2_pe(node); 1861 1862 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */ 1863 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b); 1864 } 1865 1866 static inline int 1867 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node) 1868 { 1869 const struct __group_key *a = key; 1870 const struct perf_event *b = __node_2_pe(node); 1871 1872 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */ 1873 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b), 1874 b->group_index, b); 1875 } 1876 1877 /* 1878 * Insert @event into @groups' tree; using 1879 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index} 1880 * as key. This places it last inside the {cpu,pmu,cgroup} subtree. 1881 */ 1882 static void 1883 perf_event_groups_insert(struct perf_event_groups *groups, 1884 struct perf_event *event) 1885 { 1886 event->group_index = ++groups->index; 1887 1888 rb_add(&event->group_node, &groups->tree, __group_less); 1889 } 1890 1891 /* 1892 * Helper function to insert event into the pinned or flexible groups. 1893 */ 1894 static void 1895 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx) 1896 { 1897 struct perf_event_groups *groups; 1898 1899 groups = get_event_groups(event, ctx); 1900 perf_event_groups_insert(groups, event); 1901 } 1902 1903 /* 1904 * Delete a group from a tree. 1905 */ 1906 static void 1907 perf_event_groups_delete(struct perf_event_groups *groups, 1908 struct perf_event *event) 1909 { 1910 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) || 1911 RB_EMPTY_ROOT(&groups->tree)); 1912 1913 rb_erase(&event->group_node, &groups->tree); 1914 init_event_group(event); 1915 } 1916 1917 /* 1918 * Helper function to delete event from its groups. 1919 */ 1920 static void 1921 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx) 1922 { 1923 struct perf_event_groups *groups; 1924 1925 groups = get_event_groups(event, ctx); 1926 perf_event_groups_delete(groups, event); 1927 } 1928 1929 /* 1930 * Get the leftmost event in the {cpu,pmu,cgroup} subtree. 1931 */ 1932 static struct perf_event * 1933 perf_event_groups_first(struct perf_event_groups *groups, int cpu, 1934 struct pmu *pmu, struct cgroup *cgrp) 1935 { 1936 struct __group_key key = { 1937 .cpu = cpu, 1938 .pmu = pmu, 1939 .cgroup = cgrp, 1940 }; 1941 struct rb_node *node; 1942 1943 node = rb_find_first(&key, &groups->tree, __group_cmp); 1944 if (node) 1945 return __node_2_pe(node); 1946 1947 return NULL; 1948 } 1949 1950 static struct perf_event * 1951 perf_event_groups_next(struct perf_event *event, struct pmu *pmu) 1952 { 1953 struct __group_key key = { 1954 .cpu = event->cpu, 1955 .pmu = pmu, 1956 .cgroup = event_cgroup(event), 1957 }; 1958 struct rb_node *next; 1959 1960 next = rb_next_match(&key, &event->group_node, __group_cmp); 1961 if (next) 1962 return __node_2_pe(next); 1963 1964 return NULL; 1965 } 1966 1967 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \ 1968 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \ 1969 event; event = perf_event_groups_next(event, pmu)) 1970 1971 /* 1972 * Iterate through the whole groups tree. 1973 */ 1974 #define perf_event_groups_for_each(event, groups) \ 1975 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \ 1976 typeof(*event), group_node); event; \ 1977 event = rb_entry_safe(rb_next(&event->group_node), \ 1978 typeof(*event), group_node)) 1979 1980 /* 1981 * Does the event attribute request inherit with PERF_SAMPLE_READ 1982 */ 1983 static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr) 1984 { 1985 return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ); 1986 } 1987 1988 /* 1989 * Add an event from the lists for its context. 1990 * Must be called with ctx->mutex and ctx->lock held. 1991 */ 1992 static void 1993 list_add_event(struct perf_event *event, struct perf_event_context *ctx) 1994 { 1995 lockdep_assert_held(&ctx->lock); 1996 1997 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT); 1998 event->attach_state |= PERF_ATTACH_CONTEXT; 1999 2000 event->tstamp = perf_event_time(event); 2001 2002 /* 2003 * If we're a stand alone event or group leader, we go to the context 2004 * list, group events are kept attached to the group so that 2005 * perf_group_detach can, at all times, locate all siblings. 2006 */ 2007 if (event->group_leader == event) { 2008 event->group_caps = event->event_caps; 2009 add_event_to_groups(event, ctx); 2010 } 2011 2012 list_add_rcu(&event->event_entry, &ctx->event_list); 2013 ctx->nr_events++; 2014 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT) 2015 ctx->nr_user++; 2016 if (event->attr.inherit_stat) 2017 ctx->nr_stat++; 2018 if (has_inherit_and_sample_read(&event->attr)) 2019 local_inc(&ctx->nr_no_switch_fast); 2020 2021 if (event->state > PERF_EVENT_STATE_OFF) 2022 perf_cgroup_event_enable(event, ctx); 2023 2024 ctx->generation++; 2025 event->pmu_ctx->nr_events++; 2026 } 2027 2028 /* 2029 * Initialize event state based on the perf_event_attr::disabled. 2030 */ 2031 static inline void perf_event__state_init(struct perf_event *event) 2032 { 2033 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF : 2034 PERF_EVENT_STATE_INACTIVE; 2035 } 2036 2037 static int __perf_event_read_size(u64 read_format, int nr_siblings) 2038 { 2039 int entry = sizeof(u64); /* value */ 2040 int size = 0; 2041 int nr = 1; 2042 2043 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 2044 size += sizeof(u64); 2045 2046 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 2047 size += sizeof(u64); 2048 2049 if (read_format & PERF_FORMAT_ID) 2050 entry += sizeof(u64); 2051 2052 if (read_format & PERF_FORMAT_LOST) 2053 entry += sizeof(u64); 2054 2055 if (read_format & PERF_FORMAT_GROUP) { 2056 nr += nr_siblings; 2057 size += sizeof(u64); 2058 } 2059 2060 /* 2061 * Since perf_event_validate_size() limits this to 16k and inhibits 2062 * adding more siblings, this will never overflow. 2063 */ 2064 return size + nr * entry; 2065 } 2066 2067 static void __perf_event_header_size(struct perf_event *event, u64 sample_type) 2068 { 2069 struct perf_sample_data *data; 2070 u16 size = 0; 2071 2072 if (sample_type & PERF_SAMPLE_IP) 2073 size += sizeof(data->ip); 2074 2075 if (sample_type & PERF_SAMPLE_ADDR) 2076 size += sizeof(data->addr); 2077 2078 if (sample_type & PERF_SAMPLE_PERIOD) 2079 size += sizeof(data->period); 2080 2081 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) 2082 size += sizeof(data->weight.full); 2083 2084 if (sample_type & PERF_SAMPLE_READ) 2085 size += event->read_size; 2086 2087 if (sample_type & PERF_SAMPLE_DATA_SRC) 2088 size += sizeof(data->data_src.val); 2089 2090 if (sample_type & PERF_SAMPLE_TRANSACTION) 2091 size += sizeof(data->txn); 2092 2093 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 2094 size += sizeof(data->phys_addr); 2095 2096 if (sample_type & PERF_SAMPLE_CGROUP) 2097 size += sizeof(data->cgroup); 2098 2099 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) 2100 size += sizeof(data->data_page_size); 2101 2102 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) 2103 size += sizeof(data->code_page_size); 2104 2105 event->header_size = size; 2106 } 2107 2108 /* 2109 * Called at perf_event creation and when events are attached/detached from a 2110 * group. 2111 */ 2112 static void perf_event__header_size(struct perf_event *event) 2113 { 2114 event->read_size = 2115 __perf_event_read_size(event->attr.read_format, 2116 event->group_leader->nr_siblings); 2117 __perf_event_header_size(event, event->attr.sample_type); 2118 } 2119 2120 static void perf_event__id_header_size(struct perf_event *event) 2121 { 2122 struct perf_sample_data *data; 2123 u64 sample_type = event->attr.sample_type; 2124 u16 size = 0; 2125 2126 if (sample_type & PERF_SAMPLE_TID) 2127 size += sizeof(data->tid_entry); 2128 2129 if (sample_type & PERF_SAMPLE_TIME) 2130 size += sizeof(data->time); 2131 2132 if (sample_type & PERF_SAMPLE_IDENTIFIER) 2133 size += sizeof(data->id); 2134 2135 if (sample_type & PERF_SAMPLE_ID) 2136 size += sizeof(data->id); 2137 2138 if (sample_type & PERF_SAMPLE_STREAM_ID) 2139 size += sizeof(data->stream_id); 2140 2141 if (sample_type & PERF_SAMPLE_CPU) 2142 size += sizeof(data->cpu_entry); 2143 2144 event->id_header_size = size; 2145 } 2146 2147 /* 2148 * Check that adding an event to the group does not result in anybody 2149 * overflowing the 64k event limit imposed by the output buffer. 2150 * 2151 * Specifically, check that the read_size for the event does not exceed 16k, 2152 * read_size being the one term that grows with groups size. Since read_size 2153 * depends on per-event read_format, also (re)check the existing events. 2154 * 2155 * This leaves 48k for the constant size fields and things like callchains, 2156 * branch stacks and register sets. 2157 */ 2158 static bool perf_event_validate_size(struct perf_event *event) 2159 { 2160 struct perf_event *sibling, *group_leader = event->group_leader; 2161 2162 if (__perf_event_read_size(event->attr.read_format, 2163 group_leader->nr_siblings + 1) > 16*1024) 2164 return false; 2165 2166 if (__perf_event_read_size(group_leader->attr.read_format, 2167 group_leader->nr_siblings + 1) > 16*1024) 2168 return false; 2169 2170 /* 2171 * When creating a new group leader, group_leader->ctx is initialized 2172 * after the size has been validated, but we cannot safely use 2173 * for_each_sibling_event() until group_leader->ctx is set. A new group 2174 * leader cannot have any siblings yet, so we can safely skip checking 2175 * the non-existent siblings. 2176 */ 2177 if (event == group_leader) 2178 return true; 2179 2180 for_each_sibling_event(sibling, group_leader) { 2181 if (__perf_event_read_size(sibling->attr.read_format, 2182 group_leader->nr_siblings + 1) > 16*1024) 2183 return false; 2184 } 2185 2186 return true; 2187 } 2188 2189 static void perf_group_attach(struct perf_event *event) 2190 { 2191 struct perf_event *group_leader = event->group_leader, *pos; 2192 2193 lockdep_assert_held(&event->ctx->lock); 2194 2195 /* 2196 * We can have double attach due to group movement (move_group) in 2197 * perf_event_open(). 2198 */ 2199 if (event->attach_state & PERF_ATTACH_GROUP) 2200 return; 2201 2202 event->attach_state |= PERF_ATTACH_GROUP; 2203 2204 if (group_leader == event) 2205 return; 2206 2207 WARN_ON_ONCE(group_leader->ctx != event->ctx); 2208 2209 group_leader->group_caps &= event->event_caps; 2210 2211 list_add_tail(&event->sibling_list, &group_leader->sibling_list); 2212 group_leader->nr_siblings++; 2213 group_leader->group_generation++; 2214 2215 perf_event__header_size(group_leader); 2216 2217 for_each_sibling_event(pos, group_leader) 2218 perf_event__header_size(pos); 2219 } 2220 2221 /* 2222 * Remove an event from the lists for its context. 2223 * Must be called with ctx->mutex and ctx->lock held. 2224 */ 2225 static void 2226 list_del_event(struct perf_event *event, struct perf_event_context *ctx) 2227 { 2228 WARN_ON_ONCE(event->ctx != ctx); 2229 lockdep_assert_held(&ctx->lock); 2230 2231 /* 2232 * We can have double detach due to exit/hot-unplug + close. 2233 */ 2234 if (!(event->attach_state & PERF_ATTACH_CONTEXT)) 2235 return; 2236 2237 event->attach_state &= ~PERF_ATTACH_CONTEXT; 2238 2239 ctx->nr_events--; 2240 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT) 2241 ctx->nr_user--; 2242 if (event->attr.inherit_stat) 2243 ctx->nr_stat--; 2244 if (has_inherit_and_sample_read(&event->attr)) 2245 local_dec(&ctx->nr_no_switch_fast); 2246 2247 list_del_rcu(&event->event_entry); 2248 2249 if (event->group_leader == event) 2250 del_event_from_groups(event, ctx); 2251 2252 ctx->generation++; 2253 event->pmu_ctx->nr_events--; 2254 } 2255 2256 static int 2257 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event) 2258 { 2259 if (!has_aux(aux_event)) 2260 return 0; 2261 2262 if (!event->pmu->aux_output_match) 2263 return 0; 2264 2265 return event->pmu->aux_output_match(aux_event); 2266 } 2267 2268 static void put_event(struct perf_event *event); 2269 static void __event_disable(struct perf_event *event, 2270 struct perf_event_context *ctx, 2271 enum perf_event_state state); 2272 2273 static void perf_put_aux_event(struct perf_event *event) 2274 { 2275 struct perf_event_context *ctx = event->ctx; 2276 struct perf_event *iter; 2277 2278 /* 2279 * If event uses aux_event tear down the link 2280 */ 2281 if (event->aux_event) { 2282 iter = event->aux_event; 2283 event->aux_event = NULL; 2284 put_event(iter); 2285 return; 2286 } 2287 2288 /* 2289 * If the event is an aux_event, tear down all links to 2290 * it from other events. 2291 */ 2292 for_each_sibling_event(iter, event) { 2293 if (iter->aux_event != event) 2294 continue; 2295 2296 iter->aux_event = NULL; 2297 put_event(event); 2298 2299 /* 2300 * If it's ACTIVE, schedule it out and put it into ERROR 2301 * state so that we don't try to schedule it again. Note 2302 * that perf_event_enable() will clear the ERROR status. 2303 */ 2304 __event_disable(iter, ctx, PERF_EVENT_STATE_ERROR); 2305 } 2306 } 2307 2308 static bool perf_need_aux_event(struct perf_event *event) 2309 { 2310 return event->attr.aux_output || has_aux_action(event); 2311 } 2312 2313 static int perf_get_aux_event(struct perf_event *event, 2314 struct perf_event *group_leader) 2315 { 2316 /* 2317 * Our group leader must be an aux event if we want to be 2318 * an aux_output. This way, the aux event will precede its 2319 * aux_output events in the group, and therefore will always 2320 * schedule first. 2321 */ 2322 if (!group_leader) 2323 return 0; 2324 2325 /* 2326 * aux_output and aux_sample_size are mutually exclusive. 2327 */ 2328 if (event->attr.aux_output && event->attr.aux_sample_size) 2329 return 0; 2330 2331 if (event->attr.aux_output && 2332 !perf_aux_output_match(event, group_leader)) 2333 return 0; 2334 2335 if ((event->attr.aux_pause || event->attr.aux_resume) && 2336 !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) 2337 return 0; 2338 2339 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux) 2340 return 0; 2341 2342 if (!atomic_long_inc_not_zero(&group_leader->refcount)) 2343 return 0; 2344 2345 /* 2346 * Link aux_outputs to their aux event; this is undone in 2347 * perf_group_detach() by perf_put_aux_event(). When the 2348 * group in torn down, the aux_output events loose their 2349 * link to the aux_event and can't schedule any more. 2350 */ 2351 event->aux_event = group_leader; 2352 2353 return 1; 2354 } 2355 2356 static inline struct list_head *get_event_list(struct perf_event *event) 2357 { 2358 return event->attr.pinned ? &event->pmu_ctx->pinned_active : 2359 &event->pmu_ctx->flexible_active; 2360 } 2361 2362 /* @sibling must already be unlinked from its old leader's sibling_list. */ 2363 static void perf_promote_sibling_to_leader(struct perf_event *sibling, 2364 struct perf_event_context *ctx, 2365 int group_caps) 2366 { 2367 /* 2368 * Events that have PERF_EV_CAP_SIBLING require being part of 2369 * a group and cannot exist on their own, schedule them out 2370 * and move them into the ERROR state. Also see 2371 * _perf_event_enable(), it will not be able to recover this 2372 * ERROR state. 2373 */ 2374 if (sibling->event_caps & PERF_EV_CAP_SIBLING) 2375 __event_disable(sibling, ctx, PERF_EVENT_STATE_ERROR); 2376 2377 sibling->group_leader = sibling; 2378 sibling->group_caps = group_caps; 2379 2380 if (sibling->attach_state & PERF_ATTACH_CONTEXT) { 2381 add_event_to_groups(sibling, ctx); 2382 2383 if (sibling->state == PERF_EVENT_STATE_ACTIVE) 2384 list_add_tail(&sibling->active_list, get_event_list(sibling)); 2385 } 2386 2387 perf_event__header_size(sibling); 2388 } 2389 2390 static void perf_group_detach(struct perf_event *event) 2391 { 2392 struct perf_event *leader = event->group_leader; 2393 struct perf_event *sibling, *tmp; 2394 struct perf_event_context *ctx = event->ctx; 2395 2396 lockdep_assert_held(&ctx->lock); 2397 2398 /* 2399 * We can have double detach due to exit/hot-unplug + close. 2400 */ 2401 if (!(event->attach_state & PERF_ATTACH_GROUP)) 2402 return; 2403 2404 event->attach_state &= ~PERF_ATTACH_GROUP; 2405 2406 perf_put_aux_event(event); 2407 2408 /* 2409 * If this is a sibling, remove it from its group. 2410 */ 2411 if (leader != event) { 2412 list_del_init(&event->sibling_list); 2413 leader->nr_siblings--; 2414 leader->group_generation++; 2415 perf_promote_sibling_to_leader(event, ctx, event->event_caps); 2416 goto out; 2417 } 2418 2419 /* 2420 * If this was a group event with sibling events then 2421 * upgrade the siblings to singleton events by adding them 2422 * to whatever list we are on. 2423 */ 2424 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) { 2425 list_del_init(&sibling->sibling_list); 2426 2427 /* Inherit group flags from the previous leader */ 2428 perf_promote_sibling_to_leader(sibling, ctx, event->group_caps); 2429 2430 WARN_ON_ONCE(sibling->ctx != event->ctx); 2431 } 2432 event->nr_siblings = 0; 2433 2434 out: 2435 for_each_sibling_event(tmp, leader) 2436 perf_event__header_size(tmp); 2437 2438 perf_event__header_size(leader); 2439 } 2440 2441 static void perf_child_detach(struct perf_event *event) 2442 { 2443 struct perf_event *parent_event = event->parent; 2444 2445 if (!(event->attach_state & PERF_ATTACH_CHILD)) 2446 return; 2447 2448 event->attach_state &= ~PERF_ATTACH_CHILD; 2449 2450 if (WARN_ON_ONCE(!parent_event)) 2451 return; 2452 2453 /* 2454 * Can't check this from an IPI, the holder is likey another CPU. 2455 * 2456 lockdep_assert_held(&parent_event->child_mutex); 2457 */ 2458 2459 list_del_init(&event->child_list); 2460 } 2461 2462 static bool is_orphaned_event(struct perf_event *event) 2463 { 2464 return event->state == PERF_EVENT_STATE_DEAD; 2465 } 2466 2467 static inline int 2468 event_filter_match(struct perf_event *event) 2469 { 2470 return (event->cpu == -1 || event->cpu == smp_processor_id()) && 2471 perf_cgroup_match(event); 2472 } 2473 2474 static inline bool is_event_in_freq_mode(struct perf_event *event) 2475 { 2476 return event->attr.freq && event->attr.sample_freq; 2477 } 2478 2479 static void 2480 event_sched_out(struct perf_event *event, struct perf_event_context *ctx) 2481 { 2482 struct perf_event_pmu_context *epc = event->pmu_ctx; 2483 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu); 2484 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE; 2485 2486 // XXX cpc serialization, probably per-cpu IRQ disabled 2487 2488 WARN_ON_ONCE(event->ctx != ctx); 2489 lockdep_assert_held(&ctx->lock); 2490 2491 if (event->state != PERF_EVENT_STATE_ACTIVE) 2492 return; 2493 2494 /* 2495 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but 2496 * we can schedule events _OUT_ individually through things like 2497 * __perf_remove_from_context(). 2498 */ 2499 list_del_init(&event->active_list); 2500 2501 perf_pmu_disable(event->pmu); 2502 2503 event->pmu->del(event, 0); 2504 event->oncpu = -1; 2505 2506 if (event->pending_disable) { 2507 event->pending_disable = 0; 2508 perf_cgroup_event_disable(event, ctx); 2509 state = PERF_EVENT_STATE_OFF; 2510 } 2511 2512 perf_event_set_state(event, state); 2513 2514 if (!is_software_event(event)) 2515 cpc->active_oncpu--; 2516 if (is_event_in_freq_mode(event)) { 2517 ctx->nr_freq--; 2518 epc->nr_freq--; 2519 } 2520 if (event->attr.exclusive || !cpc->active_oncpu) 2521 cpc->exclusive = 0; 2522 2523 perf_pmu_enable(event->pmu); 2524 } 2525 2526 static void 2527 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx) 2528 { 2529 struct perf_event *event; 2530 2531 if (group_event->state != PERF_EVENT_STATE_ACTIVE) 2532 return; 2533 2534 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu); 2535 2536 event_sched_out(group_event, ctx); 2537 2538 /* 2539 * Schedule out siblings (if any): 2540 */ 2541 for_each_sibling_event(event, group_event) 2542 event_sched_out(event, ctx); 2543 } 2544 2545 static inline void 2546 __ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, 2547 bool final, enum event_type_t event_type) 2548 { 2549 if (ctx->is_active & EVENT_TIME) { 2550 if (ctx->is_active & EVENT_FROZEN) 2551 return; 2552 2553 update_context_time(ctx); 2554 /* vPMU should not stop time */ 2555 update_cgrp_time_from_cpuctx(cpuctx, !(event_type & EVENT_GUEST) && final); 2556 } 2557 } 2558 2559 static inline void 2560 ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) 2561 { 2562 __ctx_time_update(cpuctx, ctx, false, 0); 2563 } 2564 2565 /* 2566 * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock(). 2567 */ 2568 static inline void 2569 ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) 2570 { 2571 ctx_time_update(cpuctx, ctx); 2572 if (ctx->is_active & EVENT_TIME) 2573 ctx->is_active |= EVENT_FROZEN; 2574 } 2575 2576 static inline void 2577 ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event) 2578 { 2579 if (ctx->is_active & EVENT_TIME) { 2580 if (ctx->is_active & EVENT_FROZEN) 2581 return; 2582 update_context_time(ctx); 2583 update_cgrp_time_from_event(event); 2584 } 2585 } 2586 2587 #define DETACH_GROUP 0x01UL 2588 #define DETACH_CHILD 0x02UL 2589 #define DETACH_EXIT 0x04UL 2590 #define DETACH_REVOKE 0x08UL 2591 #define DETACH_DEAD 0x10UL 2592 2593 /* 2594 * Cross CPU call to remove a performance event 2595 * 2596 * We disable the event on the hardware level first. After that we 2597 * remove it from the context list. 2598 */ 2599 static void 2600 __perf_remove_from_context(struct perf_event *event, 2601 struct perf_cpu_context *cpuctx, 2602 struct perf_event_context *ctx, 2603 void *info) 2604 { 2605 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx; 2606 enum perf_event_state state = PERF_EVENT_STATE_OFF; 2607 unsigned long flags = (unsigned long)info; 2608 2609 perf_pmu_disable(pmu_ctx->pmu); 2610 ctx_time_update(cpuctx, ctx); 2611 2612 /* 2613 * Ensure event_sched_out() switches to OFF, at the very least 2614 * this avoids raising perf_pending_task() at this time. 2615 */ 2616 if (flags & DETACH_EXIT) 2617 state = PERF_EVENT_STATE_EXIT; 2618 if (flags & DETACH_REVOKE) 2619 state = PERF_EVENT_STATE_REVOKED; 2620 if (flags & DETACH_DEAD) 2621 state = PERF_EVENT_STATE_DEAD; 2622 2623 /* 2624 * When disabling a group leader, the whole group becomes ineligible 2625 * to run, so schedule out the full group. 2626 */ 2627 if (!(flags & DETACH_GROUP) && event == event->group_leader) 2628 group_sched_out(event, ctx); 2629 2630 __event_disable(event, ctx, state); 2631 2632 if (flags & DETACH_GROUP) 2633 perf_group_detach(event); 2634 if (flags & DETACH_CHILD) 2635 perf_child_detach(event); 2636 list_del_event(event, ctx); 2637 2638 if (!pmu_ctx->nr_events) { 2639 pmu_ctx->rotate_necessary = 0; 2640 2641 if (ctx->task && ctx->is_active) { 2642 struct perf_cpu_pmu_context *cpc = this_cpc(pmu_ctx->pmu); 2643 2644 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx); 2645 cpc->task_epc = NULL; 2646 } 2647 } 2648 2649 if (!ctx->nr_events && ctx->is_active) { 2650 if (ctx == &cpuctx->ctx) 2651 update_cgrp_time_from_cpuctx(cpuctx, true); 2652 2653 ctx->is_active = 0; 2654 if (ctx->task) { 2655 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 2656 cpuctx->task_ctx = NULL; 2657 } 2658 } 2659 perf_pmu_enable(pmu_ctx->pmu); 2660 } 2661 2662 /* 2663 * Remove the event from a task's (or a CPU's) list of events. 2664 * 2665 * If event->ctx is a cloned context, callers must make sure that 2666 * every task struct that event->ctx->task could possibly point to 2667 * remains valid. This is OK when called from perf_release since 2668 * that only calls us on the top-level context, which can't be a clone. 2669 * When called from perf_event_exit_task, it's OK because the 2670 * context has been detached from its task. 2671 */ 2672 static void perf_remove_from_context(struct perf_event *event, unsigned long flags) 2673 { 2674 struct perf_event_context *ctx = event->ctx; 2675 2676 lockdep_assert_held(&ctx->mutex); 2677 2678 /* 2679 * Because of perf_event_exit_task(), perf_remove_from_context() ought 2680 * to work in the face of TASK_TOMBSTONE, unlike every other 2681 * event_function_call() user. 2682 */ 2683 raw_spin_lock_irq(&ctx->lock); 2684 if (!ctx->is_active) { 2685 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context), 2686 ctx, (void *)flags); 2687 raw_spin_unlock_irq(&ctx->lock); 2688 return; 2689 } 2690 raw_spin_unlock_irq(&ctx->lock); 2691 2692 event_function_call(event, __perf_remove_from_context, (void *)flags); 2693 } 2694 2695 static void __event_disable(struct perf_event *event, 2696 struct perf_event_context *ctx, 2697 enum perf_event_state state) 2698 { 2699 event_sched_out(event, ctx); 2700 if (event->state > PERF_EVENT_STATE_OFF) 2701 perf_cgroup_event_disable(event, ctx); 2702 perf_event_set_state(event, min(event->state, state)); 2703 } 2704 2705 /* 2706 * Cross CPU call to disable a performance event 2707 */ 2708 static void __perf_event_disable(struct perf_event *event, 2709 struct perf_cpu_context *cpuctx, 2710 struct perf_event_context *ctx, 2711 void *info) 2712 { 2713 if (event->state < PERF_EVENT_STATE_INACTIVE) 2714 return; 2715 2716 perf_pmu_disable(event->pmu_ctx->pmu); 2717 ctx_time_update_event(ctx, event); 2718 2719 /* 2720 * When disabling a group leader, the whole group becomes ineligible 2721 * to run, so schedule out the full group. 2722 */ 2723 if (event == event->group_leader) 2724 group_sched_out(event, ctx); 2725 2726 /* 2727 * But only mark the leader OFF; the siblings will remain 2728 * INACTIVE. 2729 */ 2730 __event_disable(event, ctx, PERF_EVENT_STATE_OFF); 2731 2732 perf_pmu_enable(event->pmu_ctx->pmu); 2733 } 2734 2735 /* 2736 * Disable an event. 2737 * 2738 * If event->ctx is a cloned context, callers must make sure that 2739 * every task struct that event->ctx->task could possibly point to 2740 * remains valid. This condition is satisfied when called through 2741 * perf_event_for_each_child or perf_event_for_each because they 2742 * hold the top-level event's child_mutex, so any descendant that 2743 * goes to exit will block in perf_event_exit_event(). 2744 * 2745 * When called from perf_pending_disable it's OK because event->ctx 2746 * is the current context on this CPU and preemption is disabled, 2747 * hence we can't get into perf_event_task_sched_out for this context. 2748 */ 2749 static void _perf_event_disable(struct perf_event *event) 2750 { 2751 struct perf_event_context *ctx = event->ctx; 2752 2753 raw_spin_lock_irq(&ctx->lock); 2754 if (event->state <= PERF_EVENT_STATE_OFF) { 2755 raw_spin_unlock_irq(&ctx->lock); 2756 return; 2757 } 2758 raw_spin_unlock_irq(&ctx->lock); 2759 2760 event_function_call(event, __perf_event_disable, NULL); 2761 } 2762 2763 void perf_event_disable_local(struct perf_event *event) 2764 { 2765 event_function_local(event, __perf_event_disable, NULL); 2766 } 2767 2768 /* 2769 * Strictly speaking kernel users cannot create groups and therefore this 2770 * interface does not need the perf_event_ctx_lock() magic. 2771 */ 2772 void perf_event_disable(struct perf_event *event) 2773 { 2774 struct perf_event_context *ctx; 2775 2776 ctx = perf_event_ctx_lock(event); 2777 _perf_event_disable(event); 2778 perf_event_ctx_unlock(event, ctx); 2779 } 2780 EXPORT_SYMBOL_GPL(perf_event_disable); 2781 2782 void perf_event_disable_inatomic(struct perf_event *event) 2783 { 2784 event->pending_disable = 1; 2785 irq_work_queue(&event->pending_disable_irq); 2786 } 2787 2788 #define MAX_INTERRUPTS (~0ULL) 2789 2790 static void perf_log_throttle(struct perf_event *event, int enable); 2791 static void perf_log_itrace_start(struct perf_event *event); 2792 2793 static void perf_event_unthrottle(struct perf_event *event, bool start) 2794 { 2795 if (event->state != PERF_EVENT_STATE_ACTIVE) 2796 return; 2797 2798 event->hw.interrupts = 0; 2799 if (start) 2800 event->pmu->start(event, 0); 2801 if (event == event->group_leader) 2802 perf_log_throttle(event, 1); 2803 } 2804 2805 static void perf_event_throttle(struct perf_event *event) 2806 { 2807 if (event->state != PERF_EVENT_STATE_ACTIVE) 2808 return; 2809 2810 event->hw.interrupts = MAX_INTERRUPTS; 2811 event->pmu->stop(event, 0); 2812 if (event == event->group_leader) 2813 perf_log_throttle(event, 0); 2814 } 2815 2816 static void perf_event_unthrottle_group(struct perf_event *event, bool skip_start_event) 2817 { 2818 struct perf_event *sibling, *leader = event->group_leader; 2819 2820 perf_event_unthrottle(leader, skip_start_event ? leader != event : true); 2821 for_each_sibling_event(sibling, leader) 2822 perf_event_unthrottle(sibling, skip_start_event ? sibling != event : true); 2823 } 2824 2825 static void perf_event_throttle_group(struct perf_event *event) 2826 { 2827 struct perf_event *sibling, *leader = event->group_leader; 2828 2829 perf_event_throttle(leader); 2830 for_each_sibling_event(sibling, leader) 2831 perf_event_throttle(sibling); 2832 } 2833 2834 static int 2835 event_sched_in(struct perf_event *event, struct perf_event_context *ctx) 2836 { 2837 struct perf_event_pmu_context *epc = event->pmu_ctx; 2838 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu); 2839 int ret = 0; 2840 2841 WARN_ON_ONCE(event->ctx != ctx); 2842 2843 lockdep_assert_held(&ctx->lock); 2844 2845 if (event->state <= PERF_EVENT_STATE_OFF) 2846 return 0; 2847 2848 WRITE_ONCE(event->oncpu, smp_processor_id()); 2849 /* 2850 * Order event::oncpu write to happen before the ACTIVE state is 2851 * visible. This allows perf_event_{stop,read}() to observe the correct 2852 * ->oncpu if it sees ACTIVE. 2853 */ 2854 smp_wmb(); 2855 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE); 2856 2857 /* 2858 * Unthrottle events, since we scheduled we might have missed several 2859 * ticks already, also for a heavily scheduling task there is little 2860 * guarantee it'll get a tick in a timely manner. 2861 */ 2862 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) 2863 perf_event_unthrottle(event, false); 2864 2865 perf_pmu_disable(event->pmu); 2866 2867 perf_log_itrace_start(event); 2868 2869 if (event->pmu->add(event, PERF_EF_START)) { 2870 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 2871 event->oncpu = -1; 2872 ret = -EAGAIN; 2873 goto out; 2874 } 2875 2876 if (!is_software_event(event)) 2877 cpc->active_oncpu++; 2878 if (is_event_in_freq_mode(event)) { 2879 ctx->nr_freq++; 2880 epc->nr_freq++; 2881 } 2882 if (event->attr.exclusive) 2883 cpc->exclusive = 1; 2884 2885 out: 2886 perf_pmu_enable(event->pmu); 2887 2888 return ret; 2889 } 2890 2891 static int 2892 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx) 2893 { 2894 struct perf_event *event, *partial_group = NULL; 2895 struct pmu *pmu = group_event->pmu_ctx->pmu; 2896 2897 if (group_event->state == PERF_EVENT_STATE_OFF) 2898 return 0; 2899 2900 pmu->start_txn(pmu, PERF_PMU_TXN_ADD); 2901 2902 if (event_sched_in(group_event, ctx)) 2903 goto error; 2904 2905 /* 2906 * Schedule in siblings as one group (if any): 2907 */ 2908 for_each_sibling_event(event, group_event) { 2909 if (event_sched_in(event, ctx)) { 2910 partial_group = event; 2911 goto group_error; 2912 } 2913 } 2914 2915 if (!pmu->commit_txn(pmu)) 2916 return 0; 2917 2918 group_error: 2919 /* 2920 * Groups can be scheduled in as one unit only, so undo any 2921 * partial group before returning: 2922 * The events up to the failed event are scheduled out normally. 2923 */ 2924 for_each_sibling_event(event, group_event) { 2925 if (event == partial_group) 2926 break; 2927 2928 event_sched_out(event, ctx); 2929 } 2930 event_sched_out(group_event, ctx); 2931 2932 error: 2933 pmu->cancel_txn(pmu); 2934 return -EAGAIN; 2935 } 2936 2937 /* 2938 * Work out whether we can put this event group on the CPU now. 2939 */ 2940 static int group_can_go_on(struct perf_event *event, int can_add_hw) 2941 { 2942 struct perf_event_pmu_context *epc = event->pmu_ctx; 2943 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu); 2944 2945 /* 2946 * Groups consisting entirely of software events can always go on. 2947 */ 2948 if (event->group_caps & PERF_EV_CAP_SOFTWARE) 2949 return 1; 2950 /* 2951 * If an exclusive group is already on, no other hardware 2952 * events can go on. 2953 */ 2954 if (cpc->exclusive) 2955 return 0; 2956 /* 2957 * If this group is exclusive and there are already 2958 * events on the CPU, it can't go on. 2959 */ 2960 if (event->attr.exclusive && !list_empty(get_event_list(event))) 2961 return 0; 2962 /* 2963 * Otherwise, try to add it if all previous groups were able 2964 * to go on. 2965 */ 2966 return can_add_hw; 2967 } 2968 2969 static void add_event_to_ctx(struct perf_event *event, 2970 struct perf_event_context *ctx) 2971 { 2972 list_add_event(event, ctx); 2973 perf_group_attach(event); 2974 } 2975 2976 static void task_ctx_sched_out(struct perf_event_context *ctx, 2977 struct pmu *pmu, 2978 enum event_type_t event_type) 2979 { 2980 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 2981 2982 if (!cpuctx->task_ctx) 2983 return; 2984 2985 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx)) 2986 return; 2987 2988 ctx_sched_out(ctx, pmu, event_type); 2989 } 2990 2991 static void perf_event_sched_in(struct perf_cpu_context *cpuctx, 2992 struct perf_event_context *ctx, 2993 struct pmu *pmu, 2994 enum event_type_t event_type) 2995 { 2996 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED | event_type); 2997 if (ctx) 2998 ctx_sched_in(ctx, pmu, EVENT_PINNED | event_type); 2999 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE | event_type); 3000 if (ctx) 3001 ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE | event_type); 3002 } 3003 3004 /* 3005 * We want to maintain the following priority of scheduling: 3006 * - CPU pinned (EVENT_CPU | EVENT_PINNED) 3007 * - task pinned (EVENT_PINNED) 3008 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE) 3009 * - task flexible (EVENT_FLEXIBLE). 3010 * 3011 * In order to avoid unscheduling and scheduling back in everything every 3012 * time an event is added, only do it for the groups of equal priority and 3013 * below. 3014 * 3015 * This can be called after a batch operation on task events, in which case 3016 * event_type is a bit mask of the types of events involved. For CPU events, 3017 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE. 3018 */ 3019 static void ctx_resched(struct perf_cpu_context *cpuctx, 3020 struct perf_event_context *task_ctx, 3021 struct pmu *pmu, enum event_type_t event_type) 3022 { 3023 bool cpu_event = !!(event_type & EVENT_CPU); 3024 struct perf_event_pmu_context *epc; 3025 3026 /* 3027 * If pinned groups are involved, flexible groups also need to be 3028 * scheduled out. 3029 */ 3030 if (event_type & EVENT_PINNED) 3031 event_type |= EVENT_FLEXIBLE; 3032 3033 event_type &= EVENT_ALL; 3034 3035 for_each_epc(epc, &cpuctx->ctx, pmu, 0) 3036 perf_pmu_disable(epc->pmu); 3037 3038 if (task_ctx) { 3039 for_each_epc(epc, task_ctx, pmu, 0) 3040 perf_pmu_disable(epc->pmu); 3041 3042 task_ctx_sched_out(task_ctx, pmu, event_type); 3043 } 3044 3045 /* 3046 * Decide which cpu ctx groups to schedule out based on the types 3047 * of events that caused rescheduling: 3048 * - EVENT_CPU: schedule out corresponding groups; 3049 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups; 3050 * - otherwise, do nothing more. 3051 */ 3052 if (cpu_event) 3053 ctx_sched_out(&cpuctx->ctx, pmu, event_type); 3054 else if (event_type & EVENT_PINNED) 3055 ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE); 3056 3057 perf_event_sched_in(cpuctx, task_ctx, pmu, 0); 3058 3059 for_each_epc(epc, &cpuctx->ctx, pmu, 0) 3060 perf_pmu_enable(epc->pmu); 3061 3062 if (task_ctx) { 3063 for_each_epc(epc, task_ctx, pmu, 0) 3064 perf_pmu_enable(epc->pmu); 3065 } 3066 } 3067 3068 void perf_pmu_resched(struct pmu *pmu) 3069 { 3070 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3071 struct perf_event_context *task_ctx = cpuctx->task_ctx; 3072 3073 perf_ctx_lock(cpuctx, task_ctx); 3074 ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU); 3075 perf_ctx_unlock(cpuctx, task_ctx); 3076 } 3077 3078 /* 3079 * Cross CPU call to install and enable a performance event 3080 * 3081 * Very similar to remote_function() + event_function() but cannot assume that 3082 * things like ctx->is_active and cpuctx->task_ctx are set. 3083 */ 3084 static int __perf_install_in_context(void *info) 3085 { 3086 struct perf_event *event = info; 3087 struct perf_event_context *ctx = event->ctx; 3088 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3089 struct perf_event_context *task_ctx = cpuctx->task_ctx; 3090 bool reprogram = true; 3091 int ret = 0; 3092 3093 raw_spin_lock(&cpuctx->ctx.lock); 3094 if (ctx->task) { 3095 raw_spin_lock(&ctx->lock); 3096 task_ctx = ctx; 3097 3098 reprogram = (ctx->task == current); 3099 3100 /* 3101 * If the task is running, it must be running on this CPU, 3102 * otherwise we cannot reprogram things. 3103 * 3104 * If its not running, we don't care, ctx->lock will 3105 * serialize against it becoming runnable. 3106 */ 3107 if (task_curr(ctx->task) && !reprogram) { 3108 ret = -ESRCH; 3109 goto unlock; 3110 } 3111 3112 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx); 3113 } else if (task_ctx) { 3114 raw_spin_lock(&task_ctx->lock); 3115 } 3116 3117 #ifdef CONFIG_CGROUP_PERF 3118 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) { 3119 /* 3120 * If the current cgroup doesn't match the event's 3121 * cgroup, we should not try to schedule it. 3122 */ 3123 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx); 3124 reprogram = cgroup_is_descendant(cgrp->css.cgroup, 3125 event->cgrp->css.cgroup); 3126 } 3127 #endif 3128 3129 if (reprogram) { 3130 ctx_time_freeze(cpuctx, ctx); 3131 add_event_to_ctx(event, ctx); 3132 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, 3133 get_event_type(event)); 3134 } else { 3135 add_event_to_ctx(event, ctx); 3136 } 3137 3138 unlock: 3139 perf_ctx_unlock(cpuctx, task_ctx); 3140 3141 return ret; 3142 } 3143 3144 static bool exclusive_event_installable(struct perf_event *event, 3145 struct perf_event_context *ctx); 3146 3147 /* 3148 * Attach a performance event to a context. 3149 * 3150 * Very similar to event_function_call, see comment there. 3151 */ 3152 static void 3153 perf_install_in_context(struct perf_event_context *ctx, 3154 struct perf_event *event, 3155 int cpu) 3156 { 3157 struct task_struct *task = READ_ONCE(ctx->task); 3158 3159 lockdep_assert_held(&ctx->mutex); 3160 3161 WARN_ON_ONCE(!exclusive_event_installable(event, ctx)); 3162 3163 if (event->cpu != -1) 3164 WARN_ON_ONCE(event->cpu != cpu); 3165 3166 /* 3167 * Ensures that if we can observe event->ctx, both the event and ctx 3168 * will be 'complete'. See perf_iterate_sb_cpu(). 3169 */ 3170 smp_store_release(&event->ctx, ctx); 3171 3172 /* 3173 * perf_event_attr::disabled events will not run and can be initialized 3174 * without IPI. Except when this is the first event for the context, in 3175 * that case we need the magic of the IPI to set ctx->is_active. 3176 * 3177 * The IOC_ENABLE that is sure to follow the creation of a disabled 3178 * event will issue the IPI and reprogram the hardware. 3179 */ 3180 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && 3181 ctx->nr_events && !is_cgroup_event(event)) { 3182 raw_spin_lock_irq(&ctx->lock); 3183 if (ctx->task == TASK_TOMBSTONE) { 3184 raw_spin_unlock_irq(&ctx->lock); 3185 return; 3186 } 3187 add_event_to_ctx(event, ctx); 3188 raw_spin_unlock_irq(&ctx->lock); 3189 return; 3190 } 3191 3192 if (!task) { 3193 cpu_function_call(cpu, __perf_install_in_context, event); 3194 return; 3195 } 3196 3197 /* 3198 * Should not happen, we validate the ctx is still alive before calling. 3199 */ 3200 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) 3201 return; 3202 3203 /* 3204 * Installing events is tricky because we cannot rely on ctx->is_active 3205 * to be set in case this is the nr_events 0 -> 1 transition. 3206 * 3207 * Instead we use task_curr(), which tells us if the task is running. 3208 * However, since we use task_curr() outside of rq::lock, we can race 3209 * against the actual state. This means the result can be wrong. 3210 * 3211 * If we get a false positive, we retry, this is harmless. 3212 * 3213 * If we get a false negative, things are complicated. If we are after 3214 * perf_event_context_sched_in() ctx::lock will serialize us, and the 3215 * value must be correct. If we're before, it doesn't matter since 3216 * perf_event_context_sched_in() will program the counter. 3217 * 3218 * However, this hinges on the remote context switch having observed 3219 * our task->perf_event_ctxp[] store, such that it will in fact take 3220 * ctx::lock in perf_event_context_sched_in(). 3221 * 3222 * We do this by task_function_call(), if the IPI fails to hit the task 3223 * we know any future context switch of task must see the 3224 * perf_event_ctpx[] store. 3225 */ 3226 3227 /* 3228 * This smp_mb() orders the task->perf_event_ctxp[] store with the 3229 * task_cpu() load, such that if the IPI then does not find the task 3230 * running, a future context switch of that task must observe the 3231 * store. 3232 */ 3233 smp_mb(); 3234 again: 3235 if (!task_function_call(task, __perf_install_in_context, event)) 3236 return; 3237 3238 raw_spin_lock_irq(&ctx->lock); 3239 task = ctx->task; 3240 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) { 3241 /* 3242 * Cannot happen because we already checked above (which also 3243 * cannot happen), and we hold ctx->mutex, which serializes us 3244 * against perf_event_exit_task_context(). 3245 */ 3246 raw_spin_unlock_irq(&ctx->lock); 3247 return; 3248 } 3249 /* 3250 * If the task is not running, ctx->lock will avoid it becoming so, 3251 * thus we can safely install the event. 3252 */ 3253 if (task_curr(task)) { 3254 raw_spin_unlock_irq(&ctx->lock); 3255 goto again; 3256 } 3257 add_event_to_ctx(event, ctx); 3258 raw_spin_unlock_irq(&ctx->lock); 3259 } 3260 3261 /* 3262 * Cross CPU call to enable a performance event 3263 */ 3264 static void __perf_event_enable(struct perf_event *event, 3265 struct perf_cpu_context *cpuctx, 3266 struct perf_event_context *ctx, 3267 void *info) 3268 { 3269 struct perf_event *leader = event->group_leader; 3270 struct perf_event_context *task_ctx; 3271 3272 if (event->state >= PERF_EVENT_STATE_INACTIVE || 3273 event->state <= PERF_EVENT_STATE_ERROR) 3274 return; 3275 3276 ctx_time_freeze(cpuctx, ctx); 3277 3278 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 3279 perf_cgroup_event_enable(event, ctx); 3280 3281 if (!ctx->is_active) 3282 return; 3283 3284 if (!event_filter_match(event)) 3285 return; 3286 3287 /* 3288 * If the event is in a group and isn't the group leader, 3289 * then don't put it on unless the group is on. 3290 */ 3291 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) 3292 return; 3293 3294 task_ctx = cpuctx->task_ctx; 3295 if (ctx->task) 3296 WARN_ON_ONCE(task_ctx != ctx); 3297 3298 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event)); 3299 } 3300 3301 /* 3302 * Enable an event. 3303 * 3304 * If event->ctx is a cloned context, callers must make sure that 3305 * every task struct that event->ctx->task could possibly point to 3306 * remains valid. This condition is satisfied when called through 3307 * perf_event_for_each_child or perf_event_for_each as described 3308 * for perf_event_disable. 3309 */ 3310 static void _perf_event_enable(struct perf_event *event) 3311 { 3312 struct perf_event_context *ctx = event->ctx; 3313 3314 raw_spin_lock_irq(&ctx->lock); 3315 if (event->state >= PERF_EVENT_STATE_INACTIVE || 3316 event->state < PERF_EVENT_STATE_ERROR) { 3317 out: 3318 raw_spin_unlock_irq(&ctx->lock); 3319 return; 3320 } 3321 3322 /* 3323 * If the event is in error state, clear that first. 3324 * 3325 * That way, if we see the event in error state below, we know that it 3326 * has gone back into error state, as distinct from the task having 3327 * been scheduled away before the cross-call arrived. 3328 */ 3329 if (event->state == PERF_EVENT_STATE_ERROR) { 3330 /* 3331 * Detached SIBLING events cannot leave ERROR state. 3332 */ 3333 if (event->event_caps & PERF_EV_CAP_SIBLING && 3334 event->group_leader == event) 3335 goto out; 3336 3337 event->state = PERF_EVENT_STATE_OFF; 3338 } 3339 raw_spin_unlock_irq(&ctx->lock); 3340 3341 event_function_call(event, __perf_event_enable, NULL); 3342 } 3343 3344 /* 3345 * See perf_event_disable(); 3346 */ 3347 void perf_event_enable(struct perf_event *event) 3348 { 3349 struct perf_event_context *ctx; 3350 3351 ctx = perf_event_ctx_lock(event); 3352 _perf_event_enable(event); 3353 perf_event_ctx_unlock(event, ctx); 3354 } 3355 EXPORT_SYMBOL_GPL(perf_event_enable); 3356 3357 struct stop_event_data { 3358 struct perf_event *event; 3359 unsigned int restart; 3360 }; 3361 3362 static int __perf_event_stop(void *info) 3363 { 3364 struct stop_event_data *sd = info; 3365 struct perf_event *event = sd->event; 3366 3367 /* if it's already INACTIVE, do nothing */ 3368 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) 3369 return 0; 3370 3371 /* matches smp_wmb() in event_sched_in() */ 3372 smp_rmb(); 3373 3374 /* 3375 * There is a window with interrupts enabled before we get here, 3376 * so we need to check again lest we try to stop another CPU's event. 3377 */ 3378 if (READ_ONCE(event->oncpu) != smp_processor_id()) 3379 return -EAGAIN; 3380 3381 event->pmu->stop(event, PERF_EF_UPDATE); 3382 3383 /* 3384 * May race with the actual stop (through perf_pmu_output_stop()), 3385 * but it is only used for events with AUX ring buffer, and such 3386 * events will refuse to restart because of rb::aux_mmap_count==0, 3387 * see comments in perf_aux_output_begin(). 3388 * 3389 * Since this is happening on an event-local CPU, no trace is lost 3390 * while restarting. 3391 */ 3392 if (sd->restart) 3393 event->pmu->start(event, 0); 3394 3395 return 0; 3396 } 3397 3398 static int perf_event_stop(struct perf_event *event, int restart) 3399 { 3400 struct stop_event_data sd = { 3401 .event = event, 3402 .restart = restart, 3403 }; 3404 int ret = 0; 3405 3406 do { 3407 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) 3408 return 0; 3409 3410 /* matches smp_wmb() in event_sched_in() */ 3411 smp_rmb(); 3412 3413 /* 3414 * We only want to restart ACTIVE events, so if the event goes 3415 * inactive here (event->oncpu==-1), there's nothing more to do; 3416 * fall through with ret==-ENXIO. 3417 */ 3418 ret = cpu_function_call(READ_ONCE(event->oncpu), 3419 __perf_event_stop, &sd); 3420 } while (ret == -EAGAIN); 3421 3422 return ret; 3423 } 3424 3425 /* 3426 * In order to contain the amount of racy and tricky in the address filter 3427 * configuration management, it is a two part process: 3428 * 3429 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below, 3430 * we update the addresses of corresponding vmas in 3431 * event::addr_filter_ranges array and bump the event::addr_filters_gen; 3432 * (p2) when an event is scheduled in (pmu::add), it calls 3433 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync() 3434 * if the generation has changed since the previous call. 3435 * 3436 * If (p1) happens while the event is active, we restart it to force (p2). 3437 * 3438 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on 3439 * pre-existing mappings, called once when new filters arrive via SET_FILTER 3440 * ioctl; 3441 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly 3442 * registered mapping, called for every new mmap(), with mm::mmap_lock down 3443 * for reading; 3444 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process 3445 * of exec. 3446 */ 3447 void perf_event_addr_filters_sync(struct perf_event *event) 3448 { 3449 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 3450 3451 if (!has_addr_filter(event)) 3452 return; 3453 3454 raw_spin_lock(&ifh->lock); 3455 if (event->addr_filters_gen != event->hw.addr_filters_gen) { 3456 event->pmu->addr_filters_sync(event); 3457 event->hw.addr_filters_gen = event->addr_filters_gen; 3458 } 3459 raw_spin_unlock(&ifh->lock); 3460 } 3461 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync); 3462 3463 static int _perf_event_refresh(struct perf_event *event, int refresh) 3464 { 3465 /* 3466 * not supported on inherited events 3467 */ 3468 if (event->attr.inherit || !is_sampling_event(event)) 3469 return -EINVAL; 3470 3471 atomic_add(refresh, &event->event_limit); 3472 _perf_event_enable(event); 3473 3474 return 0; 3475 } 3476 3477 /* 3478 * See perf_event_disable() 3479 */ 3480 int perf_event_refresh(struct perf_event *event, int refresh) 3481 { 3482 struct perf_event_context *ctx; 3483 int ret; 3484 3485 ctx = perf_event_ctx_lock(event); 3486 ret = _perf_event_refresh(event, refresh); 3487 perf_event_ctx_unlock(event, ctx); 3488 3489 return ret; 3490 } 3491 EXPORT_SYMBOL_GPL(perf_event_refresh); 3492 3493 static int perf_event_modify_breakpoint(struct perf_event *bp, 3494 struct perf_event_attr *attr) 3495 { 3496 int err; 3497 3498 _perf_event_disable(bp); 3499 3500 err = modify_user_hw_breakpoint_check(bp, attr, true); 3501 3502 if (!bp->attr.disabled) 3503 _perf_event_enable(bp); 3504 3505 return err; 3506 } 3507 3508 /* 3509 * Copy event-type-independent attributes that may be modified. 3510 */ 3511 static void perf_event_modify_copy_attr(struct perf_event_attr *to, 3512 const struct perf_event_attr *from) 3513 { 3514 to->sig_data = from->sig_data; 3515 } 3516 3517 static int perf_event_modify_attr(struct perf_event *event, 3518 struct perf_event_attr *attr) 3519 { 3520 int (*func)(struct perf_event *, struct perf_event_attr *); 3521 struct perf_event *child; 3522 int err; 3523 3524 if (event->attr.type != attr->type) 3525 return -EINVAL; 3526 3527 switch (event->attr.type) { 3528 case PERF_TYPE_BREAKPOINT: 3529 func = perf_event_modify_breakpoint; 3530 break; 3531 default: 3532 /* Place holder for future additions. */ 3533 return -EOPNOTSUPP; 3534 } 3535 3536 WARN_ON_ONCE(event->ctx->parent_ctx); 3537 3538 mutex_lock(&event->child_mutex); 3539 /* 3540 * Event-type-independent attributes must be copied before event-type 3541 * modification, which will validate that final attributes match the 3542 * source attributes after all relevant attributes have been copied. 3543 */ 3544 perf_event_modify_copy_attr(&event->attr, attr); 3545 err = func(event, attr); 3546 if (err) 3547 goto out; 3548 list_for_each_entry(child, &event->child_list, child_list) { 3549 perf_event_modify_copy_attr(&child->attr, attr); 3550 err = func(child, attr); 3551 if (err) 3552 goto out; 3553 } 3554 out: 3555 mutex_unlock(&event->child_mutex); 3556 return err; 3557 } 3558 3559 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx, 3560 enum event_type_t event_type) 3561 { 3562 struct perf_event_context *ctx = pmu_ctx->ctx; 3563 struct perf_event *event, *tmp; 3564 struct pmu *pmu = pmu_ctx->pmu; 3565 3566 if (ctx->task && !(ctx->is_active & EVENT_ALL)) { 3567 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 3568 3569 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx); 3570 cpc->task_epc = NULL; 3571 } 3572 3573 if (!(event_type & EVENT_ALL)) 3574 return; 3575 3576 perf_pmu_disable(pmu); 3577 if (event_type & EVENT_PINNED) { 3578 list_for_each_entry_safe(event, tmp, 3579 &pmu_ctx->pinned_active, 3580 active_list) 3581 group_sched_out(event, ctx); 3582 } 3583 3584 if (event_type & EVENT_FLEXIBLE) { 3585 list_for_each_entry_safe(event, tmp, 3586 &pmu_ctx->flexible_active, 3587 active_list) 3588 group_sched_out(event, ctx); 3589 /* 3590 * Since we cleared EVENT_FLEXIBLE, also clear 3591 * rotate_necessary, is will be reset by 3592 * ctx_flexible_sched_in() when needed. 3593 */ 3594 pmu_ctx->rotate_necessary = 0; 3595 } 3596 perf_pmu_enable(pmu); 3597 } 3598 3599 /* 3600 * Be very careful with the @pmu argument since this will change ctx state. 3601 * The @pmu argument works for ctx_resched(), because that is symmetric in 3602 * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant. 3603 * 3604 * However, if you were to be asymmetrical, you could end up with messed up 3605 * state, eg. ctx->is_active cleared even though most EPCs would still actually 3606 * be active. 3607 */ 3608 static void 3609 ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type) 3610 { 3611 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3612 enum event_type_t active_type = event_type & ~EVENT_FLAGS; 3613 struct perf_event_pmu_context *pmu_ctx; 3614 int is_active = ctx->is_active; 3615 3616 3617 lockdep_assert_held(&ctx->lock); 3618 3619 if (likely(!ctx->nr_events)) { 3620 /* 3621 * See __perf_remove_from_context(). 3622 */ 3623 WARN_ON_ONCE(ctx->is_active); 3624 if (ctx->task) 3625 WARN_ON_ONCE(cpuctx->task_ctx); 3626 return; 3627 } 3628 3629 /* 3630 * Always update time if it was set; not only when it changes. 3631 * Otherwise we can 'forget' to update time for any but the last 3632 * context we sched out. For example: 3633 * 3634 * ctx_sched_out(.event_type = EVENT_FLEXIBLE) 3635 * ctx_sched_out(.event_type = EVENT_PINNED) 3636 * 3637 * would only update time for the pinned events. 3638 */ 3639 __ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx, event_type); 3640 3641 /* 3642 * CPU-release for the below ->is_active store, 3643 * see __load_acquire() in perf_event_time_now() 3644 */ 3645 barrier(); 3646 ctx->is_active &= ~active_type; 3647 3648 if (!(ctx->is_active & EVENT_ALL)) { 3649 /* 3650 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now() 3651 * does not observe a hole. perf_ctx_unlock() will clean up. 3652 */ 3653 if (ctx->is_active & EVENT_FROZEN) 3654 ctx->is_active &= EVENT_TIME_FROZEN; 3655 else 3656 ctx->is_active = 0; 3657 } 3658 3659 if (ctx->task) { 3660 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 3661 if (!(ctx->is_active & EVENT_ALL)) 3662 cpuctx->task_ctx = NULL; 3663 } 3664 3665 if (event_type & EVENT_GUEST) { 3666 /* 3667 * Schedule out all exclude_guest events of PMU 3668 * with PERF_PMU_CAP_MEDIATED_VPMU. 3669 */ 3670 is_active = EVENT_ALL; 3671 __update_context_guest_time(ctx, false); 3672 perf_cgroup_set_timestamp(cpuctx, true); 3673 barrier(); 3674 } else { 3675 is_active ^= ctx->is_active; /* changed bits */ 3676 } 3677 3678 for_each_epc(pmu_ctx, ctx, pmu, event_type) 3679 __pmu_ctx_sched_out(pmu_ctx, is_active); 3680 } 3681 3682 /* 3683 * Test whether two contexts are equivalent, i.e. whether they have both been 3684 * cloned from the same version of the same context. 3685 * 3686 * Equivalence is measured using a generation number in the context that is 3687 * incremented on each modification to it; see unclone_ctx(), list_add_event() 3688 * and list_del_event(). 3689 */ 3690 static int context_equiv(struct perf_event_context *ctx1, 3691 struct perf_event_context *ctx2) 3692 { 3693 lockdep_assert_held(&ctx1->lock); 3694 lockdep_assert_held(&ctx2->lock); 3695 3696 /* Pinning disables the swap optimization */ 3697 if (ctx1->pin_count || ctx2->pin_count) 3698 return 0; 3699 3700 /* If ctx1 is the parent of ctx2 */ 3701 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen) 3702 return 1; 3703 3704 /* If ctx2 is the parent of ctx1 */ 3705 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation) 3706 return 1; 3707 3708 /* 3709 * If ctx1 and ctx2 have the same parent; we flatten the parent 3710 * hierarchy, see perf_event_init_context(). 3711 */ 3712 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx && 3713 ctx1->parent_gen == ctx2->parent_gen) 3714 return 1; 3715 3716 /* Unmatched */ 3717 return 0; 3718 } 3719 3720 static void __perf_event_sync_stat(struct perf_event *event, 3721 struct perf_event *next_event) 3722 { 3723 u64 value; 3724 3725 if (!event->attr.inherit_stat) 3726 return; 3727 3728 /* 3729 * Update the event value, we cannot use perf_event_read() 3730 * because we're in the middle of a context switch and have IRQs 3731 * disabled, which upsets smp_call_function_single(), however 3732 * we know the event must be on the current CPU, therefore we 3733 * don't need to use it. 3734 */ 3735 perf_pmu_read(event); 3736 3737 perf_event_update_time(event); 3738 3739 /* 3740 * In order to keep per-task stats reliable we need to flip the event 3741 * values when we flip the contexts. 3742 */ 3743 value = local64_read(&next_event->count); 3744 value = local64_xchg(&event->count, value); 3745 local64_set(&next_event->count, value); 3746 3747 swap(event->total_time_enabled, next_event->total_time_enabled); 3748 swap(event->total_time_running, next_event->total_time_running); 3749 3750 /* 3751 * Since we swizzled the values, update the user visible data too. 3752 */ 3753 perf_event_update_userpage(event); 3754 perf_event_update_userpage(next_event); 3755 } 3756 3757 static void perf_event_sync_stat(struct perf_event_context *ctx, 3758 struct perf_event_context *next_ctx) 3759 { 3760 struct perf_event *event, *next_event; 3761 3762 if (!ctx->nr_stat) 3763 return; 3764 3765 update_context_time(ctx); 3766 3767 event = list_first_entry(&ctx->event_list, 3768 struct perf_event, event_entry); 3769 3770 next_event = list_first_entry(&next_ctx->event_list, 3771 struct perf_event, event_entry); 3772 3773 while (&event->event_entry != &ctx->event_list && 3774 &next_event->event_entry != &next_ctx->event_list) { 3775 3776 __perf_event_sync_stat(event, next_event); 3777 3778 event = list_next_entry(event, event_entry); 3779 next_event = list_next_entry(next_event, event_entry); 3780 } 3781 } 3782 3783 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx, 3784 struct task_struct *task, bool sched_in) 3785 { 3786 struct perf_event_pmu_context *pmu_ctx; 3787 struct perf_cpu_pmu_context *cpc; 3788 3789 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) { 3790 cpc = this_cpc(pmu_ctx->pmu); 3791 3792 if (cpc->task_epc != pmu_ctx) 3793 continue; 3794 3795 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task) 3796 pmu_ctx->pmu->sched_task(pmu_ctx, task, sched_in); 3797 } 3798 } 3799 3800 static void 3801 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next) 3802 { 3803 struct perf_event_context *ctx = task->perf_event_ctxp; 3804 struct perf_event_context *next_ctx; 3805 struct perf_event_context *parent, *next_parent; 3806 int do_switch = 1; 3807 3808 if (likely(!ctx)) 3809 return; 3810 3811 rcu_read_lock(); 3812 next_ctx = rcu_dereference(next->perf_event_ctxp); 3813 if (!next_ctx) 3814 goto unlock; 3815 3816 parent = rcu_dereference(ctx->parent_ctx); 3817 next_parent = rcu_dereference(next_ctx->parent_ctx); 3818 3819 /* If neither context have a parent context; they cannot be clones. */ 3820 if (!parent && !next_parent) 3821 goto unlock; 3822 3823 if (next_parent == ctx || next_ctx == parent || next_parent == parent) { 3824 /* 3825 * Looks like the two contexts are clones, so we might be 3826 * able to optimize the context switch. We lock both 3827 * contexts and check that they are clones under the 3828 * lock (including re-checking that neither has been 3829 * uncloned in the meantime). It doesn't matter which 3830 * order we take the locks because no other cpu could 3831 * be trying to lock both of these tasks. 3832 */ 3833 raw_spin_lock(&ctx->lock); 3834 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING); 3835 if (context_equiv(ctx, next_ctx)) { 3836 3837 perf_ctx_disable(ctx, 0); 3838 3839 /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */ 3840 if (local_read(&ctx->nr_no_switch_fast) || 3841 local_read(&next_ctx->nr_no_switch_fast)) { 3842 /* 3843 * Must not swap out ctx when there's pending 3844 * events that rely on the ctx->task relation. 3845 * 3846 * Likewise, when a context contains inherit + 3847 * SAMPLE_READ events they should be switched 3848 * out using the slow path so that they are 3849 * treated as if they were distinct contexts. 3850 */ 3851 raw_spin_unlock(&next_ctx->lock); 3852 rcu_read_unlock(); 3853 goto inside_switch; 3854 } 3855 3856 WRITE_ONCE(ctx->task, next); 3857 WRITE_ONCE(next_ctx->task, task); 3858 3859 perf_ctx_sched_task_cb(ctx, task, false); 3860 3861 perf_ctx_enable(ctx, 0); 3862 3863 /* 3864 * RCU_INIT_POINTER here is safe because we've not 3865 * modified the ctx and the above modification of 3866 * ctx->task is immaterial since this value is 3867 * always verified under ctx->lock which we're now 3868 * holding. 3869 */ 3870 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx); 3871 RCU_INIT_POINTER(next->perf_event_ctxp, ctx); 3872 3873 do_switch = 0; 3874 3875 perf_event_sync_stat(ctx, next_ctx); 3876 } 3877 raw_spin_unlock(&next_ctx->lock); 3878 raw_spin_unlock(&ctx->lock); 3879 } 3880 unlock: 3881 rcu_read_unlock(); 3882 3883 if (do_switch) { 3884 raw_spin_lock(&ctx->lock); 3885 perf_ctx_disable(ctx, 0); 3886 3887 inside_switch: 3888 perf_ctx_sched_task_cb(ctx, task, false); 3889 task_ctx_sched_out(ctx, NULL, EVENT_ALL); 3890 3891 perf_ctx_enable(ctx, 0); 3892 raw_spin_unlock(&ctx->lock); 3893 } 3894 } 3895 3896 static DEFINE_PER_CPU(struct list_head, sched_cb_list); 3897 static DEFINE_PER_CPU(int, perf_sched_cb_usages); 3898 3899 void perf_sched_cb_dec(struct pmu *pmu) 3900 { 3901 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 3902 3903 this_cpu_dec(perf_sched_cb_usages); 3904 barrier(); 3905 3906 if (!--cpc->sched_cb_usage) 3907 list_del(&cpc->sched_cb_entry); 3908 } 3909 3910 3911 void perf_sched_cb_inc(struct pmu *pmu) 3912 { 3913 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 3914 3915 if (!cpc->sched_cb_usage++) 3916 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list)); 3917 3918 barrier(); 3919 this_cpu_inc(perf_sched_cb_usages); 3920 } 3921 3922 /* 3923 * This function provides the context switch callback to the lower code 3924 * layer. It is invoked ONLY when the context switch callback is enabled. 3925 * 3926 * This callback is relevant even to per-cpu events; for example multi event 3927 * PEBS requires this to provide PID/TID information. This requires we flush 3928 * all queued PEBS records before we context switch to a new task. 3929 */ 3930 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc, 3931 struct task_struct *task, bool sched_in) 3932 { 3933 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3934 struct pmu *pmu; 3935 3936 pmu = cpc->epc.pmu; 3937 3938 /* software PMUs will not have sched_task */ 3939 if (WARN_ON_ONCE(!pmu->sched_task)) 3940 return; 3941 3942 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 3943 perf_pmu_disable(pmu); 3944 3945 pmu->sched_task(&cpc->epc, task, sched_in); 3946 3947 perf_pmu_enable(pmu); 3948 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 3949 } 3950 3951 static void perf_pmu_sched_task(struct task_struct *prev, 3952 struct task_struct *next, 3953 bool sched_in) 3954 { 3955 struct perf_cpu_pmu_context *cpc, *cpc2; 3956 3957 if (prev == next) 3958 return; 3959 3960 list_for_each_entry_safe(cpc, cpc2, this_cpu_ptr(&sched_cb_list), sched_cb_entry) { 3961 if (cpc->task_epc) 3962 continue; 3963 3964 __perf_pmu_sched_task(cpc, sched_in ? next : prev, sched_in); 3965 } 3966 } 3967 3968 static void perf_event_switch(struct task_struct *task, 3969 struct task_struct *next_prev, bool sched_in); 3970 3971 /* 3972 * Called from scheduler to remove the events of the current task, 3973 * with interrupts disabled. 3974 * 3975 * We stop each event and update the event value in event->count. 3976 * 3977 * This does not protect us against NMI, but disable() 3978 * sets the disabled bit in the control field of event _before_ 3979 * accessing the event control register. If a NMI hits, then it will 3980 * not restart the event. 3981 */ 3982 void __perf_event_task_sched_out(struct task_struct *task, 3983 struct task_struct *next) 3984 { 3985 if (__this_cpu_read(perf_sched_cb_usages)) 3986 perf_pmu_sched_task(task, next, false); 3987 3988 if (atomic_read(&nr_switch_events)) 3989 perf_event_switch(task, next, false); 3990 3991 perf_event_context_sched_out(task, next); 3992 3993 /* 3994 * if cgroup events exist on this CPU, then we need 3995 * to check if we have to switch out PMU state. 3996 * cgroup event are system-wide mode only 3997 */ 3998 perf_cgroup_switch(next); 3999 } 4000 4001 static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args) 4002 { 4003 const struct perf_event *le = *(const struct perf_event **)l; 4004 const struct perf_event *re = *(const struct perf_event **)r; 4005 4006 return le->group_index < re->group_index; 4007 } 4008 4009 DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap); 4010 4011 static const struct min_heap_callbacks perf_min_heap = { 4012 .less = perf_less_group_idx, 4013 .swp = NULL, 4014 }; 4015 4016 static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event) 4017 { 4018 struct perf_event **itrs = heap->data; 4019 4020 if (event) { 4021 itrs[heap->nr] = event; 4022 heap->nr++; 4023 } 4024 } 4025 4026 static void __link_epc(struct perf_event_pmu_context *pmu_ctx) 4027 { 4028 struct perf_cpu_pmu_context *cpc; 4029 4030 if (!pmu_ctx->ctx->task) 4031 return; 4032 4033 cpc = this_cpc(pmu_ctx->pmu); 4034 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx); 4035 cpc->task_epc = pmu_ctx; 4036 } 4037 4038 static noinline int visit_groups_merge(struct perf_event_context *ctx, 4039 struct perf_event_groups *groups, int cpu, 4040 struct pmu *pmu, 4041 int (*func)(struct perf_event *, void *), 4042 void *data) 4043 { 4044 #ifdef CONFIG_CGROUP_PERF 4045 struct cgroup_subsys_state *css = NULL; 4046 #endif 4047 struct perf_cpu_context *cpuctx = NULL; 4048 /* Space for per CPU and/or any CPU event iterators. */ 4049 struct perf_event *itrs[2]; 4050 struct perf_event_min_heap event_heap; 4051 struct perf_event **evt; 4052 int ret; 4053 4054 if (pmu->filter && pmu->filter(pmu, cpu)) 4055 return 0; 4056 4057 if (!ctx->task) { 4058 cpuctx = this_cpu_ptr(&perf_cpu_context); 4059 event_heap = (struct perf_event_min_heap){ 4060 .data = cpuctx->heap, 4061 .nr = 0, 4062 .size = cpuctx->heap_size, 4063 }; 4064 4065 lockdep_assert_held(&cpuctx->ctx.lock); 4066 4067 #ifdef CONFIG_CGROUP_PERF 4068 if (cpuctx->cgrp) 4069 css = &cpuctx->cgrp->css; 4070 #endif 4071 } else { 4072 event_heap = (struct perf_event_min_heap){ 4073 .data = itrs, 4074 .nr = 0, 4075 .size = ARRAY_SIZE(itrs), 4076 }; 4077 /* Events not within a CPU context may be on any CPU. */ 4078 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL)); 4079 } 4080 evt = event_heap.data; 4081 4082 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL)); 4083 4084 #ifdef CONFIG_CGROUP_PERF 4085 for (; css; css = css->parent) 4086 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup)); 4087 #endif 4088 4089 if (event_heap.nr) { 4090 __link_epc((*evt)->pmu_ctx); 4091 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu); 4092 } 4093 4094 min_heapify_all_inline(&event_heap, &perf_min_heap, NULL); 4095 4096 while (event_heap.nr) { 4097 ret = func(*evt, data); 4098 if (ret) 4099 return ret; 4100 4101 *evt = perf_event_groups_next(*evt, pmu); 4102 if (*evt) 4103 min_heap_sift_down_inline(&event_heap, 0, &perf_min_heap, NULL); 4104 else 4105 min_heap_pop_inline(&event_heap, &perf_min_heap, NULL); 4106 } 4107 4108 return 0; 4109 } 4110 4111 /* 4112 * Because the userpage is strictly per-event (there is no concept of context, 4113 * so there cannot be a context indirection), every userpage must be updated 4114 * when context time starts :-( 4115 * 4116 * IOW, we must not miss EVENT_TIME edges. 4117 */ 4118 static inline bool event_update_userpage(struct perf_event *event) 4119 { 4120 if (likely(!refcount_read(&event->mmap_count))) 4121 return false; 4122 4123 perf_event_update_time(event); 4124 perf_event_update_userpage(event); 4125 4126 return true; 4127 } 4128 4129 static inline void group_update_userpage(struct perf_event *group_event) 4130 { 4131 struct perf_event *event; 4132 4133 if (!event_update_userpage(group_event)) 4134 return; 4135 4136 for_each_sibling_event(event, group_event) 4137 event_update_userpage(event); 4138 } 4139 4140 struct merge_sched_data { 4141 int can_add_hw; 4142 enum event_type_t event_type; 4143 }; 4144 4145 static int merge_sched_in(struct perf_event *event, void *data) 4146 { 4147 struct perf_event_context *ctx = event->ctx; 4148 struct merge_sched_data *msd = data; 4149 4150 if (event->state <= PERF_EVENT_STATE_OFF) 4151 return 0; 4152 4153 if (!event_filter_match(event)) 4154 return 0; 4155 4156 /* 4157 * Don't schedule in any host events from PMU with 4158 * PERF_PMU_CAP_MEDIATED_VPMU, while a guest is running. 4159 */ 4160 if (is_guest_mediated_pmu_loaded() && 4161 event->pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU && 4162 !(msd->event_type & EVENT_GUEST)) 4163 return 0; 4164 4165 if (group_can_go_on(event, msd->can_add_hw)) { 4166 if (!group_sched_in(event, ctx)) 4167 list_add_tail(&event->active_list, get_event_list(event)); 4168 } 4169 4170 if (event->state == PERF_EVENT_STATE_INACTIVE) { 4171 msd->can_add_hw = 0; 4172 if (event->attr.pinned) { 4173 perf_cgroup_event_disable(event, ctx); 4174 perf_event_set_state(event, PERF_EVENT_STATE_ERROR); 4175 4176 if (*perf_event_fasync(event)) 4177 event->pending_kill = POLL_ERR; 4178 4179 event->pending_wakeup = 1; 4180 irq_work_queue(&event->pending_irq); 4181 } else { 4182 struct perf_cpu_pmu_context *cpc = this_cpc(event->pmu_ctx->pmu); 4183 4184 event->pmu_ctx->rotate_necessary = 1; 4185 perf_mux_hrtimer_restart(cpc); 4186 group_update_userpage(event); 4187 } 4188 } 4189 4190 return 0; 4191 } 4192 4193 static void pmu_groups_sched_in(struct perf_event_context *ctx, 4194 struct perf_event_groups *groups, 4195 struct pmu *pmu, 4196 enum event_type_t event_type) 4197 { 4198 struct merge_sched_data msd = { 4199 .can_add_hw = 1, 4200 .event_type = event_type, 4201 }; 4202 visit_groups_merge(ctx, groups, smp_processor_id(), pmu, 4203 merge_sched_in, &msd); 4204 } 4205 4206 static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx, 4207 enum event_type_t event_type) 4208 { 4209 struct perf_event_context *ctx = pmu_ctx->ctx; 4210 4211 if (event_type & EVENT_PINNED) 4212 pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu, event_type); 4213 if (event_type & EVENT_FLEXIBLE) 4214 pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu, event_type); 4215 } 4216 4217 static void 4218 ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type) 4219 { 4220 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4221 enum event_type_t active_type = event_type & ~EVENT_FLAGS; 4222 struct perf_event_pmu_context *pmu_ctx; 4223 int is_active = ctx->is_active; 4224 4225 lockdep_assert_held(&ctx->lock); 4226 4227 if (likely(!ctx->nr_events)) 4228 return; 4229 4230 if (!(is_active & EVENT_TIME)) { 4231 /* EVENT_TIME should be active while the guest runs */ 4232 WARN_ON_ONCE(event_type & EVENT_GUEST); 4233 /* start ctx time */ 4234 __update_context_time(ctx, false); 4235 perf_cgroup_set_timestamp(cpuctx, false); 4236 /* 4237 * CPU-release for the below ->is_active store, 4238 * see __load_acquire() in perf_event_time_now() 4239 */ 4240 barrier(); 4241 } 4242 4243 ctx->is_active |= active_type | EVENT_TIME; 4244 if (ctx->task) { 4245 if (!(is_active & EVENT_ALL)) 4246 cpuctx->task_ctx = ctx; 4247 else 4248 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 4249 } 4250 4251 if (event_type & EVENT_GUEST) { 4252 /* 4253 * Schedule in the required exclude_guest events of PMU 4254 * with PERF_PMU_CAP_MEDIATED_VPMU. 4255 */ 4256 is_active = event_type & EVENT_ALL; 4257 4258 /* 4259 * Update ctx time to set the new start time for 4260 * the exclude_guest events. 4261 */ 4262 update_context_time(ctx); 4263 update_cgrp_time_from_cpuctx(cpuctx, false); 4264 barrier(); 4265 } else { 4266 is_active ^= ctx->is_active; /* changed bits */ 4267 } 4268 4269 /* 4270 * First go through the list and put on any pinned groups 4271 * in order to give them the best chance of going on. 4272 */ 4273 if (is_active & EVENT_PINNED) { 4274 for_each_epc(pmu_ctx, ctx, pmu, event_type) 4275 __pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED | (event_type & EVENT_GUEST)); 4276 } 4277 4278 /* Then walk through the lower prio flexible groups */ 4279 if (is_active & EVENT_FLEXIBLE) { 4280 for_each_epc(pmu_ctx, ctx, pmu, event_type) 4281 __pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE | (event_type & EVENT_GUEST)); 4282 } 4283 } 4284 4285 static void perf_event_context_sched_in(struct task_struct *task) 4286 { 4287 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4288 struct perf_event_context *ctx; 4289 4290 rcu_read_lock(); 4291 ctx = rcu_dereference(task->perf_event_ctxp); 4292 if (!ctx) 4293 goto rcu_unlock; 4294 4295 if (cpuctx->task_ctx == ctx) { 4296 perf_ctx_lock(cpuctx, ctx); 4297 perf_ctx_disable(ctx, 0); 4298 4299 perf_ctx_sched_task_cb(ctx, task, true); 4300 4301 perf_ctx_enable(ctx, 0); 4302 perf_ctx_unlock(cpuctx, ctx); 4303 goto rcu_unlock; 4304 } 4305 4306 perf_ctx_lock(cpuctx, ctx); 4307 /* 4308 * We must check ctx->nr_events while holding ctx->lock, such 4309 * that we serialize against perf_install_in_context(). 4310 */ 4311 if (!ctx->nr_events) 4312 goto unlock; 4313 4314 perf_ctx_disable(ctx, 0); 4315 /* 4316 * We want to keep the following priority order: 4317 * cpu pinned (that don't need to move), task pinned, 4318 * cpu flexible, task flexible. 4319 * 4320 * However, if task's ctx is not carrying any pinned 4321 * events, no need to flip the cpuctx's events around. 4322 */ 4323 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) { 4324 perf_ctx_disable(&cpuctx->ctx, 0); 4325 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE); 4326 } 4327 4328 perf_event_sched_in(cpuctx, ctx, NULL, 0); 4329 4330 perf_ctx_sched_task_cb(cpuctx->task_ctx, task, true); 4331 4332 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) 4333 perf_ctx_enable(&cpuctx->ctx, 0); 4334 4335 perf_ctx_enable(ctx, 0); 4336 4337 unlock: 4338 perf_ctx_unlock(cpuctx, ctx); 4339 rcu_unlock: 4340 rcu_read_unlock(); 4341 } 4342 4343 /* 4344 * Called from scheduler to add the events of the current task 4345 * with interrupts disabled. 4346 * 4347 * We restore the event value and then enable it. 4348 * 4349 * This does not protect us against NMI, but enable() 4350 * sets the enabled bit in the control field of event _before_ 4351 * accessing the event control register. If a NMI hits, then it will 4352 * keep the event running. 4353 */ 4354 void __perf_event_task_sched_in(struct task_struct *prev, 4355 struct task_struct *task) 4356 { 4357 perf_event_context_sched_in(task); 4358 4359 if (atomic_read(&nr_switch_events)) 4360 perf_event_switch(task, prev, true); 4361 4362 if (__this_cpu_read(perf_sched_cb_usages)) 4363 perf_pmu_sched_task(prev, task, true); 4364 } 4365 4366 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count) 4367 { 4368 u64 frequency = event->attr.sample_freq; 4369 u64 sec = NSEC_PER_SEC; 4370 u64 divisor, dividend; 4371 4372 int count_fls, nsec_fls, frequency_fls, sec_fls; 4373 4374 count_fls = fls64(count); 4375 nsec_fls = fls64(nsec); 4376 frequency_fls = fls64(frequency); 4377 sec_fls = 30; 4378 4379 /* 4380 * We got @count in @nsec, with a target of sample_freq HZ 4381 * the target period becomes: 4382 * 4383 * @count * 10^9 4384 * period = ------------------- 4385 * @nsec * sample_freq 4386 * 4387 */ 4388 4389 /* 4390 * Reduce accuracy by one bit such that @a and @b converge 4391 * to a similar magnitude. 4392 */ 4393 #define REDUCE_FLS(a, b) \ 4394 do { \ 4395 if (a##_fls > b##_fls) { \ 4396 a >>= 1; \ 4397 a##_fls--; \ 4398 } else { \ 4399 b >>= 1; \ 4400 b##_fls--; \ 4401 } \ 4402 } while (0) 4403 4404 /* 4405 * Reduce accuracy until either term fits in a u64, then proceed with 4406 * the other, so that finally we can do a u64/u64 division. 4407 */ 4408 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) { 4409 REDUCE_FLS(nsec, frequency); 4410 REDUCE_FLS(sec, count); 4411 } 4412 4413 if (count_fls + sec_fls > 64) { 4414 divisor = nsec * frequency; 4415 4416 while (count_fls + sec_fls > 64) { 4417 REDUCE_FLS(count, sec); 4418 divisor >>= 1; 4419 } 4420 4421 dividend = count * sec; 4422 } else { 4423 dividend = count * sec; 4424 4425 while (nsec_fls + frequency_fls > 64) { 4426 REDUCE_FLS(nsec, frequency); 4427 dividend >>= 1; 4428 } 4429 4430 divisor = nsec * frequency; 4431 } 4432 4433 if (!divisor) 4434 return dividend; 4435 4436 return div64_u64(dividend, divisor); 4437 } 4438 4439 static DEFINE_PER_CPU(int, perf_throttled_count); 4440 static DEFINE_PER_CPU(u64, perf_throttled_seq); 4441 4442 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable) 4443 { 4444 struct hw_perf_event *hwc = &event->hw; 4445 s64 period, sample_period; 4446 s64 delta; 4447 4448 period = perf_calculate_period(event, nsec, count); 4449 4450 delta = (s64)(period - hwc->sample_period); 4451 if (delta >= 0) 4452 delta += 7; 4453 else 4454 delta -= 7; 4455 delta /= 8; /* low pass filter */ 4456 4457 sample_period = hwc->sample_period + delta; 4458 4459 if (!sample_period) 4460 sample_period = 1; 4461 4462 hwc->sample_period = sample_period; 4463 4464 if (local64_read(&hwc->period_left) > 8*sample_period) { 4465 if (disable) 4466 event->pmu->stop(event, PERF_EF_UPDATE); 4467 4468 local64_set(&hwc->period_left, 0); 4469 4470 if (disable) 4471 event->pmu->start(event, PERF_EF_RELOAD); 4472 } 4473 } 4474 4475 static void perf_adjust_freq_unthr_events(struct list_head *event_list) 4476 { 4477 struct perf_event *event; 4478 struct hw_perf_event *hwc; 4479 u64 now, period = TICK_NSEC; 4480 s64 delta; 4481 4482 list_for_each_entry(event, event_list, active_list) { 4483 if (event->state != PERF_EVENT_STATE_ACTIVE) 4484 continue; 4485 4486 // XXX use visit thingy to avoid the -1,cpu match 4487 if (!event_filter_match(event)) 4488 continue; 4489 4490 hwc = &event->hw; 4491 4492 if (hwc->interrupts == MAX_INTERRUPTS) 4493 perf_event_unthrottle_group(event, is_event_in_freq_mode(event)); 4494 4495 if (!is_event_in_freq_mode(event)) 4496 continue; 4497 4498 /* 4499 * stop the event and update event->count 4500 */ 4501 event->pmu->stop(event, PERF_EF_UPDATE); 4502 4503 now = local64_read(&event->count); 4504 delta = now - hwc->freq_count_stamp; 4505 hwc->freq_count_stamp = now; 4506 4507 /* 4508 * restart the event 4509 * reload only if value has changed 4510 * we have stopped the event so tell that 4511 * to perf_adjust_period() to avoid stopping it 4512 * twice. 4513 */ 4514 if (delta > 0) 4515 perf_adjust_period(event, period, delta, false); 4516 4517 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0); 4518 } 4519 } 4520 4521 /* 4522 * combine freq adjustment with unthrottling to avoid two passes over the 4523 * events. At the same time, make sure, having freq events does not change 4524 * the rate of unthrottling as that would introduce bias. 4525 */ 4526 static void 4527 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle) 4528 { 4529 struct perf_event_pmu_context *pmu_ctx; 4530 4531 /* 4532 * only need to iterate over all events iff: 4533 * - context have events in frequency mode (needs freq adjust) 4534 * - there are events to unthrottle on this cpu 4535 */ 4536 if (!(ctx->nr_freq || unthrottle)) 4537 return; 4538 4539 raw_spin_lock(&ctx->lock); 4540 4541 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) { 4542 if (!(pmu_ctx->nr_freq || unthrottle)) 4543 continue; 4544 if (!perf_pmu_ctx_is_active(pmu_ctx)) 4545 continue; 4546 if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) 4547 continue; 4548 4549 perf_pmu_disable(pmu_ctx->pmu); 4550 perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active); 4551 perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active); 4552 perf_pmu_enable(pmu_ctx->pmu); 4553 } 4554 4555 raw_spin_unlock(&ctx->lock); 4556 } 4557 4558 /* 4559 * Move @event to the tail of the @ctx's elegible events. 4560 */ 4561 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event) 4562 { 4563 /* 4564 * Rotate the first entry last of non-pinned groups. Rotation might be 4565 * disabled by the inheritance code. 4566 */ 4567 if (ctx->rotate_disable) 4568 return; 4569 4570 perf_event_groups_delete(&ctx->flexible_groups, event); 4571 perf_event_groups_insert(&ctx->flexible_groups, event); 4572 } 4573 4574 /* pick an event from the flexible_groups to rotate */ 4575 static inline struct perf_event * 4576 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx) 4577 { 4578 struct perf_event *event; 4579 struct rb_node *node; 4580 struct rb_root *tree; 4581 struct __group_key key = { 4582 .pmu = pmu_ctx->pmu, 4583 }; 4584 4585 /* pick the first active flexible event */ 4586 event = list_first_entry_or_null(&pmu_ctx->flexible_active, 4587 struct perf_event, active_list); 4588 if (event) 4589 goto out; 4590 4591 /* if no active flexible event, pick the first event */ 4592 tree = &pmu_ctx->ctx->flexible_groups.tree; 4593 4594 if (!pmu_ctx->ctx->task) { 4595 key.cpu = smp_processor_id(); 4596 4597 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup); 4598 if (node) 4599 event = __node_2_pe(node); 4600 goto out; 4601 } 4602 4603 key.cpu = -1; 4604 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup); 4605 if (node) { 4606 event = __node_2_pe(node); 4607 goto out; 4608 } 4609 4610 key.cpu = smp_processor_id(); 4611 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup); 4612 if (node) 4613 event = __node_2_pe(node); 4614 4615 out: 4616 /* 4617 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in() 4618 * finds there are unschedulable events, it will set it again. 4619 */ 4620 pmu_ctx->rotate_necessary = 0; 4621 4622 return event; 4623 } 4624 4625 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc) 4626 { 4627 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4628 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL; 4629 struct perf_event *cpu_event = NULL, *task_event = NULL; 4630 int cpu_rotate, task_rotate; 4631 struct pmu *pmu; 4632 4633 /* 4634 * Since we run this from IRQ context, nobody can install new 4635 * events, thus the event count values are stable. 4636 */ 4637 4638 cpu_epc = &cpc->epc; 4639 pmu = cpu_epc->pmu; 4640 task_epc = cpc->task_epc; 4641 4642 cpu_rotate = cpu_epc->rotate_necessary; 4643 task_rotate = task_epc ? task_epc->rotate_necessary : 0; 4644 4645 if (!(cpu_rotate || task_rotate)) 4646 return false; 4647 4648 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 4649 perf_pmu_disable(pmu); 4650 4651 if (task_rotate) 4652 task_event = ctx_event_to_rotate(task_epc); 4653 if (cpu_rotate) 4654 cpu_event = ctx_event_to_rotate(cpu_epc); 4655 4656 /* 4657 * As per the order given at ctx_resched() first 'pop' task flexible 4658 * and then, if needed CPU flexible. 4659 */ 4660 if (task_event || (task_epc && cpu_event)) { 4661 update_context_time(task_epc->ctx); 4662 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE); 4663 } 4664 4665 if (cpu_event) { 4666 update_context_time(&cpuctx->ctx); 4667 update_cgrp_time_from_cpuctx(cpuctx, false); 4668 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE); 4669 rotate_ctx(&cpuctx->ctx, cpu_event); 4670 __pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE); 4671 } 4672 4673 if (task_event) 4674 rotate_ctx(task_epc->ctx, task_event); 4675 4676 if (task_event || (task_epc && cpu_event)) 4677 __pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE); 4678 4679 perf_pmu_enable(pmu); 4680 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 4681 4682 return true; 4683 } 4684 4685 void perf_event_task_tick(void) 4686 { 4687 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4688 struct perf_event_context *ctx; 4689 int throttled; 4690 4691 lockdep_assert_irqs_disabled(); 4692 4693 __this_cpu_inc(perf_throttled_seq); 4694 throttled = __this_cpu_xchg(perf_throttled_count, 0); 4695 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 4696 4697 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled); 4698 4699 rcu_read_lock(); 4700 ctx = rcu_dereference(current->perf_event_ctxp); 4701 if (ctx) 4702 perf_adjust_freq_unthr_context(ctx, !!throttled); 4703 rcu_read_unlock(); 4704 } 4705 4706 static int event_enable_on_exec(struct perf_event *event, 4707 struct perf_event_context *ctx) 4708 { 4709 if (!event->attr.enable_on_exec) 4710 return 0; 4711 4712 event->attr.enable_on_exec = 0; 4713 if (event->state >= PERF_EVENT_STATE_INACTIVE) 4714 return 0; 4715 4716 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 4717 4718 return 1; 4719 } 4720 4721 /* 4722 * Enable all of a task's events that have been marked enable-on-exec. 4723 * This expects task == current. 4724 */ 4725 static void perf_event_enable_on_exec(struct perf_event_context *ctx) 4726 { 4727 struct perf_event_context *clone_ctx = NULL; 4728 enum event_type_t event_type = 0; 4729 struct perf_cpu_context *cpuctx; 4730 struct perf_event *event; 4731 unsigned long flags; 4732 int enabled = 0; 4733 4734 local_irq_save(flags); 4735 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx)) 4736 goto out; 4737 4738 if (!ctx->nr_events) 4739 goto out; 4740 4741 cpuctx = this_cpu_ptr(&perf_cpu_context); 4742 perf_ctx_lock(cpuctx, ctx); 4743 ctx_time_freeze(cpuctx, ctx); 4744 4745 list_for_each_entry(event, &ctx->event_list, event_entry) { 4746 enabled |= event_enable_on_exec(event, ctx); 4747 event_type |= get_event_type(event); 4748 } 4749 4750 /* 4751 * Unclone and reschedule this context if we enabled any event. 4752 */ 4753 if (enabled) { 4754 clone_ctx = unclone_ctx(ctx); 4755 ctx_resched(cpuctx, ctx, NULL, event_type); 4756 } 4757 perf_ctx_unlock(cpuctx, ctx); 4758 4759 out: 4760 local_irq_restore(flags); 4761 4762 if (clone_ctx) 4763 put_ctx(clone_ctx); 4764 } 4765 4766 static void perf_remove_from_owner(struct perf_event *event); 4767 static void perf_event_exit_event(struct perf_event *event, 4768 struct perf_event_context *ctx, 4769 struct task_struct *task, 4770 unsigned long detach_flags); 4771 4772 /* 4773 * Removes all events from the current task that have been marked 4774 * remove-on-exec, and feeds their values back to parent events. 4775 */ 4776 static void perf_event_remove_on_exec(struct perf_event_context *ctx) 4777 { 4778 struct perf_event_context *clone_ctx = NULL; 4779 struct perf_event *event, *next; 4780 unsigned long flags; 4781 bool modified = false; 4782 4783 mutex_lock(&ctx->mutex); 4784 4785 if (WARN_ON_ONCE(ctx->task != current)) 4786 goto unlock; 4787 4788 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) { 4789 if (!event->attr.remove_on_exec) 4790 continue; 4791 4792 if (!is_kernel_event(event)) 4793 perf_remove_from_owner(event); 4794 4795 modified = true; 4796 4797 perf_event_exit_event(event, ctx, ctx->task, DETACH_GROUP); 4798 } 4799 4800 raw_spin_lock_irqsave(&ctx->lock, flags); 4801 if (modified) 4802 clone_ctx = unclone_ctx(ctx); 4803 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4804 4805 unlock: 4806 mutex_unlock(&ctx->mutex); 4807 4808 if (clone_ctx) 4809 put_ctx(clone_ctx); 4810 } 4811 4812 struct perf_read_data { 4813 struct perf_event *event; 4814 bool group; 4815 int ret; 4816 }; 4817 4818 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu); 4819 4820 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu) 4821 { 4822 int local_cpu = smp_processor_id(); 4823 u16 local_pkg, event_pkg; 4824 4825 if ((unsigned)event_cpu >= nr_cpu_ids) 4826 return event_cpu; 4827 4828 if (event->group_caps & PERF_EV_CAP_READ_SCOPE) { 4829 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu); 4830 4831 if (cpumask && cpumask_test_cpu(local_cpu, cpumask)) 4832 return local_cpu; 4833 } 4834 4835 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) { 4836 event_pkg = topology_physical_package_id(event_cpu); 4837 local_pkg = topology_physical_package_id(local_cpu); 4838 4839 if (event_pkg == local_pkg) 4840 return local_cpu; 4841 } 4842 4843 return event_cpu; 4844 } 4845 4846 /* 4847 * Cross CPU call to read the hardware event 4848 */ 4849 static void __perf_event_read(void *info) 4850 { 4851 struct perf_read_data *data = info; 4852 struct perf_event *sub, *event = data->event; 4853 struct perf_event_context *ctx = event->ctx; 4854 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4855 struct pmu *pmu; 4856 4857 /* 4858 * If this is a task context, we need to check whether it is 4859 * the current task context of this cpu. If not it has been 4860 * scheduled out before the smp call arrived. In that case 4861 * event->count would have been updated to a recent sample 4862 * when the event was scheduled out. 4863 */ 4864 if (ctx->task && cpuctx->task_ctx != ctx) 4865 return; 4866 4867 guard(raw_spinlock)(&ctx->lock); 4868 ctx_time_update_event(ctx, event); 4869 4870 perf_event_update_time(event); 4871 if (data->group) 4872 perf_event_update_sibling_time(event); 4873 4874 if (event->state != PERF_EVENT_STATE_ACTIVE) 4875 return; 4876 4877 if (!data->group) { 4878 perf_pmu_read(event); 4879 data->ret = 0; 4880 return; 4881 } 4882 4883 pmu = event->pmu_ctx->pmu; 4884 pmu->start_txn(pmu, PERF_PMU_TXN_READ); 4885 4886 perf_pmu_read(event); 4887 for_each_sibling_event(sub, event) 4888 perf_pmu_read(sub); 4889 4890 data->ret = pmu->commit_txn(pmu); 4891 } 4892 4893 static inline u64 perf_event_count(struct perf_event *event, bool self) 4894 { 4895 if (self) 4896 return local64_read(&event->count); 4897 4898 return local64_read(&event->count) + atomic64_read(&event->child_count); 4899 } 4900 4901 static void calc_timer_values(struct perf_event *event, 4902 u64 *now, 4903 u64 *enabled, 4904 u64 *running) 4905 { 4906 u64 ctx_time; 4907 4908 *now = perf_clock(); 4909 ctx_time = perf_event_time_now(event, *now); 4910 __perf_update_times(event, ctx_time, enabled, running); 4911 } 4912 4913 /* 4914 * NMI-safe method to read a local event, that is an event that 4915 * is: 4916 * - either for the current task, or for this CPU 4917 * - does not have inherit set, for inherited task events 4918 * will not be local and we cannot read them atomically 4919 * - must not have a pmu::count method 4920 */ 4921 int perf_event_read_local(struct perf_event *event, u64 *value, 4922 u64 *enabled, u64 *running) 4923 { 4924 unsigned long flags; 4925 int event_oncpu; 4926 int event_cpu; 4927 int ret = 0; 4928 4929 /* 4930 * Disabling interrupts avoids all counter scheduling (context 4931 * switches, timer based rotation and IPIs). 4932 */ 4933 local_irq_save(flags); 4934 4935 /* 4936 * It must not be an event with inherit set, we cannot read 4937 * all child counters from atomic context. 4938 */ 4939 if (event->attr.inherit) { 4940 ret = -EOPNOTSUPP; 4941 goto out; 4942 } 4943 4944 /* If this is a per-task event, it must be for current */ 4945 if ((event->attach_state & PERF_ATTACH_TASK) && 4946 event->hw.target != current) { 4947 ret = -EINVAL; 4948 goto out; 4949 } 4950 4951 /* 4952 * Get the event CPU numbers, and adjust them to local if the event is 4953 * a per-package event that can be read locally 4954 */ 4955 event_oncpu = __perf_event_read_cpu(event, event->oncpu); 4956 event_cpu = __perf_event_read_cpu(event, event->cpu); 4957 4958 /* If this is a per-CPU event, it must be for this CPU */ 4959 if (!(event->attach_state & PERF_ATTACH_TASK) && 4960 event_cpu != smp_processor_id()) { 4961 ret = -EINVAL; 4962 goto out; 4963 } 4964 4965 /* If this is a pinned event it must be running on this CPU */ 4966 if (event->attr.pinned && event_oncpu != smp_processor_id()) { 4967 ret = -EBUSY; 4968 goto out; 4969 } 4970 4971 /* 4972 * If the event is currently on this CPU, its either a per-task event, 4973 * or local to this CPU. Furthermore it means its ACTIVE (otherwise 4974 * oncpu == -1). 4975 */ 4976 if (event_oncpu == smp_processor_id()) 4977 event->pmu->read(event); 4978 4979 *value = local64_read(&event->count); 4980 if (enabled || running) { 4981 u64 __enabled, __running, __now; 4982 4983 calc_timer_values(event, &__now, &__enabled, &__running); 4984 if (enabled) 4985 *enabled = __enabled; 4986 if (running) 4987 *running = __running; 4988 } 4989 out: 4990 local_irq_restore(flags); 4991 4992 return ret; 4993 } 4994 4995 static int perf_event_read(struct perf_event *event, bool group) 4996 { 4997 enum perf_event_state state = READ_ONCE(event->state); 4998 int event_cpu, ret = 0; 4999 5000 /* 5001 * If event is enabled and currently active on a CPU, update the 5002 * value in the event structure: 5003 */ 5004 again: 5005 if (state == PERF_EVENT_STATE_ACTIVE) { 5006 struct perf_read_data data; 5007 5008 /* 5009 * Orders the ->state and ->oncpu loads such that if we see 5010 * ACTIVE we must also see the right ->oncpu. 5011 * 5012 * Matches the smp_wmb() from event_sched_in(). 5013 */ 5014 smp_rmb(); 5015 5016 event_cpu = READ_ONCE(event->oncpu); 5017 if ((unsigned)event_cpu >= nr_cpu_ids) 5018 return 0; 5019 5020 data = (struct perf_read_data){ 5021 .event = event, 5022 .group = group, 5023 .ret = 0, 5024 }; 5025 5026 preempt_disable(); 5027 event_cpu = __perf_event_read_cpu(event, event_cpu); 5028 5029 /* 5030 * Purposely ignore the smp_call_function_single() return 5031 * value. 5032 * 5033 * If event_cpu isn't a valid CPU it means the event got 5034 * scheduled out and that will have updated the event count. 5035 * 5036 * Therefore, either way, we'll have an up-to-date event count 5037 * after this. 5038 */ 5039 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1); 5040 preempt_enable(); 5041 ret = data.ret; 5042 5043 } else if (state == PERF_EVENT_STATE_INACTIVE) { 5044 struct perf_event_context *ctx = event->ctx; 5045 unsigned long flags; 5046 5047 raw_spin_lock_irqsave(&ctx->lock, flags); 5048 state = event->state; 5049 if (state != PERF_EVENT_STATE_INACTIVE) { 5050 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5051 goto again; 5052 } 5053 5054 /* 5055 * May read while context is not active (e.g., thread is 5056 * blocked), in that case we cannot update context time 5057 */ 5058 ctx_time_update_event(ctx, event); 5059 5060 perf_event_update_time(event); 5061 if (group) 5062 perf_event_update_sibling_time(event); 5063 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5064 } 5065 5066 return ret; 5067 } 5068 5069 /* 5070 * Initialize the perf_event context in a task_struct: 5071 */ 5072 static void __perf_event_init_context(struct perf_event_context *ctx) 5073 { 5074 raw_spin_lock_init(&ctx->lock); 5075 mutex_init(&ctx->mutex); 5076 INIT_LIST_HEAD(&ctx->pmu_ctx_list); 5077 perf_event_groups_init(&ctx->pinned_groups); 5078 perf_event_groups_init(&ctx->flexible_groups); 5079 INIT_LIST_HEAD(&ctx->event_list); 5080 refcount_set(&ctx->refcount, 1); 5081 } 5082 5083 static void 5084 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu) 5085 { 5086 epc->pmu = pmu; 5087 INIT_LIST_HEAD(&epc->pmu_ctx_entry); 5088 INIT_LIST_HEAD(&epc->pinned_active); 5089 INIT_LIST_HEAD(&epc->flexible_active); 5090 atomic_set(&epc->refcount, 1); 5091 } 5092 5093 static struct perf_event_context * 5094 alloc_perf_context(struct task_struct *task) 5095 { 5096 struct perf_event_context *ctx; 5097 5098 ctx = kzalloc_obj(struct perf_event_context); 5099 if (!ctx) 5100 return NULL; 5101 5102 __perf_event_init_context(ctx); 5103 if (task) 5104 ctx->task = get_task_struct(task); 5105 5106 return ctx; 5107 } 5108 5109 static struct task_struct * 5110 find_lively_task_by_vpid(pid_t vpid) 5111 { 5112 struct task_struct *task; 5113 5114 rcu_read_lock(); 5115 if (!vpid) 5116 task = current; 5117 else 5118 task = find_task_by_vpid(vpid); 5119 if (task) 5120 get_task_struct(task); 5121 rcu_read_unlock(); 5122 5123 if (!task) 5124 return ERR_PTR(-ESRCH); 5125 5126 return task; 5127 } 5128 5129 /* 5130 * Returns a matching context with refcount and pincount. 5131 */ 5132 static struct perf_event_context * 5133 find_get_context(struct task_struct *task, struct perf_event *event) 5134 { 5135 struct perf_event_context *ctx, *clone_ctx = NULL; 5136 struct perf_cpu_context *cpuctx; 5137 unsigned long flags; 5138 int err; 5139 5140 if (!task) { 5141 /* Must be root to operate on a CPU event: */ 5142 err = perf_allow_cpu(); 5143 if (err) 5144 return ERR_PTR(err); 5145 5146 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu); 5147 ctx = &cpuctx->ctx; 5148 get_ctx(ctx); 5149 raw_spin_lock_irqsave(&ctx->lock, flags); 5150 ++ctx->pin_count; 5151 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5152 5153 return ctx; 5154 } 5155 5156 err = -EINVAL; 5157 retry: 5158 ctx = perf_lock_task_context(task, &flags); 5159 if (ctx) { 5160 clone_ctx = unclone_ctx(ctx); 5161 ++ctx->pin_count; 5162 5163 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5164 5165 if (clone_ctx) 5166 put_ctx(clone_ctx); 5167 } else { 5168 ctx = alloc_perf_context(task); 5169 err = -ENOMEM; 5170 if (!ctx) 5171 goto errout; 5172 5173 err = 0; 5174 mutex_lock(&task->perf_event_mutex); 5175 /* 5176 * If it has already passed perf_event_exit_task(). 5177 * we must see PF_EXITING, it takes this mutex too. 5178 */ 5179 if (task->flags & PF_EXITING) 5180 err = -ESRCH; 5181 else if (task->perf_event_ctxp) 5182 err = -EAGAIN; 5183 else { 5184 get_ctx(ctx); 5185 ++ctx->pin_count; 5186 rcu_assign_pointer(task->perf_event_ctxp, ctx); 5187 } 5188 mutex_unlock(&task->perf_event_mutex); 5189 5190 if (unlikely(err)) { 5191 put_ctx(ctx); 5192 5193 if (err == -EAGAIN) 5194 goto retry; 5195 goto errout; 5196 } 5197 } 5198 5199 return ctx; 5200 5201 errout: 5202 return ERR_PTR(err); 5203 } 5204 5205 static struct perf_event_pmu_context * 5206 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx, 5207 struct perf_event *event) 5208 { 5209 struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc; 5210 5211 if (!ctx->task) { 5212 /* 5213 * perf_pmu_migrate_context() / __perf_pmu_install_event() 5214 * relies on the fact that find_get_pmu_context() cannot fail 5215 * for CPU contexts. 5216 */ 5217 struct perf_cpu_pmu_context *cpc; 5218 5219 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, event->cpu); 5220 epc = &cpc->epc; 5221 raw_spin_lock_irq(&ctx->lock); 5222 if (!epc->ctx) { 5223 /* 5224 * One extra reference for the pmu; see perf_pmu_free(). 5225 */ 5226 atomic_set(&epc->refcount, 2); 5227 epc->embedded = 1; 5228 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list); 5229 epc->ctx = ctx; 5230 } else { 5231 WARN_ON_ONCE(epc->ctx != ctx); 5232 atomic_inc(&epc->refcount); 5233 } 5234 raw_spin_unlock_irq(&ctx->lock); 5235 return epc; 5236 } 5237 5238 new = kzalloc_obj(*epc); 5239 if (!new) 5240 return ERR_PTR(-ENOMEM); 5241 5242 __perf_init_event_pmu_context(new, pmu); 5243 5244 /* 5245 * XXX 5246 * 5247 * lockdep_assert_held(&ctx->mutex); 5248 * 5249 * can't because perf_event_init_task() doesn't actually hold the 5250 * child_ctx->mutex. 5251 */ 5252 5253 raw_spin_lock_irq(&ctx->lock); 5254 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) { 5255 if (epc->pmu == pmu) { 5256 WARN_ON_ONCE(epc->ctx != ctx); 5257 atomic_inc(&epc->refcount); 5258 goto found_epc; 5259 } 5260 /* Make sure the pmu_ctx_list is sorted by PMU type: */ 5261 if (!pos && epc->pmu->type > pmu->type) 5262 pos = epc; 5263 } 5264 5265 epc = new; 5266 new = NULL; 5267 5268 if (!pos) 5269 list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list); 5270 else 5271 list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev); 5272 5273 epc->ctx = ctx; 5274 5275 found_epc: 5276 raw_spin_unlock_irq(&ctx->lock); 5277 kfree(new); 5278 5279 return epc; 5280 } 5281 5282 static void get_pmu_ctx(struct perf_event_pmu_context *epc) 5283 { 5284 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount)); 5285 } 5286 5287 static void free_cpc_rcu(struct rcu_head *head) 5288 { 5289 struct perf_cpu_pmu_context *cpc = 5290 container_of(head, typeof(*cpc), epc.rcu_head); 5291 5292 kfree(cpc); 5293 } 5294 5295 static void free_epc_rcu(struct rcu_head *head) 5296 { 5297 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head); 5298 5299 kfree(epc); 5300 } 5301 5302 static void put_pmu_ctx(struct perf_event_pmu_context *epc) 5303 { 5304 struct perf_event_context *ctx = epc->ctx; 5305 unsigned long flags; 5306 5307 /* 5308 * XXX 5309 * 5310 * lockdep_assert_held(&ctx->mutex); 5311 * 5312 * can't because of the call-site in _free_event()/put_event() 5313 * which isn't always called under ctx->mutex. 5314 */ 5315 if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags)) 5316 return; 5317 5318 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry)); 5319 5320 list_del_init(&epc->pmu_ctx_entry); 5321 epc->ctx = NULL; 5322 5323 WARN_ON_ONCE(!list_empty(&epc->pinned_active)); 5324 WARN_ON_ONCE(!list_empty(&epc->flexible_active)); 5325 5326 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5327 5328 if (epc->embedded) { 5329 call_rcu(&epc->rcu_head, free_cpc_rcu); 5330 return; 5331 } 5332 5333 call_rcu(&epc->rcu_head, free_epc_rcu); 5334 } 5335 5336 static void perf_event_free_filter(struct perf_event *event); 5337 5338 static void free_event_rcu(struct rcu_head *head) 5339 { 5340 struct perf_event *event = container_of(head, typeof(*event), rcu_head); 5341 5342 if (event->ns) 5343 put_pid_ns(event->ns); 5344 perf_event_free_filter(event); 5345 kfree(event->addr_filter_ranges); 5346 kmem_cache_free(perf_event_cache, event); 5347 } 5348 5349 static void ring_buffer_attach(struct perf_event *event, 5350 struct perf_buffer *rb); 5351 5352 static void detach_sb_event(struct perf_event *event) 5353 { 5354 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 5355 5356 raw_spin_lock(&pel->lock); 5357 list_del_rcu(&event->sb_list); 5358 raw_spin_unlock(&pel->lock); 5359 } 5360 5361 static bool is_sb_event(struct perf_event *event) 5362 { 5363 struct perf_event_attr *attr = &event->attr; 5364 5365 if (event->parent) 5366 return false; 5367 5368 if (event->attach_state & PERF_ATTACH_TASK) 5369 return false; 5370 5371 if (attr->mmap || attr->mmap_data || attr->mmap2 || 5372 attr->comm || attr->comm_exec || 5373 attr->task || attr->ksymbol || 5374 attr->context_switch || attr->text_poke || 5375 attr->bpf_event || attr->defer_output) 5376 return true; 5377 5378 return false; 5379 } 5380 5381 static void unaccount_pmu_sb_event(struct perf_event *event) 5382 { 5383 if (is_sb_event(event)) 5384 detach_sb_event(event); 5385 } 5386 5387 #ifdef CONFIG_NO_HZ_FULL 5388 static DEFINE_SPINLOCK(nr_freq_lock); 5389 #endif 5390 5391 static void unaccount_freq_event_nohz(void) 5392 { 5393 #ifdef CONFIG_NO_HZ_FULL 5394 spin_lock(&nr_freq_lock); 5395 if (atomic_dec_and_test(&nr_freq_events)) 5396 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS); 5397 spin_unlock(&nr_freq_lock); 5398 #endif 5399 } 5400 5401 static void unaccount_freq_event(void) 5402 { 5403 if (tick_nohz_full_enabled()) 5404 unaccount_freq_event_nohz(); 5405 else 5406 atomic_dec(&nr_freq_events); 5407 } 5408 5409 5410 static struct perf_ctx_data * 5411 alloc_perf_ctx_data(struct kmem_cache *ctx_cache, bool global, gfp_t gfp_flags) 5412 { 5413 struct perf_ctx_data *cd; 5414 5415 cd = kzalloc_obj(*cd, gfp_flags); 5416 if (!cd) 5417 return NULL; 5418 5419 cd->data = kmem_cache_zalloc(ctx_cache, gfp_flags); 5420 if (!cd->data) { 5421 kfree(cd); 5422 return NULL; 5423 } 5424 5425 cd->global = global; 5426 cd->ctx_cache = ctx_cache; 5427 refcount_set(&cd->refcount, 1); 5428 5429 return cd; 5430 } 5431 5432 static void free_perf_ctx_data(struct perf_ctx_data *cd) 5433 { 5434 kmem_cache_free(cd->ctx_cache, cd->data); 5435 kfree(cd); 5436 } 5437 5438 static void __free_perf_ctx_data_rcu(struct rcu_head *rcu_head) 5439 { 5440 struct perf_ctx_data *cd; 5441 5442 cd = container_of(rcu_head, struct perf_ctx_data, rcu_head); 5443 free_perf_ctx_data(cd); 5444 } 5445 5446 static inline void perf_free_ctx_data_rcu(struct perf_ctx_data *cd) 5447 { 5448 call_rcu(&cd->rcu_head, __free_perf_ctx_data_rcu); 5449 } 5450 5451 static int 5452 attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache, 5453 bool global, gfp_t gfp_flags) 5454 { 5455 struct perf_ctx_data *cd, *old = NULL; 5456 5457 cd = alloc_perf_ctx_data(ctx_cache, global, gfp_flags); 5458 if (!cd) 5459 return -ENOMEM; 5460 5461 for (;;) { 5462 /* Protect @old until inc_not_zero(&old->refcount) */ 5463 guard(rcu)(); 5464 5465 if (try_cmpxchg(&task->perf_ctx_data, &old, cd)) { 5466 if (old) 5467 perf_free_ctx_data_rcu(old); 5468 /* 5469 * Above try_cmpxchg() pairs with try_cmpxchg() from 5470 * detach_task_ctx_data() such that 5471 * if we race with perf_event_exit_task(), we must 5472 * observe PF_EXITING. 5473 */ 5474 if (task->flags & PF_EXITING) { 5475 /* detach_task_ctx_data() may free it already */ 5476 if (try_cmpxchg(&task->perf_ctx_data, &cd, NULL)) 5477 perf_free_ctx_data_rcu(cd); 5478 } 5479 return 0; 5480 } 5481 5482 if (!old) { 5483 /* 5484 * After seeing a dead @old, we raced with 5485 * removal and lost, try again to install @cd. 5486 */ 5487 continue; 5488 } 5489 5490 if (refcount_inc_not_zero(&old->refcount)) { 5491 if (global) 5492 old->global = true; 5493 free_perf_ctx_data(cd); /* unused */ 5494 return 0; 5495 } 5496 5497 /* 5498 * @old is a dead object, refcount==0 is stable, try and 5499 * replace it with @cd. 5500 */ 5501 } 5502 return 0; 5503 } 5504 5505 static void __detach_global_ctx_data(void); 5506 DEFINE_STATIC_PERCPU_RWSEM(global_ctx_data_rwsem); 5507 static refcount_t global_ctx_data_ref; 5508 5509 static int 5510 attach_global_ctx_data(struct kmem_cache *ctx_cache) 5511 { 5512 struct task_struct *g, *p; 5513 struct perf_ctx_data *cd; 5514 int ret; 5515 5516 if (refcount_inc_not_zero(&global_ctx_data_ref)) 5517 return 0; 5518 5519 guard(percpu_write)(&global_ctx_data_rwsem); 5520 if (refcount_inc_not_zero(&global_ctx_data_ref)) 5521 return 0; 5522 again: 5523 /* Allocate everything */ 5524 scoped_guard (rcu) { 5525 for_each_process_thread(g, p) { 5526 if (p->flags & PF_EXITING) 5527 continue; 5528 cd = rcu_dereference(p->perf_ctx_data); 5529 if (cd && !cd->global) { 5530 cd->global = 1; 5531 if (!refcount_inc_not_zero(&cd->refcount)) 5532 cd = NULL; 5533 } 5534 if (!cd) { 5535 /* 5536 * Try to allocate context quickly before 5537 * traversing the whole thread list again. 5538 */ 5539 if (!attach_task_ctx_data(p, ctx_cache, true, GFP_NOWAIT)) 5540 continue; 5541 get_task_struct(p); 5542 goto alloc; 5543 } 5544 } 5545 } 5546 5547 refcount_set(&global_ctx_data_ref, 1); 5548 5549 return 0; 5550 alloc: 5551 ret = attach_task_ctx_data(p, ctx_cache, true, GFP_KERNEL); 5552 put_task_struct(p); 5553 if (ret) { 5554 __detach_global_ctx_data(); 5555 return ret; 5556 } 5557 goto again; 5558 } 5559 5560 static int 5561 attach_perf_ctx_data(struct perf_event *event) 5562 { 5563 struct task_struct *task = event->hw.target; 5564 struct kmem_cache *ctx_cache = event->pmu->task_ctx_cache; 5565 int ret; 5566 5567 if (!ctx_cache) 5568 return -ENOMEM; 5569 5570 if (task) 5571 return attach_task_ctx_data(task, ctx_cache, false, GFP_KERNEL); 5572 5573 ret = attach_global_ctx_data(ctx_cache); 5574 if (ret) 5575 return ret; 5576 5577 event->attach_state |= PERF_ATTACH_GLOBAL_DATA; 5578 return 0; 5579 } 5580 5581 static void 5582 detach_task_ctx_data(struct task_struct *p) 5583 { 5584 struct perf_ctx_data *cd; 5585 5586 scoped_guard (rcu) { 5587 cd = rcu_dereference(p->perf_ctx_data); 5588 if (!cd || !refcount_dec_and_test(&cd->refcount)) 5589 return; 5590 } 5591 5592 /* 5593 * The old ctx_data may be lost because of the race. 5594 * Nothing is required to do for the case. 5595 * See attach_task_ctx_data(). 5596 */ 5597 if (try_cmpxchg((struct perf_ctx_data **)&p->perf_ctx_data, &cd, NULL)) 5598 perf_free_ctx_data_rcu(cd); 5599 } 5600 5601 static void __detach_global_ctx_data(void) 5602 { 5603 struct task_struct *g, *p; 5604 struct perf_ctx_data *cd; 5605 5606 scoped_guard (rcu) { 5607 for_each_process_thread(g, p) { 5608 cd = rcu_dereference(p->perf_ctx_data); 5609 if (cd && cd->global) { 5610 cd->global = 0; 5611 detach_task_ctx_data(p); 5612 } 5613 } 5614 } 5615 } 5616 5617 static void detach_global_ctx_data(void) 5618 { 5619 if (refcount_dec_not_one(&global_ctx_data_ref)) 5620 return; 5621 5622 guard(percpu_write)(&global_ctx_data_rwsem); 5623 if (!refcount_dec_and_test(&global_ctx_data_ref)) 5624 return; 5625 5626 /* remove everything */ 5627 __detach_global_ctx_data(); 5628 } 5629 5630 static void detach_perf_ctx_data(struct perf_event *event) 5631 { 5632 struct task_struct *task = event->hw.target; 5633 5634 event->attach_state &= ~PERF_ATTACH_TASK_DATA; 5635 5636 if (task) 5637 return detach_task_ctx_data(task); 5638 5639 if (event->attach_state & PERF_ATTACH_GLOBAL_DATA) { 5640 detach_global_ctx_data(); 5641 event->attach_state &= ~PERF_ATTACH_GLOBAL_DATA; 5642 } 5643 } 5644 5645 static void unaccount_event(struct perf_event *event) 5646 { 5647 bool dec = false; 5648 5649 if (event->parent) 5650 return; 5651 5652 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB)) 5653 dec = true; 5654 if (event->attr.mmap || event->attr.mmap_data) 5655 atomic_dec(&nr_mmap_events); 5656 if (event->attr.build_id) 5657 atomic_dec(&nr_build_id_events); 5658 if (event->attr.comm) 5659 atomic_dec(&nr_comm_events); 5660 if (event->attr.namespaces) 5661 atomic_dec(&nr_namespaces_events); 5662 if (event->attr.cgroup) 5663 atomic_dec(&nr_cgroup_events); 5664 if (event->attr.task) 5665 atomic_dec(&nr_task_events); 5666 if (event->attr.freq) 5667 unaccount_freq_event(); 5668 if (event->attr.context_switch) { 5669 dec = true; 5670 atomic_dec(&nr_switch_events); 5671 } 5672 if (is_cgroup_event(event)) 5673 dec = true; 5674 if (has_branch_stack(event)) 5675 dec = true; 5676 if (event->attr.ksymbol) 5677 atomic_dec(&nr_ksymbol_events); 5678 if (event->attr.bpf_event) 5679 atomic_dec(&nr_bpf_events); 5680 if (event->attr.text_poke) 5681 atomic_dec(&nr_text_poke_events); 5682 5683 if (dec) { 5684 if (!atomic_add_unless(&perf_sched_count, -1, 1)) 5685 schedule_delayed_work(&perf_sched_work, HZ); 5686 } 5687 5688 unaccount_pmu_sb_event(event); 5689 } 5690 5691 static void perf_sched_delayed(struct work_struct *work) 5692 { 5693 mutex_lock(&perf_sched_mutex); 5694 if (atomic_dec_and_test(&perf_sched_count)) 5695 static_branch_disable(&perf_sched_events); 5696 mutex_unlock(&perf_sched_mutex); 5697 } 5698 5699 /* 5700 * The following implement mutual exclusion of events on "exclusive" pmus 5701 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled 5702 * at a time, so we disallow creating events that might conflict, namely: 5703 * 5704 * 1) cpu-wide events in the presence of per-task events, 5705 * 2) per-task events in the presence of cpu-wide events, 5706 * 3) two matching events on the same perf_event_context. 5707 * 5708 * The former two cases are handled in the allocation path (perf_event_alloc(), 5709 * _free_event()), the latter -- before the first perf_install_in_context(). 5710 */ 5711 static int exclusive_event_init(struct perf_event *event) 5712 { 5713 struct pmu *pmu = event->pmu; 5714 5715 if (!is_exclusive_pmu(pmu)) 5716 return 0; 5717 5718 /* 5719 * Prevent co-existence of per-task and cpu-wide events on the 5720 * same exclusive pmu. 5721 * 5722 * Negative pmu::exclusive_cnt means there are cpu-wide 5723 * events on this "exclusive" pmu, positive means there are 5724 * per-task events. 5725 * 5726 * Since this is called in perf_event_alloc() path, event::ctx 5727 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK 5728 * to mean "per-task event", because unlike other attach states it 5729 * never gets cleared. 5730 */ 5731 if (event->attach_state & PERF_ATTACH_TASK) { 5732 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt)) 5733 return -EBUSY; 5734 } else { 5735 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt)) 5736 return -EBUSY; 5737 } 5738 5739 event->attach_state |= PERF_ATTACH_EXCLUSIVE; 5740 5741 return 0; 5742 } 5743 5744 static void exclusive_event_destroy(struct perf_event *event) 5745 { 5746 struct pmu *pmu = event->pmu; 5747 5748 /* see comment in exclusive_event_init() */ 5749 if (event->attach_state & PERF_ATTACH_TASK) 5750 atomic_dec(&pmu->exclusive_cnt); 5751 else 5752 atomic_inc(&pmu->exclusive_cnt); 5753 5754 event->attach_state &= ~PERF_ATTACH_EXCLUSIVE; 5755 } 5756 5757 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2) 5758 { 5759 if ((e1->pmu == e2->pmu) && 5760 (e1->cpu == e2->cpu || 5761 e1->cpu == -1 || 5762 e2->cpu == -1)) 5763 return true; 5764 return false; 5765 } 5766 5767 static bool exclusive_event_installable(struct perf_event *event, 5768 struct perf_event_context *ctx) 5769 { 5770 struct perf_event *iter_event; 5771 struct pmu *pmu = event->pmu; 5772 5773 lockdep_assert_held(&ctx->mutex); 5774 5775 if (!is_exclusive_pmu(pmu)) 5776 return true; 5777 5778 list_for_each_entry(iter_event, &ctx->event_list, event_entry) { 5779 if (exclusive_event_match(iter_event, event)) 5780 return false; 5781 } 5782 5783 return true; 5784 } 5785 5786 static void perf_free_addr_filters(struct perf_event *event); 5787 5788 /* vs perf_event_alloc() error */ 5789 static void __free_event(struct perf_event *event) 5790 { 5791 struct pmu *pmu = event->pmu; 5792 5793 security_perf_event_free(event); 5794 5795 if (event->attach_state & PERF_ATTACH_CALLCHAIN) 5796 put_callchain_buffers(); 5797 5798 if (event->attach_state & PERF_ATTACH_EXCLUSIVE) 5799 exclusive_event_destroy(event); 5800 5801 if (is_cgroup_event(event)) 5802 perf_detach_cgroup(event); 5803 5804 if (event->attach_state & PERF_ATTACH_TASK_DATA) 5805 detach_perf_ctx_data(event); 5806 5807 if (event->destroy) 5808 event->destroy(event); 5809 5810 /* 5811 * Must be after ->destroy(), due to uprobe_perf_close() using 5812 * hw.target. 5813 */ 5814 if (event->hw.target) 5815 put_task_struct(event->hw.target); 5816 5817 if (event->pmu_ctx) { 5818 /* 5819 * put_pmu_ctx() needs an event->ctx reference, because of 5820 * epc->ctx. 5821 */ 5822 WARN_ON_ONCE(!pmu); 5823 WARN_ON_ONCE(!event->ctx); 5824 WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx); 5825 put_pmu_ctx(event->pmu_ctx); 5826 } 5827 5828 /* 5829 * perf_event_free_task() relies on put_ctx() being 'last', in 5830 * particular all task references must be cleaned up. 5831 */ 5832 if (event->ctx) 5833 put_ctx(event->ctx); 5834 5835 if (pmu) { 5836 module_put(pmu->module); 5837 scoped_guard (spinlock, &pmu->events_lock) { 5838 list_del(&event->pmu_list); 5839 wake_up_var(pmu); 5840 } 5841 } 5842 5843 call_rcu(&event->rcu_head, free_event_rcu); 5844 } 5845 5846 static void mediated_pmu_unaccount_event(struct perf_event *event); 5847 5848 DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T)) 5849 5850 /* vs perf_event_alloc() success */ 5851 static void _free_event(struct perf_event *event) 5852 { 5853 irq_work_sync(&event->pending_irq); 5854 irq_work_sync(&event->pending_disable_irq); 5855 5856 unaccount_event(event); 5857 mediated_pmu_unaccount_event(event); 5858 5859 if (event->rb) { 5860 /* 5861 * Can happen when we close an event with re-directed output. 5862 * 5863 * Since we have a 0 refcount, perf_mmap_close() will skip 5864 * over us; possibly making our ring_buffer_put() the last. 5865 */ 5866 mutex_lock(&event->mmap_mutex); 5867 ring_buffer_attach(event, NULL); 5868 mutex_unlock(&event->mmap_mutex); 5869 } 5870 5871 perf_event_free_bpf_prog(event); 5872 perf_free_addr_filters(event); 5873 5874 __free_event(event); 5875 } 5876 5877 /* 5878 * Used to free events which have a known refcount of 1, such as in error paths 5879 * of inherited events. 5880 */ 5881 static void free_event(struct perf_event *event) 5882 { 5883 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1, 5884 "unexpected event refcount: %ld; ptr=%p\n", 5885 atomic_long_read(&event->refcount), event)) { 5886 /* leak to avoid use-after-free */ 5887 return; 5888 } 5889 5890 _free_event(event); 5891 } 5892 5893 /* 5894 * Remove user event from the owner task. 5895 */ 5896 static void perf_remove_from_owner(struct perf_event *event) 5897 { 5898 struct task_struct *owner; 5899 5900 rcu_read_lock(); 5901 /* 5902 * Matches the smp_store_release() in perf_event_exit_task(). If we 5903 * observe !owner it means the list deletion is complete and we can 5904 * indeed free this event, otherwise we need to serialize on 5905 * owner->perf_event_mutex. 5906 */ 5907 owner = READ_ONCE(event->owner); 5908 if (owner) { 5909 /* 5910 * Since delayed_put_task_struct() also drops the last 5911 * task reference we can safely take a new reference 5912 * while holding the rcu_read_lock(). 5913 */ 5914 get_task_struct(owner); 5915 } 5916 rcu_read_unlock(); 5917 5918 if (owner) { 5919 /* 5920 * If we're here through perf_event_exit_task() we're already 5921 * holding ctx->mutex which would be an inversion wrt. the 5922 * normal lock order. 5923 * 5924 * However we can safely take this lock because its the child 5925 * ctx->mutex. 5926 */ 5927 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING); 5928 5929 /* 5930 * We have to re-check the event->owner field, if it is cleared 5931 * we raced with perf_event_exit_task(), acquiring the mutex 5932 * ensured they're done, and we can proceed with freeing the 5933 * event. 5934 */ 5935 if (event->owner) { 5936 list_del_init(&event->owner_entry); 5937 smp_store_release(&event->owner, NULL); 5938 } 5939 mutex_unlock(&owner->perf_event_mutex); 5940 put_task_struct(owner); 5941 } 5942 } 5943 5944 static void put_event(struct perf_event *event) 5945 { 5946 struct perf_event *parent; 5947 5948 if (!atomic_long_dec_and_test(&event->refcount)) 5949 return; 5950 5951 parent = event->parent; 5952 _free_event(event); 5953 5954 /* Matches the refcount bump in inherit_event() */ 5955 if (parent) 5956 put_event(parent); 5957 } 5958 5959 /* 5960 * Kill an event dead; while event:refcount will preserve the event 5961 * object, it will not preserve its functionality. Once the last 'user' 5962 * gives up the object, we'll destroy the thing. 5963 */ 5964 int perf_event_release_kernel(struct perf_event *event) 5965 { 5966 struct perf_event_context *ctx = event->ctx; 5967 struct perf_event *child, *tmp; 5968 5969 /* 5970 * If we got here through err_alloc: free_event(event); we will not 5971 * have attached to a context yet. 5972 */ 5973 if (!ctx) { 5974 WARN_ON_ONCE(event->attach_state & 5975 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP)); 5976 goto no_ctx; 5977 } 5978 5979 if (!is_kernel_event(event)) 5980 perf_remove_from_owner(event); 5981 5982 ctx = perf_event_ctx_lock(event); 5983 WARN_ON_ONCE(ctx->parent_ctx); 5984 5985 /* 5986 * Mark this event as STATE_DEAD, there is no external reference to it 5987 * anymore. 5988 * 5989 * Anybody acquiring event->child_mutex after the below loop _must_ 5990 * also see this, most importantly inherit_event() which will avoid 5991 * placing more children on the list. 5992 * 5993 * Thus this guarantees that we will in fact observe and kill _ALL_ 5994 * child events. 5995 */ 5996 if (event->state > PERF_EVENT_STATE_REVOKED) { 5997 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD); 5998 } else { 5999 event->state = PERF_EVENT_STATE_DEAD; 6000 } 6001 6002 perf_event_ctx_unlock(event, ctx); 6003 6004 again: 6005 mutex_lock(&event->child_mutex); 6006 list_for_each_entry(child, &event->child_list, child_list) { 6007 /* 6008 * Cannot change, child events are not migrated, see the 6009 * comment with perf_event_ctx_lock_nested(). 6010 */ 6011 ctx = READ_ONCE(child->ctx); 6012 /* 6013 * Since child_mutex nests inside ctx::mutex, we must jump 6014 * through hoops. We start by grabbing a reference on the ctx. 6015 * 6016 * Since the event cannot get freed while we hold the 6017 * child_mutex, the context must also exist and have a !0 6018 * reference count. 6019 */ 6020 get_ctx(ctx); 6021 6022 /* 6023 * Now that we have a ctx ref, we can drop child_mutex, and 6024 * acquire ctx::mutex without fear of it going away. Then we 6025 * can re-acquire child_mutex. 6026 */ 6027 mutex_unlock(&event->child_mutex); 6028 mutex_lock(&ctx->mutex); 6029 mutex_lock(&event->child_mutex); 6030 6031 /* 6032 * Now that we hold ctx::mutex and child_mutex, revalidate our 6033 * state, if child is still the first entry, it didn't get freed 6034 * and we can continue doing so. 6035 */ 6036 tmp = list_first_entry_or_null(&event->child_list, 6037 struct perf_event, child_list); 6038 if (tmp == child) { 6039 perf_remove_from_context(child, DETACH_GROUP | DETACH_CHILD); 6040 } else { 6041 child = NULL; 6042 } 6043 6044 mutex_unlock(&event->child_mutex); 6045 mutex_unlock(&ctx->mutex); 6046 6047 if (child) { 6048 /* Last reference unless ->pending_task work is pending */ 6049 put_event(child); 6050 } 6051 put_ctx(ctx); 6052 6053 goto again; 6054 } 6055 mutex_unlock(&event->child_mutex); 6056 6057 no_ctx: 6058 /* 6059 * Last reference unless ->pending_task work is pending on this event 6060 * or any of its children. 6061 */ 6062 put_event(event); 6063 return 0; 6064 } 6065 EXPORT_SYMBOL_GPL(perf_event_release_kernel); 6066 6067 /* 6068 * Called when the last reference to the file is gone. 6069 */ 6070 static int perf_release(struct inode *inode, struct file *file) 6071 { 6072 perf_event_release_kernel(file->private_data); 6073 return 0; 6074 } 6075 6076 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 6077 { 6078 struct perf_event *child; 6079 u64 total = 0; 6080 6081 *enabled = 0; 6082 *running = 0; 6083 6084 mutex_lock(&event->child_mutex); 6085 6086 (void)perf_event_read(event, false); 6087 total += perf_event_count(event, false); 6088 6089 *enabled += event->total_time_enabled + 6090 atomic64_read(&event->child_total_time_enabled); 6091 *running += event->total_time_running + 6092 atomic64_read(&event->child_total_time_running); 6093 6094 list_for_each_entry(child, &event->child_list, child_list) { 6095 (void)perf_event_read(child, false); 6096 total += perf_event_count(child, false); 6097 *enabled += child->total_time_enabled; 6098 *running += child->total_time_running; 6099 } 6100 mutex_unlock(&event->child_mutex); 6101 6102 return total; 6103 } 6104 6105 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 6106 { 6107 struct perf_event_context *ctx; 6108 u64 count; 6109 6110 ctx = perf_event_ctx_lock(event); 6111 count = __perf_event_read_value(event, enabled, running); 6112 perf_event_ctx_unlock(event, ctx); 6113 6114 return count; 6115 } 6116 EXPORT_SYMBOL_GPL(perf_event_read_value); 6117 6118 static int __perf_read_group_add(struct perf_event *leader, 6119 u64 read_format, u64 *values) 6120 { 6121 struct perf_event_context *ctx = leader->ctx; 6122 struct perf_event *sub, *parent; 6123 unsigned long flags; 6124 int n = 1; /* skip @nr */ 6125 int ret; 6126 6127 ret = perf_event_read(leader, true); 6128 if (ret) 6129 return ret; 6130 6131 raw_spin_lock_irqsave(&ctx->lock, flags); 6132 /* 6133 * Verify the grouping between the parent and child (inherited) 6134 * events is still in tact. 6135 * 6136 * Specifically: 6137 * - leader->ctx->lock pins leader->sibling_list 6138 * - parent->child_mutex pins parent->child_list 6139 * - parent->ctx->mutex pins parent->sibling_list 6140 * 6141 * Because parent->ctx != leader->ctx (and child_list nests inside 6142 * ctx->mutex), group destruction is not atomic between children, also 6143 * see perf_event_release_kernel(). Additionally, parent can grow the 6144 * group. 6145 * 6146 * Therefore it is possible to have parent and child groups in a 6147 * different configuration and summing over such a beast makes no sense 6148 * what so ever. 6149 * 6150 * Reject this. 6151 */ 6152 parent = leader->parent; 6153 if (parent && 6154 (parent->group_generation != leader->group_generation || 6155 parent->nr_siblings != leader->nr_siblings)) { 6156 ret = -ECHILD; 6157 goto unlock; 6158 } 6159 6160 /* 6161 * Since we co-schedule groups, {enabled,running} times of siblings 6162 * will be identical to those of the leader, so we only publish one 6163 * set. 6164 */ 6165 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 6166 values[n++] += leader->total_time_enabled + 6167 atomic64_read(&leader->child_total_time_enabled); 6168 } 6169 6170 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 6171 values[n++] += leader->total_time_running + 6172 atomic64_read(&leader->child_total_time_running); 6173 } 6174 6175 /* 6176 * Write {count,id} tuples for every sibling. 6177 */ 6178 values[n++] += perf_event_count(leader, false); 6179 if (read_format & PERF_FORMAT_ID) 6180 values[n++] = primary_event_id(leader); 6181 if (read_format & PERF_FORMAT_LOST) 6182 values[n++] = atomic64_read(&leader->lost_samples); 6183 6184 for_each_sibling_event(sub, leader) { 6185 values[n++] += perf_event_count(sub, false); 6186 if (read_format & PERF_FORMAT_ID) 6187 values[n++] = primary_event_id(sub); 6188 if (read_format & PERF_FORMAT_LOST) 6189 values[n++] = atomic64_read(&sub->lost_samples); 6190 } 6191 6192 unlock: 6193 raw_spin_unlock_irqrestore(&ctx->lock, flags); 6194 return ret; 6195 } 6196 6197 static int perf_read_group(struct perf_event *event, 6198 u64 read_format, char __user *buf) 6199 { 6200 struct perf_event *leader = event->group_leader, *child; 6201 struct perf_event_context *ctx = leader->ctx; 6202 int ret; 6203 u64 *values; 6204 6205 lockdep_assert_held(&ctx->mutex); 6206 6207 values = kzalloc(event->read_size, GFP_KERNEL); 6208 if (!values) 6209 return -ENOMEM; 6210 6211 values[0] = 1 + leader->nr_siblings; 6212 6213 mutex_lock(&leader->child_mutex); 6214 6215 ret = __perf_read_group_add(leader, read_format, values); 6216 if (ret) 6217 goto unlock; 6218 6219 list_for_each_entry(child, &leader->child_list, child_list) { 6220 ret = __perf_read_group_add(child, read_format, values); 6221 if (ret) 6222 goto unlock; 6223 } 6224 6225 mutex_unlock(&leader->child_mutex); 6226 6227 ret = event->read_size; 6228 if (copy_to_user(buf, values, event->read_size)) 6229 ret = -EFAULT; 6230 goto out; 6231 6232 unlock: 6233 mutex_unlock(&leader->child_mutex); 6234 out: 6235 kfree(values); 6236 return ret; 6237 } 6238 6239 static int perf_read_one(struct perf_event *event, 6240 u64 read_format, char __user *buf) 6241 { 6242 u64 enabled, running; 6243 u64 values[5]; 6244 int n = 0; 6245 6246 values[n++] = __perf_event_read_value(event, &enabled, &running); 6247 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 6248 values[n++] = enabled; 6249 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 6250 values[n++] = running; 6251 if (read_format & PERF_FORMAT_ID) 6252 values[n++] = primary_event_id(event); 6253 if (read_format & PERF_FORMAT_LOST) 6254 values[n++] = atomic64_read(&event->lost_samples); 6255 6256 if (copy_to_user(buf, values, n * sizeof(u64))) 6257 return -EFAULT; 6258 6259 return n * sizeof(u64); 6260 } 6261 6262 static bool is_event_hup(struct perf_event *event) 6263 { 6264 bool no_children; 6265 6266 if (event->state > PERF_EVENT_STATE_EXIT) 6267 return false; 6268 6269 mutex_lock(&event->child_mutex); 6270 no_children = list_empty(&event->child_list); 6271 mutex_unlock(&event->child_mutex); 6272 return no_children; 6273 } 6274 6275 /* 6276 * Read the performance event - simple non blocking version for now 6277 */ 6278 static ssize_t 6279 __perf_read(struct perf_event *event, char __user *buf, size_t count) 6280 { 6281 u64 read_format = event->attr.read_format; 6282 int ret; 6283 6284 /* 6285 * Return end-of-file for a read on an event that is in 6286 * error state (i.e. because it was pinned but it couldn't be 6287 * scheduled on to the CPU at some point). 6288 */ 6289 if (event->state == PERF_EVENT_STATE_ERROR) 6290 return 0; 6291 6292 if (count < event->read_size) 6293 return -ENOSPC; 6294 6295 WARN_ON_ONCE(event->ctx->parent_ctx); 6296 if (read_format & PERF_FORMAT_GROUP) 6297 ret = perf_read_group(event, read_format, buf); 6298 else 6299 ret = perf_read_one(event, read_format, buf); 6300 6301 return ret; 6302 } 6303 6304 static ssize_t 6305 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) 6306 { 6307 struct perf_event *event = file->private_data; 6308 struct perf_event_context *ctx; 6309 int ret; 6310 6311 ret = security_perf_event_read(event); 6312 if (ret) 6313 return ret; 6314 6315 ctx = perf_event_ctx_lock(event); 6316 ret = __perf_read(event, buf, count); 6317 perf_event_ctx_unlock(event, ctx); 6318 6319 return ret; 6320 } 6321 6322 static __poll_t perf_poll(struct file *file, poll_table *wait) 6323 { 6324 struct perf_event *event = file->private_data; 6325 struct perf_buffer *rb; 6326 __poll_t events = EPOLLHUP; 6327 6328 if (event->state <= PERF_EVENT_STATE_REVOKED) 6329 return EPOLLERR; 6330 6331 poll_wait(file, &event->waitq, wait); 6332 6333 if (event->state <= PERF_EVENT_STATE_REVOKED) 6334 return EPOLLERR; 6335 6336 if (is_event_hup(event)) 6337 return events; 6338 6339 if (unlikely(READ_ONCE(event->state) == PERF_EVENT_STATE_ERROR && 6340 event->attr.pinned)) 6341 return EPOLLERR; 6342 6343 /* 6344 * Pin the event->rb by taking event->mmap_mutex; otherwise 6345 * perf_event_set_output() can swizzle our rb and make us miss wakeups. 6346 */ 6347 mutex_lock(&event->mmap_mutex); 6348 rb = event->rb; 6349 if (rb) 6350 events = atomic_xchg(&rb->poll, 0); 6351 mutex_unlock(&event->mmap_mutex); 6352 return events; 6353 } 6354 6355 static void _perf_event_reset(struct perf_event *event) 6356 { 6357 (void)perf_event_read(event, false); 6358 local64_set(&event->count, 0); 6359 perf_event_update_userpage(event); 6360 } 6361 6362 /* Assume it's not an event with inherit set. */ 6363 u64 perf_event_pause(struct perf_event *event, bool reset) 6364 { 6365 struct perf_event_context *ctx; 6366 u64 count; 6367 6368 ctx = perf_event_ctx_lock(event); 6369 WARN_ON_ONCE(event->attr.inherit); 6370 _perf_event_disable(event); 6371 count = local64_read(&event->count); 6372 if (reset) 6373 local64_set(&event->count, 0); 6374 perf_event_ctx_unlock(event, ctx); 6375 6376 return count; 6377 } 6378 EXPORT_SYMBOL_GPL(perf_event_pause); 6379 6380 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU 6381 static atomic_t nr_include_guest_events __read_mostly; 6382 6383 static atomic_t nr_mediated_pmu_vms __read_mostly; 6384 static DEFINE_MUTEX(perf_mediated_pmu_mutex); 6385 6386 /* !exclude_guest event of PMU with PERF_PMU_CAP_MEDIATED_VPMU */ 6387 static inline bool is_include_guest_event(struct perf_event *event) 6388 { 6389 if (!event->pmu) 6390 return false; 6391 6392 if ((event->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU) && 6393 !event->attr.exclude_guest) 6394 return true; 6395 6396 return false; 6397 } 6398 6399 static int mediated_pmu_account_event(struct perf_event *event) 6400 { 6401 if (!is_include_guest_event(event)) 6402 return 0; 6403 6404 if (atomic_inc_not_zero(&nr_include_guest_events)) 6405 return 0; 6406 6407 guard(mutex)(&perf_mediated_pmu_mutex); 6408 if (atomic_read(&nr_mediated_pmu_vms)) 6409 return -EOPNOTSUPP; 6410 6411 atomic_inc(&nr_include_guest_events); 6412 return 0; 6413 } 6414 6415 static void mediated_pmu_unaccount_event(struct perf_event *event) 6416 { 6417 if (!is_include_guest_event(event)) 6418 return; 6419 6420 if (WARN_ON_ONCE(!atomic_read(&nr_include_guest_events))) 6421 return; 6422 6423 atomic_dec(&nr_include_guest_events); 6424 } 6425 6426 /* 6427 * Currently invoked at VM creation to 6428 * - Check whether there are existing !exclude_guest events of PMU with 6429 * PERF_PMU_CAP_MEDIATED_VPMU 6430 * - Set nr_mediated_pmu_vms to prevent !exclude_guest event creation on 6431 * PMUs with PERF_PMU_CAP_MEDIATED_VPMU 6432 * 6433 * No impact for the PMU without PERF_PMU_CAP_MEDIATED_VPMU. The perf 6434 * still owns all the PMU resources. 6435 */ 6436 int perf_create_mediated_pmu(void) 6437 { 6438 if (atomic_inc_not_zero(&nr_mediated_pmu_vms)) 6439 return 0; 6440 6441 guard(mutex)(&perf_mediated_pmu_mutex); 6442 if (atomic_read(&nr_include_guest_events)) 6443 return -EBUSY; 6444 6445 atomic_inc(&nr_mediated_pmu_vms); 6446 return 0; 6447 } 6448 EXPORT_SYMBOL_FOR_KVM(perf_create_mediated_pmu); 6449 6450 void perf_release_mediated_pmu(void) 6451 { 6452 if (WARN_ON_ONCE(!atomic_read(&nr_mediated_pmu_vms))) 6453 return; 6454 6455 atomic_dec(&nr_mediated_pmu_vms); 6456 } 6457 EXPORT_SYMBOL_FOR_KVM(perf_release_mediated_pmu); 6458 6459 /* When loading a guest's mediated PMU, schedule out all exclude_guest events. */ 6460 void perf_load_guest_context(void) 6461 { 6462 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 6463 6464 lockdep_assert_irqs_disabled(); 6465 6466 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx); 6467 6468 if (WARN_ON_ONCE(__this_cpu_read(guest_ctx_loaded))) 6469 return; 6470 6471 perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST); 6472 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_GUEST); 6473 if (cpuctx->task_ctx) { 6474 perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST); 6475 task_ctx_sched_out(cpuctx->task_ctx, NULL, EVENT_GUEST); 6476 } 6477 6478 perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST); 6479 if (cpuctx->task_ctx) 6480 perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST); 6481 6482 __this_cpu_write(guest_ctx_loaded, true); 6483 } 6484 EXPORT_SYMBOL_GPL(perf_load_guest_context); 6485 6486 void perf_put_guest_context(void) 6487 { 6488 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 6489 6490 lockdep_assert_irqs_disabled(); 6491 6492 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx); 6493 6494 if (WARN_ON_ONCE(!__this_cpu_read(guest_ctx_loaded))) 6495 return; 6496 6497 perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST); 6498 if (cpuctx->task_ctx) 6499 perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST); 6500 6501 perf_event_sched_in(cpuctx, cpuctx->task_ctx, NULL, EVENT_GUEST); 6502 6503 if (cpuctx->task_ctx) 6504 perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST); 6505 perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST); 6506 6507 __this_cpu_write(guest_ctx_loaded, false); 6508 } 6509 EXPORT_SYMBOL_GPL(perf_put_guest_context); 6510 #else 6511 static int mediated_pmu_account_event(struct perf_event *event) { return 0; } 6512 static void mediated_pmu_unaccount_event(struct perf_event *event) {} 6513 #endif 6514 6515 /* 6516 * Holding the top-level event's child_mutex means that any 6517 * descendant process that has inherited this event will block 6518 * in perf_event_exit_event() if it goes to exit, thus satisfying the 6519 * task existence requirements of perf_event_enable/disable. 6520 */ 6521 static void perf_event_for_each_child(struct perf_event *event, 6522 void (*func)(struct perf_event *)) 6523 { 6524 struct perf_event *child; 6525 6526 WARN_ON_ONCE(event->ctx->parent_ctx); 6527 6528 mutex_lock(&event->child_mutex); 6529 func(event); 6530 list_for_each_entry(child, &event->child_list, child_list) 6531 func(child); 6532 mutex_unlock(&event->child_mutex); 6533 } 6534 6535 static void perf_event_for_each(struct perf_event *event, 6536 void (*func)(struct perf_event *)) 6537 { 6538 struct perf_event_context *ctx = event->ctx; 6539 struct perf_event *sibling; 6540 6541 lockdep_assert_held(&ctx->mutex); 6542 6543 event = event->group_leader; 6544 6545 perf_event_for_each_child(event, func); 6546 for_each_sibling_event(sibling, event) 6547 perf_event_for_each_child(sibling, func); 6548 } 6549 6550 static void __perf_event_period(struct perf_event *event, 6551 struct perf_cpu_context *cpuctx, 6552 struct perf_event_context *ctx, 6553 void *info) 6554 { 6555 u64 value = *((u64 *)info); 6556 bool active; 6557 6558 if (event->attr.freq) { 6559 event->attr.sample_freq = value; 6560 } else { 6561 event->attr.sample_period = value; 6562 event->hw.sample_period = value; 6563 } 6564 6565 active = (event->state == PERF_EVENT_STATE_ACTIVE); 6566 if (active) { 6567 perf_pmu_disable(event->pmu); 6568 event->pmu->stop(event, PERF_EF_UPDATE); 6569 } 6570 6571 local64_set(&event->hw.period_left, 0); 6572 6573 if (active) { 6574 event->pmu->start(event, PERF_EF_RELOAD); 6575 /* 6576 * Once the period is force-reset, the event starts immediately. 6577 * But the event/group could be throttled. Unthrottle the 6578 * event/group now to avoid the next tick trying to unthrottle 6579 * while we already re-started the event/group. 6580 */ 6581 if (event->hw.interrupts == MAX_INTERRUPTS) 6582 perf_event_unthrottle_group(event, true); 6583 perf_pmu_enable(event->pmu); 6584 } 6585 } 6586 6587 static int perf_event_check_period(struct perf_event *event, u64 value) 6588 { 6589 return event->pmu->check_period(event, value); 6590 } 6591 6592 static int _perf_event_period(struct perf_event *event, u64 value) 6593 { 6594 if (!is_sampling_event(event)) 6595 return -EINVAL; 6596 6597 if (!value) 6598 return -EINVAL; 6599 6600 if (event->attr.freq) { 6601 if (value > sysctl_perf_event_sample_rate) 6602 return -EINVAL; 6603 } else { 6604 if (perf_event_check_period(event, value)) 6605 return -EINVAL; 6606 if (value & (1ULL << 63)) 6607 return -EINVAL; 6608 } 6609 6610 event_function_call(event, __perf_event_period, &value); 6611 6612 return 0; 6613 } 6614 6615 int perf_event_period(struct perf_event *event, u64 value) 6616 { 6617 struct perf_event_context *ctx; 6618 int ret; 6619 6620 ctx = perf_event_ctx_lock(event); 6621 ret = _perf_event_period(event, value); 6622 perf_event_ctx_unlock(event, ctx); 6623 6624 return ret; 6625 } 6626 EXPORT_SYMBOL_GPL(perf_event_period); 6627 6628 static const struct file_operations perf_fops; 6629 6630 static inline bool is_perf_file(struct fd f) 6631 { 6632 return !fd_empty(f) && fd_file(f)->f_op == &perf_fops; 6633 } 6634 6635 static int perf_event_set_output(struct perf_event *event, 6636 struct perf_event *output_event); 6637 static int perf_event_set_filter(struct perf_event *event, void __user *arg); 6638 static int perf_copy_attr(struct perf_event_attr __user *uattr, 6639 struct perf_event_attr *attr); 6640 static int __perf_event_set_bpf_prog(struct perf_event *event, 6641 struct bpf_prog *prog, 6642 u64 bpf_cookie); 6643 6644 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg) 6645 { 6646 void (*func)(struct perf_event *); 6647 u32 flags = arg; 6648 6649 if (event->state <= PERF_EVENT_STATE_REVOKED) 6650 return -ENODEV; 6651 6652 switch (cmd) { 6653 case PERF_EVENT_IOC_ENABLE: 6654 func = _perf_event_enable; 6655 break; 6656 case PERF_EVENT_IOC_DISABLE: 6657 func = _perf_event_disable; 6658 break; 6659 case PERF_EVENT_IOC_RESET: 6660 func = _perf_event_reset; 6661 break; 6662 6663 case PERF_EVENT_IOC_REFRESH: 6664 return _perf_event_refresh(event, arg); 6665 6666 case PERF_EVENT_IOC_PERIOD: 6667 { 6668 u64 value; 6669 6670 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value))) 6671 return -EFAULT; 6672 6673 return _perf_event_period(event, value); 6674 } 6675 case PERF_EVENT_IOC_ID: 6676 { 6677 u64 id = primary_event_id(event); 6678 6679 if (copy_to_user((void __user *)arg, &id, sizeof(id))) 6680 return -EFAULT; 6681 return 0; 6682 } 6683 6684 case PERF_EVENT_IOC_SET_OUTPUT: 6685 { 6686 CLASS(fd, output)(arg); // arg == -1 => empty 6687 struct perf_event *output_event = NULL; 6688 if (arg != -1) { 6689 if (!is_perf_file(output)) 6690 return -EBADF; 6691 output_event = fd_file(output)->private_data; 6692 } 6693 return perf_event_set_output(event, output_event); 6694 } 6695 6696 case PERF_EVENT_IOC_SET_FILTER: 6697 return perf_event_set_filter(event, (void __user *)arg); 6698 6699 case PERF_EVENT_IOC_SET_BPF: 6700 { 6701 struct bpf_prog *prog; 6702 int err; 6703 6704 prog = bpf_prog_get(arg); 6705 if (IS_ERR(prog)) 6706 return PTR_ERR(prog); 6707 6708 err = __perf_event_set_bpf_prog(event, prog, 0); 6709 if (err) { 6710 bpf_prog_put(prog); 6711 return err; 6712 } 6713 6714 return 0; 6715 } 6716 6717 case PERF_EVENT_IOC_PAUSE_OUTPUT: { 6718 struct perf_buffer *rb; 6719 6720 rcu_read_lock(); 6721 rb = rcu_dereference(event->rb); 6722 if (!rb || !rb->nr_pages) { 6723 rcu_read_unlock(); 6724 return -EINVAL; 6725 } 6726 rb_toggle_paused(rb, !!arg); 6727 rcu_read_unlock(); 6728 return 0; 6729 } 6730 6731 case PERF_EVENT_IOC_QUERY_BPF: 6732 return perf_event_query_prog_array(event, (void __user *)arg); 6733 6734 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: { 6735 struct perf_event_attr new_attr; 6736 int err = perf_copy_attr((struct perf_event_attr __user *)arg, 6737 &new_attr); 6738 6739 if (err) 6740 return err; 6741 6742 return perf_event_modify_attr(event, &new_attr); 6743 } 6744 default: 6745 return -ENOTTY; 6746 } 6747 6748 if (flags & PERF_IOC_FLAG_GROUP) 6749 perf_event_for_each(event, func); 6750 else 6751 perf_event_for_each_child(event, func); 6752 6753 return 0; 6754 } 6755 6756 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg) 6757 { 6758 struct perf_event *event = file->private_data; 6759 struct perf_event_context *ctx; 6760 long ret; 6761 6762 /* Treat ioctl like writes as it is likely a mutating operation. */ 6763 ret = security_perf_event_write(event); 6764 if (ret) 6765 return ret; 6766 6767 ctx = perf_event_ctx_lock(event); 6768 ret = _perf_ioctl(event, cmd, arg); 6769 perf_event_ctx_unlock(event, ctx); 6770 6771 return ret; 6772 } 6773 6774 #ifdef CONFIG_COMPAT 6775 static long perf_compat_ioctl(struct file *file, unsigned int cmd, 6776 unsigned long arg) 6777 { 6778 switch (_IOC_NR(cmd)) { 6779 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER): 6780 case _IOC_NR(PERF_EVENT_IOC_ID): 6781 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF): 6782 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES): 6783 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */ 6784 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) { 6785 cmd &= ~IOCSIZE_MASK; 6786 cmd |= sizeof(void *) << IOCSIZE_SHIFT; 6787 } 6788 break; 6789 } 6790 return perf_ioctl(file, cmd, arg); 6791 } 6792 #else 6793 # define perf_compat_ioctl NULL 6794 #endif 6795 6796 int perf_event_task_enable(void) 6797 { 6798 struct perf_event_context *ctx; 6799 struct perf_event *event; 6800 6801 mutex_lock(¤t->perf_event_mutex); 6802 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) { 6803 ctx = perf_event_ctx_lock(event); 6804 perf_event_for_each_child(event, _perf_event_enable); 6805 perf_event_ctx_unlock(event, ctx); 6806 } 6807 mutex_unlock(¤t->perf_event_mutex); 6808 6809 return 0; 6810 } 6811 6812 int perf_event_task_disable(void) 6813 { 6814 struct perf_event_context *ctx; 6815 struct perf_event *event; 6816 6817 mutex_lock(¤t->perf_event_mutex); 6818 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) { 6819 ctx = perf_event_ctx_lock(event); 6820 perf_event_for_each_child(event, _perf_event_disable); 6821 perf_event_ctx_unlock(event, ctx); 6822 } 6823 mutex_unlock(¤t->perf_event_mutex); 6824 6825 return 0; 6826 } 6827 6828 static int perf_event_index(struct perf_event *event) 6829 { 6830 if (event->hw.state & PERF_HES_STOPPED) 6831 return 0; 6832 6833 if (event->state != PERF_EVENT_STATE_ACTIVE) 6834 return 0; 6835 6836 return event->pmu->event_idx(event); 6837 } 6838 6839 static void perf_event_init_userpage(struct perf_event *event) 6840 { 6841 struct perf_event_mmap_page *userpg; 6842 struct perf_buffer *rb; 6843 6844 rcu_read_lock(); 6845 rb = rcu_dereference(event->rb); 6846 if (!rb) 6847 goto unlock; 6848 6849 userpg = rb->user_page; 6850 6851 /* Allow new userspace to detect that bit 0 is deprecated */ 6852 userpg->cap_bit0_is_deprecated = 1; 6853 userpg->size = offsetof(struct perf_event_mmap_page, __reserved); 6854 userpg->data_offset = PAGE_SIZE; 6855 userpg->data_size = perf_data_size(rb); 6856 6857 unlock: 6858 rcu_read_unlock(); 6859 } 6860 6861 void __weak arch_perf_update_userpage( 6862 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now) 6863 { 6864 } 6865 6866 /* 6867 * Callers need to ensure there can be no nesting of this function, otherwise 6868 * the seqlock logic goes bad. We can not serialize this because the arch 6869 * code calls this from NMI context. 6870 */ 6871 void perf_event_update_userpage(struct perf_event *event) 6872 { 6873 struct perf_event_mmap_page *userpg; 6874 struct perf_buffer *rb; 6875 u64 enabled, running, now; 6876 6877 rcu_read_lock(); 6878 rb = rcu_dereference(event->rb); 6879 if (!rb) 6880 goto unlock; 6881 6882 /* 6883 * Disable preemption to guarantee consistent time stamps are stored to 6884 * the user page. 6885 */ 6886 preempt_disable(); 6887 6888 /* 6889 * Compute total_time_enabled, total_time_running based on snapshot 6890 * values taken when the event was last scheduled in. 6891 * 6892 * We cannot simply call update_context_time() because doing so would 6893 * lead to deadlock when called from NMI context. 6894 */ 6895 calc_timer_values(event, &now, &enabled, &running); 6896 6897 userpg = rb->user_page; 6898 6899 ++userpg->lock; 6900 barrier(); 6901 userpg->index = perf_event_index(event); 6902 userpg->offset = perf_event_count(event, false); 6903 if (userpg->index) 6904 userpg->offset -= local64_read(&event->hw.prev_count); 6905 6906 userpg->time_enabled = enabled + 6907 atomic64_read(&event->child_total_time_enabled); 6908 6909 userpg->time_running = running + 6910 atomic64_read(&event->child_total_time_running); 6911 6912 arch_perf_update_userpage(event, userpg, now); 6913 6914 barrier(); 6915 ++userpg->lock; 6916 preempt_enable(); 6917 unlock: 6918 rcu_read_unlock(); 6919 } 6920 EXPORT_SYMBOL_GPL(perf_event_update_userpage); 6921 6922 static void ring_buffer_attach(struct perf_event *event, 6923 struct perf_buffer *rb) 6924 { 6925 struct perf_buffer *old_rb = NULL; 6926 unsigned long flags; 6927 6928 WARN_ON_ONCE(event->parent); 6929 6930 if (event->rb) { 6931 /* 6932 * Should be impossible, we set this when removing 6933 * event->rb_entry and wait/clear when adding event->rb_entry. 6934 */ 6935 WARN_ON_ONCE(event->rcu_pending); 6936 6937 old_rb = event->rb; 6938 spin_lock_irqsave(&old_rb->event_lock, flags); 6939 list_del_rcu(&event->rb_entry); 6940 spin_unlock_irqrestore(&old_rb->event_lock, flags); 6941 6942 event->rcu_batches = get_state_synchronize_rcu(); 6943 event->rcu_pending = 1; 6944 } 6945 6946 if (rb) { 6947 if (event->rcu_pending) { 6948 cond_synchronize_rcu(event->rcu_batches); 6949 event->rcu_pending = 0; 6950 } 6951 6952 spin_lock_irqsave(&rb->event_lock, flags); 6953 list_add_rcu(&event->rb_entry, &rb->event_list); 6954 spin_unlock_irqrestore(&rb->event_lock, flags); 6955 } 6956 6957 /* 6958 * Avoid racing with perf_mmap_close(AUX): stop the event 6959 * before swizzling the event::rb pointer; if it's getting 6960 * unmapped, its aux_mmap_count will be 0 and it won't 6961 * restart. See the comment in __perf_pmu_output_stop(). 6962 * 6963 * Data will inevitably be lost when set_output is done in 6964 * mid-air, but then again, whoever does it like this is 6965 * not in for the data anyway. 6966 */ 6967 if (has_aux(event)) 6968 perf_event_stop(event, 0); 6969 6970 rcu_assign_pointer(event->rb, rb); 6971 6972 if (old_rb) { 6973 ring_buffer_put(old_rb); 6974 /* 6975 * Since we detached before setting the new rb, so that we 6976 * could attach the new rb, we could have missed a wakeup. 6977 * Provide it now. 6978 */ 6979 wake_up_all(&event->waitq); 6980 } 6981 } 6982 6983 static void ring_buffer_wakeup(struct perf_event *event) 6984 { 6985 struct perf_buffer *rb; 6986 6987 if (event->parent) 6988 event = event->parent; 6989 6990 rcu_read_lock(); 6991 rb = rcu_dereference(event->rb); 6992 if (rb) { 6993 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) 6994 wake_up_all(&event->waitq); 6995 } 6996 rcu_read_unlock(); 6997 } 6998 6999 struct perf_buffer *ring_buffer_get(struct perf_event *event) 7000 { 7001 struct perf_buffer *rb; 7002 7003 if (event->parent) 7004 event = event->parent; 7005 7006 rcu_read_lock(); 7007 rb = rcu_dereference(event->rb); 7008 if (rb) { 7009 if (!refcount_inc_not_zero(&rb->refcount)) 7010 rb = NULL; 7011 } 7012 rcu_read_unlock(); 7013 7014 return rb; 7015 } 7016 7017 void ring_buffer_put(struct perf_buffer *rb) 7018 { 7019 if (!refcount_dec_and_test(&rb->refcount)) 7020 return; 7021 7022 WARN_ON_ONCE(!list_empty(&rb->event_list)); 7023 7024 call_rcu(&rb->rcu_head, rb_free_rcu); 7025 } 7026 7027 typedef void (*mapped_f)(struct perf_event *event, struct mm_struct *mm); 7028 7029 #define get_mapped(event, func) \ 7030 ({ struct pmu *pmu; \ 7031 mapped_f f = NULL; \ 7032 guard(rcu)(); \ 7033 pmu = READ_ONCE(event->pmu); \ 7034 if (pmu) \ 7035 f = pmu->func; \ 7036 f; \ 7037 }) 7038 7039 static void perf_mmap_open(struct vm_area_struct *vma) 7040 { 7041 struct perf_event *event = vma->vm_file->private_data; 7042 mapped_f mapped = get_mapped(event, event_mapped); 7043 7044 refcount_inc(&event->mmap_count); 7045 refcount_inc(&event->rb->mmap_count); 7046 7047 if (vma_start_pgoff(vma)) 7048 refcount_inc(&event->rb->aux_mmap_count); 7049 7050 if (mapped) 7051 mapped(event, vma->vm_mm); 7052 } 7053 7054 static void perf_pmu_output_stop(struct perf_event *event); 7055 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb); 7056 7057 /* 7058 * A buffer can be mmap()ed multiple times; either directly through the same 7059 * event, or through other events by use of perf_event_set_output(). 7060 * 7061 * In order to undo the VM accounting done by perf_mmap() we need to destroy 7062 * the buffer here, where we still have a VM context. This means we need 7063 * to detach all events redirecting to us. 7064 */ 7065 static void perf_mmap_close(struct vm_area_struct *vma) 7066 { 7067 struct perf_event *event = vma->vm_file->private_data; 7068 mapped_f unmapped = get_mapped(event, event_unmapped); 7069 struct perf_buffer *rb = ring_buffer_get(event); 7070 struct user_struct *mmap_user = rb->mmap_user; 7071 7072 /* FIXIES vs perf_pmu_unregister() */ 7073 if (unmapped) 7074 unmapped(event, vma->vm_mm); 7075 7076 /* 7077 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex 7078 * to avoid complications. 7079 */ 7080 if (rb_has_aux(rb) && vma_start_pgoff(vma) == rb->aux_pgoff && 7081 refcount_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) { 7082 /* 7083 * Stop all AUX events that are writing to this buffer, 7084 * so that we can free its AUX pages and corresponding PMU 7085 * data. Note that after rb::aux_mmap_count dropped to zero, 7086 * they won't start any more (see perf_aux_output_begin()). 7087 */ 7088 perf_pmu_output_stop(event); 7089 7090 /* now it's safe to free the pages */ 7091 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->perf_mlock); 7092 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm); 7093 7094 /* this has to be the last one */ 7095 rb_free_aux(rb); 7096 WARN_ON_ONCE(refcount_read(&rb->aux_refcount)); 7097 7098 mutex_unlock(&rb->aux_mutex); 7099 } 7100 7101 /* 7102 * Drop references in reverse order of perf_mmap() to prevent 7103 * rb revival after rb->mmap_count reaches zero. 7104 */ 7105 if (refcount_dec_and_mutex_lock(&event->mmap_count, 7106 &event->mmap_mutex)) { 7107 ring_buffer_attach(event, NULL); 7108 mutex_unlock(&event->mmap_mutex); 7109 } 7110 7111 /* If there's still other mmap()s of this buffer, we're done. */ 7112 if (!refcount_dec_and_test(&rb->mmap_count)) 7113 goto out_put; 7114 7115 /* 7116 * No other mmap()s, detach from all other events that might redirect 7117 * into the now unreachable buffer. Somewhat complicated by the 7118 * fact that rb::event_lock otherwise nests inside mmap_mutex. 7119 */ 7120 again: 7121 rcu_read_lock(); 7122 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) { 7123 if (!atomic_long_inc_not_zero(&event->refcount)) { 7124 /* 7125 * This event is en-route to free_event() which will 7126 * detach it and remove it from the list. 7127 */ 7128 continue; 7129 } 7130 rcu_read_unlock(); 7131 7132 mutex_lock(&event->mmap_mutex); 7133 /* 7134 * Check we didn't race with perf_event_set_output() which can 7135 * swizzle the rb from under us while we were waiting to 7136 * acquire mmap_mutex. 7137 * 7138 * If we find a different rb; ignore this event, a next 7139 * iteration will no longer find it on the list. We have to 7140 * still restart the iteration to make sure we're not now 7141 * iterating the wrong list. 7142 */ 7143 if (event->rb == rb) 7144 ring_buffer_attach(event, NULL); 7145 7146 mutex_unlock(&event->mmap_mutex); 7147 put_event(event); 7148 7149 /* 7150 * Restart the iteration; either we're on the wrong list or 7151 * destroyed its integrity by doing a deletion. 7152 */ 7153 goto again; 7154 } 7155 rcu_read_unlock(); 7156 7157 /* 7158 * It could be there's still a few 0-ref events on the list; they'll 7159 * get cleaned up by free_event() -- they'll also still have their 7160 * ref on the rb and will free it whenever they are done with it. 7161 * 7162 * Aside from that, this buffer is 'fully' detached and unmapped, 7163 * undo the VM accounting. 7164 */ 7165 perf_mmap_unaccount(vma, rb); 7166 7167 out_put: 7168 ring_buffer_put(rb); /* could be last */ 7169 } 7170 7171 static vm_fault_t perf_mmap_pfn_mkwrite(struct vm_fault *vmf) 7172 { 7173 /* The first page is the user control page, others are read-only. */ 7174 return vmf->pgoff == 0 ? 0 : VM_FAULT_SIGBUS; 7175 } 7176 7177 static int perf_mmap_may_split(struct vm_area_struct *vma, unsigned long addr) 7178 { 7179 /* 7180 * Forbid splitting perf mappings to prevent refcount leaks due to 7181 * the resulting non-matching offsets and sizes. See open()/close(). 7182 */ 7183 return -EINVAL; 7184 } 7185 7186 static const struct vm_operations_struct perf_mmap_vmops = { 7187 .open = perf_mmap_open, 7188 .close = perf_mmap_close, /* non mergeable */ 7189 .pfn_mkwrite = perf_mmap_pfn_mkwrite, 7190 .may_split = perf_mmap_may_split, 7191 }; 7192 7193 static int map_range(struct perf_buffer *rb, struct vm_area_struct *vma) 7194 { 7195 unsigned long nr_pages = vma_pages(vma); 7196 int err = 0; 7197 unsigned long pagenum; 7198 7199 guard(mutex)(&rb->aux_mutex); 7200 7201 /* 7202 * We map this as a VM_PFNMAP VMA. 7203 * 7204 * This is not ideal as this is designed broadly for mappings of PFNs 7205 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which 7206 * !pfn_valid(pfn). 7207 * 7208 * We are mapping kernel-allocated memory (memory we manage ourselves) 7209 * which would more ideally be mapped using vm_insert_page() or a 7210 * similar mechanism, that is as a VM_MIXEDMAP mapping. 7211 * 7212 * However this won't work here, because: 7213 * 7214 * 1. It uses vma->vm_page_prot, but this field has not been completely 7215 * setup at the point of the f_op->mmp() hook, so we are unable to 7216 * indicate that this should be mapped CoW in order that the 7217 * mkwrite() hook can be invoked to make the first page R/W and the 7218 * rest R/O as desired. 7219 * 7220 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in 7221 * vm_normal_page() returning a struct page * pointer, which means 7222 * vm_ops->page_mkwrite() will be invoked rather than 7223 * vm_ops->pfn_mkwrite(), and this means we have to set page->mapping 7224 * to work around retry logic in the fault handler, however this 7225 * field is no longer allowed to be used within struct page. 7226 * 7227 * 3. Having a struct page * made available in the fault logic also 7228 * means that the page gets put on the rmap and becomes 7229 * inappropriately accessible and subject to map and ref counting. 7230 * 7231 * Ideally we would have a mechanism that could explicitly express our 7232 * desires, but this is not currently the case, so we instead use 7233 * VM_PFNMAP. 7234 * 7235 * We manage the lifetime of these mappings with internal refcounts (see 7236 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of 7237 * this mapping is maintained correctly. 7238 */ 7239 for (pagenum = 0; pagenum < nr_pages; pagenum++) { 7240 unsigned long va = vma->vm_start + PAGE_SIZE * pagenum; 7241 struct page *page = perf_mmap_to_page(rb, 7242 vma_start_pgoff(vma) + pagenum); 7243 7244 if (page == NULL) { 7245 err = -EINVAL; 7246 break; 7247 } 7248 7249 /* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */ 7250 err = remap_pfn_range(vma, va, page_to_pfn(page), PAGE_SIZE, 7251 vm_get_page_prot(vma->vm_flags & ~VM_SHARED)); 7252 if (err) 7253 break; 7254 } 7255 7256 #ifdef CONFIG_MMU 7257 /* Clear any partial mappings on error. */ 7258 if (err) 7259 zap_vma_range(vma, vma->vm_start, nr_pages * PAGE_SIZE); 7260 #endif 7261 7262 return err; 7263 } 7264 7265 static bool perf_mmap_calc_limits(struct vm_area_struct *vma, long *user_extra, long *extra) 7266 { 7267 unsigned long user_locked, user_lock_limit, locked, lock_limit; 7268 struct user_struct *user = current_user(); 7269 7270 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10); 7271 /* Increase the limit linearly with more CPUs */ 7272 user_lock_limit *= num_online_cpus(); 7273 7274 user_locked = atomic_long_read(&user->perf_mlock); 7275 7276 /* 7277 * sysctl_perf_event_mlock may have changed, so that 7278 * user->perf_mlock > user_lock_limit 7279 */ 7280 if (user_locked > user_lock_limit) 7281 user_locked = user_lock_limit; 7282 user_locked += *user_extra; 7283 7284 if (user_locked > user_lock_limit) { 7285 /* 7286 * charge perf_mlock until it hits user_lock_limit; 7287 * charge the rest from pinned_vm 7288 */ 7289 *extra = user_locked - user_lock_limit; 7290 *user_extra -= *extra; 7291 } 7292 7293 lock_limit = rlimit(RLIMIT_MEMLOCK); 7294 lock_limit >>= PAGE_SHIFT; 7295 locked = atomic64_read(&vma->vm_mm->pinned_vm) + *extra; 7296 7297 return locked <= lock_limit || !perf_is_paranoid() || capable(CAP_IPC_LOCK); 7298 } 7299 7300 static void perf_mmap_account(struct vm_area_struct *vma, long user_extra, long extra) 7301 { 7302 struct user_struct *user = current_user(); 7303 7304 atomic_long_add(user_extra, &user->perf_mlock); 7305 atomic64_add(extra, &vma->vm_mm->pinned_vm); 7306 } 7307 7308 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb) 7309 { 7310 struct user_struct *user = rb->mmap_user; 7311 7312 atomic_long_sub((perf_data_size(rb) >> PAGE_SHIFT) + 1 - rb->mmap_locked, 7313 &user->perf_mlock); 7314 atomic64_sub(rb->mmap_locked, &vma->vm_mm->pinned_vm); 7315 } 7316 7317 static int perf_mmap_rb(struct vm_area_struct *vma, struct perf_event *event, 7318 unsigned long nr_pages) 7319 { 7320 long extra = 0, user_extra = nr_pages; 7321 struct perf_buffer *rb; 7322 int rb_flags = 0; 7323 7324 nr_pages -= 1; 7325 7326 /* 7327 * If we have rb pages ensure they're a power-of-two number, so we 7328 * can do bitmasks instead of modulo. 7329 */ 7330 if (nr_pages != 0 && !is_power_of_2(nr_pages)) 7331 return -EINVAL; 7332 7333 WARN_ON_ONCE(event->ctx->parent_ctx); 7334 7335 if (event->rb) { 7336 if (data_page_nr(event->rb) != nr_pages) 7337 return -EINVAL; 7338 7339 /* 7340 * If this event doesn't have mmap_count, we're attempting to 7341 * create an alias of another event's mmap(); this would mean 7342 * both events will end up scribbling the same user_page; 7343 * which makes no sense. 7344 */ 7345 if (!refcount_read(&event->mmap_count)) 7346 return -EBUSY; 7347 7348 if (refcount_inc_not_zero(&event->rb->mmap_count)) { 7349 /* 7350 * Success -- managed to mmap() the same buffer 7351 * multiple times. 7352 */ 7353 perf_mmap_account(vma, user_extra, extra); 7354 refcount_inc(&event->mmap_count); 7355 return 0; 7356 } 7357 7358 /* 7359 * Raced against perf_mmap_close()'s 7360 * refcount_dec_and_mutex_lock() remove the 7361 * event and continue as if !event->rb 7362 */ 7363 ring_buffer_attach(event, NULL); 7364 } 7365 7366 if (!perf_mmap_calc_limits(vma, &user_extra, &extra)) 7367 return -EPERM; 7368 7369 if (vma->vm_flags & VM_WRITE) 7370 rb_flags |= RING_BUFFER_WRITABLE; 7371 7372 rb = rb_alloc(nr_pages, 7373 event->attr.watermark ? event->attr.wakeup_watermark : 0, 7374 event->cpu, rb_flags); 7375 7376 if (!rb) 7377 return -ENOMEM; 7378 7379 rb->mmap_locked = extra; 7380 7381 ring_buffer_attach(event, rb); 7382 7383 perf_event_update_time(event); 7384 perf_event_init_userpage(event); 7385 perf_event_update_userpage(event); 7386 7387 perf_mmap_account(vma, user_extra, extra); 7388 refcount_set(&event->mmap_count, 1); 7389 7390 return 0; 7391 } 7392 7393 static int perf_mmap_aux(struct vm_area_struct *vma, struct perf_event *event, 7394 unsigned long nr_pages) 7395 { 7396 const pgoff_t pgoff_start = vma_start_pgoff(vma); 7397 long extra = 0, user_extra = nr_pages; 7398 u64 aux_offset, aux_size; 7399 struct perf_buffer *rb; 7400 int ret, rb_flags = 0; 7401 7402 rb = event->rb; 7403 if (!rb) 7404 return -EINVAL; 7405 7406 guard(mutex)(&rb->aux_mutex); 7407 7408 /* 7409 * AUX area mapping: if rb->aux_nr_pages != 0, it's already 7410 * mapped, all subsequent mappings should have the same size 7411 * and offset. Must be above the normal perf buffer. 7412 */ 7413 aux_offset = READ_ONCE(rb->user_page->aux_offset); 7414 aux_size = READ_ONCE(rb->user_page->aux_size); 7415 7416 if (aux_offset < perf_data_size(rb) + PAGE_SIZE) 7417 return -EINVAL; 7418 7419 if (aux_offset != pgoff_start << PAGE_SHIFT) 7420 return -EINVAL; 7421 7422 /* already mapped with a different offset */ 7423 if (rb_has_aux(rb) && rb->aux_pgoff != pgoff_start) 7424 return -EINVAL; 7425 7426 if (aux_size != nr_pages * PAGE_SIZE) 7427 return -EINVAL; 7428 7429 /* already mapped with a different size */ 7430 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages) 7431 return -EINVAL; 7432 7433 if (!is_power_of_2(nr_pages)) 7434 return -EINVAL; 7435 7436 if (!refcount_inc_not_zero(&rb->mmap_count)) 7437 return -EINVAL; 7438 7439 if (rb_has_aux(rb)) { 7440 refcount_inc(&rb->aux_mmap_count); 7441 7442 } else { 7443 if (!perf_mmap_calc_limits(vma, &user_extra, &extra)) { 7444 refcount_dec(&rb->mmap_count); 7445 return -EPERM; 7446 } 7447 7448 WARN_ON(!rb && event->rb); 7449 7450 if (vma->vm_flags & VM_WRITE) 7451 rb_flags |= RING_BUFFER_WRITABLE; 7452 7453 ret = rb_alloc_aux(rb, event, pgoff_start, nr_pages, 7454 event->attr.aux_watermark, rb_flags); 7455 if (ret) { 7456 refcount_dec(&rb->mmap_count); 7457 return ret; 7458 } 7459 7460 refcount_set(&rb->aux_mmap_count, 1); 7461 rb->aux_mmap_locked = extra; 7462 } 7463 7464 perf_mmap_account(vma, user_extra, extra); 7465 refcount_inc(&event->mmap_count); 7466 7467 return 0; 7468 } 7469 7470 static int perf_mmap(struct file *file, struct vm_area_struct *vma) 7471 { 7472 struct perf_event *event = file->private_data; 7473 unsigned long vma_size, nr_pages; 7474 mapped_f mapped; 7475 int ret; 7476 7477 /* 7478 * Don't allow mmap() of inherited per-task counters. This would 7479 * create a performance issue due to all children writing to the 7480 * same rb. 7481 */ 7482 if (event->cpu == -1 && event->attr.inherit) 7483 return -EINVAL; 7484 7485 if (!(vma->vm_flags & VM_SHARED)) 7486 return -EINVAL; 7487 7488 ret = security_perf_event_read(event); 7489 if (ret) 7490 return ret; 7491 7492 vma_size = vma->vm_end - vma->vm_start; 7493 nr_pages = vma_size / PAGE_SIZE; 7494 7495 if (nr_pages > INT_MAX) 7496 return -ENOMEM; 7497 7498 if (vma_size != PAGE_SIZE * nr_pages) 7499 return -EINVAL; 7500 7501 scoped_guard (mutex, &event->mmap_mutex) { 7502 /* 7503 * This relies on __pmu_detach_event() taking mmap_mutex after marking 7504 * the event REVOKED. Either we observe the state, or __pmu_detach_event() 7505 * will detach the rb created here. 7506 */ 7507 if (event->state <= PERF_EVENT_STATE_REVOKED) 7508 return -ENODEV; 7509 7510 if (!vma_start_pgoff(vma)) 7511 ret = perf_mmap_rb(vma, event, nr_pages); 7512 else 7513 ret = perf_mmap_aux(vma, event, nr_pages); 7514 if (ret) 7515 return ret; 7516 7517 /* 7518 * Since pinned accounting is per vm we cannot allow fork() to copy our 7519 * vma. 7520 */ 7521 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP); 7522 vma->vm_ops = &perf_mmap_vmops; 7523 7524 mapped = get_mapped(event, event_mapped); 7525 if (mapped) 7526 mapped(event, vma->vm_mm); 7527 7528 /* 7529 * Try to map it into the page table. On fail undo the above, 7530 * as the callsite expects full cleanup in this case and 7531 * therefore does not invoke vmops::close(). 7532 */ 7533 ret = map_range(event->rb, vma); 7534 if (likely(!ret)) 7535 return 0; 7536 7537 /* Error path */ 7538 7539 /* 7540 * If this is the first mmap(), then event->mmap_count should 7541 * be stable at 1. It is only modified by: 7542 * perf_mmap_{open,close}() and perf_mmap(). 7543 * 7544 * The former are not possible because this mmap() hasn't been 7545 * successful yet, and the latter is serialized by 7546 * event->mmap_mutex which we still hold (note that mmap_lock 7547 * is not strictly sufficient here, because the event fd can 7548 * be passed to another process through trivial means like 7549 * fork(), leading to concurrent mmap() from different mm). 7550 * 7551 * Make sure to remove event->rb before releasing 7552 * event->mmap_mutex, such that any concurrent mmap() will not 7553 * attempt use this failed buffer. 7554 */ 7555 if (refcount_read(&event->mmap_count) == 1) { 7556 /* 7557 * Minimal perf_mmap_close(); there can't be AUX or 7558 * other events on account of this being the first. 7559 */ 7560 mapped = get_mapped(event, event_unmapped); 7561 if (mapped) 7562 mapped(event, vma->vm_mm); 7563 perf_mmap_unaccount(vma, event->rb); 7564 ring_buffer_attach(event, NULL); /* drops last rb->refcount */ 7565 refcount_set(&event->mmap_count, 0); 7566 return ret; 7567 } 7568 7569 /* 7570 * Otherwise this is an already existing buffer, and there is 7571 * no race vs first exposure, so fall-through and call 7572 * perf_mmap_close(). 7573 */ 7574 } 7575 7576 perf_mmap_close(vma); 7577 return ret; 7578 } 7579 7580 static int perf_fasync(int fd, struct file *filp, int on) 7581 { 7582 struct inode *inode = file_inode(filp); 7583 struct perf_event *event = filp->private_data; 7584 int retval; 7585 7586 if (event->state <= PERF_EVENT_STATE_REVOKED) 7587 return -ENODEV; 7588 7589 inode_lock(inode); 7590 retval = fasync_helper(fd, filp, on, &event->fasync); 7591 inode_unlock(inode); 7592 7593 if (retval < 0) 7594 return retval; 7595 7596 return 0; 7597 } 7598 7599 static void perf_show_fdinfo(struct seq_file *m, struct file *f) 7600 { 7601 struct perf_event *event = f->private_data; 7602 struct perf_event_context *ctx; 7603 struct mutex *child_mutex; 7604 7605 ctx = perf_event_ctx_lock(event); 7606 child_mutex = event->parent ? &event->parent->child_mutex : &event->child_mutex; 7607 mutex_lock(child_mutex); 7608 7609 seq_printf(m, "perf_event_attr.type:\t%u\n", event->orig_type); 7610 if (event->pmu) 7611 seq_printf(m, "pmu_type:\t%u\n", event->pmu->type); 7612 seq_printf(m, "perf_event_attr.config:\t0x%llx\n", (unsigned long long)event->attr.config); 7613 seq_printf(m, "perf_event_attr.config1:\t0x%llx\n", 7614 (unsigned long long)event->attr.config1); 7615 seq_printf(m, "perf_event_attr.config2:\t0x%llx\n", 7616 (unsigned long long)event->attr.config2); 7617 seq_printf(m, "perf_event_attr.config3:\t0x%llx\n", 7618 (unsigned long long)event->attr.config3); 7619 seq_printf(m, "perf_event_attr.config4:\t0x%llx\n", 7620 (unsigned long long)event->attr.config4); 7621 7622 mutex_unlock(child_mutex); 7623 perf_event_ctx_unlock(event, ctx); 7624 } 7625 7626 static const struct file_operations perf_fops = { 7627 .release = perf_release, 7628 .read = perf_read, 7629 .poll = perf_poll, 7630 .unlocked_ioctl = perf_ioctl, 7631 .compat_ioctl = perf_compat_ioctl, 7632 .mmap = perf_mmap, 7633 .fasync = perf_fasync, 7634 .show_fdinfo = perf_show_fdinfo, 7635 }; 7636 7637 /* 7638 * Perf event wakeup 7639 * 7640 * If there's data, ensure we set the poll() state and publish everything 7641 * to user-space before waking everybody up. 7642 */ 7643 7644 void perf_event_wakeup(struct perf_event *event) 7645 { 7646 ring_buffer_wakeup(event); 7647 7648 if (event->pending_kill) { 7649 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill); 7650 event->pending_kill = 0; 7651 } 7652 } 7653 7654 static void perf_sigtrap(struct perf_event *event) 7655 { 7656 /* 7657 * Both perf_pending_task() and perf_pending_irq() can race with the 7658 * task exiting or exec-ing. We can determine if such a race has 7659 * occurred by checking if perf_event_exit_task(), which will set 7660 * ctx->task to TASK_TOMBSTONE, has already been called. 7661 */ 7662 if (event->ctx->task == TASK_TOMBSTONE) 7663 return; 7664 7665 /* 7666 * The event was removed after this signal was queued, e.g. by exec() 7667 * (remove_on_exec), which may also have closed its fd (close-on-exec). 7668 * The new program has default signal handlers, so a SIGTRAP would 7669 * kill it. 7670 */ 7671 if (READ_ONCE(event->state) <= PERF_EVENT_STATE_EXIT) 7672 return; 7673 7674 /* 7675 * We'd expect this to only occur if the irq_work is delayed and either 7676 * ctx->task or current has changed in the meantime. This can be the 7677 * case on architectures that do not implement arch_irq_work_raise(). 7678 */ 7679 if (WARN_ON_ONCE(event->ctx->task != current)) 7680 return; 7681 7682 send_sig_perf((void __user *)event->pending_addr, 7683 event->orig_type, event->attr.sig_data); 7684 } 7685 7686 /* 7687 * Deliver the pending work in-event-context or follow the context. 7688 */ 7689 static void __perf_pending_disable(struct perf_event *event) 7690 { 7691 int cpu = READ_ONCE(event->oncpu); 7692 7693 /* 7694 * If the event isn't running; we done. event_sched_out() will have 7695 * taken care of things. 7696 */ 7697 if (cpu < 0) 7698 return; 7699 7700 /* 7701 * Yay, we hit home and are in the context of the event. 7702 */ 7703 if (cpu == smp_processor_id()) { 7704 if (event->pending_disable) { 7705 event->pending_disable = 0; 7706 perf_event_disable_local(event); 7707 } 7708 return; 7709 } 7710 7711 /* 7712 * CPU-A CPU-B 7713 * 7714 * perf_event_disable_inatomic() 7715 * @pending_disable = 1; 7716 * irq_work_queue(); 7717 * 7718 * sched-out 7719 * @pending_disable = 0; 7720 * 7721 * sched-in 7722 * perf_event_disable_inatomic() 7723 * @pending_disable = 1; 7724 * irq_work_queue(); // FAILS 7725 * 7726 * irq_work_run() 7727 * perf_pending_disable() 7728 * 7729 * But the event runs on CPU-B and wants disabling there. 7730 */ 7731 irq_work_queue_on(&event->pending_disable_irq, cpu); 7732 } 7733 7734 static void perf_pending_disable(struct irq_work *entry) 7735 { 7736 struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq); 7737 int rctx; 7738 7739 /* 7740 * If we 'fail' here, that's OK, it means recursion is already disabled 7741 * and we won't recurse 'further'. 7742 */ 7743 rctx = perf_swevent_get_recursion_context(); 7744 __perf_pending_disable(event); 7745 if (rctx >= 0) 7746 perf_swevent_put_recursion_context(rctx); 7747 } 7748 7749 static void perf_pending_irq(struct irq_work *entry) 7750 { 7751 struct perf_event *event = container_of(entry, struct perf_event, pending_irq); 7752 int rctx; 7753 7754 /* 7755 * If we 'fail' here, that's OK, it means recursion is already disabled 7756 * and we won't recurse 'further'. 7757 */ 7758 rctx = perf_swevent_get_recursion_context(); 7759 7760 /* 7761 * The wakeup isn't bound to the context of the event -- it can happen 7762 * irrespective of where the event is. 7763 */ 7764 if (event->pending_wakeup) { 7765 event->pending_wakeup = 0; 7766 perf_event_wakeup(event); 7767 } 7768 7769 if (rctx >= 0) 7770 perf_swevent_put_recursion_context(rctx); 7771 } 7772 7773 static void perf_pending_task(struct callback_head *head) 7774 { 7775 struct perf_event *event = container_of(head, struct perf_event, pending_task); 7776 int rctx; 7777 7778 /* 7779 * If we 'fail' here, that's OK, it means recursion is already disabled 7780 * and we won't recurse 'further'. 7781 */ 7782 rctx = perf_swevent_get_recursion_context(); 7783 7784 if (event->pending_work) { 7785 perf_sigtrap(event); 7786 local_dec(&event->ctx->nr_no_switch_fast); 7787 /* 7788 * event->pending_work also acts as a 'lock' for 7789 * event->{pending_addr, orig_type, attr.sig_data}. As such we 7790 * must clear after perf_sigtrap is complete. 7791 */ 7792 barrier(); 7793 event->pending_work = 0; 7794 } 7795 put_event(event); 7796 7797 if (rctx >= 0) 7798 perf_swevent_put_recursion_context(rctx); 7799 } 7800 7801 #ifdef CONFIG_GUEST_PERF_EVENTS 7802 struct perf_guest_info_callbacks __rcu *perf_guest_cbs; 7803 7804 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state); 7805 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip); 7806 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr); 7807 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi); 7808 7809 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7810 { 7811 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs))) 7812 return; 7813 7814 rcu_assign_pointer(perf_guest_cbs, cbs); 7815 static_call_update(__perf_guest_state, cbs->state); 7816 static_call_update(__perf_guest_get_ip, cbs->get_ip); 7817 7818 /* Implementing ->handle_intel_pt_intr is optional. */ 7819 if (cbs->handle_intel_pt_intr) 7820 static_call_update(__perf_guest_handle_intel_pt_intr, 7821 cbs->handle_intel_pt_intr); 7822 7823 if (cbs->handle_mediated_pmi) 7824 static_call_update(__perf_guest_handle_mediated_pmi, 7825 cbs->handle_mediated_pmi); 7826 } 7827 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks); 7828 7829 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7830 { 7831 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs)) 7832 return; 7833 7834 rcu_assign_pointer(perf_guest_cbs, NULL); 7835 static_call_update(__perf_guest_state, (void *)&__static_call_return0); 7836 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0); 7837 static_call_update(__perf_guest_handle_intel_pt_intr, (void *)&__static_call_return0); 7838 static_call_update(__perf_guest_handle_mediated_pmi, (void *)&__static_call_return0); 7839 synchronize_rcu(); 7840 } 7841 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks); 7842 #endif 7843 7844 static bool should_sample_guest(struct perf_event *event) 7845 { 7846 return !event->attr.exclude_guest && perf_guest_state(); 7847 } 7848 7849 unsigned long perf_misc_flags(struct perf_event *event, 7850 struct pt_regs *regs) 7851 { 7852 if (should_sample_guest(event)) 7853 return perf_arch_guest_misc_flags(regs); 7854 7855 return perf_arch_misc_flags(regs); 7856 } 7857 7858 unsigned long perf_instruction_pointer(struct perf_event *event, 7859 struct pt_regs *regs) 7860 { 7861 /* 7862 * Hardware skid can lead to a scenario where a PMI is 7863 * delivered after the CPU has already entered kernel mode. 7864 * In that case, user-space sampling must not expose kernel 7865 * register state. 7866 */ 7867 if (should_sample_guest(event)) { 7868 return event->attr.exclude_kernel && 7869 !(perf_guest_state() & PERF_GUEST_USER) ? 7870 0 : perf_guest_get_ip(); 7871 } 7872 7873 return event->attr.exclude_kernel && !user_mode(regs) ? 7874 0 : perf_arch_instruction_pointer(regs); 7875 } 7876 7877 u64 __weak perf_reg_value(struct pt_regs *regs, int idx) 7878 { 7879 return 0; 7880 } 7881 7882 int __weak perf_reg_validate(u64 mask, bool simd_enabled) 7883 { 7884 return mask ? -ENOSYS : 0; 7885 } 7886 7887 u64 __weak perf_reg_abi(struct task_struct *task) 7888 { 7889 return PERF_SAMPLE_REGS_ABI_NONE; 7890 } 7891 7892 void __weak perf_get_regs_user(struct perf_regs *regs_user, 7893 struct pt_regs *regs) 7894 { 7895 regs_user->regs = task_pt_regs(current); 7896 regs_user->abi = perf_reg_abi(current); 7897 } 7898 7899 #define word_for_each_set_bit(bit, val) \ 7900 for (unsigned long long __v = (val); \ 7901 __v && ((bit = __builtin_ctzll(__v)), 1); \ 7902 __v &= __v - 1) 7903 7904 static void 7905 perf_output_sample_regs(struct perf_output_handle *handle, 7906 struct pt_regs *regs, u64 mask) 7907 { 7908 int bit; 7909 7910 word_for_each_set_bit(bit, mask) { 7911 u64 val = perf_reg_value(regs, bit); 7912 perf_output_put(handle, val); 7913 } 7914 } 7915 7916 static void 7917 perf_output_sample_simd_regs(struct perf_output_handle *handle, 7918 struct perf_event *event, 7919 struct pt_regs *regs, 7920 u64 mask, u32 pred_mask) 7921 { 7922 u64 pred_qwords = event->attr.sample_simd_pred_reg_qwords; 7923 u64 vec_qwords = event->attr.sample_simd_vec_reg_qwords; 7924 u64 nr_vectors = hweight64(mask); 7925 u64 nr_pred = hweight32(pred_mask); 7926 int bit; 7927 7928 perf_output_put(handle, nr_vectors); 7929 perf_output_put(handle, vec_qwords); 7930 perf_output_put(handle, nr_pred); 7931 perf_output_put(handle, pred_qwords); 7932 7933 if (nr_vectors) { 7934 word_for_each_set_bit(bit, mask) { 7935 for (int i = 0; i < vec_qwords; i++) { 7936 u64 val = perf_simd_reg_value(regs, bit, 7937 i, false); 7938 perf_output_put(handle, val); 7939 } 7940 } 7941 } 7942 if (nr_pred) { 7943 word_for_each_set_bit(bit, pred_mask) { 7944 for (int i = 0; i < pred_qwords; i++) { 7945 u64 val = perf_simd_reg_value(regs, bit, 7946 i, true); 7947 perf_output_put(handle, val); 7948 } 7949 } 7950 } 7951 } 7952 7953 void perf_sample_regs_user(struct perf_regs *regs_user, 7954 struct pt_regs *regs) 7955 { 7956 if (user_mode(regs)) { 7957 regs_user->abi = perf_reg_abi(current); 7958 regs_user->regs = regs; 7959 } else if (is_user_task(current)) { 7960 perf_get_regs_user(regs_user, regs); 7961 } else { 7962 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE; 7963 regs_user->regs = NULL; 7964 } 7965 } 7966 7967 void perf_sample_regs_intr(struct perf_regs *regs_intr, 7968 struct pt_regs *regs, 7969 bool exclude_kernel) 7970 { 7971 /* 7972 * Hardware skid can lead to a scenario where a PMI is 7973 * delivered after the CPU has already entered kernel mode. 7974 * In that case, user-space sampling must not expose kernel 7975 * register state. 7976 */ 7977 if (exclude_kernel && !user_mode(regs)) { 7978 regs_intr->abi = PERF_SAMPLE_REGS_ABI_NONE; 7979 regs_intr->regs = NULL; 7980 } else { 7981 regs_intr->regs = regs; 7982 regs_intr->abi = perf_reg_abi(current); 7983 } 7984 } 7985 7986 int __weak perf_simd_reg_validate(u16 vec_qwords, u64 vec_mask, 7987 u16 pred_qwords, u32 pred_mask) 7988 { 7989 return -EINVAL; 7990 } 7991 7992 u64 __weak perf_simd_reg_value(struct pt_regs *regs, int idx, 7993 u16 qwords_idx, bool pred) 7994 { 7995 return 0; 7996 } 7997 7998 /* 7999 * Get remaining task size from user stack pointer. 8000 * 8001 * It'd be better to take stack vma map and limit this more 8002 * precisely, but there's no way to get it safely under interrupt, 8003 * so using TASK_SIZE as limit. 8004 */ 8005 static u64 perf_ustack_task_size(struct pt_regs *regs) 8006 { 8007 unsigned long addr = perf_user_stack_pointer(regs); 8008 8009 if (!addr || addr >= TASK_SIZE) 8010 return 0; 8011 8012 return TASK_SIZE - addr; 8013 } 8014 8015 static u16 8016 perf_sample_ustack_size(u16 stack_size, u16 header_size, 8017 struct pt_regs *regs) 8018 { 8019 u64 task_size; 8020 8021 /* No regs, no stack pointer, no dump. */ 8022 if (!regs) 8023 return 0; 8024 8025 /* No mm, no stack, no dump. */ 8026 if (!current->mm) 8027 return 0; 8028 8029 /* 8030 * Check if we fit in with the requested stack size into the: 8031 * - TASK_SIZE 8032 * If we don't, we limit the size to the TASK_SIZE. 8033 * 8034 * - remaining sample size 8035 * If we don't, we customize the stack size to 8036 * fit in to the remaining sample size. 8037 */ 8038 8039 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs)); 8040 stack_size = min(stack_size, (u16) task_size); 8041 8042 /* Current header size plus static size and dynamic size. */ 8043 header_size += 2 * sizeof(u64); 8044 8045 /* Do we fit in with the current stack dump size? */ 8046 if ((u16) (header_size + stack_size) < header_size) { 8047 /* 8048 * If we overflow the maximum size for the sample, 8049 * we customize the stack dump size to fit in. 8050 */ 8051 stack_size = USHRT_MAX - header_size - sizeof(u64); 8052 stack_size = round_up(stack_size, sizeof(u64)); 8053 } 8054 8055 return stack_size; 8056 } 8057 8058 static void 8059 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size, 8060 struct pt_regs *regs) 8061 { 8062 /* Case of a kernel thread, nothing to dump */ 8063 if (!regs) { 8064 u64 size = 0; 8065 perf_output_put(handle, size); 8066 } else { 8067 unsigned long sp; 8068 unsigned int rem; 8069 u64 dyn_size; 8070 8071 /* 8072 * We dump: 8073 * static size 8074 * - the size requested by user or the best one we can fit 8075 * in to the sample max size 8076 * data 8077 * - user stack dump data 8078 * dynamic size 8079 * - the actual dumped size 8080 */ 8081 8082 /* Static size. */ 8083 perf_output_put(handle, dump_size); 8084 8085 /* Data. */ 8086 sp = perf_user_stack_pointer(regs); 8087 rem = __output_copy_user(handle, (void *) sp, dump_size); 8088 dyn_size = dump_size - rem; 8089 8090 perf_output_skip(handle, rem); 8091 8092 /* Dynamic size. */ 8093 perf_output_put(handle, dyn_size); 8094 } 8095 } 8096 8097 static unsigned long perf_prepare_sample_aux(struct perf_event *event, 8098 struct perf_sample_data *data, 8099 size_t size) 8100 { 8101 struct perf_event *sampler = event->aux_event; 8102 struct perf_buffer *rb; 8103 8104 data->aux_size = 0; 8105 8106 if (!sampler) 8107 goto out; 8108 8109 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE)) 8110 goto out; 8111 8112 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id())) 8113 goto out; 8114 8115 rb = ring_buffer_get(sampler); 8116 if (!rb) 8117 goto out; 8118 8119 /* 8120 * If this is an NMI hit inside sampling code, don't take 8121 * the sample. See also perf_aux_sample_output(). 8122 */ 8123 if (READ_ONCE(rb->aux_in_sampling)) { 8124 data->aux_size = 0; 8125 } else { 8126 size = min_t(size_t, size, perf_aux_size(rb)); 8127 data->aux_size = ALIGN(size, sizeof(u64)); 8128 } 8129 ring_buffer_put(rb); 8130 8131 out: 8132 return data->aux_size; 8133 } 8134 8135 static long perf_pmu_snapshot_aux(struct perf_buffer *rb, 8136 struct perf_event *event, 8137 struct perf_output_handle *handle, 8138 unsigned long size) 8139 { 8140 unsigned long flags; 8141 long ret; 8142 8143 /* 8144 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler 8145 * paths. If we start calling them in NMI context, they may race with 8146 * the IRQ ones, that is, for example, re-starting an event that's just 8147 * been stopped, which is why we're using a separate callback that 8148 * doesn't change the event state. 8149 * 8150 * IRQs need to be disabled to prevent IPIs from racing with us. 8151 */ 8152 local_irq_save(flags); 8153 /* 8154 * Guard against NMI hits inside the critical section; 8155 * see also perf_prepare_sample_aux(). 8156 */ 8157 WRITE_ONCE(rb->aux_in_sampling, 1); 8158 barrier(); 8159 8160 ret = event->pmu->snapshot_aux(event, handle, size); 8161 8162 barrier(); 8163 WRITE_ONCE(rb->aux_in_sampling, 0); 8164 local_irq_restore(flags); 8165 8166 return ret; 8167 } 8168 8169 static void perf_aux_sample_output(struct perf_event *event, 8170 struct perf_output_handle *handle, 8171 struct perf_sample_data *data) 8172 { 8173 struct perf_event *sampler = event->aux_event; 8174 struct perf_buffer *rb; 8175 unsigned long pad; 8176 long size; 8177 8178 if (WARN_ON_ONCE(!sampler || !data->aux_size)) 8179 return; 8180 8181 rb = ring_buffer_get(sampler); 8182 if (!rb) 8183 return; 8184 8185 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size); 8186 8187 /* 8188 * An error here means that perf_output_copy() failed (returned a 8189 * non-zero surplus that it didn't copy), which in its current 8190 * enlightened implementation is not possible. If that changes, we'd 8191 * like to know. 8192 */ 8193 if (WARN_ON_ONCE(size < 0)) 8194 goto out_put; 8195 8196 /* 8197 * The pad comes from ALIGN()ing data->aux_size up to u64 in 8198 * perf_prepare_sample_aux(), so should not be more than that. 8199 */ 8200 pad = data->aux_size - size; 8201 if (WARN_ON_ONCE(pad >= sizeof(u64))) 8202 pad = 8; 8203 8204 if (pad) { 8205 u64 zero = 0; 8206 perf_output_copy(handle, &zero, pad); 8207 } 8208 8209 out_put: 8210 ring_buffer_put(rb); 8211 } 8212 8213 /* 8214 * A set of common sample data types saved even for non-sample records 8215 * when event->attr.sample_id_all is set. 8216 */ 8217 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \ 8218 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \ 8219 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER) 8220 8221 static void __perf_event_header__init_id(struct perf_sample_data *data, 8222 struct perf_event *event, 8223 u64 sample_type) 8224 { 8225 data->type = event->attr.sample_type; 8226 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL; 8227 8228 if (sample_type & PERF_SAMPLE_TID) { 8229 /* namespace issues */ 8230 data->tid_entry.pid = perf_event_pid(event, current); 8231 data->tid_entry.tid = perf_event_tid(event, current); 8232 } 8233 8234 if (sample_type & PERF_SAMPLE_TIME) 8235 data->time = perf_event_clock(event); 8236 8237 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) 8238 data->id = primary_event_id(event); 8239 8240 if (sample_type & PERF_SAMPLE_STREAM_ID) 8241 data->stream_id = event->id; 8242 8243 if (sample_type & PERF_SAMPLE_CPU) { 8244 data->cpu_entry.cpu = raw_smp_processor_id(); 8245 data->cpu_entry.reserved = 0; 8246 } 8247 } 8248 8249 void perf_event_header__init(struct perf_event_header *header, 8250 struct perf_sample_data *data, 8251 u32 type, u16 misc, u16 size, 8252 struct perf_event *event) 8253 { 8254 header->type = type; 8255 header->misc = misc; 8256 header->size = size; 8257 8258 if (event->attr.sample_id_all) { 8259 header->size += event->id_header_size; 8260 __perf_event_header__init_id(data, event, event->attr.sample_type); 8261 } 8262 } 8263 8264 static void __perf_event__output_id_sample(struct perf_output_handle *handle, 8265 struct perf_sample_data *data) 8266 { 8267 u64 sample_type = data->type; 8268 8269 if (sample_type & PERF_SAMPLE_TID) 8270 perf_output_put(handle, data->tid_entry); 8271 8272 if (sample_type & PERF_SAMPLE_TIME) 8273 perf_output_put(handle, data->time); 8274 8275 if (sample_type & PERF_SAMPLE_ID) 8276 perf_output_put(handle, data->id); 8277 8278 if (sample_type & PERF_SAMPLE_STREAM_ID) 8279 perf_output_put(handle, data->stream_id); 8280 8281 if (sample_type & PERF_SAMPLE_CPU) 8282 perf_output_put(handle, data->cpu_entry); 8283 8284 if (sample_type & PERF_SAMPLE_IDENTIFIER) 8285 perf_output_put(handle, data->id); 8286 } 8287 8288 void perf_event__output_id_sample(struct perf_event *event, 8289 struct perf_output_handle *handle, 8290 struct perf_sample_data *sample) 8291 { 8292 if (event->attr.sample_id_all) 8293 __perf_event__output_id_sample(handle, sample); 8294 } 8295 8296 static void perf_output_read_one(struct perf_output_handle *handle, 8297 struct perf_event *event, 8298 u64 enabled, u64 running) 8299 { 8300 u64 read_format = event->attr.read_format; 8301 u64 values[5]; 8302 int n = 0; 8303 8304 values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr)); 8305 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 8306 values[n++] = enabled + 8307 atomic64_read(&event->child_total_time_enabled); 8308 } 8309 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 8310 values[n++] = running + 8311 atomic64_read(&event->child_total_time_running); 8312 } 8313 if (read_format & PERF_FORMAT_ID) 8314 values[n++] = primary_event_id(event); 8315 if (read_format & PERF_FORMAT_LOST) 8316 values[n++] = atomic64_read(&event->lost_samples); 8317 8318 __output_copy(handle, values, n * sizeof(u64)); 8319 } 8320 8321 static void perf_output_read_group(struct perf_output_handle *handle, 8322 struct perf_event *event, 8323 u64 enabled, u64 running) 8324 { 8325 struct perf_event *leader = event->group_leader, *sub; 8326 u64 read_format = event->attr.read_format; 8327 unsigned long flags; 8328 u64 values[6]; 8329 int n = 0; 8330 bool self = has_inherit_and_sample_read(&event->attr); 8331 8332 /* 8333 * Disabling interrupts avoids all counter scheduling 8334 * (context switches, timer based rotation and IPIs). 8335 */ 8336 local_irq_save(flags); 8337 8338 values[n++] = 1 + leader->nr_siblings; 8339 8340 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 8341 values[n++] = enabled; 8342 8343 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 8344 values[n++] = running; 8345 8346 if ((leader != event) && !handle->skip_read) 8347 perf_pmu_read(leader); 8348 8349 values[n++] = perf_event_count(leader, self); 8350 if (read_format & PERF_FORMAT_ID) 8351 values[n++] = primary_event_id(leader); 8352 if (read_format & PERF_FORMAT_LOST) 8353 values[n++] = atomic64_read(&leader->lost_samples); 8354 8355 __output_copy(handle, values, n * sizeof(u64)); 8356 8357 for_each_sibling_event(sub, leader) { 8358 n = 0; 8359 8360 if ((sub != event) && !handle->skip_read) 8361 perf_pmu_read(sub); 8362 8363 values[n++] = perf_event_count(sub, self); 8364 if (read_format & PERF_FORMAT_ID) 8365 values[n++] = primary_event_id(sub); 8366 if (read_format & PERF_FORMAT_LOST) 8367 values[n++] = atomic64_read(&sub->lost_samples); 8368 8369 __output_copy(handle, values, n * sizeof(u64)); 8370 } 8371 8372 local_irq_restore(flags); 8373 } 8374 8375 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\ 8376 PERF_FORMAT_TOTAL_TIME_RUNNING) 8377 8378 /* 8379 * XXX PERF_SAMPLE_READ vs inherited events seems difficult. 8380 * 8381 * The problem is that its both hard and excessively expensive to iterate the 8382 * child list, not to mention that its impossible to IPI the children running 8383 * on another CPU, from interrupt/NMI context. 8384 * 8385 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread 8386 * counts rather than attempting to accumulate some value across all children on 8387 * all cores. 8388 */ 8389 static void perf_output_read(struct perf_output_handle *handle, 8390 struct perf_event *event) 8391 { 8392 u64 enabled = 0, running = 0, now; 8393 u64 read_format = event->attr.read_format; 8394 8395 /* 8396 * Compute total_time_enabled, total_time_running based on snapshot 8397 * values taken when the event was last scheduled in. 8398 * 8399 * We cannot simply call update_context_time() because doing so would 8400 * lead to deadlock when called from NMI context. 8401 */ 8402 if (read_format & PERF_FORMAT_TOTAL_TIMES) 8403 calc_timer_values(event, &now, &enabled, &running); 8404 8405 if (event->attr.read_format & PERF_FORMAT_GROUP) 8406 perf_output_read_group(handle, event, enabled, running); 8407 else 8408 perf_output_read_one(handle, event, enabled, running); 8409 } 8410 8411 void perf_output_sample(struct perf_output_handle *handle, 8412 struct perf_event_header *header, 8413 struct perf_sample_data *data, 8414 struct perf_event *event) 8415 { 8416 u64 sample_type = data->type; 8417 8418 if (data->sample_flags & PERF_SAMPLE_READ) 8419 handle->skip_read = 1; 8420 8421 perf_output_put(handle, *header); 8422 8423 if (sample_type & PERF_SAMPLE_IDENTIFIER) 8424 perf_output_put(handle, data->id); 8425 8426 if (sample_type & PERF_SAMPLE_IP) 8427 perf_output_put(handle, data->ip); 8428 8429 if (sample_type & PERF_SAMPLE_TID) 8430 perf_output_put(handle, data->tid_entry); 8431 8432 if (sample_type & PERF_SAMPLE_TIME) 8433 perf_output_put(handle, data->time); 8434 8435 if (sample_type & PERF_SAMPLE_ADDR) 8436 perf_output_put(handle, data->addr); 8437 8438 if (sample_type & PERF_SAMPLE_ID) 8439 perf_output_put(handle, data->id); 8440 8441 if (sample_type & PERF_SAMPLE_STREAM_ID) 8442 perf_output_put(handle, data->stream_id); 8443 8444 if (sample_type & PERF_SAMPLE_CPU) 8445 perf_output_put(handle, data->cpu_entry); 8446 8447 if (sample_type & PERF_SAMPLE_PERIOD) 8448 perf_output_put(handle, data->period); 8449 8450 if (sample_type & PERF_SAMPLE_READ) 8451 perf_output_read(handle, event); 8452 8453 if (sample_type & PERF_SAMPLE_CALLCHAIN) { 8454 int size = 1; 8455 8456 size += data->callchain->nr; 8457 size *= sizeof(u64); 8458 __output_copy(handle, data->callchain, size); 8459 } 8460 8461 if (sample_type & PERF_SAMPLE_RAW) { 8462 struct perf_raw_record *raw = data->raw; 8463 8464 if (raw) { 8465 struct perf_raw_frag *frag = &raw->frag; 8466 8467 perf_output_put(handle, raw->size); 8468 do { 8469 if (frag->copy) { 8470 __output_custom(handle, frag->copy, 8471 frag->data, frag->size); 8472 } else { 8473 __output_copy(handle, frag->data, 8474 frag->size); 8475 } 8476 if (perf_raw_frag_last(frag)) 8477 break; 8478 frag = frag->next; 8479 } while (1); 8480 if (frag->pad) 8481 __output_skip(handle, NULL, frag->pad); 8482 } else { 8483 struct { 8484 u32 size; 8485 u32 data; 8486 } raw = { 8487 .size = sizeof(u32), 8488 .data = 0, 8489 }; 8490 perf_output_put(handle, raw); 8491 } 8492 } 8493 8494 if (sample_type & PERF_SAMPLE_BRANCH_STACK) { 8495 if (data->br_stack) { 8496 size_t size; 8497 8498 size = data->br_stack->nr 8499 * sizeof(struct perf_branch_entry); 8500 8501 perf_output_put(handle, data->br_stack->nr); 8502 if (branch_sample_hw_index(event)) 8503 perf_output_put(handle, data->br_stack->hw_idx); 8504 perf_output_copy(handle, data->br_stack->entries, size); 8505 /* 8506 * Add the extension space which is appended 8507 * right after the struct perf_branch_stack. 8508 */ 8509 if (data->br_stack_cntr) { 8510 size = data->br_stack->nr * sizeof(u64); 8511 perf_output_copy(handle, data->br_stack_cntr, size); 8512 } 8513 } else { 8514 /* 8515 * we always store at least the value of nr 8516 */ 8517 u64 nr = 0; 8518 perf_output_put(handle, nr); 8519 } 8520 } 8521 8522 if (sample_type & PERF_SAMPLE_REGS_USER) { 8523 u64 abi = data->regs_user.abi; 8524 8525 /* 8526 * If there are no regs to dump, notice it through 8527 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 8528 */ 8529 perf_output_put(handle, abi); 8530 8531 if (abi) { 8532 struct perf_event_attr *attr = &event->attr; 8533 u64 mask = attr->sample_regs_user; 8534 perf_output_sample_regs(handle, 8535 data->regs_user.regs, 8536 mask); 8537 if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { 8538 perf_output_sample_simd_regs(handle, event, 8539 data->regs_user.regs, 8540 attr->sample_simd_vec_reg_user, 8541 attr->sample_simd_pred_reg_user); 8542 } 8543 } 8544 } 8545 8546 if (sample_type & PERF_SAMPLE_STACK_USER) { 8547 perf_output_sample_ustack(handle, 8548 data->stack_user_size, 8549 data->regs_user.regs); 8550 } 8551 8552 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) 8553 perf_output_put(handle, data->weight.full); 8554 8555 if (sample_type & PERF_SAMPLE_DATA_SRC) 8556 perf_output_put(handle, data->data_src.val); 8557 8558 if (sample_type & PERF_SAMPLE_TRANSACTION) 8559 perf_output_put(handle, data->txn); 8560 8561 if (sample_type & PERF_SAMPLE_REGS_INTR) { 8562 u64 abi = data->regs_intr.abi; 8563 /* 8564 * If there are no regs to dump, notice it through 8565 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 8566 */ 8567 perf_output_put(handle, abi); 8568 8569 if (abi) { 8570 struct perf_event_attr *attr = &event->attr; 8571 u64 mask = attr->sample_regs_intr; 8572 8573 perf_output_sample_regs(handle, 8574 data->regs_intr.regs, 8575 mask); 8576 if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { 8577 perf_output_sample_simd_regs(handle, event, 8578 data->regs_intr.regs, 8579 attr->sample_simd_vec_reg_intr, 8580 attr->sample_simd_pred_reg_intr); 8581 } 8582 } 8583 } 8584 8585 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 8586 perf_output_put(handle, data->phys_addr); 8587 8588 if (sample_type & PERF_SAMPLE_CGROUP) 8589 perf_output_put(handle, data->cgroup); 8590 8591 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) 8592 perf_output_put(handle, data->data_page_size); 8593 8594 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) 8595 perf_output_put(handle, data->code_page_size); 8596 8597 if (sample_type & PERF_SAMPLE_AUX) { 8598 perf_output_put(handle, data->aux_size); 8599 8600 if (data->aux_size) 8601 perf_aux_sample_output(event, handle, data); 8602 } 8603 8604 if (!event->attr.watermark) { 8605 int wakeup_events = event->attr.wakeup_events; 8606 8607 if (wakeup_events) { 8608 struct perf_buffer *rb = handle->rb; 8609 int events = local_inc_return(&rb->events); 8610 8611 if (events >= wakeup_events) { 8612 local_sub(wakeup_events, &rb->events); 8613 local_inc(&rb->wakeup); 8614 } 8615 } 8616 } 8617 } 8618 8619 static u64 perf_virt_to_phys(u64 virt) 8620 { 8621 u64 phys_addr = 0; 8622 8623 if (!virt) 8624 return 0; 8625 8626 if (virt >= TASK_SIZE) { 8627 /* If it's vmalloc()d memory, leave phys_addr as 0 */ 8628 if (virt_addr_valid((void *)(uintptr_t)virt) && 8629 !(virt >= VMALLOC_START && virt < VMALLOC_END)) 8630 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt); 8631 } else { 8632 /* 8633 * Walking the pages tables for user address. 8634 * Interrupts are disabled, so it prevents any tear down 8635 * of the page tables. 8636 * Try IRQ-safe get_user_page_fast_only first. 8637 * If failed, leave phys_addr as 0. 8638 */ 8639 if (is_user_task(current)) { 8640 struct page *p; 8641 8642 pagefault_disable(); 8643 if (get_user_page_fast_only(virt, 0, &p)) { 8644 phys_addr = page_to_phys(p) + virt % PAGE_SIZE; 8645 put_page(p); 8646 } 8647 pagefault_enable(); 8648 } 8649 } 8650 8651 return phys_addr; 8652 } 8653 8654 /* 8655 * Return the pagetable size of a given virtual address. 8656 */ 8657 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr) 8658 { 8659 u64 size = 0; 8660 8661 #ifdef CONFIG_HAVE_GUP_FAST 8662 pgd_t *pgdp, pgd; 8663 p4d_t *p4dp, p4d; 8664 pud_t *pudp, pud; 8665 pmd_t *pmdp, pmd; 8666 pte_t *ptep, pte; 8667 8668 pgdp = pgd_offset(mm, addr); 8669 pgd = pgdp_get(pgdp); 8670 if (pgd_none(pgd)) 8671 return 0; 8672 8673 if (pgd_leaf(pgd)) 8674 return pgd_leaf_size(pgd); 8675 8676 p4dp = p4d_offset_lockless(pgdp, pgd, addr); 8677 p4d = p4dp_get(p4dp); 8678 if (!p4d_present(p4d)) 8679 return 0; 8680 8681 if (p4d_leaf(p4d)) 8682 return p4d_leaf_size(p4d); 8683 8684 pudp = pud_offset_lockless(p4dp, p4d, addr); 8685 pud = pudp_get(pudp); 8686 if (!pud_present(pud)) 8687 return 0; 8688 8689 if (pud_leaf(pud)) 8690 return pud_leaf_size(pud); 8691 8692 pmdp = pmd_offset_lockless(pudp, pud, addr); 8693 again: 8694 pmd = pmdp_get_lockless(pmdp); 8695 if (!pmd_present(pmd)) 8696 return 0; 8697 8698 if (pmd_leaf(pmd)) 8699 return pmd_leaf_size(pmd); 8700 8701 ptep = pte_offset_map(&pmd, addr); 8702 if (!ptep) 8703 goto again; 8704 8705 pte = ptep_get_lockless(ptep); 8706 if (pte_present(pte)) 8707 size = __pte_leaf_size(pmd, pte); 8708 pte_unmap(ptep); 8709 #endif /* CONFIG_HAVE_GUP_FAST */ 8710 8711 return size; 8712 } 8713 8714 static u64 perf_get_page_size(unsigned long addr) 8715 { 8716 struct mm_struct *mm; 8717 unsigned long flags; 8718 u64 size; 8719 8720 if (!addr) 8721 return 0; 8722 8723 /* 8724 * Software page-table walkers must disable IRQs, 8725 * which prevents any tear down of the page tables. 8726 */ 8727 local_irq_save(flags); 8728 8729 mm = current->mm; 8730 if (!mm) { 8731 /* 8732 * For kernel threads and the like, use init_mm so that 8733 * we can find kernel memory. 8734 */ 8735 mm = &init_mm; 8736 } 8737 8738 size = perf_get_pgtable_size(mm, addr); 8739 8740 local_irq_restore(flags); 8741 8742 return size; 8743 } 8744 8745 static struct perf_callchain_entry __empty_callchain = { .nr = 0, }; 8746 8747 static struct unwind_work perf_unwind_work; 8748 8749 struct perf_callchain_entry * 8750 perf_callchain(struct perf_event *event, struct pt_regs *regs) 8751 { 8752 bool kernel = !event->attr.exclude_callchain_kernel; 8753 bool user = !event->attr.exclude_callchain_user && 8754 is_user_task(current); 8755 /* Disallow cross-task user callchains. */ 8756 bool crosstask = event->ctx->task && event->ctx->task != current; 8757 bool defer_user = IS_ENABLED(CONFIG_UNWIND_USER) && user && 8758 event->attr.defer_callchain; 8759 const u32 max_stack = event->attr.sample_max_stack; 8760 struct perf_callchain_entry *callchain; 8761 u64 defer_cookie; 8762 8763 if (!current->mm) 8764 user = false; 8765 8766 if (!kernel && !user) 8767 return &__empty_callchain; 8768 8769 if (!(user && defer_user && !crosstask && 8770 unwind_deferred_request(&perf_unwind_work, &defer_cookie) >= 0)) 8771 defer_cookie = 0; 8772 8773 callchain = get_perf_callchain(regs, kernel, user, max_stack, 8774 crosstask, true, defer_cookie); 8775 8776 return callchain ?: &__empty_callchain; 8777 } 8778 8779 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d) 8780 { 8781 return d * !!(flags & s); 8782 } 8783 8784 u64 perf_update_xregs_size(struct perf_event *event, bool intr) 8785 { 8786 u16 pred_qwords = event->attr.sample_simd_pred_reg_qwords; 8787 u16 vec_qwords = event->attr.sample_simd_vec_reg_qwords; 8788 u64 pred_mask; 8789 u64 mask; 8790 int size; 8791 8792 if (intr) { 8793 mask = event->attr.sample_simd_vec_reg_intr; 8794 pred_mask = event->attr.sample_simd_pred_reg_intr; 8795 } else { 8796 mask = event->attr.sample_simd_vec_reg_user; 8797 pred_mask = event->attr.sample_simd_pred_reg_user; 8798 } 8799 8800 size = sizeof(u64) * 4; 8801 size += (hweight64(mask) * vec_qwords + 8802 hweight64(pred_mask) * pred_qwords) * sizeof(u64); 8803 8804 return size; 8805 } 8806 8807 void perf_prepare_sample(struct perf_sample_data *data, 8808 struct perf_event *event, 8809 struct pt_regs *regs) 8810 { 8811 u64 sample_type = event->attr.sample_type; 8812 u64 filtered_sample_type; 8813 8814 /* 8815 * Add the sample flags that are dependent to others. And clear the 8816 * sample flags that have already been done by the PMU driver. 8817 */ 8818 filtered_sample_type = sample_type; 8819 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE, 8820 PERF_SAMPLE_IP); 8821 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE | 8822 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR); 8823 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER, 8824 PERF_SAMPLE_REGS_USER); 8825 filtered_sample_type &= ~data->sample_flags; 8826 8827 if (filtered_sample_type == 0) { 8828 /* Make sure it has the correct data->type for output */ 8829 data->type = event->attr.sample_type; 8830 return; 8831 } 8832 8833 __perf_event_header__init_id(data, event, filtered_sample_type); 8834 8835 if (filtered_sample_type & PERF_SAMPLE_IP) { 8836 data->ip = perf_instruction_pointer(event, regs); 8837 data->sample_flags |= PERF_SAMPLE_IP; 8838 } 8839 8840 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN) 8841 perf_sample_save_callchain(data, event, regs); 8842 8843 if (filtered_sample_type & PERF_SAMPLE_RAW) { 8844 data->raw = NULL; 8845 data->dyn_size += sizeof(u64); 8846 data->sample_flags |= PERF_SAMPLE_RAW; 8847 } 8848 8849 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) { 8850 data->br_stack = NULL; 8851 data->dyn_size += sizeof(u64); 8852 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK; 8853 } 8854 8855 if (filtered_sample_type & PERF_SAMPLE_REGS_USER) 8856 perf_sample_regs_user(&data->regs_user, regs); 8857 8858 /* 8859 * It cannot use the filtered_sample_type here as REGS_USER can be set 8860 * by STACK_USER (using __cond_set() above) and we don't want to update 8861 * the dyn_size if it's not requested by users. 8862 */ 8863 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) { 8864 /* regs dump ABI info */ 8865 int size = sizeof(u64); 8866 8867 if (data->regs_user.regs) { 8868 u64 mask = event->attr.sample_regs_user; 8869 8870 size += hweight64(mask) * sizeof(u64); 8871 if (event_has_simd_regs(event)) { 8872 size += perf_update_xregs_size(event, false); 8873 data->regs_user.abi |= PERF_SAMPLE_REGS_ABI_SIMD; 8874 } 8875 } 8876 8877 data->dyn_size += size; 8878 data->sample_flags |= PERF_SAMPLE_REGS_USER; 8879 } 8880 8881 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) { 8882 /* 8883 * Either we need PERF_SAMPLE_STACK_USER bit to be always 8884 * processed as the last one or have additional check added 8885 * in case new sample type is added, because we could eat 8886 * up the rest of the sample size. 8887 */ 8888 u16 stack_size = event->attr.sample_stack_user; 8889 u16 header_size = perf_sample_data_size(data, event); 8890 u16 size = sizeof(u64); 8891 8892 stack_size = perf_sample_ustack_size(stack_size, header_size, 8893 data->regs_user.regs); 8894 8895 /* 8896 * If there is something to dump, add space for the dump 8897 * itself and for the field that tells the dynamic size, 8898 * which is how many have been actually dumped. 8899 */ 8900 if (stack_size) 8901 size += sizeof(u64) + stack_size; 8902 8903 data->stack_user_size = stack_size; 8904 data->dyn_size += size; 8905 data->sample_flags |= PERF_SAMPLE_STACK_USER; 8906 } 8907 8908 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) { 8909 data->weight.full = 0; 8910 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE; 8911 } 8912 8913 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) { 8914 data->data_src.val = PERF_MEM_NA; 8915 data->sample_flags |= PERF_SAMPLE_DATA_SRC; 8916 } 8917 8918 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) { 8919 data->txn = 0; 8920 data->sample_flags |= PERF_SAMPLE_TRANSACTION; 8921 } 8922 8923 if (filtered_sample_type & PERF_SAMPLE_ADDR) { 8924 data->addr = 0; 8925 data->sample_flags |= PERF_SAMPLE_ADDR; 8926 } 8927 8928 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) { 8929 /* regs dump ABI info */ 8930 int size = sizeof(u64); 8931 8932 perf_sample_regs_intr(&data->regs_intr, regs, 8933 event->attr.exclude_kernel); 8934 8935 if (data->regs_intr.regs) { 8936 u64 mask = event->attr.sample_regs_intr; 8937 8938 size += hweight64(mask) * sizeof(u64); 8939 if (event_has_simd_regs(event)) { 8940 size += perf_update_xregs_size(event, true); 8941 data->regs_intr.abi |= PERF_SAMPLE_REGS_ABI_SIMD; 8942 } 8943 } 8944 8945 data->dyn_size += size; 8946 data->sample_flags |= PERF_SAMPLE_REGS_INTR; 8947 } 8948 8949 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) { 8950 data->phys_addr = perf_virt_to_phys(data->addr); 8951 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR; 8952 } 8953 8954 #ifdef CONFIG_CGROUP_PERF 8955 if (filtered_sample_type & PERF_SAMPLE_CGROUP) { 8956 struct cgroup *cgrp; 8957 8958 /* protected by RCU */ 8959 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup; 8960 data->cgroup = cgroup_id(cgrp); 8961 data->sample_flags |= PERF_SAMPLE_CGROUP; 8962 } 8963 #endif 8964 8965 /* 8966 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't 8967 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr, 8968 * but the value will not dump to the userspace. 8969 */ 8970 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) { 8971 data->data_page_size = perf_get_page_size(data->addr); 8972 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE; 8973 } 8974 8975 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) { 8976 data->code_page_size = perf_get_page_size(data->ip); 8977 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE; 8978 } 8979 8980 if (filtered_sample_type & PERF_SAMPLE_AUX) { 8981 u64 size; 8982 u16 header_size = perf_sample_data_size(data, event); 8983 8984 header_size += sizeof(u64); /* size */ 8985 8986 /* 8987 * Given the 16bit nature of header::size, an AUX sample can 8988 * easily overflow it, what with all the preceding sample bits. 8989 * Make sure this doesn't happen by using up to U16_MAX bytes 8990 * per sample in total (rounded down to 8 byte boundary). 8991 */ 8992 size = min_t(size_t, U16_MAX - header_size, 8993 event->attr.aux_sample_size); 8994 size = rounddown(size, 8); 8995 size = perf_prepare_sample_aux(event, data, size); 8996 8997 WARN_ON_ONCE(size + header_size > U16_MAX); 8998 data->dyn_size += size + sizeof(u64); /* size above */ 8999 data->sample_flags |= PERF_SAMPLE_AUX; 9000 } 9001 } 9002 9003 void perf_prepare_header(struct perf_event_header *header, 9004 struct perf_sample_data *data, 9005 struct perf_event *event, 9006 struct pt_regs *regs) 9007 { 9008 header->type = PERF_RECORD_SAMPLE; 9009 header->size = perf_sample_data_size(data, event); 9010 header->misc = perf_misc_flags(event, regs); 9011 9012 /* 9013 * If you're adding more sample types here, you likely need to do 9014 * something about the overflowing header::size, like repurpose the 9015 * lowest 3 bits of size, which should be always zero at the moment. 9016 * This raises a more important question, do we really need 512k sized 9017 * samples and why, so good argumentation is in order for whatever you 9018 * do here next. 9019 */ 9020 WARN_ON_ONCE(header->size & 7); 9021 } 9022 9023 static void __perf_event_aux_pause(struct perf_event *event, bool pause) 9024 { 9025 if (pause) { 9026 if (!event->hw.aux_paused) { 9027 event->hw.aux_paused = 1; 9028 event->pmu->stop(event, PERF_EF_PAUSE); 9029 } 9030 } else { 9031 if (event->hw.aux_paused) { 9032 event->hw.aux_paused = 0; 9033 event->pmu->start(event, PERF_EF_RESUME); 9034 } 9035 } 9036 } 9037 9038 static void perf_event_aux_pause(struct perf_event *event, bool pause) 9039 { 9040 struct perf_buffer *rb; 9041 9042 if (WARN_ON_ONCE(!event)) 9043 return; 9044 9045 rb = ring_buffer_get(event); 9046 if (!rb) 9047 return; 9048 9049 scoped_guard (irqsave) { 9050 /* 9051 * Guard against self-recursion here. Another event could trip 9052 * this same from NMI context. 9053 */ 9054 if (READ_ONCE(rb->aux_in_pause_resume)) 9055 break; 9056 9057 WRITE_ONCE(rb->aux_in_pause_resume, 1); 9058 barrier(); 9059 __perf_event_aux_pause(event, pause); 9060 barrier(); 9061 WRITE_ONCE(rb->aux_in_pause_resume, 0); 9062 } 9063 ring_buffer_put(rb); 9064 } 9065 9066 static __always_inline int 9067 __perf_event_output(struct perf_event *event, 9068 struct perf_sample_data *data, 9069 struct pt_regs *regs, 9070 int (*output_begin)(struct perf_output_handle *, 9071 struct perf_sample_data *, 9072 struct perf_event *, 9073 unsigned int)) 9074 { 9075 struct perf_output_handle handle; 9076 struct perf_event_header header; 9077 int err; 9078 9079 /* protect the callchain buffers */ 9080 rcu_read_lock(); 9081 9082 perf_prepare_sample(data, event, regs); 9083 perf_prepare_header(&header, data, event, regs); 9084 9085 err = output_begin(&handle, data, event, header.size); 9086 if (err) 9087 goto exit; 9088 9089 perf_output_sample(&handle, &header, data, event); 9090 9091 perf_output_end(&handle); 9092 9093 exit: 9094 rcu_read_unlock(); 9095 return err; 9096 } 9097 9098 void 9099 perf_event_output_forward(struct perf_event *event, 9100 struct perf_sample_data *data, 9101 struct pt_regs *regs) 9102 { 9103 __perf_event_output(event, data, regs, perf_output_begin_forward); 9104 } 9105 9106 void 9107 perf_event_output_backward(struct perf_event *event, 9108 struct perf_sample_data *data, 9109 struct pt_regs *regs) 9110 { 9111 __perf_event_output(event, data, regs, perf_output_begin_backward); 9112 } 9113 9114 int 9115 perf_event_output(struct perf_event *event, 9116 struct perf_sample_data *data, 9117 struct pt_regs *regs) 9118 { 9119 return __perf_event_output(event, data, regs, perf_output_begin); 9120 } 9121 9122 /* 9123 * read event_id 9124 */ 9125 9126 struct perf_read_event { 9127 struct perf_event_header header; 9128 9129 u32 pid; 9130 u32 tid; 9131 }; 9132 9133 static void 9134 perf_event_read_event(struct perf_event *event, 9135 struct task_struct *task) 9136 { 9137 struct perf_output_handle handle; 9138 struct perf_sample_data sample; 9139 struct perf_read_event read_event = { 9140 .pid = perf_event_pid(event, task), 9141 .tid = perf_event_tid(event, task), 9142 }; 9143 int ret; 9144 9145 perf_event_header__init(&read_event.header, &sample, 9146 PERF_RECORD_READ, 9147 /* misc= */ 0, 9148 sizeof(read_event) + event->read_size, 9149 event); 9150 ret = perf_output_begin(&handle, &sample, event, read_event.header.size); 9151 if (ret) 9152 return; 9153 9154 perf_output_put(&handle, read_event); 9155 perf_output_read(&handle, event); 9156 perf_event__output_id_sample(event, &handle, &sample); 9157 9158 perf_output_end(&handle); 9159 } 9160 9161 typedef void (perf_iterate_f)(struct perf_event *event, void *data); 9162 9163 static void 9164 perf_iterate_ctx(struct perf_event_context *ctx, 9165 perf_iterate_f output, 9166 void *data, bool all) 9167 { 9168 struct perf_event *event; 9169 9170 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { 9171 if (!all) { 9172 if (event->state < PERF_EVENT_STATE_INACTIVE) 9173 continue; 9174 if (!event_filter_match(event)) 9175 continue; 9176 } 9177 9178 output(event, data); 9179 } 9180 } 9181 9182 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data) 9183 { 9184 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events); 9185 struct perf_event *event; 9186 9187 list_for_each_entry_rcu(event, &pel->list, sb_list) { 9188 /* 9189 * Skip events that are not fully formed yet; ensure that 9190 * if we observe event->ctx, both event and ctx will be 9191 * complete enough. See perf_install_in_context(). 9192 */ 9193 if (!smp_load_acquire(&event->ctx)) 9194 continue; 9195 9196 if (event->state < PERF_EVENT_STATE_INACTIVE) 9197 continue; 9198 if (!event_filter_match(event)) 9199 continue; 9200 output(event, data); 9201 } 9202 } 9203 9204 /* 9205 * Iterate all events that need to receive side-band events. 9206 * 9207 * For new callers; ensure that account_pmu_sb_event() includes 9208 * your event, otherwise it might not get delivered. 9209 */ 9210 static void 9211 perf_iterate_sb(perf_iterate_f output, void *data, 9212 struct perf_event_context *task_ctx) 9213 { 9214 struct perf_event_context *ctx; 9215 9216 rcu_read_lock(); 9217 preempt_disable(); 9218 9219 /* 9220 * If we have task_ctx != NULL we only notify the task context itself. 9221 * The task_ctx is set only for EXIT events before releasing task 9222 * context. 9223 */ 9224 if (task_ctx) { 9225 perf_iterate_ctx(task_ctx, output, data, false); 9226 goto done; 9227 } 9228 9229 perf_iterate_sb_cpu(output, data); 9230 9231 ctx = rcu_dereference(current->perf_event_ctxp); 9232 if (ctx) 9233 perf_iterate_ctx(ctx, output, data, false); 9234 done: 9235 preempt_enable(); 9236 rcu_read_unlock(); 9237 } 9238 9239 /* 9240 * Clear all file-based filters at exec, they'll have to be 9241 * re-instated when/if these objects are mmapped again. 9242 */ 9243 static void perf_event_addr_filters_exec(struct perf_event *event, void *data) 9244 { 9245 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 9246 struct perf_addr_filter *filter; 9247 unsigned int restart = 0, count = 0; 9248 unsigned long flags; 9249 9250 if (!has_addr_filter(event)) 9251 return; 9252 9253 raw_spin_lock_irqsave(&ifh->lock, flags); 9254 list_for_each_entry(filter, &ifh->list, entry) { 9255 if (filter->path.dentry) { 9256 event->addr_filter_ranges[count].start = 0; 9257 event->addr_filter_ranges[count].size = 0; 9258 restart++; 9259 } 9260 9261 count++; 9262 } 9263 9264 if (restart) 9265 event->addr_filters_gen++; 9266 raw_spin_unlock_irqrestore(&ifh->lock, flags); 9267 9268 if (restart) 9269 perf_event_stop(event, 1); 9270 } 9271 9272 void perf_event_exec(void) 9273 { 9274 struct perf_event_context *ctx; 9275 9276 ctx = perf_pin_task_context(current); 9277 if (!ctx) 9278 return; 9279 9280 perf_event_enable_on_exec(ctx); 9281 perf_event_remove_on_exec(ctx); 9282 scoped_guard(rcu) 9283 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true); 9284 9285 perf_unpin_context(ctx); 9286 put_ctx(ctx); 9287 } 9288 9289 struct remote_output { 9290 struct perf_buffer *rb; 9291 int err; 9292 }; 9293 9294 static void __perf_event_output_stop(struct perf_event *event, void *data) 9295 { 9296 struct perf_event *parent = event->parent; 9297 struct remote_output *ro = data; 9298 struct perf_buffer *rb = ro->rb; 9299 struct stop_event_data sd = { 9300 .event = event, 9301 }; 9302 9303 if (!has_aux(event)) 9304 return; 9305 9306 if (!parent) 9307 parent = event; 9308 9309 /* 9310 * In case of inheritance, it will be the parent that links to the 9311 * ring-buffer, but it will be the child that's actually using it. 9312 * 9313 * We are using event::rb to determine if the event should be stopped, 9314 * however this may race with ring_buffer_attach() (through set_output), 9315 * which will make us skip the event that actually needs to be stopped. 9316 * So ring_buffer_attach() has to stop an aux event before re-assigning 9317 * its rb pointer. 9318 */ 9319 if (rcu_dereference(parent->rb) == rb) 9320 ro->err = __perf_event_stop(&sd); 9321 } 9322 9323 static int __perf_pmu_output_stop(void *info) 9324 { 9325 struct perf_event *event = info; 9326 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 9327 struct remote_output ro = { 9328 .rb = event->rb, 9329 }; 9330 9331 rcu_read_lock(); 9332 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false); 9333 if (cpuctx->task_ctx) 9334 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop, 9335 &ro, false); 9336 rcu_read_unlock(); 9337 9338 return ro.err; 9339 } 9340 9341 static void perf_pmu_output_stop(struct perf_event *event) 9342 { 9343 struct perf_event *iter; 9344 int err, cpu; 9345 9346 restart: 9347 rcu_read_lock(); 9348 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) { 9349 /* 9350 * For per-CPU events, we need to make sure that neither they 9351 * nor their children are running; for cpu==-1 events it's 9352 * sufficient to stop the event itself if it's active, since 9353 * it can't have children. 9354 */ 9355 cpu = iter->cpu; 9356 if (cpu == -1) 9357 cpu = READ_ONCE(iter->oncpu); 9358 9359 if (cpu == -1) 9360 continue; 9361 9362 err = cpu_function_call(cpu, __perf_pmu_output_stop, event); 9363 if (err == -EAGAIN) { 9364 rcu_read_unlock(); 9365 goto restart; 9366 } 9367 } 9368 rcu_read_unlock(); 9369 } 9370 9371 /* 9372 * task tracking -- fork/exit 9373 * 9374 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task 9375 */ 9376 9377 struct perf_task_event { 9378 struct task_struct *task; 9379 struct perf_event_context *task_ctx; 9380 9381 struct { 9382 struct perf_event_header header; 9383 9384 u32 pid; 9385 u32 ppid; 9386 u32 tid; 9387 u32 ptid; 9388 u64 time; 9389 } event_id; 9390 int new; 9391 }; 9392 9393 static int perf_event_task_match(struct perf_event *event) 9394 { 9395 return event->attr.comm || event->attr.mmap || 9396 event->attr.mmap2 || event->attr.mmap_data || 9397 event->attr.task; 9398 } 9399 9400 static void perf_event_task_output(struct perf_event *event, 9401 void *data) 9402 { 9403 struct perf_task_event *task_event = data; 9404 struct perf_output_handle handle; 9405 struct perf_sample_data sample; 9406 struct task_struct *task = task_event->task; 9407 int ret; 9408 9409 if (!perf_event_task_match(event)) 9410 return; 9411 9412 perf_event_header__init(&task_event->event_id.header, &sample, 9413 task_event->new ? PERF_RECORD_FORK : PERF_RECORD_EXIT, 9414 /* misc= */ 0, 9415 sizeof(task_event->event_id), 9416 event); 9417 9418 ret = perf_output_begin(&handle, &sample, event, 9419 task_event->event_id.header.size); 9420 if (ret) 9421 return; 9422 9423 task_event->event_id.pid = perf_event_pid(event, task); 9424 task_event->event_id.tid = perf_event_tid(event, task); 9425 9426 if (task_event->event_id.header.type == PERF_RECORD_EXIT) { 9427 task_event->event_id.ppid = perf_event_pid(event, 9428 task->real_parent); 9429 task_event->event_id.ptid = perf_event_pid(event, 9430 task->real_parent); 9431 } else { /* PERF_RECORD_FORK */ 9432 task_event->event_id.ppid = perf_event_pid(event, current); 9433 task_event->event_id.ptid = perf_event_tid(event, current); 9434 } 9435 9436 task_event->event_id.time = perf_event_clock(event); 9437 9438 perf_output_put(&handle, task_event->event_id); 9439 9440 perf_event__output_id_sample(event, &handle, &sample); 9441 9442 perf_output_end(&handle); 9443 } 9444 9445 static void perf_event_task(struct task_struct *task, 9446 struct perf_event_context *task_ctx, 9447 int new) 9448 { 9449 struct perf_task_event task_event; 9450 9451 if (!atomic_read(&nr_comm_events) && 9452 !atomic_read(&nr_mmap_events) && 9453 !atomic_read(&nr_task_events)) 9454 return; 9455 9456 task_event = (struct perf_task_event){ 9457 .task = task, 9458 .task_ctx = task_ctx, 9459 .new = new, 9460 }; 9461 9462 perf_iterate_sb(perf_event_task_output, 9463 &task_event, 9464 task_ctx); 9465 } 9466 9467 /* 9468 * Allocate data for a new task when profiling system-wide 9469 * events which require PMU specific data 9470 */ 9471 static void 9472 perf_event_alloc_task_data(struct task_struct *child, 9473 struct task_struct *parent) 9474 { 9475 struct kmem_cache *ctx_cache = NULL; 9476 struct perf_ctx_data *cd; 9477 9478 if (!refcount_read(&global_ctx_data_ref)) 9479 return; 9480 9481 scoped_guard (rcu) { 9482 cd = rcu_dereference(parent->perf_ctx_data); 9483 if (cd) 9484 ctx_cache = cd->ctx_cache; 9485 } 9486 9487 if (!ctx_cache) 9488 return; 9489 9490 guard(percpu_read)(&global_ctx_data_rwsem); 9491 scoped_guard (rcu) { 9492 cd = rcu_dereference(child->perf_ctx_data); 9493 if (!cd) { 9494 /* 9495 * A system-wide event may be unaccount, 9496 * when attaching the perf_ctx_data. 9497 */ 9498 if (!refcount_read(&global_ctx_data_ref)) 9499 return; 9500 goto attach; 9501 } 9502 9503 if (!cd->global) { 9504 cd->global = 1; 9505 refcount_inc(&cd->refcount); 9506 } 9507 } 9508 9509 return; 9510 attach: 9511 attach_task_ctx_data(child, ctx_cache, true, GFP_KERNEL); 9512 } 9513 9514 void perf_event_fork(struct task_struct *task) 9515 { 9516 perf_event_task(task, NULL, 1); 9517 perf_event_namespaces(task); 9518 perf_event_alloc_task_data(task, current); 9519 } 9520 9521 /* 9522 * comm tracking 9523 */ 9524 9525 struct perf_comm_event { 9526 struct task_struct *task; 9527 char *comm; 9528 int comm_size; 9529 9530 struct { 9531 struct perf_event_header header; 9532 9533 u32 pid; 9534 u32 tid; 9535 } event_id; 9536 bool exec; 9537 }; 9538 9539 static int perf_event_comm_match(struct perf_event *event) 9540 { 9541 return event->attr.comm; 9542 } 9543 9544 static void perf_event_comm_output(struct perf_event *event, 9545 void *data) 9546 { 9547 struct perf_comm_event *comm_event = data; 9548 struct perf_output_handle handle; 9549 struct perf_sample_data sample; 9550 int ret; 9551 9552 if (!perf_event_comm_match(event)) 9553 return; 9554 9555 perf_event_header__init(&comm_event->event_id.header, &sample, 9556 PERF_RECORD_COMM, 9557 comm_event->exec ? PERF_RECORD_MISC_COMM_EXEC : 0, 9558 sizeof(comm_event->event_id) + comm_event->comm_size, 9559 event); 9560 ret = perf_output_begin(&handle, &sample, event, 9561 comm_event->event_id.header.size); 9562 9563 if (ret) 9564 return; 9565 9566 comm_event->event_id.pid = perf_event_pid(event, comm_event->task); 9567 comm_event->event_id.tid = perf_event_tid(event, comm_event->task); 9568 9569 perf_output_put(&handle, comm_event->event_id); 9570 __output_copy(&handle, comm_event->comm, 9571 comm_event->comm_size); 9572 9573 perf_event__output_id_sample(event, &handle, &sample); 9574 9575 perf_output_end(&handle); 9576 } 9577 9578 static void perf_event_comm_event(struct perf_comm_event *comm_event) 9579 { 9580 char comm[TASK_COMM_LEN]; 9581 unsigned int size; 9582 9583 memset(comm, 0, sizeof(comm)); 9584 strscpy(comm, comm_event->task->comm); 9585 size = ALIGN(strlen(comm)+1, sizeof(u64)); 9586 9587 comm_event->comm = comm; 9588 comm_event->comm_size = size; 9589 9590 perf_iterate_sb(perf_event_comm_output, 9591 comm_event, 9592 NULL); 9593 } 9594 9595 void perf_event_comm(struct task_struct *task, bool exec) 9596 { 9597 struct perf_comm_event comm_event; 9598 9599 if (!atomic_read(&nr_comm_events)) 9600 return; 9601 9602 comm_event = (struct perf_comm_event){ 9603 .task = task, 9604 /* .comm */ 9605 /* .comm_size */ 9606 /* .event_id */ 9607 .exec = exec, 9608 }; 9609 9610 perf_event_comm_event(&comm_event); 9611 } 9612 9613 /* 9614 * namespaces tracking 9615 */ 9616 9617 struct perf_namespaces_event { 9618 struct task_struct *task; 9619 9620 struct { 9621 struct perf_event_header header; 9622 9623 u32 pid; 9624 u32 tid; 9625 u64 nr_namespaces; 9626 struct perf_ns_link_info link_info[NR_NAMESPACES]; 9627 } event_id; 9628 }; 9629 9630 static int perf_event_namespaces_match(struct perf_event *event) 9631 { 9632 return event->attr.namespaces; 9633 } 9634 9635 static void perf_event_namespaces_output(struct perf_event *event, 9636 void *data) 9637 { 9638 struct perf_namespaces_event *namespaces_event = data; 9639 struct perf_output_handle handle; 9640 struct perf_sample_data sample; 9641 int ret; 9642 9643 if (!perf_event_namespaces_match(event)) 9644 return; 9645 9646 perf_event_header__init(&namespaces_event->event_id.header, &sample, 9647 PERF_RECORD_NAMESPACES, 9648 /* misc= */ 0, 9649 sizeof(namespaces_event->event_id), 9650 event); 9651 ret = perf_output_begin(&handle, &sample, event, 9652 namespaces_event->event_id.header.size); 9653 if (ret) 9654 return; 9655 9656 namespaces_event->event_id.pid = perf_event_pid(event, 9657 namespaces_event->task); 9658 namespaces_event->event_id.tid = perf_event_tid(event, 9659 namespaces_event->task); 9660 9661 perf_output_put(&handle, namespaces_event->event_id); 9662 9663 perf_event__output_id_sample(event, &handle, &sample); 9664 9665 perf_output_end(&handle); 9666 } 9667 9668 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info, 9669 struct task_struct *task, 9670 const struct proc_ns_operations *ns_ops) 9671 { 9672 struct path ns_path; 9673 struct inode *ns_inode; 9674 int error; 9675 9676 error = ns_get_path(&ns_path, task, ns_ops); 9677 if (!error) { 9678 ns_inode = ns_path.dentry->d_inode; 9679 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev); 9680 ns_link_info->ino = ns_inode->i_ino; 9681 path_put(&ns_path); 9682 } 9683 } 9684 9685 void perf_event_namespaces(struct task_struct *task) 9686 { 9687 struct perf_namespaces_event namespaces_event; 9688 struct perf_ns_link_info *ns_link_info; 9689 9690 if (!atomic_read(&nr_namespaces_events)) 9691 return; 9692 9693 namespaces_event = (struct perf_namespaces_event){ 9694 .task = task, 9695 .event_id = { 9696 /* .header */ 9697 /* .pid */ 9698 /* .tid */ 9699 .nr_namespaces = NR_NAMESPACES, 9700 /* .link_info[NR_NAMESPACES] */ 9701 }, 9702 }; 9703 9704 ns_link_info = namespaces_event.event_id.link_info; 9705 9706 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX], 9707 task, &mntns_operations); 9708 9709 #ifdef CONFIG_USER_NS 9710 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX], 9711 task, &userns_operations); 9712 #endif 9713 #ifdef CONFIG_NET_NS 9714 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX], 9715 task, &netns_operations); 9716 #endif 9717 #ifdef CONFIG_UTS_NS 9718 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX], 9719 task, &utsns_operations); 9720 #endif 9721 #ifdef CONFIG_IPC_NS 9722 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX], 9723 task, &ipcns_operations); 9724 #endif 9725 #ifdef CONFIG_PID_NS 9726 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX], 9727 task, &pidns_operations); 9728 #endif 9729 #ifdef CONFIG_CGROUPS 9730 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX], 9731 task, &cgroupns_operations); 9732 #endif 9733 9734 perf_iterate_sb(perf_event_namespaces_output, 9735 &namespaces_event, 9736 NULL); 9737 } 9738 9739 /* 9740 * cgroup tracking 9741 */ 9742 #ifdef CONFIG_CGROUP_PERF 9743 9744 struct perf_cgroup_event { 9745 char *path; 9746 int path_size; 9747 struct { 9748 struct perf_event_header header; 9749 u64 id; 9750 char path[]; 9751 } event_id; 9752 }; 9753 9754 static int perf_event_cgroup_match(struct perf_event *event) 9755 { 9756 return event->attr.cgroup; 9757 } 9758 9759 static void perf_event_cgroup_output(struct perf_event *event, void *data) 9760 { 9761 struct perf_cgroup_event *cgroup_event = data; 9762 struct perf_output_handle handle; 9763 struct perf_sample_data sample; 9764 int ret; 9765 u16 size = sizeof(cgroup_event->event_id) + cgroup_event->path_size; 9766 9767 if (!perf_event_cgroup_match(event)) 9768 return; 9769 9770 perf_event_header__init(&cgroup_event->event_id.header, &sample, 9771 PERF_RECORD_CGROUP, /* misc= */ 0, size, 9772 event); 9773 ret = perf_output_begin(&handle, &sample, event, 9774 cgroup_event->event_id.header.size); 9775 if (ret) 9776 return; 9777 9778 perf_output_put(&handle, cgroup_event->event_id); 9779 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size); 9780 9781 perf_event__output_id_sample(event, &handle, &sample); 9782 9783 perf_output_end(&handle); 9784 } 9785 9786 static void perf_event_cgroup(struct cgroup *cgrp) 9787 { 9788 struct perf_cgroup_event cgroup_event; 9789 char path_enomem[16] = "//enomem"; 9790 char *pathname; 9791 size_t size; 9792 9793 if (!atomic_read(&nr_cgroup_events)) 9794 return; 9795 9796 cgroup_event = (struct perf_cgroup_event){ 9797 .event_id = { 9798 .id = cgroup_id(cgrp), 9799 }, 9800 }; 9801 9802 pathname = kmalloc(PATH_MAX, GFP_KERNEL); 9803 if (pathname == NULL) { 9804 cgroup_event.path = path_enomem; 9805 } else { 9806 /* just to be sure to have enough space for alignment */ 9807 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64)); 9808 cgroup_event.path = pathname; 9809 } 9810 9811 /* 9812 * Since our buffer works in 8 byte units we need to align our string 9813 * size to a multiple of 8. However, we must guarantee the tail end is 9814 * zero'd out to avoid leaking random bits to userspace. 9815 */ 9816 size = strlen(cgroup_event.path) + 1; 9817 while (!IS_ALIGNED(size, sizeof(u64))) 9818 cgroup_event.path[size++] = '\0'; 9819 9820 cgroup_event.path_size = size; 9821 9822 perf_iterate_sb(perf_event_cgroup_output, 9823 &cgroup_event, 9824 NULL); 9825 9826 kfree(pathname); 9827 } 9828 9829 #endif 9830 9831 /* 9832 * mmap tracking 9833 */ 9834 9835 struct perf_mmap_event { 9836 struct vm_area_struct *vma; 9837 9838 const char *file_name; 9839 int file_size; 9840 int maj, min; 9841 u64 ino; 9842 u64 ino_generation; 9843 u32 prot, flags; 9844 u8 build_id[BUILD_ID_SIZE_MAX]; 9845 u32 build_id_size; 9846 9847 struct { 9848 struct perf_event_header header; 9849 9850 u32 pid; 9851 u32 tid; 9852 u64 start; 9853 u64 len; 9854 u64 pgoff; 9855 } event_id; 9856 }; 9857 9858 static int perf_event_mmap_match(struct perf_event *event, 9859 void *data) 9860 { 9861 struct perf_mmap_event *mmap_event = data; 9862 struct vm_area_struct *vma = mmap_event->vma; 9863 int executable = vma->vm_flags & VM_EXEC; 9864 9865 return (!executable && event->attr.mmap_data) || 9866 (executable && (event->attr.mmap || event->attr.mmap2)); 9867 } 9868 9869 static void perf_event_mmap_output(struct perf_event *event, 9870 void *data) 9871 { 9872 struct perf_mmap_event *mmap_event = data; 9873 struct perf_output_handle handle; 9874 struct perf_sample_data sample; 9875 int size = sizeof(mmap_event->event_id) + mmap_event->file_size; 9876 u32 type = PERF_RECORD_MMAP; 9877 u16 misc = PERF_RECORD_MISC_USER; 9878 bool use_build_id = false; 9879 int ret; 9880 9881 if (!perf_event_mmap_match(event, data)) 9882 return; 9883 9884 if (event->attr.mmap2) { 9885 type = PERF_RECORD_MMAP2; 9886 size += sizeof(mmap_event->maj); 9887 size += sizeof(mmap_event->min); 9888 size += sizeof(mmap_event->ino); 9889 size += sizeof(mmap_event->ino_generation); 9890 size += sizeof(mmap_event->prot); 9891 size += sizeof(mmap_event->flags); 9892 use_build_id = event->attr.build_id && mmap_event->build_id_size; 9893 if (use_build_id) 9894 misc |= PERF_RECORD_MISC_MMAP_BUILD_ID; 9895 } 9896 if (!(mmap_event->vma->vm_flags & VM_EXEC)) 9897 misc |= PERF_RECORD_MISC_MMAP_DATA; 9898 9899 perf_event_header__init(&mmap_event->event_id.header, &sample, 9900 type, misc, size, event); 9901 ret = perf_output_begin(&handle, &sample, event, 9902 mmap_event->event_id.header.size); 9903 if (ret) 9904 return; 9905 9906 mmap_event->event_id.pid = perf_event_pid(event, current); 9907 mmap_event->event_id.tid = perf_event_tid(event, current); 9908 9909 perf_output_put(&handle, mmap_event->event_id); 9910 9911 if (event->attr.mmap2) { 9912 if (use_build_id) { 9913 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 }; 9914 9915 __output_copy(&handle, size, 4); 9916 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX); 9917 } else { 9918 perf_output_put(&handle, mmap_event->maj); 9919 perf_output_put(&handle, mmap_event->min); 9920 perf_output_put(&handle, mmap_event->ino); 9921 perf_output_put(&handle, mmap_event->ino_generation); 9922 } 9923 perf_output_put(&handle, mmap_event->prot); 9924 perf_output_put(&handle, mmap_event->flags); 9925 } 9926 9927 __output_copy(&handle, mmap_event->file_name, 9928 mmap_event->file_size); 9929 9930 perf_event__output_id_sample(event, &handle, &sample); 9931 9932 perf_output_end(&handle); 9933 } 9934 9935 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event) 9936 { 9937 struct vm_area_struct *vma = mmap_event->vma; 9938 struct file *file = vma->vm_file; 9939 int maj = 0, min = 0; 9940 u64 ino = 0, gen = 0; 9941 u32 prot = 0, flags = 0; 9942 unsigned int size; 9943 char tmp[16]; 9944 char *buf = NULL; 9945 char *name = NULL; 9946 9947 if (vma->vm_flags & VM_READ) 9948 prot |= PROT_READ; 9949 if (vma->vm_flags & VM_WRITE) 9950 prot |= PROT_WRITE; 9951 if (vma->vm_flags & VM_EXEC) 9952 prot |= PROT_EXEC; 9953 9954 if (vma->vm_flags & VM_MAYSHARE) 9955 flags = MAP_SHARED; 9956 else 9957 flags = MAP_PRIVATE; 9958 9959 if (vma->vm_flags & VM_LOCKED) 9960 flags |= MAP_LOCKED; 9961 if (vma_is_hugetlb(vma)) 9962 flags |= MAP_HUGETLB; 9963 9964 if (file) { 9965 const struct inode *inode; 9966 dev_t dev; 9967 9968 buf = kmalloc(PATH_MAX, GFP_KERNEL); 9969 if (!buf) { 9970 name = "//enomem"; 9971 goto cpy_name; 9972 } 9973 /* 9974 * d_path() works from the end of the rb backwards, so we 9975 * need to add enough zero bytes after the string to handle 9976 * the 64bit alignment we do later. 9977 */ 9978 name = d_path(file_user_path(file), buf, PATH_MAX - sizeof(u64)); 9979 if (IS_ERR(name)) { 9980 name = "//toolong"; 9981 goto cpy_name; 9982 } 9983 inode = file_user_inode(vma->vm_file); 9984 dev = inode->i_sb->s_dev; 9985 ino = inode->i_ino; 9986 gen = inode->i_generation; 9987 maj = MAJOR(dev); 9988 min = MINOR(dev); 9989 9990 goto got_name; 9991 } else { 9992 if (vma->vm_ops && vma->vm_ops->name) 9993 name = (char *) vma->vm_ops->name(vma); 9994 if (!name) 9995 name = (char *)arch_vma_name(vma); 9996 if (!name) { 9997 if (vma_is_initial_heap(vma)) 9998 name = "[heap]"; 9999 else if (vma_is_initial_stack(vma)) 10000 name = "[stack]"; 10001 else 10002 name = "//anon"; 10003 } 10004 } 10005 10006 cpy_name: 10007 strscpy(tmp, name); 10008 name = tmp; 10009 got_name: 10010 /* 10011 * Since our buffer works in 8 byte units we need to align our string 10012 * size to a multiple of 8. However, we must guarantee the tail end is 10013 * zero'd out to avoid leaking random bits to userspace. 10014 */ 10015 size = strlen(name)+1; 10016 while (!IS_ALIGNED(size, sizeof(u64))) 10017 name[size++] = '\0'; 10018 10019 mmap_event->file_name = name; 10020 mmap_event->file_size = size; 10021 mmap_event->maj = maj; 10022 mmap_event->min = min; 10023 mmap_event->ino = ino; 10024 mmap_event->ino_generation = gen; 10025 mmap_event->prot = prot; 10026 mmap_event->flags = flags; 10027 10028 if (atomic_read(&nr_build_id_events)) 10029 build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size); 10030 10031 perf_iterate_sb(perf_event_mmap_output, 10032 mmap_event, 10033 NULL); 10034 10035 kfree(buf); 10036 } 10037 10038 /* 10039 * Check whether inode and address range match filter criteria. 10040 */ 10041 static bool perf_addr_filter_match(struct perf_addr_filter *filter, 10042 struct file *file, unsigned long offset, 10043 unsigned long size) 10044 { 10045 /* d_inode(NULL) won't be equal to any mapped user-space file */ 10046 if (!filter->path.dentry) 10047 return false; 10048 10049 if (d_inode(filter->path.dentry) != file_user_inode(file)) 10050 return false; 10051 10052 if (filter->offset > offset + size) 10053 return false; 10054 10055 if (filter->offset + filter->size < offset) 10056 return false; 10057 10058 return true; 10059 } 10060 10061 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter, 10062 struct vm_area_struct *vma, 10063 struct perf_addr_filter_range *fr) 10064 { 10065 unsigned long vma_size = vma->vm_end - vma->vm_start; 10066 unsigned long off = vma_start_pgoff(vma) << PAGE_SHIFT; 10067 struct file *file = vma->vm_file; 10068 10069 if (!perf_addr_filter_match(filter, file, off, vma_size)) 10070 return false; 10071 10072 if (filter->offset < off) { 10073 fr->start = vma->vm_start; 10074 fr->size = min(vma_size, filter->size - (off - filter->offset)); 10075 } else { 10076 fr->start = vma->vm_start + filter->offset - off; 10077 fr->size = min(vma->vm_end - fr->start, filter->size); 10078 } 10079 10080 return true; 10081 } 10082 10083 static void __perf_addr_filters_adjust(struct perf_event *event, void *data) 10084 { 10085 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 10086 struct vm_area_struct *vma = data; 10087 struct perf_addr_filter *filter; 10088 unsigned int restart = 0, count = 0; 10089 unsigned long flags; 10090 10091 if (!has_addr_filter(event)) 10092 return; 10093 10094 if (!vma->vm_file) 10095 return; 10096 10097 raw_spin_lock_irqsave(&ifh->lock, flags); 10098 list_for_each_entry(filter, &ifh->list, entry) { 10099 if (perf_addr_filter_vma_adjust(filter, vma, 10100 &event->addr_filter_ranges[count])) 10101 restart++; 10102 10103 count++; 10104 } 10105 10106 if (restart) 10107 event->addr_filters_gen++; 10108 raw_spin_unlock_irqrestore(&ifh->lock, flags); 10109 10110 if (restart) 10111 perf_event_stop(event, 1); 10112 } 10113 10114 /* 10115 * Adjust all task's events' filters to the new vma 10116 */ 10117 static void perf_addr_filters_adjust(struct vm_area_struct *vma) 10118 { 10119 struct perf_event_context *ctx; 10120 10121 /* 10122 * Data tracing isn't supported yet and as such there is no need 10123 * to keep track of anything that isn't related to executable code: 10124 */ 10125 if (!(vma->vm_flags & VM_EXEC)) 10126 return; 10127 10128 rcu_read_lock(); 10129 ctx = rcu_dereference(current->perf_event_ctxp); 10130 if (ctx) 10131 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true); 10132 rcu_read_unlock(); 10133 } 10134 10135 void perf_event_mmap(struct vm_area_struct *vma) 10136 { 10137 struct perf_mmap_event mmap_event; 10138 10139 if (!atomic_read(&nr_mmap_events)) 10140 return; 10141 10142 mmap_event = (struct perf_mmap_event){ 10143 .vma = vma, 10144 /* .file_name */ 10145 /* .file_size */ 10146 .event_id = { 10147 /* .header */ 10148 /* .pid */ 10149 /* .tid */ 10150 .start = vma->vm_start, 10151 .len = vma->vm_end - vma->vm_start, 10152 .pgoff = (u64)vma_start_pgoff(vma) << PAGE_SHIFT, 10153 }, 10154 /* .maj (attr_mmap2 only) */ 10155 /* .min (attr_mmap2 only) */ 10156 /* .ino (attr_mmap2 only) */ 10157 /* .ino_generation (attr_mmap2 only) */ 10158 /* .prot (attr_mmap2 only) */ 10159 /* .flags (attr_mmap2 only) */ 10160 }; 10161 10162 perf_addr_filters_adjust(vma); 10163 perf_event_mmap_event(&mmap_event); 10164 } 10165 10166 void perf_event_aux_event(struct perf_event *event, unsigned long head, 10167 unsigned long size, u64 flags) 10168 { 10169 struct perf_output_handle handle; 10170 struct perf_sample_data sample; 10171 struct perf_aux_event { 10172 struct perf_event_header header; 10173 u64 offset; 10174 u64 size; 10175 u64 flags; 10176 } rec = { 10177 .offset = head, 10178 .size = size, 10179 .flags = flags, 10180 }; 10181 int ret; 10182 10183 perf_event_header__init(&rec.header, &sample, 10184 PERF_RECORD_AUX, /* misc= */ 0, sizeof(rec), 10185 event); 10186 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10187 10188 if (ret) 10189 return; 10190 10191 perf_output_put(&handle, rec); 10192 perf_event__output_id_sample(event, &handle, &sample); 10193 10194 perf_output_end(&handle); 10195 } 10196 10197 /* 10198 * Lost/dropped samples logging 10199 */ 10200 void perf_log_lost_samples(struct perf_event *event, u64 lost) 10201 { 10202 struct perf_output_handle handle; 10203 struct perf_sample_data sample; 10204 int ret; 10205 10206 struct { 10207 struct perf_event_header header; 10208 u64 lost; 10209 } lost_samples_event = { 10210 .lost = lost, 10211 }; 10212 10213 perf_event_header__init(&lost_samples_event.header, &sample, 10214 PERF_RECORD_LOST_SAMPLES, 10215 /* misc= */ 0, 10216 sizeof(lost_samples_event), 10217 event); 10218 10219 ret = perf_output_begin(&handle, &sample, event, 10220 lost_samples_event.header.size); 10221 if (ret) 10222 return; 10223 10224 perf_output_put(&handle, lost_samples_event); 10225 perf_event__output_id_sample(event, &handle, &sample); 10226 perf_output_end(&handle); 10227 } 10228 10229 /* 10230 * context_switch tracking 10231 */ 10232 10233 struct perf_switch_event { 10234 struct task_struct *task; 10235 struct task_struct *next_prev; 10236 10237 struct { 10238 struct perf_event_header header; 10239 u32 next_prev_pid; 10240 u32 next_prev_tid; 10241 } event_id; 10242 bool sched_in; 10243 bool preempt; 10244 }; 10245 10246 static int perf_event_switch_match(struct perf_event *event) 10247 { 10248 return event->attr.context_switch; 10249 } 10250 10251 static void perf_event_switch_output(struct perf_event *event, void *data) 10252 { 10253 struct perf_switch_event *se = data; 10254 struct perf_output_handle handle; 10255 struct perf_sample_data sample; 10256 u32 type; 10257 u16 misc; 10258 u16 size; 10259 int ret; 10260 10261 if (!perf_event_switch_match(event)) 10262 return; 10263 10264 /* Only CPU-wide events are allowed to see next/prev pid/tid */ 10265 if (event->ctx->task) { 10266 type = PERF_RECORD_SWITCH; 10267 size = sizeof(se->event_id.header); 10268 } else { 10269 type = PERF_RECORD_SWITCH_CPU_WIDE; 10270 size = sizeof(se->event_id); 10271 se->event_id.next_prev_pid = 10272 perf_event_pid(event, se->next_prev); 10273 se->event_id.next_prev_tid = 10274 perf_event_tid(event, se->next_prev); 10275 } 10276 misc = se->sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT; 10277 if (se->preempt) 10278 misc |= PERF_RECORD_MISC_SWITCH_OUT_PREEMPT; 10279 10280 perf_event_header__init(&se->event_id.header, &sample, 10281 type, misc, size, event); 10282 10283 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size); 10284 if (ret) 10285 return; 10286 10287 if (event->ctx->task) 10288 perf_output_put(&handle, se->event_id.header); 10289 else 10290 perf_output_put(&handle, se->event_id); 10291 10292 perf_event__output_id_sample(event, &handle, &sample); 10293 10294 perf_output_end(&handle); 10295 } 10296 10297 static void perf_event_switch(struct task_struct *task, 10298 struct task_struct *next_prev, bool sched_in) 10299 { 10300 struct perf_switch_event switch_event; 10301 10302 /* N.B. caller checks nr_switch_events != 0 */ 10303 10304 switch_event = (struct perf_switch_event){ 10305 .task = task, 10306 .next_prev = next_prev, 10307 /* .event_id */ 10308 .sched_in = sched_in, 10309 .preempt = !sched_in && task_is_runnable(task), 10310 }; 10311 10312 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL); 10313 } 10314 10315 /* 10316 * IRQ throttle logging 10317 */ 10318 10319 static void perf_log_throttle(struct perf_event *event, int enable) 10320 { 10321 struct perf_output_handle handle; 10322 struct perf_sample_data sample; 10323 int ret; 10324 10325 struct { 10326 struct perf_event_header header; 10327 u64 time; 10328 u64 id; 10329 u64 stream_id; 10330 } throttle_event = { 10331 .time = perf_event_clock(event), 10332 .id = primary_event_id(event), 10333 .stream_id = event->id, 10334 }; 10335 10336 perf_event_header__init(&throttle_event.header, &sample, 10337 enable ? PERF_RECORD_UNTHROTTLE 10338 : PERF_RECORD_THROTTLE, 10339 /* misc= */ 0, 10340 sizeof(throttle_event), 10341 event); 10342 10343 ret = perf_output_begin(&handle, &sample, event, 10344 throttle_event.header.size); 10345 if (ret) 10346 return; 10347 10348 perf_output_put(&handle, throttle_event); 10349 perf_event__output_id_sample(event, &handle, &sample); 10350 perf_output_end(&handle); 10351 } 10352 10353 /* 10354 * ksymbol register/unregister tracking 10355 */ 10356 10357 struct perf_ksymbol_event { 10358 const char *name; 10359 int name_len; 10360 struct { 10361 struct perf_event_header header; 10362 u64 addr; 10363 u32 len; 10364 u16 ksym_type; 10365 u16 flags; 10366 } event_id; 10367 }; 10368 10369 static int perf_event_ksymbol_match(struct perf_event *event) 10370 { 10371 return event->attr.ksymbol; 10372 } 10373 10374 static void perf_event_ksymbol_output(struct perf_event *event, void *data) 10375 { 10376 struct perf_ksymbol_event *ksymbol_event = data; 10377 struct perf_output_handle handle; 10378 struct perf_sample_data sample; 10379 int ret; 10380 u16 size = sizeof(ksymbol_event->event_id) + ksymbol_event->name_len; 10381 10382 if (!perf_event_ksymbol_match(event)) 10383 return; 10384 10385 perf_event_header__init(&ksymbol_event->event_id.header, &sample, 10386 PERF_RECORD_KSYMBOL, /* misc= */ 0, size, 10387 event); 10388 ret = perf_output_begin(&handle, &sample, event, 10389 ksymbol_event->event_id.header.size); 10390 if (ret) 10391 return; 10392 10393 perf_output_put(&handle, ksymbol_event->event_id); 10394 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len); 10395 perf_event__output_id_sample(event, &handle, &sample); 10396 10397 perf_output_end(&handle); 10398 } 10399 10400 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister, 10401 const char *sym) 10402 { 10403 struct perf_ksymbol_event ksymbol_event; 10404 char name[KSYM_NAME_LEN]; 10405 u16 flags = 0; 10406 int name_len; 10407 10408 if (!atomic_read(&nr_ksymbol_events)) 10409 return; 10410 10411 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX || 10412 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN) 10413 goto err; 10414 10415 strscpy(name, sym); 10416 name_len = strlen(name) + 1; 10417 while (!IS_ALIGNED(name_len, sizeof(u64))) 10418 name[name_len++] = '\0'; 10419 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64)); 10420 10421 if (unregister) 10422 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER; 10423 10424 ksymbol_event = (struct perf_ksymbol_event){ 10425 .name = name, 10426 .name_len = name_len, 10427 .event_id = { 10428 .addr = addr, 10429 .len = len, 10430 .ksym_type = ksym_type, 10431 .flags = flags, 10432 }, 10433 }; 10434 10435 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL); 10436 return; 10437 err: 10438 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type); 10439 } 10440 10441 /* 10442 * bpf program load/unload tracking 10443 */ 10444 10445 struct perf_bpf_event { 10446 struct bpf_prog *prog; 10447 struct { 10448 struct perf_event_header header; 10449 u16 type; 10450 u16 flags; 10451 u32 id; 10452 u8 tag[BPF_TAG_SIZE]; 10453 } event_id; 10454 }; 10455 10456 static int perf_event_bpf_match(struct perf_event *event) 10457 { 10458 return event->attr.bpf_event; 10459 } 10460 10461 static void perf_event_bpf_output(struct perf_event *event, void *data) 10462 { 10463 struct perf_bpf_event *bpf_event = data; 10464 struct perf_output_handle handle; 10465 struct perf_sample_data sample; 10466 int ret; 10467 10468 if (!perf_event_bpf_match(event)) 10469 return; 10470 10471 perf_event_header__init(&bpf_event->event_id.header, &sample, 10472 PERF_RECORD_BPF_EVENT, 10473 /* misc= */ 0, 10474 sizeof(bpf_event->event_id), 10475 event); 10476 ret = perf_output_begin(&handle, &sample, event, 10477 bpf_event->event_id.header.size); 10478 if (ret) 10479 return; 10480 10481 perf_output_put(&handle, bpf_event->event_id); 10482 perf_event__output_id_sample(event, &handle, &sample); 10483 10484 perf_output_end(&handle); 10485 } 10486 10487 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog, 10488 enum perf_bpf_event_type type) 10489 { 10490 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD; 10491 int i; 10492 10493 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, 10494 (u64)(unsigned long)prog->bpf_func, 10495 prog->jited_len, unregister, 10496 prog->aux->ksym.name); 10497 10498 for (i = 1; i < prog->aux->func_cnt; i++) { 10499 struct bpf_prog *subprog = prog->aux->func[i]; 10500 10501 perf_event_ksymbol( 10502 PERF_RECORD_KSYMBOL_TYPE_BPF, 10503 (u64)(unsigned long)subprog->bpf_func, 10504 subprog->jited_len, unregister, 10505 subprog->aux->ksym.name); 10506 } 10507 } 10508 10509 void perf_event_bpf_event(struct bpf_prog *prog, 10510 enum perf_bpf_event_type type, 10511 u16 flags) 10512 { 10513 struct perf_bpf_event bpf_event; 10514 10515 switch (type) { 10516 case PERF_BPF_EVENT_PROG_LOAD: 10517 case PERF_BPF_EVENT_PROG_UNLOAD: 10518 if (atomic_read(&nr_ksymbol_events)) 10519 perf_event_bpf_emit_ksymbols(prog, type); 10520 break; 10521 default: 10522 return; 10523 } 10524 10525 if (!atomic_read(&nr_bpf_events)) 10526 return; 10527 10528 bpf_event = (struct perf_bpf_event){ 10529 .prog = prog, 10530 .event_id = { 10531 .type = type, 10532 .flags = flags, 10533 .id = prog->aux->id, 10534 }, 10535 }; 10536 10537 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64)); 10538 10539 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE); 10540 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL); 10541 } 10542 10543 struct perf_callchain_deferred_event { 10544 struct unwind_stacktrace *trace; 10545 struct { 10546 struct perf_event_header header; 10547 u64 cookie; 10548 } event; 10549 }; 10550 10551 static void perf_callchain_deferred_output(struct perf_event *event, void *data) 10552 { 10553 struct perf_callchain_deferred_event *deferred_event = data; 10554 struct perf_output_handle handle; 10555 struct perf_sample_data sample; 10556 u64 nr = deferred_event->trace->nr; 10557 u16 size, id_size, max_payload; 10558 int ret; 10559 10560 if (!event->attr.defer_output) 10561 return; 10562 10563 id_size = event->attr.sample_id_all ? event->id_header_size : 0; 10564 max_payload = round_down(U16_MAX - sizeof(deferred_event->event) - 10565 sizeof(u64) - id_size, sizeof(u64)); 10566 nr = min_t(u64, nr, max_payload / sizeof(u64)); 10567 size = sizeof(deferred_event->event) + sizeof(u64) + nr * sizeof(u64); 10568 10569 /* XXX do we really need sample_id_all for this ??? */ 10570 perf_event_header__init(&deferred_event->event.header, &sample, 10571 PERF_RECORD_CALLCHAIN_DEFERRED, 10572 PERF_RECORD_MISC_USER, 10573 size, 10574 event); 10575 10576 ret = perf_output_begin(&handle, &sample, event, 10577 deferred_event->event.header.size); 10578 if (ret) 10579 return; 10580 10581 perf_output_put(&handle, deferred_event->event); 10582 perf_output_put(&handle, nr); 10583 for (u64 i = 0; i < nr; i++) { 10584 u64 entry = deferred_event->trace->entries[i]; 10585 10586 perf_output_put(&handle, entry); 10587 } 10588 perf_event__output_id_sample(event, &handle, &sample); 10589 10590 perf_output_end(&handle); 10591 } 10592 10593 static void perf_unwind_deferred_callback(struct unwind_work *work, 10594 struct unwind_stacktrace *trace, u64 cookie) 10595 { 10596 struct perf_callchain_deferred_event deferred_event = { 10597 .trace = trace, 10598 .event = { 10599 .cookie = cookie, 10600 }, 10601 }; 10602 10603 perf_iterate_sb(perf_callchain_deferred_output, &deferred_event, NULL); 10604 } 10605 10606 struct perf_text_poke_event { 10607 const void *old_bytes; 10608 const void *new_bytes; 10609 u16 tot; 10610 u16 pad; 10611 u16 old_len; 10612 u16 new_len; 10613 10614 struct { 10615 struct perf_event_header header; 10616 10617 u64 addr; 10618 } event_id; 10619 }; 10620 10621 static int perf_event_text_poke_match(struct perf_event *event) 10622 { 10623 return event->attr.text_poke; 10624 } 10625 10626 static void perf_event_text_poke_output(struct perf_event *event, void *data) 10627 { 10628 struct perf_text_poke_event *text_poke_event = data; 10629 struct perf_output_handle handle; 10630 struct perf_sample_data sample; 10631 u16 size = sizeof(text_poke_event->event_id) + text_poke_event->tot + text_poke_event->pad; 10632 u64 padding = 0; 10633 int ret; 10634 10635 if (!perf_event_text_poke_match(event)) 10636 return; 10637 10638 perf_event_header__init(&text_poke_event->event_id.header, &sample, 10639 PERF_RECORD_TEXT_POKE, 10640 PERF_RECORD_MISC_KERNEL, 10641 size, 10642 event); 10643 10644 ret = perf_output_begin(&handle, &sample, event, 10645 text_poke_event->event_id.header.size); 10646 if (ret) 10647 return; 10648 10649 perf_output_put(&handle, text_poke_event->event_id); 10650 perf_output_put(&handle, text_poke_event->old_len); 10651 perf_output_put(&handle, text_poke_event->new_len); 10652 10653 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len); 10654 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len); 10655 10656 if (text_poke_event->pad) 10657 __output_copy(&handle, &padding, text_poke_event->pad); 10658 10659 perf_event__output_id_sample(event, &handle, &sample); 10660 10661 perf_output_end(&handle); 10662 } 10663 10664 void perf_event_text_poke(const void *addr, const void *old_bytes, 10665 size_t old_len, const void *new_bytes, size_t new_len) 10666 { 10667 struct perf_text_poke_event text_poke_event; 10668 size_t tot, pad; 10669 10670 if (!atomic_read(&nr_text_poke_events)) 10671 return; 10672 10673 tot = sizeof(text_poke_event.old_len) + old_len; 10674 tot += sizeof(text_poke_event.new_len) + new_len; 10675 pad = ALIGN(tot, sizeof(u64)) - tot; 10676 10677 text_poke_event = (struct perf_text_poke_event){ 10678 .old_bytes = old_bytes, 10679 .new_bytes = new_bytes, 10680 .tot = tot, 10681 .pad = pad, 10682 .old_len = old_len, 10683 .new_len = new_len, 10684 .event_id = { 10685 .addr = (unsigned long)addr, 10686 }, 10687 }; 10688 10689 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL); 10690 } 10691 10692 void perf_event_itrace_started(struct perf_event *event) 10693 { 10694 WRITE_ONCE(event->attach_state, event->attach_state | PERF_ATTACH_ITRACE); 10695 } 10696 EXPORT_SYMBOL_GPL(perf_event_itrace_started); 10697 10698 static void perf_log_itrace_start(struct perf_event *event) 10699 { 10700 struct perf_output_handle handle; 10701 struct perf_sample_data sample; 10702 struct perf_aux_event { 10703 struct perf_event_header header; 10704 u32 pid; 10705 u32 tid; 10706 } rec; 10707 int ret; 10708 10709 if (event->parent) 10710 event = event->parent; 10711 10712 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) || 10713 event->attach_state & PERF_ATTACH_ITRACE) 10714 return; 10715 10716 rec.pid = perf_event_pid(event, current); 10717 rec.tid = perf_event_tid(event, current); 10718 10719 perf_event_header__init(&rec.header, &sample, 10720 PERF_RECORD_ITRACE_START, /* misc= */ 0, sizeof(rec), 10721 event); 10722 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10723 10724 if (ret) 10725 return; 10726 10727 perf_output_put(&handle, rec); 10728 perf_event__output_id_sample(event, &handle, &sample); 10729 10730 perf_output_end(&handle); 10731 } 10732 10733 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id) 10734 { 10735 struct perf_output_handle handle; 10736 struct perf_sample_data sample; 10737 struct perf_aux_event { 10738 struct perf_event_header header; 10739 u64 hw_id; 10740 } rec; 10741 int ret; 10742 10743 if (event->parent) 10744 event = event->parent; 10745 10746 rec.hw_id = hw_id; 10747 perf_event_header__init(&rec.header, &sample, 10748 PERF_RECORD_AUX_OUTPUT_HW_ID, /* misc= */ 0, 10749 sizeof(rec), event); 10750 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10751 10752 if (ret) 10753 return; 10754 10755 perf_output_put(&handle, rec); 10756 perf_event__output_id_sample(event, &handle, &sample); 10757 10758 perf_output_end(&handle); 10759 } 10760 EXPORT_SYMBOL_GPL(perf_report_aux_output_id); 10761 10762 /* 10763 * @period is the period of the interval that just ended. PMU drivers 10764 * re-arm the counter before calling perf_event_overflow(), which sets 10765 * hwc->last_period to the period of the next interval, so the overflow 10766 * path passes the sample's period instead. 10767 */ 10768 static int 10769 __perf_event_account_interrupt(struct perf_event *event, int throttle, 10770 u64 period) 10771 { 10772 struct hw_perf_event *hwc = &event->hw; 10773 int ret = 0; 10774 u64 seq; 10775 10776 seq = __this_cpu_read(perf_throttled_seq); 10777 if (seq != hwc->interrupts_seq) { 10778 hwc->interrupts_seq = seq; 10779 hwc->interrupts = 1; 10780 } else { 10781 hwc->interrupts++; 10782 } 10783 10784 if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) { 10785 __this_cpu_inc(perf_throttled_count); 10786 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 10787 perf_event_throttle_group(event); 10788 ret = 1; 10789 } 10790 10791 if (event->attr.freq) { 10792 u64 now = perf_clock(); 10793 s64 delta = now - hwc->freq_time_stamp; 10794 10795 hwc->freq_time_stamp = now; 10796 10797 if (delta > 0 && delta < 2*TICK_NSEC) 10798 perf_adjust_period(event, delta, period, true); 10799 } 10800 10801 return ret; 10802 } 10803 10804 int perf_event_account_interrupt(struct perf_event *event) 10805 { 10806 return __perf_event_account_interrupt(event, 1, event->hw.last_period); 10807 } 10808 10809 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs) 10810 { 10811 /* 10812 * Due to interrupt latency (AKA "skid"), we may enter the 10813 * kernel before taking an overflow, even if the PMU is only 10814 * counting user events. 10815 */ 10816 if (event->attr.exclude_kernel && !user_mode(regs)) 10817 return false; 10818 10819 return true; 10820 } 10821 10822 #ifdef CONFIG_BPF_SYSCALL 10823 static int bpf_overflow_handler(struct perf_event *event, 10824 struct perf_sample_data *data, 10825 struct pt_regs *regs) 10826 { 10827 struct bpf_perf_event_data_kern ctx = { 10828 .data = data, 10829 .event = event, 10830 }; 10831 struct bpf_prog *prog; 10832 int ret = 0; 10833 10834 ctx.regs = perf_arch_bpf_user_pt_regs(regs); 10835 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) 10836 goto out; 10837 rcu_read_lock(); 10838 prog = READ_ONCE(event->prog); 10839 if (prog) { 10840 perf_prepare_sample(data, event, regs); 10841 /* bpf_perf_event_data::addr is readable without PERF_SAMPLE_ADDR */ 10842 if (!(data->sample_flags & PERF_SAMPLE_ADDR)) 10843 data->addr = 0; 10844 ret = bpf_prog_run(prog, &ctx); 10845 } 10846 rcu_read_unlock(); 10847 out: 10848 __this_cpu_dec(bpf_prog_active); 10849 10850 return ret; 10851 } 10852 10853 static inline int perf_event_set_bpf_handler(struct perf_event *event, 10854 struct bpf_prog *prog, 10855 u64 bpf_cookie) 10856 { 10857 if (event->overflow_handler_context) 10858 /* hw breakpoint or kernel counter */ 10859 return -EINVAL; 10860 10861 if (event->prog) 10862 return -EEXIST; 10863 10864 if (prog->type != BPF_PROG_TYPE_PERF_EVENT) 10865 return -EINVAL; 10866 10867 if (event->attr.precise_ip && 10868 prog->call_get_stack && 10869 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) || 10870 event->attr.exclude_callchain_kernel || 10871 event->attr.exclude_callchain_user)) { 10872 /* 10873 * On perf_event with precise_ip, calling bpf_get_stack() 10874 * may trigger unwinder warnings and occasional crashes. 10875 * bpf_get_[stack|stackid] works around this issue by using 10876 * callchain attached to perf_sample_data. If the 10877 * perf_event does not full (kernel and user) callchain 10878 * attached to perf_sample_data, do not allow attaching BPF 10879 * program that calls bpf_get_[stack|stackid]. 10880 */ 10881 return -EPROTO; 10882 } 10883 10884 event->prog = prog; 10885 event->bpf_cookie = bpf_cookie; 10886 return 0; 10887 } 10888 10889 static inline void perf_event_free_bpf_handler(struct perf_event *event) 10890 { 10891 struct bpf_prog *prog = event->prog; 10892 10893 if (!prog) 10894 return; 10895 10896 event->prog = NULL; 10897 bpf_prog_put(prog); 10898 } 10899 #else 10900 static inline int bpf_overflow_handler(struct perf_event *event, 10901 struct perf_sample_data *data, 10902 struct pt_regs *regs) 10903 { 10904 return 1; 10905 } 10906 10907 static inline int perf_event_set_bpf_handler(struct perf_event *event, 10908 struct bpf_prog *prog, 10909 u64 bpf_cookie) 10910 { 10911 return -EOPNOTSUPP; 10912 } 10913 10914 static inline void perf_event_free_bpf_handler(struct perf_event *event) 10915 { 10916 } 10917 #endif 10918 10919 /* 10920 * Generic event overflow handling, sampling. 10921 */ 10922 10923 static int __perf_event_overflow(struct perf_event *event, 10924 int throttle, struct perf_sample_data *data, 10925 struct pt_regs *regs) 10926 { 10927 int events = atomic_read(&event->event_limit); 10928 int ret = 0; 10929 10930 /* 10931 * Non-sampling counters might still use the PMI to fold short 10932 * hardware counters, ignore those. 10933 */ 10934 if (unlikely(!is_sampling_event(event))) 10935 return 0; 10936 10937 ret = __perf_event_account_interrupt(event, throttle, data->period); 10938 10939 if (event->attr.aux_pause) 10940 perf_event_aux_pause(event->aux_event, true); 10941 10942 if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT && 10943 !bpf_overflow_handler(event, data, regs)) 10944 goto out; 10945 10946 /* 10947 * XXX event_limit might not quite work as expected on inherited 10948 * events 10949 */ 10950 10951 event->pending_kill = POLL_IN; 10952 if (events && atomic_dec_and_test(&event->event_limit)) { 10953 ret = 1; 10954 event->pending_kill = POLL_HUP; 10955 perf_event_disable_inatomic(event); 10956 event->pmu->stop(event, 0); 10957 } 10958 10959 if (event->attr.sigtrap) { 10960 /* 10961 * The desired behaviour of sigtrap vs invalid samples is a bit 10962 * tricky; on the one hand, one should not loose the SIGTRAP if 10963 * it is the first event, on the other hand, we should also not 10964 * trigger the WARN or override the data address. 10965 */ 10966 bool valid_sample = sample_is_allowed(event, regs); 10967 unsigned int pending_id = 1; 10968 enum task_work_notify_mode notify_mode; 10969 10970 if (regs) 10971 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1; 10972 10973 notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME; 10974 10975 /* 10976 * Software events can nest and attempt this recursively; 10977 * claim the pending_work before task_work_add() recurses. 10978 */ 10979 if (cmpxchg_local(&event->pending_work, 0, 1) == 0) { 10980 if (!task_work_add(event->ctx->task, &event->pending_task, notify_mode)) { 10981 event->pending_work = pending_id; 10982 local_inc(&event->ctx->nr_no_switch_fast); 10983 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount)); 10984 10985 event->pending_addr = 0; 10986 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR)) 10987 event->pending_addr = data->addr; 10988 } else { 10989 event->pending_work = 0; 10990 } 10991 } else if (event->attr.exclude_kernel && valid_sample) { 10992 /* 10993 * Should not be able to return to user space without 10994 * consuming pending_work; with exceptions: 10995 * 10996 * 1. Where !exclude_kernel, events can overflow again 10997 * in the kernel without returning to user space. 10998 * 10999 * 2. Events that can overflow again before the IRQ- 11000 * work without user space progress (e.g. hrtimer). 11001 * To approximate progress (with false negatives), 11002 * check 32-bit hash of the current IP. 11003 */ 11004 WARN_ON_ONCE(event->pending_work != pending_id); 11005 } 11006 } 11007 11008 READ_ONCE(event->overflow_handler)(event, data, regs); 11009 11010 if (*perf_event_fasync(event) && event->pending_kill) { 11011 event->pending_wakeup = 1; 11012 irq_work_queue(&event->pending_irq); 11013 } 11014 out: 11015 if (event->attr.aux_resume) 11016 perf_event_aux_pause(event->aux_event, false); 11017 11018 return ret; 11019 } 11020 11021 int perf_event_overflow(struct perf_event *event, 11022 struct perf_sample_data *data, 11023 struct pt_regs *regs) 11024 { 11025 /* 11026 * Entry point from hardware PMI, interrupts should be disabled here. 11027 * This serializes us against perf_event_remove_from_context() in 11028 * things like perf_event_release_kernel(). 11029 */ 11030 lockdep_assert_irqs_disabled(); 11031 11032 return __perf_event_overflow(event, 1, data, regs); 11033 } 11034 11035 /* 11036 * Generic software event infrastructure 11037 */ 11038 11039 struct swevent_htable { 11040 struct swevent_hlist *swevent_hlist; 11041 struct mutex hlist_mutex; 11042 int hlist_refcount; 11043 }; 11044 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable); 11045 11046 /* 11047 * We directly increment event->count and keep a second value in 11048 * event->hw.period_left to count intervals. This period event 11049 * is kept in the range [-sample_period, 0] so that we can use the 11050 * sign as trigger. 11051 */ 11052 11053 u64 perf_swevent_set_period(struct perf_event *event) 11054 { 11055 struct hw_perf_event *hwc = &event->hw; 11056 u64 period = hwc->last_period; 11057 u64 nr, offset; 11058 s64 old, val; 11059 11060 hwc->last_period = hwc->sample_period; 11061 11062 old = local64_read(&hwc->period_left); 11063 do { 11064 val = old; 11065 if (val < 0) 11066 return 0; 11067 11068 nr = div64_u64(period + val, period); 11069 offset = nr * period; 11070 val -= offset; 11071 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val)); 11072 11073 return nr; 11074 } 11075 11076 static void perf_swevent_overflow(struct perf_event *event, u64 overflow, 11077 struct perf_sample_data *data, 11078 struct pt_regs *regs) 11079 { 11080 struct hw_perf_event *hwc = &event->hw; 11081 int throttle = 0; 11082 11083 if (!overflow) 11084 overflow = perf_swevent_set_period(event); 11085 11086 if (hwc->interrupts == MAX_INTERRUPTS) 11087 return; 11088 11089 for (; overflow; overflow--) { 11090 if (__perf_event_overflow(event, throttle, 11091 data, regs)) { 11092 /* 11093 * We inhibit the overflow from happening when 11094 * hwc->interrupts == MAX_INTERRUPTS. 11095 */ 11096 break; 11097 } 11098 throttle = 1; 11099 } 11100 } 11101 11102 static void perf_swevent_event(struct perf_event *event, u64 nr, 11103 struct perf_sample_data *data, 11104 struct pt_regs *regs) 11105 { 11106 struct hw_perf_event *hwc = &event->hw; 11107 11108 /* 11109 * This is: 11110 * - software preempt 11111 * - tracepoint preempt 11112 * - tp_target_task irq (ctx->lock) 11113 * - uprobes preempt/irq 11114 * - kprobes preempt/irq 11115 * - hw_breakpoint irq 11116 * 11117 * Any of these are sufficient to hold off RCU and thus ensure @event 11118 * exists. 11119 */ 11120 lockdep_assert_preemption_disabled(); 11121 local64_add(nr, &event->count); 11122 11123 if (!regs) 11124 return; 11125 11126 if (!is_sampling_event(event)) 11127 return; 11128 11129 /* 11130 * Serialize against event_function_call() IPIs like normal overflow 11131 * event handling. Specifically, must not allow 11132 * perf_event_release_kernel() -> perf_remove_from_context() to make 11133 * progress and 'release' the event from under us. 11134 */ 11135 guard(irqsave)(); 11136 if (event->state != PERF_EVENT_STATE_ACTIVE) 11137 return; 11138 11139 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) { 11140 data->period = nr; 11141 return perf_swevent_overflow(event, 1, data, regs); 11142 } else 11143 data->period = event->hw.last_period; 11144 11145 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) 11146 return perf_swevent_overflow(event, 1, data, regs); 11147 11148 if (local64_add_negative(nr, &hwc->period_left)) 11149 return; 11150 11151 perf_swevent_overflow(event, 0, data, regs); 11152 } 11153 11154 int perf_exclude_event(struct perf_event *event, struct pt_regs *regs) 11155 { 11156 if (event->hw.state & PERF_HES_STOPPED) 11157 return 1; 11158 11159 if (regs) { 11160 if (event->attr.exclude_user && user_mode(regs)) 11161 return 1; 11162 11163 if (event->attr.exclude_kernel && !user_mode(regs)) 11164 return 1; 11165 } 11166 11167 return 0; 11168 } 11169 11170 static int perf_swevent_match(struct perf_event *event, 11171 enum perf_type_id type, 11172 u32 event_id, 11173 struct pt_regs *regs) 11174 { 11175 if (!perf_pmu_enabled(event->pmu)) 11176 return 0; 11177 11178 if (event->attr.type != type) 11179 return 0; 11180 11181 if (event->attr.config != event_id) 11182 return 0; 11183 11184 if (perf_exclude_event(event, regs)) 11185 return 0; 11186 11187 return 1; 11188 } 11189 11190 static inline u64 swevent_hash(u64 type, u32 event_id) 11191 { 11192 u64 val = event_id | (type << 32); 11193 11194 return hash_64(val, SWEVENT_HLIST_BITS); 11195 } 11196 11197 static inline struct hlist_head * 11198 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id) 11199 { 11200 u64 hash = swevent_hash(type, event_id); 11201 11202 return &hlist->heads[hash]; 11203 } 11204 11205 /* For the read side: events when they trigger */ 11206 static inline struct hlist_head * 11207 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id) 11208 { 11209 struct swevent_hlist *hlist; 11210 11211 hlist = rcu_dereference(swhash->swevent_hlist); 11212 if (!hlist) 11213 return NULL; 11214 11215 return __find_swevent_head(hlist, type, event_id); 11216 } 11217 11218 /* For the event head insertion and removal in the hlist */ 11219 static inline struct hlist_head * 11220 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) 11221 { 11222 struct swevent_hlist *hlist; 11223 u32 event_id = event->attr.config; 11224 u64 type = event->attr.type; 11225 11226 /* 11227 * Event scheduling is always serialized against hlist allocation 11228 * and release. Which makes the protected version suitable here. 11229 * The context lock guarantees that. 11230 */ 11231 hlist = rcu_dereference_protected(swhash->swevent_hlist, 11232 lockdep_is_held(&event->ctx->lock)); 11233 if (!hlist) 11234 return NULL; 11235 11236 return __find_swevent_head(hlist, type, event_id); 11237 } 11238 11239 static void do_perf_sw_event(enum perf_type_id type, u32 event_id, 11240 u64 nr, struct pt_regs *regs, u64 addr) 11241 { 11242 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 11243 struct perf_sample_data data; 11244 struct perf_event *event; 11245 struct hlist_head *head; 11246 11247 rcu_read_lock(); 11248 head = find_swevent_head_rcu(swhash, type, event_id); 11249 if (!head) 11250 goto end; 11251 11252 hlist_for_each_entry_rcu(event, head, hlist_entry) { 11253 if (perf_swevent_match(event, type, event_id, regs)) { 11254 perf_sample_data_init(&data, addr, 0); 11255 perf_swevent_event(event, nr, &data, regs); 11256 } 11257 } 11258 end: 11259 rcu_read_unlock(); 11260 } 11261 11262 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]); 11263 11264 int perf_swevent_get_recursion_context(void) 11265 { 11266 return get_recursion_context(current->perf_recursion); 11267 } 11268 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context); 11269 11270 void perf_swevent_put_recursion_context(int rctx) 11271 { 11272 put_recursion_context(current->perf_recursion, rctx); 11273 } 11274 11275 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 11276 { 11277 if (WARN_ON_ONCE(!regs)) 11278 return; 11279 11280 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, regs, addr); 11281 } 11282 11283 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 11284 { 11285 int rctx; 11286 11287 preempt_disable_notrace(); 11288 rctx = perf_swevent_get_recursion_context(); 11289 if (unlikely(rctx < 0)) 11290 goto fail; 11291 11292 ___perf_sw_event(event_id, nr, regs, addr); 11293 11294 perf_swevent_put_recursion_context(rctx); 11295 fail: 11296 preempt_enable_notrace(); 11297 } 11298 11299 static void perf_swevent_read(struct perf_event *event) 11300 { 11301 } 11302 11303 static int perf_swevent_add(struct perf_event *event, int flags) 11304 { 11305 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 11306 struct hw_perf_event *hwc = &event->hw; 11307 struct hlist_head *head; 11308 11309 if (is_sampling_event(event)) { 11310 hwc->last_period = hwc->sample_period; 11311 perf_swevent_set_period(event); 11312 } 11313 11314 hwc->state = !(flags & PERF_EF_START); 11315 11316 head = find_swevent_head(swhash, event); 11317 if (WARN_ON_ONCE(!head)) 11318 return -EINVAL; 11319 11320 hlist_add_head_rcu(&event->hlist_entry, head); 11321 perf_event_update_userpage(event); 11322 11323 return 0; 11324 } 11325 11326 static void perf_swevent_del(struct perf_event *event, int flags) 11327 { 11328 hlist_del_rcu(&event->hlist_entry); 11329 } 11330 11331 static void perf_swevent_start(struct perf_event *event, int flags) 11332 { 11333 event->hw.state = 0; 11334 } 11335 11336 static void perf_swevent_stop(struct perf_event *event, int flags) 11337 { 11338 event->hw.state = PERF_HES_STOPPED; 11339 } 11340 11341 /* Deref the hlist from the update side */ 11342 static inline struct swevent_hlist * 11343 swevent_hlist_deref(struct swevent_htable *swhash) 11344 { 11345 return rcu_dereference_protected(swhash->swevent_hlist, 11346 lockdep_is_held(&swhash->hlist_mutex)); 11347 } 11348 11349 static void swevent_hlist_release(struct swevent_htable *swhash) 11350 { 11351 struct swevent_hlist *hlist = swevent_hlist_deref(swhash); 11352 11353 if (!hlist) 11354 return; 11355 11356 RCU_INIT_POINTER(swhash->swevent_hlist, NULL); 11357 kfree_rcu(hlist, rcu_head); 11358 } 11359 11360 static void swevent_hlist_put_cpu(int cpu) 11361 { 11362 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 11363 11364 mutex_lock(&swhash->hlist_mutex); 11365 11366 if (!--swhash->hlist_refcount) 11367 swevent_hlist_release(swhash); 11368 11369 mutex_unlock(&swhash->hlist_mutex); 11370 } 11371 11372 static void swevent_hlist_put(void) 11373 { 11374 int cpu; 11375 11376 for_each_possible_cpu(cpu) 11377 swevent_hlist_put_cpu(cpu); 11378 } 11379 11380 static int swevent_hlist_get_cpu(int cpu) 11381 { 11382 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 11383 int err = 0; 11384 11385 mutex_lock(&swhash->hlist_mutex); 11386 if (!swevent_hlist_deref(swhash) && 11387 cpumask_test_cpu(cpu, perf_online_mask)) { 11388 struct swevent_hlist *hlist; 11389 11390 hlist = kzalloc_obj(*hlist); 11391 if (!hlist) { 11392 err = -ENOMEM; 11393 goto exit; 11394 } 11395 rcu_assign_pointer(swhash->swevent_hlist, hlist); 11396 } 11397 swhash->hlist_refcount++; 11398 exit: 11399 mutex_unlock(&swhash->hlist_mutex); 11400 11401 return err; 11402 } 11403 11404 static int swevent_hlist_get(void) 11405 { 11406 int err, cpu, failed_cpu; 11407 11408 mutex_lock(&pmus_lock); 11409 for_each_possible_cpu(cpu) { 11410 err = swevent_hlist_get_cpu(cpu); 11411 if (err) { 11412 failed_cpu = cpu; 11413 goto fail; 11414 } 11415 } 11416 mutex_unlock(&pmus_lock); 11417 return 0; 11418 fail: 11419 for_each_possible_cpu(cpu) { 11420 if (cpu == failed_cpu) 11421 break; 11422 swevent_hlist_put_cpu(cpu); 11423 } 11424 mutex_unlock(&pmus_lock); 11425 return err; 11426 } 11427 11428 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX]; 11429 11430 static void sw_perf_event_destroy(struct perf_event *event) 11431 { 11432 u64 event_id = event->attr.config; 11433 11434 WARN_ON(event->parent); 11435 11436 static_key_slow_dec(&perf_swevent_enabled[event_id]); 11437 swevent_hlist_put(); 11438 } 11439 11440 static struct pmu perf_cpu_clock; /* fwd declaration */ 11441 static struct pmu perf_task_clock; 11442 11443 static int perf_swevent_init(struct perf_event *event) 11444 { 11445 u64 event_id = event->attr.config; 11446 11447 if (event->attr.type != PERF_TYPE_SOFTWARE) 11448 return -ENOENT; 11449 11450 /* 11451 * no branch sampling for software events 11452 */ 11453 if (has_branch_stack(event)) 11454 return -EOPNOTSUPP; 11455 11456 switch (event_id) { 11457 case PERF_COUNT_SW_CPU_CLOCK: 11458 event->attr.type = perf_cpu_clock.type; 11459 return -ENOENT; 11460 case PERF_COUNT_SW_TASK_CLOCK: 11461 event->attr.type = perf_task_clock.type; 11462 return -ENOENT; 11463 11464 default: 11465 break; 11466 } 11467 11468 if (event_id >= PERF_COUNT_SW_MAX) 11469 return -ENOENT; 11470 11471 if (!event->parent) { 11472 int err; 11473 11474 err = swevent_hlist_get(); 11475 if (err) 11476 return err; 11477 11478 static_key_slow_inc(&perf_swevent_enabled[event_id]); 11479 event->destroy = sw_perf_event_destroy; 11480 } 11481 11482 return 0; 11483 } 11484 11485 static struct pmu perf_swevent = { 11486 .task_ctx_nr = perf_sw_context, 11487 11488 .capabilities = PERF_PMU_CAP_NO_NMI, 11489 11490 .event_init = perf_swevent_init, 11491 .add = perf_swevent_add, 11492 .del = perf_swevent_del, 11493 .start = perf_swevent_start, 11494 .stop = perf_swevent_stop, 11495 .read = perf_swevent_read, 11496 }; 11497 11498 #ifdef CONFIG_EVENT_TRACING 11499 11500 static void tp_perf_event_destroy(struct perf_event *event) 11501 { 11502 perf_trace_destroy(event); 11503 } 11504 11505 static int perf_tp_event_init(struct perf_event *event) 11506 { 11507 int err; 11508 11509 if (event->attr.type != PERF_TYPE_TRACEPOINT) 11510 return -ENOENT; 11511 11512 /* 11513 * no branch sampling for tracepoint events 11514 */ 11515 if (has_branch_stack(event)) 11516 return -EOPNOTSUPP; 11517 11518 err = perf_trace_init(event); 11519 if (err) 11520 return err; 11521 11522 event->destroy = tp_perf_event_destroy; 11523 11524 return 0; 11525 } 11526 11527 static struct pmu perf_tracepoint = { 11528 .task_ctx_nr = perf_sw_context, 11529 11530 .event_init = perf_tp_event_init, 11531 .add = perf_trace_add, 11532 .del = perf_trace_del, 11533 .start = perf_swevent_start, 11534 .stop = perf_swevent_stop, 11535 .read = perf_swevent_read, 11536 }; 11537 11538 static int perf_tp_filter_match(struct perf_event *event, 11539 struct perf_raw_record *raw) 11540 { 11541 void *record = raw->frag.data; 11542 11543 /* only top level events have filters set */ 11544 if (event->parent) 11545 event = event->parent; 11546 11547 if (likely(!event->filter) || filter_match_preds(event->filter, record)) 11548 return 1; 11549 return 0; 11550 } 11551 11552 static int perf_tp_event_match(struct perf_event *event, 11553 struct perf_raw_record *raw, 11554 struct pt_regs *regs) 11555 { 11556 if (!perf_pmu_enabled(event->pmu)) 11557 return 0; 11558 11559 if (event->hw.state & PERF_HES_STOPPED) 11560 return 0; 11561 /* 11562 * If exclude_kernel, only trace user-space tracepoints (uprobes) 11563 */ 11564 if (event->attr.exclude_kernel && !user_mode(regs)) 11565 return 0; 11566 11567 if (!perf_tp_filter_match(event, raw)) 11568 return 0; 11569 11570 return 1; 11571 } 11572 11573 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx, 11574 struct trace_event_call *call, u64 count, 11575 struct pt_regs *regs, struct hlist_head *head, 11576 struct task_struct *task) 11577 { 11578 if (bpf_prog_array_valid(call)) { 11579 *(struct pt_regs **)raw_data = regs; 11580 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) { 11581 perf_swevent_put_recursion_context(rctx); 11582 return; 11583 } 11584 } 11585 perf_tp_event(call->event.type, count, raw_data, size, regs, head, 11586 rctx, task); 11587 } 11588 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit); 11589 11590 static void __perf_tp_event_target_task(u64 count, void *record, 11591 struct pt_regs *regs, 11592 struct perf_sample_data *data, 11593 struct perf_raw_record *raw, 11594 struct perf_event *event) 11595 { 11596 struct trace_entry *entry = record; 11597 11598 if (event->attr.config != entry->type) 11599 return; 11600 /* Cannot deliver synchronous signal to other task. */ 11601 if (event->attr.sigtrap) 11602 return; 11603 if (perf_tp_event_match(event, raw, regs)) { 11604 perf_sample_data_init(data, 0, 0); 11605 perf_sample_save_raw_data(data, event, raw); 11606 perf_swevent_event(event, count, data, regs); 11607 } 11608 } 11609 11610 static void perf_tp_event_target_task(u64 count, void *record, 11611 struct pt_regs *regs, 11612 struct perf_sample_data *data, 11613 struct perf_raw_record *raw, 11614 struct perf_event_context *ctx) 11615 { 11616 unsigned int cpu = smp_processor_id(); 11617 struct pmu *pmu = &perf_tracepoint; 11618 struct perf_event *event, *sibling; 11619 11620 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) { 11621 __perf_tp_event_target_task(count, record, regs, data, raw, event); 11622 for_each_sibling_event(sibling, event) 11623 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 11624 } 11625 11626 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) { 11627 __perf_tp_event_target_task(count, record, regs, data, raw, event); 11628 for_each_sibling_event(sibling, event) 11629 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 11630 } 11631 } 11632 11633 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size, 11634 struct pt_regs *regs, struct hlist_head *head, int rctx, 11635 struct task_struct *task) 11636 { 11637 struct perf_sample_data data; 11638 struct perf_event *event; 11639 11640 /* 11641 * Per being a tracepoint, this runs with preemption disabled. 11642 */ 11643 lockdep_assert_preemption_disabled(); 11644 11645 struct perf_raw_record raw = { 11646 .frag = { 11647 .size = entry_size, 11648 .data = record, 11649 }, 11650 }; 11651 11652 perf_trace_buf_update(record, event_type); 11653 11654 hlist_for_each_entry_rcu(event, head, hlist_entry) { 11655 if (perf_tp_event_match(event, &raw, regs)) { 11656 /* 11657 * Here use the same on-stack perf_sample_data, 11658 * some members in data are event-specific and 11659 * need to be re-computed for different sweveents. 11660 * Re-initialize data->sample_flags safely to avoid 11661 * the problem that next event skips preparing data 11662 * because data->sample_flags is set. 11663 */ 11664 perf_sample_data_init(&data, 0, 0); 11665 perf_sample_save_raw_data(&data, event, &raw); 11666 perf_swevent_event(event, count, &data, regs); 11667 } 11668 } 11669 11670 /* 11671 * If we got specified a target task, also iterate its context and 11672 * deliver this event there too. 11673 */ 11674 if (task && task != current) { 11675 struct perf_event_context *ctx; 11676 11677 rcu_read_lock(); 11678 ctx = rcu_dereference(task->perf_event_ctxp); 11679 if (!ctx) 11680 goto unlock; 11681 11682 raw_spin_lock(&ctx->lock); 11683 perf_tp_event_target_task(count, record, regs, &data, &raw, ctx); 11684 raw_spin_unlock(&ctx->lock); 11685 unlock: 11686 rcu_read_unlock(); 11687 } 11688 11689 perf_swevent_put_recursion_context(rctx); 11690 } 11691 EXPORT_SYMBOL_GPL(perf_tp_event); 11692 11693 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS) 11694 /* 11695 * Flags in config, used by dynamic PMU kprobe and uprobe 11696 * The flags should match following PMU_FORMAT_ATTR(). 11697 * 11698 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe 11699 * if not set, create kprobe/uprobe 11700 * 11701 * The following values specify a reference counter (or semaphore in the 11702 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically 11703 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset. 11704 * 11705 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset 11706 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left 11707 */ 11708 enum perf_probe_config { 11709 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */ 11710 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32, 11711 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS, 11712 }; 11713 11714 PMU_FORMAT_ATTR(retprobe, "config:0"); 11715 #endif 11716 11717 #ifdef CONFIG_KPROBE_EVENTS 11718 static struct attribute *kprobe_attrs[] = { 11719 &format_attr_retprobe.attr, 11720 NULL, 11721 }; 11722 11723 static struct attribute_group kprobe_format_group = { 11724 .name = "format", 11725 .attrs = kprobe_attrs, 11726 }; 11727 11728 static const struct attribute_group *kprobe_attr_groups[] = { 11729 &kprobe_format_group, 11730 NULL, 11731 }; 11732 11733 static int perf_kprobe_event_init(struct perf_event *event); 11734 static struct pmu perf_kprobe = { 11735 .task_ctx_nr = perf_sw_context, 11736 .event_init = perf_kprobe_event_init, 11737 .add = perf_trace_add, 11738 .del = perf_trace_del, 11739 .start = perf_swevent_start, 11740 .stop = perf_swevent_stop, 11741 .read = perf_swevent_read, 11742 .attr_groups = kprobe_attr_groups, 11743 }; 11744 11745 static int perf_kprobe_event_init(struct perf_event *event) 11746 { 11747 int err; 11748 bool is_retprobe; 11749 11750 if (event->attr.type != perf_kprobe.type) 11751 return -ENOENT; 11752 11753 if (!perfmon_capable()) 11754 return -EACCES; 11755 11756 /* 11757 * no branch sampling for probe events 11758 */ 11759 if (has_branch_stack(event)) 11760 return -EOPNOTSUPP; 11761 11762 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 11763 err = perf_kprobe_init(event, is_retprobe); 11764 if (err) 11765 return err; 11766 11767 event->destroy = perf_kprobe_destroy; 11768 11769 return 0; 11770 } 11771 #endif /* CONFIG_KPROBE_EVENTS */ 11772 11773 #ifdef CONFIG_UPROBE_EVENTS 11774 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63"); 11775 11776 static struct attribute *uprobe_attrs[] = { 11777 &format_attr_retprobe.attr, 11778 &format_attr_ref_ctr_offset.attr, 11779 NULL, 11780 }; 11781 11782 static struct attribute_group uprobe_format_group = { 11783 .name = "format", 11784 .attrs = uprobe_attrs, 11785 }; 11786 11787 static const struct attribute_group *uprobe_attr_groups[] = { 11788 &uprobe_format_group, 11789 NULL, 11790 }; 11791 11792 static int perf_uprobe_event_init(struct perf_event *event); 11793 static struct pmu perf_uprobe = { 11794 .task_ctx_nr = perf_sw_context, 11795 .event_init = perf_uprobe_event_init, 11796 .add = perf_trace_add, 11797 .del = perf_trace_del, 11798 .start = perf_swevent_start, 11799 .stop = perf_swevent_stop, 11800 .read = perf_swevent_read, 11801 .attr_groups = uprobe_attr_groups, 11802 }; 11803 11804 static int perf_uprobe_event_init(struct perf_event *event) 11805 { 11806 int err; 11807 unsigned long ref_ctr_offset; 11808 bool is_retprobe; 11809 11810 if (event->attr.type != perf_uprobe.type) 11811 return -ENOENT; 11812 11813 if (!capable(CAP_SYS_ADMIN)) 11814 return -EACCES; 11815 11816 /* 11817 * no branch sampling for probe events 11818 */ 11819 if (has_branch_stack(event)) 11820 return -EOPNOTSUPP; 11821 11822 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 11823 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT; 11824 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe); 11825 if (err) 11826 return err; 11827 11828 event->destroy = perf_uprobe_destroy; 11829 11830 return 0; 11831 } 11832 #endif /* CONFIG_UPROBE_EVENTS */ 11833 11834 static inline void perf_tp_register(void) 11835 { 11836 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT); 11837 #ifdef CONFIG_KPROBE_EVENTS 11838 perf_pmu_register(&perf_kprobe, "kprobe", -1); 11839 #endif 11840 #ifdef CONFIG_UPROBE_EVENTS 11841 perf_pmu_register(&perf_uprobe, "uprobe", -1); 11842 #endif 11843 } 11844 11845 static void perf_event_free_filter(struct perf_event *event) 11846 { 11847 ftrace_profile_free_filter(event); 11848 } 11849 11850 /* 11851 * returns true if the event is a tracepoint, or a kprobe/upprobe created 11852 * with perf_event_open() 11853 */ 11854 static inline bool perf_event_is_tracing(struct perf_event *event) 11855 { 11856 if (event->pmu == &perf_tracepoint) 11857 return true; 11858 #ifdef CONFIG_KPROBE_EVENTS 11859 if (event->pmu == &perf_kprobe) 11860 return true; 11861 #endif 11862 #ifdef CONFIG_UPROBE_EVENTS 11863 if (event->pmu == &perf_uprobe) 11864 return true; 11865 #endif 11866 return false; 11867 } 11868 11869 static int __perf_event_set_bpf_prog(struct perf_event *event, 11870 struct bpf_prog *prog, 11871 u64 bpf_cookie) 11872 { 11873 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp; 11874 11875 if (event->state <= PERF_EVENT_STATE_REVOKED) 11876 return -ENODEV; 11877 11878 if (!perf_event_is_tracing(event)) 11879 return perf_event_set_bpf_handler(event, prog, bpf_cookie); 11880 11881 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE; 11882 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE; 11883 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT; 11884 is_syscall_tp = is_syscall_trace_event(event->tp_event); 11885 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp) 11886 /* bpf programs can only be attached to u/kprobe or tracepoint */ 11887 return -EINVAL; 11888 11889 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) || 11890 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) || 11891 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) 11892 return -EINVAL; 11893 11894 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe) 11895 /* only uprobe programs are allowed to be sleepable */ 11896 return -EINVAL; 11897 11898 if (prog->type == BPF_PROG_TYPE_TRACEPOINT && prog->sleepable) { 11899 /* 11900 * Sleepable tracepoint programs can only attach to faultable 11901 * tracepoints. Currently only syscall tracepoints are faultable. 11902 */ 11903 if (!is_syscall_tp) 11904 return -EINVAL; 11905 } 11906 11907 /* Kprobe override only works for kprobes, not uprobes. */ 11908 if (prog->kprobe_override && !is_kprobe) 11909 return -EINVAL; 11910 11911 /* Writing to context allowed only for uprobes. */ 11912 if (prog->aux->kprobe_write_ctx && !is_uprobe) 11913 return -EINVAL; 11914 11915 if (is_tracepoint || is_syscall_tp) { 11916 int off = trace_event_get_offsets(event->tp_event); 11917 11918 if (prog->aux->max_ctx_offset > off) 11919 return -EACCES; 11920 } 11921 11922 return perf_event_attach_bpf_prog(event, prog, bpf_cookie); 11923 } 11924 11925 int perf_event_set_bpf_prog(struct perf_event *event, 11926 struct bpf_prog *prog, 11927 u64 bpf_cookie) 11928 { 11929 struct perf_event_context *ctx; 11930 int ret; 11931 11932 ctx = perf_event_ctx_lock(event); 11933 ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie); 11934 perf_event_ctx_unlock(event, ctx); 11935 11936 return ret; 11937 } 11938 11939 void perf_event_free_bpf_prog(struct perf_event *event) 11940 { 11941 if (!event->prog) 11942 return; 11943 11944 if (!perf_event_is_tracing(event)) { 11945 perf_event_free_bpf_handler(event); 11946 return; 11947 } 11948 perf_event_detach_bpf_prog(event); 11949 } 11950 11951 #else 11952 11953 static inline void perf_tp_register(void) 11954 { 11955 } 11956 11957 static void perf_event_free_filter(struct perf_event *event) 11958 { 11959 } 11960 11961 static int __perf_event_set_bpf_prog(struct perf_event *event, 11962 struct bpf_prog *prog, 11963 u64 bpf_cookie) 11964 { 11965 return -ENOENT; 11966 } 11967 11968 int perf_event_set_bpf_prog(struct perf_event *event, 11969 struct bpf_prog *prog, 11970 u64 bpf_cookie) 11971 { 11972 return -ENOENT; 11973 } 11974 11975 void perf_event_free_bpf_prog(struct perf_event *event) 11976 { 11977 } 11978 #endif /* CONFIG_EVENT_TRACING */ 11979 11980 #ifdef CONFIG_HAVE_HW_BREAKPOINT 11981 void perf_bp_event(struct perf_event *bp, void *data) 11982 { 11983 struct perf_sample_data sample; 11984 struct pt_regs *regs = data; 11985 11986 /* 11987 * Exception context, will have interrupts disabled. 11988 */ 11989 lockdep_assert_irqs_disabled(); 11990 11991 perf_sample_data_init(&sample, bp->attr.bp_addr, 0); 11992 11993 if (!bp->hw.state && !perf_exclude_event(bp, regs)) 11994 perf_swevent_event(bp, 1, &sample, regs); 11995 } 11996 #endif 11997 11998 /* 11999 * Allocate a new address filter 12000 */ 12001 static struct perf_addr_filter * 12002 perf_addr_filter_new(struct perf_event *event, struct list_head *filters) 12003 { 12004 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu); 12005 struct perf_addr_filter *filter; 12006 12007 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node); 12008 if (!filter) 12009 return NULL; 12010 12011 INIT_LIST_HEAD(&filter->entry); 12012 list_add_tail(&filter->entry, filters); 12013 12014 return filter; 12015 } 12016 12017 static void free_filters_list(struct list_head *filters) 12018 { 12019 struct perf_addr_filter *filter, *iter; 12020 12021 list_for_each_entry_safe(filter, iter, filters, entry) { 12022 path_put(&filter->path); 12023 list_del(&filter->entry); 12024 kfree(filter); 12025 } 12026 } 12027 12028 /* 12029 * Free existing address filters and optionally install new ones 12030 */ 12031 static void perf_addr_filters_splice(struct perf_event *event, 12032 struct list_head *head) 12033 { 12034 unsigned long flags; 12035 LIST_HEAD(list); 12036 12037 if (!has_addr_filter(event)) 12038 return; 12039 12040 /* don't bother with children, they don't have their own filters */ 12041 if (event->parent) 12042 return; 12043 12044 raw_spin_lock_irqsave(&event->addr_filters.lock, flags); 12045 12046 list_splice_init(&event->addr_filters.list, &list); 12047 if (head) 12048 list_splice(head, &event->addr_filters.list); 12049 12050 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags); 12051 12052 free_filters_list(&list); 12053 } 12054 12055 static void perf_free_addr_filters(struct perf_event *event) 12056 { 12057 /* 12058 * Used during free paths, there is no concurrency. 12059 */ 12060 if (list_empty(&event->addr_filters.list)) 12061 return; 12062 12063 perf_addr_filters_splice(event, NULL); 12064 } 12065 12066 /* 12067 * Scan through mm's vmas and see if one of them matches the 12068 * @filter; if so, adjust filter's address range. 12069 * Called with mm::mmap_lock down for reading. 12070 */ 12071 static void perf_addr_filter_apply(struct perf_addr_filter *filter, 12072 struct mm_struct *mm, 12073 struct perf_addr_filter_range *fr) 12074 { 12075 struct vm_area_struct *vma; 12076 VMA_ITERATOR(vmi, mm, 0); 12077 12078 for_each_vma(vmi, vma) { 12079 if (!vma->vm_file) 12080 continue; 12081 12082 if (perf_addr_filter_vma_adjust(filter, vma, fr)) 12083 return; 12084 } 12085 } 12086 12087 /* 12088 * Update event's address range filters based on the 12089 * task's existing mappings, if any. 12090 */ 12091 static void perf_event_addr_filters_apply(struct perf_event *event) 12092 { 12093 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 12094 struct task_struct *task = READ_ONCE(event->ctx->task); 12095 struct perf_addr_filter *filter; 12096 struct mm_struct *mm = NULL; 12097 unsigned int count = 0; 12098 unsigned long flags; 12099 12100 /* 12101 * We may observe TASK_TOMBSTONE, which means that the event tear-down 12102 * will stop on the parent's child_mutex that our caller is also holding 12103 */ 12104 if (task == TASK_TOMBSTONE) 12105 return; 12106 12107 if (ifh->nr_file_filters) { 12108 mm = get_task_mm(task); 12109 if (!mm) 12110 goto restart; 12111 12112 mmap_read_lock(mm); 12113 } 12114 12115 raw_spin_lock_irqsave(&ifh->lock, flags); 12116 list_for_each_entry(filter, &ifh->list, entry) { 12117 if (filter->path.dentry) { 12118 /* 12119 * Adjust base offset if the filter is associated to a 12120 * binary that needs to be mapped: 12121 */ 12122 event->addr_filter_ranges[count].start = 0; 12123 event->addr_filter_ranges[count].size = 0; 12124 12125 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]); 12126 } else { 12127 event->addr_filter_ranges[count].start = filter->offset; 12128 event->addr_filter_ranges[count].size = filter->size; 12129 } 12130 12131 count++; 12132 } 12133 12134 event->addr_filters_gen++; 12135 raw_spin_unlock_irqrestore(&ifh->lock, flags); 12136 12137 if (ifh->nr_file_filters) { 12138 mmap_read_unlock(mm); 12139 12140 mmput(mm); 12141 } 12142 12143 restart: 12144 perf_event_stop(event, 1); 12145 } 12146 12147 /* 12148 * Address range filtering: limiting the data to certain 12149 * instruction address ranges. Filters are ioctl()ed to us from 12150 * userspace as ascii strings. 12151 * 12152 * Filter string format: 12153 * 12154 * ACTION RANGE_SPEC 12155 * where ACTION is one of the 12156 * * "filter": limit the trace to this region 12157 * * "start": start tracing from this address 12158 * * "stop": stop tracing at this address/region; 12159 * RANGE_SPEC is 12160 * * for kernel addresses: <start address>[/<size>] 12161 * * for object files: <start address>[/<size>]@</path/to/object/file> 12162 * 12163 * if <size> is not specified or is zero, the range is treated as a single 12164 * address; not valid for ACTION=="filter". 12165 */ 12166 enum { 12167 IF_ACT_NONE = -1, 12168 IF_ACT_FILTER, 12169 IF_ACT_START, 12170 IF_ACT_STOP, 12171 IF_SRC_FILE, 12172 IF_SRC_KERNEL, 12173 IF_SRC_FILEADDR, 12174 IF_SRC_KERNELADDR, 12175 }; 12176 12177 enum { 12178 IF_STATE_ACTION = 0, 12179 IF_STATE_SOURCE, 12180 IF_STATE_END, 12181 }; 12182 12183 static const match_table_t if_tokens = { 12184 { IF_ACT_FILTER, "filter" }, 12185 { IF_ACT_START, "start" }, 12186 { IF_ACT_STOP, "stop" }, 12187 { IF_SRC_FILE, "%u/%u@%s" }, 12188 { IF_SRC_KERNEL, "%u/%u" }, 12189 { IF_SRC_FILEADDR, "%u@%s" }, 12190 { IF_SRC_KERNELADDR, "%u" }, 12191 { IF_ACT_NONE, NULL }, 12192 }; 12193 12194 /* 12195 * Address filter string parser 12196 */ 12197 static int 12198 perf_event_parse_addr_filter(struct perf_event *event, char *fstr, 12199 struct list_head *filters) 12200 { 12201 struct perf_addr_filter *filter = NULL; 12202 char *start, *orig, *filename = NULL; 12203 substring_t args[MAX_OPT_ARGS]; 12204 int state = IF_STATE_ACTION, token; 12205 unsigned int kernel = 0; 12206 int ret = -EINVAL; 12207 12208 orig = fstr = kstrdup(fstr, GFP_KERNEL); 12209 if (!fstr) 12210 return -ENOMEM; 12211 12212 while ((start = strsep(&fstr, " ,\n")) != NULL) { 12213 static const enum perf_addr_filter_action_t actions[] = { 12214 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER, 12215 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START, 12216 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP, 12217 }; 12218 ret = -EINVAL; 12219 12220 if (!*start) 12221 continue; 12222 12223 /* filter definition begins */ 12224 if (state == IF_STATE_ACTION) { 12225 filter = perf_addr_filter_new(event, filters); 12226 if (!filter) 12227 goto fail; 12228 } 12229 12230 token = match_token(start, if_tokens, args); 12231 switch (token) { 12232 case IF_ACT_FILTER: 12233 case IF_ACT_START: 12234 case IF_ACT_STOP: 12235 if (state != IF_STATE_ACTION) 12236 goto fail; 12237 12238 filter->action = actions[token]; 12239 state = IF_STATE_SOURCE; 12240 break; 12241 12242 case IF_SRC_KERNELADDR: 12243 case IF_SRC_KERNEL: 12244 kernel = 1; 12245 fallthrough; 12246 12247 case IF_SRC_FILEADDR: 12248 case IF_SRC_FILE: 12249 if (state != IF_STATE_SOURCE) 12250 goto fail; 12251 12252 *args[0].to = 0; 12253 ret = kstrtoul(args[0].from, 0, &filter->offset); 12254 if (ret) 12255 goto fail; 12256 12257 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) { 12258 *args[1].to = 0; 12259 ret = kstrtoul(args[1].from, 0, &filter->size); 12260 if (ret) 12261 goto fail; 12262 } 12263 12264 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) { 12265 int fpos = token == IF_SRC_FILE ? 2 : 1; 12266 12267 kfree(filename); 12268 filename = match_strdup(&args[fpos]); 12269 if (!filename) { 12270 ret = -ENOMEM; 12271 goto fail; 12272 } 12273 } 12274 12275 state = IF_STATE_END; 12276 break; 12277 12278 default: 12279 goto fail; 12280 } 12281 12282 /* 12283 * Filter definition is fully parsed, validate and install it. 12284 * Make sure that it doesn't contradict itself or the event's 12285 * attribute. 12286 */ 12287 if (state == IF_STATE_END) { 12288 ret = -EINVAL; 12289 12290 /* 12291 * ACTION "filter" must have a non-zero length region 12292 * specified. 12293 */ 12294 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER && 12295 !filter->size) 12296 goto fail; 12297 12298 if (!kernel) { 12299 if (!filename) 12300 goto fail; 12301 12302 /* 12303 * For now, we only support file-based filters 12304 * in per-task events; doing so for CPU-wide 12305 * events requires additional context switching 12306 * trickery, since same object code will be 12307 * mapped at different virtual addresses in 12308 * different processes. 12309 */ 12310 ret = -EOPNOTSUPP; 12311 if (!event->ctx->task) 12312 goto fail; 12313 12314 /* look up the path and grab its inode */ 12315 ret = kern_path(filename, LOOKUP_FOLLOW, 12316 &filter->path); 12317 if (ret) 12318 goto fail; 12319 12320 ret = -EINVAL; 12321 if (!filter->path.dentry || 12322 !S_ISREG(d_inode(filter->path.dentry) 12323 ->i_mode)) 12324 goto fail; 12325 12326 event->addr_filters.nr_file_filters++; 12327 } 12328 12329 /* ready to consume more filters */ 12330 kfree(filename); 12331 filename = NULL; 12332 state = IF_STATE_ACTION; 12333 filter = NULL; 12334 kernel = 0; 12335 } 12336 } 12337 12338 if (state != IF_STATE_ACTION) 12339 goto fail; 12340 12341 kfree(filename); 12342 kfree(orig); 12343 12344 return 0; 12345 12346 fail: 12347 kfree(filename); 12348 free_filters_list(filters); 12349 kfree(orig); 12350 12351 return ret; 12352 } 12353 12354 static int 12355 perf_event_set_addr_filter(struct perf_event *event, char *filter_str) 12356 { 12357 LIST_HEAD(filters); 12358 int ret; 12359 12360 /* 12361 * Since this is called in perf_ioctl() path, we're already holding 12362 * ctx::mutex. 12363 */ 12364 lockdep_assert_held(&event->ctx->mutex); 12365 12366 if (WARN_ON_ONCE(event->parent)) 12367 return -EINVAL; 12368 12369 ret = perf_event_parse_addr_filter(event, filter_str, &filters); 12370 if (ret) 12371 goto fail_clear_files; 12372 12373 ret = event->pmu->addr_filters_validate(&filters); 12374 if (ret) 12375 goto fail_free_filters; 12376 12377 /* remove existing filters, if any */ 12378 perf_addr_filters_splice(event, &filters); 12379 12380 /* install new filters */ 12381 perf_event_for_each_child(event, perf_event_addr_filters_apply); 12382 12383 return ret; 12384 12385 fail_free_filters: 12386 free_filters_list(&filters); 12387 12388 fail_clear_files: 12389 event->addr_filters.nr_file_filters = 0; 12390 12391 return ret; 12392 } 12393 12394 static int perf_event_set_filter(struct perf_event *event, void __user *arg) 12395 { 12396 int ret = -EINVAL; 12397 char *filter_str; 12398 12399 filter_str = strndup_user(arg, PAGE_SIZE); 12400 if (IS_ERR(filter_str)) 12401 return PTR_ERR(filter_str); 12402 12403 #ifdef CONFIG_EVENT_TRACING 12404 if (perf_event_is_tracing(event)) { 12405 struct perf_event_context *ctx = event->ctx; 12406 12407 /* 12408 * Beware, here be dragons!! 12409 * 12410 * the tracepoint muck will deadlock against ctx->mutex, but 12411 * the tracepoint stuff does not actually need it. So 12412 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we 12413 * already have a reference on ctx. 12414 * 12415 * This can result in event getting moved to a different ctx, 12416 * but that does not affect the tracepoint state. 12417 */ 12418 mutex_unlock(&ctx->mutex); 12419 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str); 12420 mutex_lock(&ctx->mutex); 12421 } else 12422 #endif 12423 if (has_addr_filter(event)) 12424 ret = perf_event_set_addr_filter(event, filter_str); 12425 12426 kfree(filter_str); 12427 return ret; 12428 } 12429 12430 /* 12431 * hrtimer based swevent callback 12432 */ 12433 12434 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer) 12435 { 12436 enum hrtimer_restart ret = HRTIMER_RESTART; 12437 struct perf_sample_data data; 12438 struct pt_regs *regs; 12439 struct perf_event *event; 12440 u64 period; 12441 12442 event = container_of(hrtimer, struct perf_event, hw.hrtimer); 12443 12444 if (event->state != PERF_EVENT_STATE_ACTIVE || 12445 event->hw.state & PERF_HES_STOPPED) 12446 return HRTIMER_NORESTART; 12447 12448 event->pmu->read(event); 12449 12450 perf_sample_data_init(&data, 0, event->hw.last_period); 12451 regs = get_irq_regs(); 12452 12453 if (regs && !perf_exclude_event(event, regs)) { 12454 if (!(event->attr.exclude_idle && is_idle_task(current))) 12455 if (perf_event_overflow(event, &data, regs)) 12456 ret = HRTIMER_NORESTART; 12457 } 12458 12459 period = max_t(u64, 10000, event->hw.sample_period); 12460 hrtimer_forward_now(hrtimer, ns_to_ktime(period)); 12461 12462 return ret; 12463 } 12464 12465 static void perf_swevent_start_hrtimer(struct perf_event *event) 12466 { 12467 struct hw_perf_event *hwc = &event->hw; 12468 s64 period; 12469 12470 if (!is_sampling_event(event)) 12471 return; 12472 12473 period = local64_read(&hwc->period_left); 12474 if (period) { 12475 if (period < 0) 12476 period = 10000; 12477 12478 local64_set(&hwc->period_left, 0); 12479 } else { 12480 period = max_t(u64, 10000, hwc->sample_period); 12481 } 12482 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period), 12483 HRTIMER_MODE_REL_PINNED_HARD); 12484 } 12485 12486 static void perf_swevent_cancel_hrtimer(struct perf_event *event) 12487 { 12488 struct hw_perf_event *hwc = &event->hw; 12489 12490 /* 12491 * Careful: this function can be triggered in the hrtimer handler, 12492 * for cpu-clock events, so hrtimer_cancel() would cause a 12493 * deadlock. 12494 * 12495 * So use hrtimer_try_to_cancel() to try to stop the hrtimer, 12496 * and the cpu-clock handler also sets the PERF_HES_STOPPED flag, 12497 * which guarantees that perf_swevent_hrtimer() will stop the 12498 * hrtimer once it sees the PERF_HES_STOPPED flag. 12499 */ 12500 if (is_sampling_event(event) && (hwc->interrupts != MAX_INTERRUPTS)) { 12501 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer); 12502 local64_set(&hwc->period_left, ktime_to_ns(remaining)); 12503 12504 hrtimer_try_to_cancel(&hwc->hrtimer); 12505 } 12506 } 12507 12508 static void perf_swevent_destroy_hrtimer(struct perf_event *event) 12509 { 12510 hrtimer_cancel(&event->hw.hrtimer); 12511 } 12512 12513 static void perf_swevent_init_hrtimer(struct perf_event *event) 12514 { 12515 struct hw_perf_event *hwc = &event->hw; 12516 12517 if (!is_sampling_event(event)) 12518 return; 12519 12520 hrtimer_setup(&hwc->hrtimer, perf_swevent_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD); 12521 event->destroy = perf_swevent_destroy_hrtimer; 12522 12523 /* 12524 * Since hrtimers have a fixed rate, we can do a static freq->period 12525 * mapping and avoid the whole period adjust feedback stuff. 12526 */ 12527 if (event->attr.freq) { 12528 long freq = event->attr.sample_freq; 12529 12530 event->attr.sample_period = NSEC_PER_SEC / freq; 12531 hwc->sample_period = event->attr.sample_period; 12532 local64_set(&hwc->period_left, hwc->sample_period); 12533 hwc->last_period = hwc->sample_period; 12534 event->attr.freq = 0; 12535 } 12536 } 12537 12538 /* 12539 * Software event: cpu wall time clock 12540 */ 12541 12542 static void cpu_clock_event_update(struct perf_event *event) 12543 { 12544 s64 prev; 12545 u64 now; 12546 12547 now = local_clock(); 12548 prev = local64_xchg(&event->hw.prev_count, now); 12549 local64_add(now - prev, &event->count); 12550 } 12551 12552 static void cpu_clock_event_start(struct perf_event *event, int flags) 12553 { 12554 event->hw.state = 0; 12555 local64_set(&event->hw.prev_count, local_clock()); 12556 perf_swevent_start_hrtimer(event); 12557 } 12558 12559 static void cpu_clock_event_stop(struct perf_event *event, int flags) 12560 { 12561 event->hw.state = PERF_HES_STOPPED; 12562 perf_swevent_cancel_hrtimer(event); 12563 if (flags & PERF_EF_UPDATE) 12564 cpu_clock_event_update(event); 12565 } 12566 12567 static int cpu_clock_event_add(struct perf_event *event, int flags) 12568 { 12569 if (flags & PERF_EF_START) 12570 cpu_clock_event_start(event, flags); 12571 perf_event_update_userpage(event); 12572 12573 return 0; 12574 } 12575 12576 static void cpu_clock_event_del(struct perf_event *event, int flags) 12577 { 12578 cpu_clock_event_stop(event, PERF_EF_UPDATE); 12579 } 12580 12581 static void cpu_clock_event_read(struct perf_event *event) 12582 { 12583 cpu_clock_event_update(event); 12584 } 12585 12586 static int cpu_clock_event_init(struct perf_event *event) 12587 { 12588 if (event->attr.type != perf_cpu_clock.type) 12589 return -ENOENT; 12590 12591 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK) 12592 return -ENOENT; 12593 12594 /* 12595 * no branch sampling for software events 12596 */ 12597 if (has_branch_stack(event)) 12598 return -EOPNOTSUPP; 12599 12600 perf_swevent_init_hrtimer(event); 12601 12602 return 0; 12603 } 12604 12605 static struct pmu perf_cpu_clock = { 12606 .task_ctx_nr = perf_sw_context, 12607 12608 .capabilities = PERF_PMU_CAP_NO_NMI, 12609 .dev = PMU_NULL_DEV, 12610 12611 .event_init = cpu_clock_event_init, 12612 .add = cpu_clock_event_add, 12613 .del = cpu_clock_event_del, 12614 .start = cpu_clock_event_start, 12615 .stop = cpu_clock_event_stop, 12616 .read = cpu_clock_event_read, 12617 }; 12618 12619 /* 12620 * Software event: task time clock 12621 */ 12622 12623 static void task_clock_event_update(struct perf_event *event, u64 now) 12624 { 12625 u64 prev; 12626 s64 delta; 12627 12628 prev = local64_xchg(&event->hw.prev_count, now); 12629 delta = now - prev; 12630 local64_add(delta, &event->count); 12631 } 12632 12633 static void task_clock_event_start(struct perf_event *event, int flags) 12634 { 12635 event->hw.state = 0; 12636 local64_set(&event->hw.prev_count, event->ctx->time.time); 12637 perf_swevent_start_hrtimer(event); 12638 } 12639 12640 static void task_clock_event_stop(struct perf_event *event, int flags) 12641 { 12642 event->hw.state = PERF_HES_STOPPED; 12643 perf_swevent_cancel_hrtimer(event); 12644 if (flags & PERF_EF_UPDATE) 12645 task_clock_event_update(event, event->ctx->time.time); 12646 } 12647 12648 static int task_clock_event_add(struct perf_event *event, int flags) 12649 { 12650 if (flags & PERF_EF_START) 12651 task_clock_event_start(event, flags); 12652 perf_event_update_userpage(event); 12653 12654 return 0; 12655 } 12656 12657 static void task_clock_event_del(struct perf_event *event, int flags) 12658 { 12659 task_clock_event_stop(event, PERF_EF_UPDATE); 12660 } 12661 12662 static void task_clock_event_read(struct perf_event *event) 12663 { 12664 u64 now = perf_clock(); 12665 u64 delta = now - event->ctx->time.stamp; 12666 u64 time = event->ctx->time.time + delta; 12667 12668 task_clock_event_update(event, time); 12669 } 12670 12671 static int task_clock_event_init(struct perf_event *event) 12672 { 12673 if (event->attr.type != perf_task_clock.type) 12674 return -ENOENT; 12675 12676 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK) 12677 return -ENOENT; 12678 12679 /* 12680 * no branch sampling for software events 12681 */ 12682 if (has_branch_stack(event)) 12683 return -EOPNOTSUPP; 12684 12685 perf_swevent_init_hrtimer(event); 12686 12687 return 0; 12688 } 12689 12690 static struct pmu perf_task_clock = { 12691 .task_ctx_nr = perf_sw_context, 12692 12693 .capabilities = PERF_PMU_CAP_NO_NMI, 12694 .dev = PMU_NULL_DEV, 12695 12696 .event_init = task_clock_event_init, 12697 .add = task_clock_event_add, 12698 .del = task_clock_event_del, 12699 .start = task_clock_event_start, 12700 .stop = task_clock_event_stop, 12701 .read = task_clock_event_read, 12702 }; 12703 12704 static void perf_pmu_nop_void(struct pmu *pmu) 12705 { 12706 } 12707 12708 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags) 12709 { 12710 } 12711 12712 static int perf_pmu_nop_int(struct pmu *pmu) 12713 { 12714 return 0; 12715 } 12716 12717 static int perf_event_nop_int(struct perf_event *event, u64 value) 12718 { 12719 return 0; 12720 } 12721 12722 static DEFINE_PER_CPU(unsigned int, nop_txn_flags); 12723 12724 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags) 12725 { 12726 __this_cpu_write(nop_txn_flags, flags); 12727 12728 if (flags & ~PERF_PMU_TXN_ADD) 12729 return; 12730 12731 perf_pmu_disable(pmu); 12732 } 12733 12734 static int perf_pmu_commit_txn(struct pmu *pmu) 12735 { 12736 unsigned int flags = __this_cpu_read(nop_txn_flags); 12737 12738 __this_cpu_write(nop_txn_flags, 0); 12739 12740 if (flags & ~PERF_PMU_TXN_ADD) 12741 return 0; 12742 12743 perf_pmu_enable(pmu); 12744 return 0; 12745 } 12746 12747 static void perf_pmu_cancel_txn(struct pmu *pmu) 12748 { 12749 unsigned int flags = __this_cpu_read(nop_txn_flags); 12750 12751 __this_cpu_write(nop_txn_flags, 0); 12752 12753 if (flags & ~PERF_PMU_TXN_ADD) 12754 return; 12755 12756 perf_pmu_enable(pmu); 12757 } 12758 12759 static int perf_event_idx_default(struct perf_event *event) 12760 { 12761 return 0; 12762 } 12763 12764 /* 12765 * Let userspace know that this PMU supports address range filtering: 12766 */ 12767 static ssize_t nr_addr_filters_show(struct device *dev, 12768 struct device_attribute *attr, 12769 char *page) 12770 { 12771 struct pmu *pmu = dev_get_drvdata(dev); 12772 12773 return sysfs_emit(page, "%d\n", pmu->nr_addr_filters); 12774 } 12775 DEVICE_ATTR_RO(nr_addr_filters); 12776 12777 static struct idr pmu_idr; 12778 12779 static ssize_t 12780 type_show(struct device *dev, struct device_attribute *attr, char *page) 12781 { 12782 struct pmu *pmu = dev_get_drvdata(dev); 12783 12784 return sysfs_emit(page, "%d\n", pmu->type); 12785 } 12786 static DEVICE_ATTR_RO(type); 12787 12788 static ssize_t 12789 perf_event_mux_interval_ms_show(struct device *dev, 12790 struct device_attribute *attr, 12791 char *page) 12792 { 12793 struct pmu *pmu = dev_get_drvdata(dev); 12794 12795 return sysfs_emit(page, "%d\n", pmu->hrtimer_interval_ms); 12796 } 12797 12798 static DEFINE_MUTEX(mux_interval_mutex); 12799 12800 static ssize_t 12801 perf_event_mux_interval_ms_store(struct device *dev, 12802 struct device_attribute *attr, 12803 const char *buf, size_t count) 12804 { 12805 struct pmu *pmu = dev_get_drvdata(dev); 12806 int timer, cpu, ret; 12807 12808 ret = kstrtoint(buf, 0, &timer); 12809 if (ret) 12810 return ret; 12811 12812 if (timer < 1) 12813 return -EINVAL; 12814 12815 /* same value, noting to do */ 12816 if (timer == pmu->hrtimer_interval_ms) 12817 return count; 12818 12819 mutex_lock(&mux_interval_mutex); 12820 pmu->hrtimer_interval_ms = timer; 12821 12822 /* update all cpuctx for this PMU */ 12823 cpus_read_lock(); 12824 for_each_online_cpu(cpu) 12825 cpu_function_call(cpu, perf_mux_hrtimer_interval_ipi, pmu); 12826 cpus_read_unlock(); 12827 mutex_unlock(&mux_interval_mutex); 12828 12829 return count; 12830 } 12831 static DEVICE_ATTR_RW(perf_event_mux_interval_ms); 12832 12833 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu) 12834 { 12835 switch (scope) { 12836 case PERF_PMU_SCOPE_CORE: 12837 return topology_sibling_cpumask(cpu); 12838 case PERF_PMU_SCOPE_DIE: 12839 return topology_die_cpumask(cpu); 12840 case PERF_PMU_SCOPE_CLUSTER: 12841 return topology_cluster_cpumask(cpu); 12842 case PERF_PMU_SCOPE_PKG: 12843 return topology_core_cpumask(cpu); 12844 case PERF_PMU_SCOPE_SYS_WIDE: 12845 return cpu_online_mask; 12846 } 12847 12848 return NULL; 12849 } 12850 12851 static inline struct cpumask *perf_scope_cpumask(unsigned int scope) 12852 { 12853 switch (scope) { 12854 case PERF_PMU_SCOPE_CORE: 12855 return perf_online_core_mask; 12856 case PERF_PMU_SCOPE_DIE: 12857 return perf_online_die_mask; 12858 case PERF_PMU_SCOPE_CLUSTER: 12859 return perf_online_cluster_mask; 12860 case PERF_PMU_SCOPE_PKG: 12861 return perf_online_pkg_mask; 12862 case PERF_PMU_SCOPE_SYS_WIDE: 12863 return perf_online_sys_mask; 12864 } 12865 12866 return NULL; 12867 } 12868 12869 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr, 12870 char *buf) 12871 { 12872 struct pmu *pmu = dev_get_drvdata(dev); 12873 struct cpumask *mask = perf_scope_cpumask(pmu->scope); 12874 12875 if (mask) 12876 return sysfs_emit(buf, "%*pbl\n", cpumask_pr_args(mask)); 12877 return 0; 12878 } 12879 12880 static DEVICE_ATTR_RO(cpumask); 12881 12882 static struct attribute *pmu_dev_attrs[] = { 12883 &dev_attr_type.attr, 12884 &dev_attr_perf_event_mux_interval_ms.attr, 12885 &dev_attr_nr_addr_filters.attr, 12886 &dev_attr_cpumask.attr, 12887 NULL, 12888 }; 12889 12890 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n) 12891 { 12892 struct device *dev = kobj_to_dev(kobj); 12893 struct pmu *pmu = dev_get_drvdata(dev); 12894 12895 if (n == 2 && !pmu->nr_addr_filters) 12896 return 0; 12897 12898 /* cpumask */ 12899 if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE) 12900 return 0; 12901 12902 return a->mode; 12903 } 12904 12905 static struct attribute_group pmu_dev_attr_group = { 12906 .is_visible = pmu_dev_is_visible, 12907 .attrs = pmu_dev_attrs, 12908 }; 12909 12910 static const struct attribute_group *pmu_dev_groups[] = { 12911 &pmu_dev_attr_group, 12912 NULL, 12913 }; 12914 12915 static int pmu_bus_running; 12916 static const struct bus_type pmu_bus = { 12917 .name = "event_source", 12918 .dev_groups = pmu_dev_groups, 12919 }; 12920 12921 static void pmu_dev_release(struct device *dev) 12922 { 12923 kfree(dev); 12924 } 12925 12926 static int pmu_dev_alloc(struct pmu *pmu) 12927 { 12928 int ret = -ENOMEM; 12929 12930 pmu->dev = kzalloc_obj(struct device); 12931 if (!pmu->dev) 12932 goto out; 12933 12934 pmu->dev->groups = pmu->attr_groups; 12935 device_initialize(pmu->dev); 12936 12937 dev_set_drvdata(pmu->dev, pmu); 12938 pmu->dev->bus = &pmu_bus; 12939 pmu->dev->parent = pmu->parent; 12940 pmu->dev->release = pmu_dev_release; 12941 12942 ret = dev_set_name(pmu->dev, "%s", pmu->name); 12943 if (ret) 12944 goto free_dev; 12945 12946 ret = device_add(pmu->dev); 12947 if (ret) 12948 goto free_dev; 12949 12950 if (pmu->attr_update) { 12951 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update); 12952 if (ret) 12953 goto del_dev; 12954 } 12955 12956 out: 12957 return ret; 12958 12959 del_dev: 12960 device_del(pmu->dev); 12961 12962 free_dev: 12963 put_device(pmu->dev); 12964 pmu->dev = NULL; 12965 goto out; 12966 } 12967 12968 static struct lock_class_key cpuctx_mutex; 12969 static struct lock_class_key cpuctx_lock; 12970 12971 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new) 12972 { 12973 void *tmp, *val = idr_find(idr, id); 12974 12975 if (val != old) 12976 return false; 12977 12978 tmp = idr_replace(idr, new, id); 12979 if (IS_ERR(tmp)) 12980 return false; 12981 12982 WARN_ON_ONCE(tmp != val); 12983 return true; 12984 } 12985 12986 static void perf_pmu_free(struct pmu *pmu) 12987 { 12988 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) { 12989 if (pmu->nr_addr_filters) 12990 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters); 12991 device_del(pmu->dev); 12992 put_device(pmu->dev); 12993 } 12994 12995 if (pmu->cpu_pmu_context) { 12996 int cpu; 12997 12998 for_each_possible_cpu(cpu) { 12999 struct perf_cpu_pmu_context *cpc; 13000 13001 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); 13002 hrtimer_cancel(&cpc->hrtimer); 13003 if (!cpc) 13004 continue; 13005 if (cpc->epc.embedded) { 13006 /* refcount managed */ 13007 put_pmu_ctx(&cpc->epc); 13008 continue; 13009 } 13010 kfree(cpc); 13011 } 13012 free_percpu(pmu->cpu_pmu_context); 13013 } 13014 } 13015 13016 DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T)) 13017 13018 int perf_pmu_register(struct pmu *_pmu, const char *name, int type) 13019 { 13020 int cpu, max = PERF_TYPE_MAX; 13021 13022 struct pmu *pmu __free(pmu_unregister) = _pmu; 13023 guard(mutex)(&pmus_lock); 13024 13025 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n")) 13026 return -EINVAL; 13027 13028 if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE, 13029 "Can not register a pmu with an invalid scope.\n")) 13030 return -EINVAL; 13031 13032 pmu->name = name; 13033 13034 if (type >= 0) 13035 max = type; 13036 13037 CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL); 13038 if (pmu_type.id < 0) 13039 return pmu_type.id; 13040 13041 WARN_ON(type >= 0 && pmu_type.id != type); 13042 13043 pmu->type = pmu_type.id; 13044 atomic_set(&pmu->exclusive_cnt, 0); 13045 13046 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *); 13047 if (!pmu->cpu_pmu_context) 13048 return -ENOMEM; 13049 13050 for_each_possible_cpu(cpu) { 13051 struct perf_cpu_pmu_context *cpc = 13052 kmalloc_node(sizeof(struct perf_cpu_pmu_context), 13053 GFP_KERNEL | __GFP_ZERO, 13054 cpu_to_node(cpu)); 13055 13056 if (!cpc) 13057 return -ENOMEM; 13058 13059 *per_cpu_ptr(pmu->cpu_pmu_context, cpu) = cpc; 13060 __perf_init_event_pmu_context(&cpc->epc, pmu); 13061 __perf_mux_hrtimer_init(cpc, cpu); 13062 } 13063 13064 if (pmu_bus_running && !pmu->dev) { 13065 int ret = pmu_dev_alloc(pmu); 13066 if (ret) 13067 return ret; 13068 } 13069 13070 if (!pmu->start_txn) { 13071 if (pmu->pmu_enable) { 13072 /* 13073 * If we have pmu_enable/pmu_disable calls, install 13074 * transaction stubs that use that to try and batch 13075 * hardware accesses. 13076 */ 13077 pmu->start_txn = perf_pmu_start_txn; 13078 pmu->commit_txn = perf_pmu_commit_txn; 13079 pmu->cancel_txn = perf_pmu_cancel_txn; 13080 } else { 13081 pmu->start_txn = perf_pmu_nop_txn; 13082 pmu->commit_txn = perf_pmu_nop_int; 13083 pmu->cancel_txn = perf_pmu_nop_void; 13084 } 13085 } 13086 13087 if (!pmu->pmu_enable) { 13088 pmu->pmu_enable = perf_pmu_nop_void; 13089 pmu->pmu_disable = perf_pmu_nop_void; 13090 } 13091 13092 if (!pmu->check_period) 13093 pmu->check_period = perf_event_nop_int; 13094 13095 if (!pmu->event_idx) 13096 pmu->event_idx = perf_event_idx_default; 13097 13098 INIT_LIST_HEAD(&pmu->events); 13099 spin_lock_init(&pmu->events_lock); 13100 13101 /* 13102 * Now that the PMU is complete, make it visible to perf_try_init_event(). 13103 */ 13104 if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu)) 13105 return -EINVAL; 13106 list_add_rcu(&pmu->entry, &pmus); 13107 13108 take_idr_id(pmu_type); 13109 _pmu = no_free_ptr(pmu); // let it rip 13110 return 0; 13111 } 13112 EXPORT_SYMBOL_GPL(perf_pmu_register); 13113 13114 static void __pmu_detach_event(struct pmu *pmu, struct perf_event *event, 13115 struct perf_event_context *ctx) 13116 { 13117 /* 13118 * De-schedule the event and mark it REVOKED. 13119 */ 13120 perf_event_exit_event(event, ctx, ctx->task, DETACH_REVOKE); 13121 13122 /* 13123 * All _free_event() bits that rely on event->pmu: 13124 * 13125 * Notably, perf_mmap() relies on the ordering here. 13126 */ 13127 scoped_guard (mutex, &event->mmap_mutex) { 13128 WARN_ON_ONCE(pmu->event_unmapped); 13129 /* 13130 * Mostly an empty lock sequence, such that perf_mmap(), which 13131 * relies on mmap_mutex, is sure to observe the state change. 13132 */ 13133 } 13134 13135 perf_event_free_bpf_prog(event); 13136 perf_free_addr_filters(event); 13137 13138 if (event->destroy) { 13139 event->destroy(event); 13140 event->destroy = NULL; 13141 } 13142 13143 if (event->pmu_ctx) { 13144 put_pmu_ctx(event->pmu_ctx); 13145 event->pmu_ctx = NULL; 13146 } 13147 13148 exclusive_event_destroy(event); 13149 module_put(pmu->module); 13150 13151 mediated_pmu_unaccount_event(event); 13152 event->pmu = NULL; /* force fault instead of UAF */ 13153 } 13154 13155 static void pmu_detach_event(struct pmu *pmu, struct perf_event *event) 13156 { 13157 struct perf_event_context *ctx; 13158 13159 ctx = perf_event_ctx_lock(event); 13160 __pmu_detach_event(pmu, event, ctx); 13161 perf_event_ctx_unlock(event, ctx); 13162 13163 scoped_guard (spinlock, &pmu->events_lock) 13164 list_del(&event->pmu_list); 13165 } 13166 13167 static struct perf_event *pmu_get_event(struct pmu *pmu) 13168 { 13169 struct perf_event *event; 13170 13171 guard(spinlock)(&pmu->events_lock); 13172 list_for_each_entry(event, &pmu->events, pmu_list) { 13173 if (atomic_long_inc_not_zero(&event->refcount)) 13174 return event; 13175 } 13176 13177 return NULL; 13178 } 13179 13180 static bool pmu_empty(struct pmu *pmu) 13181 { 13182 guard(spinlock)(&pmu->events_lock); 13183 return list_empty(&pmu->events); 13184 } 13185 13186 static void pmu_detach_events(struct pmu *pmu) 13187 { 13188 struct perf_event *event; 13189 13190 for (;;) { 13191 event = pmu_get_event(pmu); 13192 if (!event) 13193 break; 13194 13195 pmu_detach_event(pmu, event); 13196 put_event(event); 13197 } 13198 13199 /* 13200 * wait for pending _free_event()s 13201 */ 13202 wait_var_event(pmu, pmu_empty(pmu)); 13203 } 13204 13205 int perf_pmu_unregister(struct pmu *pmu) 13206 { 13207 scoped_guard (mutex, &pmus_lock) { 13208 if (!idr_cmpxchg(&pmu_idr, pmu->type, pmu, NULL)) 13209 return -EINVAL; 13210 13211 list_del_rcu(&pmu->entry); 13212 } 13213 13214 /* 13215 * We dereference the pmu list under both SRCU and regular RCU, so 13216 * synchronize against both of those. 13217 * 13218 * Notably, the entirety of event creation, from perf_init_event() 13219 * (which will now fail, because of the above) until 13220 * perf_install_in_context() should be under SRCU such that 13221 * this synchronizes against event creation. This avoids trying to 13222 * detach events that are not fully formed. 13223 */ 13224 synchronize_srcu(&pmus_srcu); 13225 synchronize_rcu(); 13226 13227 if (pmu->event_unmapped && !pmu_empty(pmu)) { 13228 /* 13229 * Can't force remove events when pmu::event_unmapped() 13230 * is used in perf_mmap_close(). 13231 */ 13232 guard(mutex)(&pmus_lock); 13233 idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu); 13234 list_add_rcu(&pmu->entry, &pmus); 13235 return -EBUSY; 13236 } 13237 13238 scoped_guard (mutex, &pmus_lock) 13239 idr_remove(&pmu_idr, pmu->type); 13240 13241 /* 13242 * PMU is removed from the pmus list, so no new events will 13243 * be created, now take care of the existing ones. 13244 */ 13245 pmu_detach_events(pmu); 13246 13247 /* 13248 * PMU is unused, make it go away. 13249 */ 13250 perf_pmu_free(pmu); 13251 return 0; 13252 } 13253 EXPORT_SYMBOL_GPL(perf_pmu_unregister); 13254 13255 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) 13256 { 13257 struct perf_event_context *ctx = NULL; 13258 int ret; 13259 13260 if (!try_module_get(pmu->module)) 13261 return -ENODEV; 13262 13263 /* 13264 * A number of pmu->event_init() methods iterate the sibling_list to, 13265 * for example, validate if the group fits on the PMU. Therefore, 13266 * if this is a sibling event, acquire the ctx->mutex to protect 13267 * the sibling_list. 13268 */ 13269 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) { 13270 /* 13271 * This ctx->mutex can nest when we're called through 13272 * inheritance. See the perf_event_ctx_lock_nested() comment. 13273 */ 13274 ctx = perf_event_ctx_lock_nested(event->group_leader, 13275 SINGLE_DEPTH_NESTING); 13276 BUG_ON(!ctx); 13277 } 13278 13279 event->pmu = pmu; 13280 ret = pmu->event_init(event); 13281 13282 if (ctx) 13283 perf_event_ctx_unlock(event->group_leader, ctx); 13284 13285 if (ret) 13286 goto err_pmu; 13287 13288 if (!(pmu->capabilities & PERF_PMU_CAP_SIMD_REGS) && 13289 event_has_simd_regs(event)) { 13290 ret = -EOPNOTSUPP; 13291 goto err_destroy; 13292 } 13293 13294 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) && 13295 event_has_extended_regs(event)) { 13296 ret = -EOPNOTSUPP; 13297 goto err_destroy; 13298 } 13299 13300 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE && 13301 event_has_any_exclude_flag(event)) { 13302 ret = -EINVAL; 13303 goto err_destroy; 13304 } 13305 13306 if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) { 13307 const struct cpumask *cpumask; 13308 struct cpumask *pmu_cpumask; 13309 int cpu; 13310 13311 cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu); 13312 pmu_cpumask = perf_scope_cpumask(pmu->scope); 13313 13314 ret = -ENODEV; 13315 if (!pmu_cpumask || !cpumask) 13316 goto err_destroy; 13317 13318 cpu = cpumask_any_and(pmu_cpumask, cpumask); 13319 if (cpu >= nr_cpu_ids) 13320 goto err_destroy; 13321 13322 event->event_caps |= PERF_EV_CAP_READ_SCOPE; 13323 } 13324 13325 return 0; 13326 13327 err_destroy: 13328 if (event->destroy) { 13329 event->destroy(event); 13330 event->destroy = NULL; 13331 } 13332 13333 err_pmu: 13334 event->pmu = NULL; 13335 module_put(pmu->module); 13336 return ret; 13337 } 13338 13339 static struct pmu *perf_init_event(struct perf_event *event) 13340 { 13341 bool extended_type = false; 13342 struct pmu *pmu; 13343 int type, ret; 13344 13345 guard(srcu)(&pmus_srcu); /* pmu idr/list access */ 13346 13347 /* 13348 * Save original type before calling pmu->event_init() since certain 13349 * pmus overwrites event->attr.type to forward event to another pmu. 13350 */ 13351 event->orig_type = event->attr.type; 13352 13353 /* Try parent's PMU first: */ 13354 if (event->parent && event->parent->pmu) { 13355 pmu = event->parent->pmu; 13356 ret = perf_try_init_event(pmu, event); 13357 if (!ret) 13358 return pmu; 13359 } 13360 13361 /* 13362 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE 13363 * are often aliases for PERF_TYPE_RAW. 13364 */ 13365 type = event->attr.type; 13366 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) { 13367 type = event->attr.config >> PERF_PMU_TYPE_SHIFT; 13368 if (!type) { 13369 type = PERF_TYPE_RAW; 13370 } else { 13371 extended_type = true; 13372 event->attr.config &= PERF_HW_EVENT_MASK; 13373 } 13374 } 13375 13376 again: 13377 scoped_guard (rcu) 13378 pmu = idr_find(&pmu_idr, type); 13379 if (pmu) { 13380 if (event->attr.type != type && type != PERF_TYPE_RAW && 13381 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE)) 13382 return ERR_PTR(-ENOENT); 13383 13384 ret = perf_try_init_event(pmu, event); 13385 if (ret == -ENOENT && event->attr.type != type && !extended_type) { 13386 type = event->attr.type; 13387 goto again; 13388 } 13389 13390 if (ret) 13391 return ERR_PTR(ret); 13392 13393 return pmu; 13394 } 13395 13396 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) { 13397 ret = perf_try_init_event(pmu, event); 13398 if (!ret) 13399 return pmu; 13400 13401 if (ret != -ENOENT) 13402 return ERR_PTR(ret); 13403 } 13404 13405 return ERR_PTR(-ENOENT); 13406 } 13407 13408 static void attach_sb_event(struct perf_event *event) 13409 { 13410 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 13411 13412 raw_spin_lock(&pel->lock); 13413 list_add_rcu(&event->sb_list, &pel->list); 13414 raw_spin_unlock(&pel->lock); 13415 } 13416 13417 /* 13418 * We keep a list of all !task (and therefore per-cpu) events 13419 * that need to receive side-band records. 13420 * 13421 * This avoids having to scan all the various PMU per-cpu contexts 13422 * looking for them. 13423 */ 13424 static void account_pmu_sb_event(struct perf_event *event) 13425 { 13426 if (is_sb_event(event)) 13427 attach_sb_event(event); 13428 } 13429 13430 /* Freq events need the tick to stay alive (see perf_event_task_tick). */ 13431 static void account_freq_event_nohz(void) 13432 { 13433 #ifdef CONFIG_NO_HZ_FULL 13434 /* Lock so we don't race with concurrent unaccount */ 13435 spin_lock(&nr_freq_lock); 13436 if (atomic_inc_return(&nr_freq_events) == 1) 13437 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS); 13438 spin_unlock(&nr_freq_lock); 13439 #endif 13440 } 13441 13442 static void account_freq_event(void) 13443 { 13444 if (tick_nohz_full_enabled()) 13445 account_freq_event_nohz(); 13446 else 13447 atomic_inc(&nr_freq_events); 13448 } 13449 13450 13451 static void account_event(struct perf_event *event) 13452 { 13453 bool inc = false; 13454 13455 if (event->parent) 13456 return; 13457 13458 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB)) 13459 inc = true; 13460 if (event->attr.mmap || event->attr.mmap_data) 13461 atomic_inc(&nr_mmap_events); 13462 if (event->attr.build_id) 13463 atomic_inc(&nr_build_id_events); 13464 if (event->attr.comm) 13465 atomic_inc(&nr_comm_events); 13466 if (event->attr.namespaces) 13467 atomic_inc(&nr_namespaces_events); 13468 if (event->attr.cgroup) 13469 atomic_inc(&nr_cgroup_events); 13470 if (event->attr.task) 13471 atomic_inc(&nr_task_events); 13472 if (event->attr.freq) 13473 account_freq_event(); 13474 if (event->attr.context_switch) { 13475 atomic_inc(&nr_switch_events); 13476 inc = true; 13477 } 13478 if (has_branch_stack(event)) 13479 inc = true; 13480 if (is_cgroup_event(event)) 13481 inc = true; 13482 if (event->attr.ksymbol) 13483 atomic_inc(&nr_ksymbol_events); 13484 if (event->attr.bpf_event) 13485 atomic_inc(&nr_bpf_events); 13486 if (event->attr.text_poke) 13487 atomic_inc(&nr_text_poke_events); 13488 13489 if (inc) { 13490 /* 13491 * We need the mutex here because static_branch_enable() 13492 * must complete *before* the perf_sched_count increment 13493 * becomes visible. 13494 */ 13495 if (atomic_inc_not_zero(&perf_sched_count)) 13496 goto enabled; 13497 13498 mutex_lock(&perf_sched_mutex); 13499 if (!atomic_read(&perf_sched_count)) { 13500 static_branch_enable(&perf_sched_events); 13501 /* 13502 * Guarantee that all CPUs observe they key change and 13503 * call the perf scheduling hooks before proceeding to 13504 * install events that need them. 13505 */ 13506 synchronize_rcu(); 13507 } 13508 /* 13509 * Now that we have waited for the sync_sched(), allow further 13510 * increments to by-pass the mutex. 13511 */ 13512 atomic_inc(&perf_sched_count); 13513 mutex_unlock(&perf_sched_mutex); 13514 } 13515 enabled: 13516 13517 account_pmu_sb_event(event); 13518 } 13519 13520 /* 13521 * Allocate and initialize an event structure 13522 */ 13523 static struct perf_event * 13524 perf_event_alloc(struct perf_event_attr *attr, int cpu, 13525 struct task_struct *task, 13526 struct perf_event *group_leader, 13527 struct perf_event *parent_event, 13528 perf_overflow_handler_t overflow_handler, 13529 void *context, int cgroup_fd) 13530 { 13531 struct pmu *pmu; 13532 struct hw_perf_event *hwc; 13533 long err = -EINVAL; 13534 int node; 13535 13536 if ((unsigned)cpu >= nr_cpu_ids) { 13537 if (!task || cpu != -1) 13538 return ERR_PTR(-EINVAL); 13539 } 13540 if (attr->sigtrap && !task) { 13541 /* Requires a task: avoid signalling random tasks. */ 13542 return ERR_PTR(-EINVAL); 13543 } 13544 13545 node = (cpu >= 0) ? cpu_to_node(cpu) : -1; 13546 struct perf_event *event __free(__free_event) = 13547 kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node); 13548 if (!event) 13549 return ERR_PTR(-ENOMEM); 13550 13551 /* 13552 * Single events are their own group leaders, with an 13553 * empty sibling list: 13554 */ 13555 if (!group_leader) 13556 group_leader = event; 13557 13558 mutex_init(&event->child_mutex); 13559 INIT_LIST_HEAD(&event->child_list); 13560 13561 INIT_LIST_HEAD(&event->event_entry); 13562 INIT_LIST_HEAD(&event->sibling_list); 13563 INIT_LIST_HEAD(&event->active_list); 13564 init_event_group(event); 13565 INIT_LIST_HEAD(&event->rb_entry); 13566 INIT_LIST_HEAD(&event->active_entry); 13567 INIT_LIST_HEAD(&event->addr_filters.list); 13568 INIT_HLIST_NODE(&event->hlist_entry); 13569 INIT_LIST_HEAD(&event->pmu_list); 13570 13571 13572 init_waitqueue_head(&event->waitq); 13573 init_irq_work(&event->pending_irq, perf_pending_irq); 13574 event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable); 13575 init_task_work(&event->pending_task, perf_pending_task); 13576 13577 mutex_init(&event->mmap_mutex); 13578 raw_spin_lock_init(&event->addr_filters.lock); 13579 13580 atomic_long_set(&event->refcount, 1); 13581 event->cpu = cpu; 13582 event->attr = *attr; 13583 event->group_leader = group_leader; 13584 event->pmu = NULL; 13585 event->oncpu = -1; 13586 13587 event->parent = parent_event; 13588 13589 event->ns = get_pid_ns(task_active_pid_ns(current)); 13590 event->id = atomic64_inc_return(&perf_event_id); 13591 13592 event->state = PERF_EVENT_STATE_INACTIVE; 13593 13594 if (parent_event) 13595 event->event_caps = parent_event->event_caps; 13596 13597 if (task) { 13598 event->attach_state = PERF_ATTACH_TASK; 13599 /* 13600 * XXX pmu::event_init needs to know what task to account to 13601 * and we cannot use the ctx information because we need the 13602 * pmu before we get a ctx. 13603 */ 13604 event->hw.target = get_task_struct(task); 13605 } 13606 13607 event->clock = &local_clock; 13608 if (parent_event) 13609 event->clock = parent_event->clock; 13610 13611 if (!overflow_handler && parent_event) { 13612 overflow_handler = parent_event->overflow_handler; 13613 context = parent_event->overflow_handler_context; 13614 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING) 13615 if (parent_event->prog) { 13616 struct bpf_prog *prog = parent_event->prog; 13617 13618 bpf_prog_inc(prog); 13619 event->prog = prog; 13620 } 13621 #endif 13622 } 13623 13624 if (overflow_handler) { 13625 event->overflow_handler = overflow_handler; 13626 event->overflow_handler_context = context; 13627 } else if (is_write_backward(event)){ 13628 event->overflow_handler = perf_event_output_backward; 13629 event->overflow_handler_context = NULL; 13630 } else { 13631 event->overflow_handler = perf_event_output_forward; 13632 event->overflow_handler_context = NULL; 13633 } 13634 13635 perf_event__state_init(event); 13636 13637 pmu = NULL; 13638 13639 hwc = &event->hw; 13640 hwc->sample_period = attr->sample_period; 13641 if (is_event_in_freq_mode(event)) 13642 hwc->sample_period = 1; 13643 hwc->last_period = hwc->sample_period; 13644 13645 local64_set(&hwc->period_left, hwc->sample_period); 13646 13647 /* 13648 * We do not support PERF_SAMPLE_READ on inherited events unless 13649 * PERF_SAMPLE_TID is also selected, which allows inherited events to 13650 * collect per-thread samples. 13651 * See perf_output_read(). 13652 */ 13653 if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID)) 13654 return ERR_PTR(-EINVAL); 13655 13656 if (!has_branch_stack(event)) 13657 event->attr.branch_sample_type = 0; 13658 13659 pmu = perf_init_event(event); 13660 if (IS_ERR(pmu)) 13661 return (void*)pmu; 13662 13663 /* 13664 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config(). 13665 * The attach should be right after the perf_init_event(). 13666 * Otherwise, the __free_event() would mistakenly detach the non-exist 13667 * perf_ctx_data because of the other errors between them. 13668 */ 13669 if (event->attach_state & PERF_ATTACH_TASK_DATA) { 13670 err = attach_perf_ctx_data(event); 13671 if (err) 13672 return ERR_PTR(err); 13673 } 13674 13675 /* 13676 * Disallow uncore-task events. Similarly, disallow uncore-cgroup 13677 * events (they don't make sense as the cgroup will be different 13678 * on other CPUs in the uncore mask). 13679 */ 13680 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) 13681 return ERR_PTR(-EINVAL); 13682 13683 if (event->attr.aux_output && 13684 (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) || 13685 event->attr.aux_pause || event->attr.aux_resume)) 13686 return ERR_PTR(-EOPNOTSUPP); 13687 13688 if (event->attr.aux_pause && event->attr.aux_resume) 13689 return ERR_PTR(-EINVAL); 13690 13691 if (event->attr.aux_start_paused) { 13692 if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) 13693 return ERR_PTR(-EOPNOTSUPP); 13694 event->hw.aux_paused = 1; 13695 } 13696 13697 if (cgroup_fd != -1) { 13698 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader); 13699 if (err) 13700 return ERR_PTR(err); 13701 } 13702 13703 err = exclusive_event_init(event); 13704 if (err) 13705 return ERR_PTR(err); 13706 13707 if (has_addr_filter(event)) { 13708 event->addr_filter_ranges = kzalloc_objs(struct perf_addr_filter_range, 13709 pmu->nr_addr_filters); 13710 if (!event->addr_filter_ranges) 13711 return ERR_PTR(-ENOMEM); 13712 13713 /* 13714 * Clone the parent's vma offsets: they are valid until exec() 13715 * even if the mm is not shared with the parent. 13716 */ 13717 if (event->parent) { 13718 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 13719 13720 raw_spin_lock_irq(&ifh->lock); 13721 memcpy(event->addr_filter_ranges, 13722 event->parent->addr_filter_ranges, 13723 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range)); 13724 raw_spin_unlock_irq(&ifh->lock); 13725 } 13726 13727 /* force hw sync on the address filters */ 13728 event->addr_filters_gen = 1; 13729 } 13730 13731 if (!event->parent) { 13732 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) { 13733 err = get_callchain_buffers(attr->sample_max_stack); 13734 if (err) 13735 return ERR_PTR(err); 13736 event->attach_state |= PERF_ATTACH_CALLCHAIN; 13737 } 13738 } 13739 13740 err = security_perf_event_alloc(event); 13741 if (err) 13742 return ERR_PTR(err); 13743 13744 err = mediated_pmu_account_event(event); 13745 if (err) 13746 return ERR_PTR(err); 13747 13748 /* symmetric to unaccount_event() in _free_event() */ 13749 account_event(event); 13750 13751 /* 13752 * Event creation should be under SRCU, see perf_pmu_unregister(). 13753 */ 13754 lockdep_assert_held(&pmus_srcu); 13755 scoped_guard (spinlock, &pmu->events_lock) 13756 list_add(&event->pmu_list, &pmu->events); 13757 13758 return_ptr(event); 13759 } 13760 13761 static int perf_copy_attr(struct perf_event_attr __user *uattr, 13762 struct perf_event_attr *attr) 13763 { 13764 u32 size; 13765 int ret; 13766 13767 /* Zero the full structure, so that a short copy will be nice. */ 13768 memset(attr, 0, sizeof(*attr)); 13769 13770 ret = get_user(size, &uattr->size); 13771 if (ret) 13772 return ret; 13773 13774 /* ABI compatibility quirk: */ 13775 if (!size) 13776 size = PERF_ATTR_SIZE_VER0; 13777 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE) 13778 goto err_size; 13779 13780 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size); 13781 if (ret) { 13782 if (ret == -E2BIG) 13783 goto err_size; 13784 return ret; 13785 } 13786 13787 attr->size = size; 13788 13789 if (attr->__reserved_1 || attr->__reserved_2 || 13790 attr->__reserved_3 || attr->__reserved_4) 13791 return -EINVAL; 13792 13793 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) 13794 return -EINVAL; 13795 13796 if (attr->read_format & ~(PERF_FORMAT_MAX-1)) 13797 return -EINVAL; 13798 13799 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) { 13800 u64 mask = attr->branch_sample_type; 13801 13802 /* only using defined bits */ 13803 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1)) 13804 return -EINVAL; 13805 13806 /* at least one branch bit must be set */ 13807 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL)) 13808 return -EINVAL; 13809 13810 /* propagate priv level, when not set for branch */ 13811 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) { 13812 13813 /* exclude_kernel checked on syscall entry */ 13814 if (!attr->exclude_kernel) 13815 mask |= PERF_SAMPLE_BRANCH_KERNEL; 13816 13817 if (!attr->exclude_user) 13818 mask |= PERF_SAMPLE_BRANCH_USER; 13819 13820 if (!attr->exclude_hv) 13821 mask |= PERF_SAMPLE_BRANCH_HV; 13822 /* 13823 * adjust user setting (for HW filter setup) 13824 */ 13825 attr->branch_sample_type = mask; 13826 } 13827 /* privileged levels capture (kernel, hv): check permissions */ 13828 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) { 13829 ret = perf_allow_kernel(); 13830 if (ret) 13831 return ret; 13832 } 13833 } 13834 13835 if (attr->sample_type & PERF_SAMPLE_REGS_USER) { 13836 ret = perf_reg_validate(attr->sample_regs_user, 13837 attr->sample_simd_regs_enabled); 13838 if (ret) 13839 return ret; 13840 if (attr->sample_simd_regs_enabled) { 13841 ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, 13842 attr->sample_simd_vec_reg_user, 13843 attr->sample_simd_pred_reg_qwords, 13844 attr->sample_simd_pred_reg_user); 13845 if (ret) 13846 return ret; 13847 } 13848 } 13849 13850 if (attr->sample_type & PERF_SAMPLE_STACK_USER) { 13851 if (!arch_perf_have_user_stack_dump()) 13852 return -ENOSYS; 13853 13854 /* 13855 * We have __u32 type for the size, but so far 13856 * we can only use __u16 as maximum due to the 13857 * __u16 sample size limit. 13858 */ 13859 if (attr->sample_stack_user >= USHRT_MAX) 13860 return -EINVAL; 13861 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64))) 13862 return -EINVAL; 13863 } 13864 13865 if (!attr->sample_max_stack) 13866 attr->sample_max_stack = sysctl_perf_event_max_stack; 13867 13868 if (attr->sample_type & PERF_SAMPLE_REGS_INTR) { 13869 ret = perf_reg_validate(attr->sample_regs_intr, 13870 attr->sample_simd_regs_enabled); 13871 if (ret) 13872 return ret; 13873 if (attr->sample_simd_regs_enabled) { 13874 ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, 13875 attr->sample_simd_vec_reg_intr, 13876 attr->sample_simd_pred_reg_qwords, 13877 attr->sample_simd_pred_reg_intr); 13878 if (ret) 13879 return ret; 13880 } 13881 } 13882 13883 #ifndef CONFIG_CGROUP_PERF 13884 if (attr->sample_type & PERF_SAMPLE_CGROUP) 13885 return -EINVAL; 13886 #endif 13887 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) && 13888 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT)) 13889 return -EINVAL; 13890 13891 if (!attr->inherit && attr->inherit_thread) 13892 return -EINVAL; 13893 13894 if (attr->remove_on_exec && attr->enable_on_exec) 13895 return -EINVAL; 13896 13897 if (attr->sigtrap && !attr->remove_on_exec) 13898 return -EINVAL; 13899 13900 out: 13901 return ret; 13902 13903 err_size: 13904 put_user(sizeof(*attr), &uattr->size); 13905 ret = -E2BIG; 13906 goto out; 13907 } 13908 13909 static void mutex_lock_double(struct mutex *a, struct mutex *b) 13910 { 13911 if (b < a) 13912 swap(a, b); 13913 13914 mutex_lock(a); 13915 mutex_lock_nested(b, SINGLE_DEPTH_NESTING); 13916 } 13917 13918 static int 13919 perf_event_set_output(struct perf_event *event, struct perf_event *output_event) 13920 { 13921 struct perf_buffer *rb = NULL; 13922 int ret = -EINVAL; 13923 13924 if (!output_event) { 13925 mutex_lock(&event->mmap_mutex); 13926 goto set; 13927 } 13928 13929 /* don't allow circular references */ 13930 if (event == output_event) 13931 goto out; 13932 13933 /* 13934 * Don't allow cross-cpu buffers 13935 */ 13936 if (output_event->cpu != event->cpu) 13937 goto out; 13938 13939 /* 13940 * If its not a per-cpu rb, it must be the same task. 13941 */ 13942 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target) 13943 goto out; 13944 13945 /* 13946 * Mixing clocks in the same buffer is trouble you don't need. 13947 */ 13948 if (output_event->clock != event->clock) 13949 goto out; 13950 13951 /* 13952 * Either writing ring buffer from beginning or from end. 13953 * Mixing is not allowed. 13954 */ 13955 if (is_write_backward(output_event) != is_write_backward(event)) 13956 goto out; 13957 13958 /* 13959 * If both events generate aux data, they must be on the same PMU 13960 */ 13961 if (has_aux(event) && has_aux(output_event) && 13962 event->pmu != output_event->pmu) 13963 goto out; 13964 13965 /* 13966 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since 13967 * output_event is already on rb->event_list, and the list iteration 13968 * restarts after every removal, it is guaranteed this new event is 13969 * observed *OR* if output_event is already removed, it's guaranteed we 13970 * observe !rb->mmap_count. 13971 */ 13972 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex); 13973 set: 13974 /* Can't redirect output if we've got an active mmap() */ 13975 if (refcount_read(&event->mmap_count)) 13976 goto unlock; 13977 13978 if (output_event) { 13979 if (output_event->state <= PERF_EVENT_STATE_REVOKED) 13980 goto unlock; 13981 13982 /* get the rb we want to redirect to */ 13983 rb = ring_buffer_get(output_event); 13984 if (!rb) 13985 goto unlock; 13986 13987 /* did we race against perf_mmap_close() */ 13988 if (!refcount_read(&rb->mmap_count)) { 13989 ring_buffer_put(rb); 13990 goto unlock; 13991 } 13992 } 13993 13994 ring_buffer_attach(event, rb); 13995 13996 ret = 0; 13997 unlock: 13998 mutex_unlock(&event->mmap_mutex); 13999 if (output_event) 14000 mutex_unlock(&output_event->mmap_mutex); 14001 14002 out: 14003 return ret; 14004 } 14005 14006 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id) 14007 { 14008 bool nmi_safe = false; 14009 14010 switch (clk_id) { 14011 case CLOCK_MONOTONIC: 14012 event->clock = &ktime_get_mono_fast_ns; 14013 nmi_safe = true; 14014 break; 14015 14016 case CLOCK_MONOTONIC_RAW: 14017 event->clock = &ktime_get_raw_fast_ns; 14018 nmi_safe = true; 14019 break; 14020 14021 case CLOCK_REALTIME: 14022 event->clock = &ktime_get_real_ns; 14023 break; 14024 14025 case CLOCK_BOOTTIME: 14026 event->clock = &ktime_get_boottime_ns; 14027 break; 14028 14029 case CLOCK_TAI: 14030 event->clock = &ktime_get_clocktai_ns; 14031 break; 14032 14033 default: 14034 return -EINVAL; 14035 } 14036 14037 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI)) 14038 return -EINVAL; 14039 14040 return 0; 14041 } 14042 14043 static bool 14044 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task) 14045 { 14046 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS; 14047 bool is_capable = perfmon_capable(); 14048 14049 if (attr->sigtrap) { 14050 /* 14051 * perf_event_attr::sigtrap sends signals to the other task. 14052 * Require the current task to also have CAP_KILL. 14053 */ 14054 rcu_read_lock(); 14055 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL); 14056 rcu_read_unlock(); 14057 14058 /* 14059 * If the required capabilities aren't available, checks for 14060 * ptrace permissions: upgrade to ATTACH, since sending signals 14061 * can effectively change the target task. 14062 */ 14063 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS; 14064 } 14065 14066 /* 14067 * Preserve ptrace permission check for backwards compatibility. The 14068 * ptrace check also includes checks that the current task and other 14069 * task have matching uids, and is therefore not done here explicitly. 14070 */ 14071 return is_capable || ptrace_may_access(task, ptrace_mode); 14072 } 14073 14074 /** 14075 * sys_perf_event_open - open a performance event, associate it to a task/cpu 14076 * 14077 * @attr_uptr: event_id type attributes for monitoring/sampling 14078 * @pid: target pid 14079 * @cpu: target cpu 14080 * @group_fd: group leader event fd 14081 * @flags: perf event open flags 14082 */ 14083 SYSCALL_DEFINE5(perf_event_open, 14084 struct perf_event_attr __user *, attr_uptr, 14085 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) 14086 { 14087 struct perf_event *group_leader = NULL, *output_event = NULL; 14088 struct perf_event_pmu_context *pmu_ctx; 14089 struct perf_event *event, *sibling; 14090 struct perf_event_attr attr; 14091 struct perf_event_context *ctx; 14092 struct file *event_file = NULL; 14093 struct task_struct *task = NULL; 14094 struct pmu *pmu; 14095 int event_fd; 14096 int move_group = 0; 14097 int err; 14098 int f_flags = O_RDWR; 14099 int cgroup_fd = -1; 14100 14101 /* for future expandability... */ 14102 if (flags & ~PERF_FLAG_ALL) 14103 return -EINVAL; 14104 14105 err = perf_copy_attr(attr_uptr, &attr); 14106 if (err) 14107 return err; 14108 14109 /* Do we allow access to perf_event_open(2) ? */ 14110 err = security_perf_event_open(PERF_SECURITY_OPEN); 14111 if (err) 14112 return err; 14113 14114 if (!attr.exclude_kernel || attr.text_poke || 14115 ((attr.sample_type & PERF_SAMPLE_CALLCHAIN) && 14116 !attr.exclude_callchain_kernel)) { 14117 err = perf_allow_kernel(); 14118 if (err) 14119 return err; 14120 } 14121 14122 if (attr.namespaces) { 14123 if (!perfmon_capable()) 14124 return -EACCES; 14125 } 14126 14127 if (attr.freq) { 14128 if (attr.sample_freq > sysctl_perf_event_sample_rate) 14129 return -EINVAL; 14130 } else { 14131 if (attr.sample_period & (1ULL << 63)) 14132 return -EINVAL; 14133 } 14134 14135 /* Only privileged users can get physical addresses */ 14136 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) { 14137 err = perf_allow_kernel(); 14138 if (err) 14139 return err; 14140 } 14141 14142 /* REGS_INTR can leak data, lockdown must prevent this */ 14143 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) { 14144 err = security_locked_down(LOCKDOWN_PERF); 14145 if (err) 14146 return err; 14147 } 14148 14149 /* 14150 * In cgroup mode, the pid argument is used to pass the fd 14151 * opened to the cgroup directory in cgroupfs. The cpu argument 14152 * designates the cpu on which to monitor threads from that 14153 * cgroup. 14154 */ 14155 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) 14156 return -EINVAL; 14157 14158 if (flags & PERF_FLAG_FD_CLOEXEC) 14159 f_flags |= O_CLOEXEC; 14160 14161 event_fd = get_unused_fd_flags(f_flags); 14162 if (event_fd < 0) 14163 return event_fd; 14164 14165 /* 14166 * Event creation should be under SRCU, see perf_pmu_unregister(). 14167 */ 14168 guard(srcu)(&pmus_srcu); 14169 14170 CLASS(fd, group)(group_fd); // group_fd == -1 => empty 14171 if (group_fd != -1) { 14172 if (!is_perf_file(group)) { 14173 err = -EBADF; 14174 goto err_fd; 14175 } 14176 group_leader = fd_file(group)->private_data; 14177 if (group_leader->state <= PERF_EVENT_STATE_EXIT) { 14178 err = -ENODEV; 14179 goto err_fd; 14180 } 14181 if (flags & PERF_FLAG_FD_OUTPUT) 14182 output_event = group_leader; 14183 if (flags & PERF_FLAG_FD_NO_GROUP) 14184 group_leader = NULL; 14185 } 14186 14187 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { 14188 task = find_lively_task_by_vpid(pid); 14189 if (IS_ERR(task)) { 14190 err = PTR_ERR(task); 14191 goto err_fd; 14192 } 14193 } 14194 14195 if (task && group_leader && 14196 group_leader->attr.inherit != attr.inherit) { 14197 err = -EINVAL; 14198 goto err_task; 14199 } 14200 14201 if (flags & PERF_FLAG_PID_CGROUP) 14202 cgroup_fd = pid; 14203 14204 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, 14205 NULL, NULL, cgroup_fd); 14206 if (IS_ERR(event)) { 14207 err = PTR_ERR(event); 14208 goto err_task; 14209 } 14210 14211 if (is_sampling_event(event)) { 14212 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { 14213 err = -EOPNOTSUPP; 14214 goto err_alloc; 14215 } 14216 } 14217 14218 /* 14219 * Special case software events and allow them to be part of 14220 * any hardware group. 14221 */ 14222 pmu = event->pmu; 14223 14224 if (attr.use_clockid) { 14225 err = perf_event_set_clock(event, attr.clockid); 14226 if (err) 14227 goto err_alloc; 14228 } 14229 14230 if (pmu->task_ctx_nr == perf_sw_context) 14231 event->event_caps |= PERF_EV_CAP_SOFTWARE; 14232 14233 if (task) { 14234 err = down_read_interruptible(&task->signal->exec_update_lock); 14235 if (err) 14236 goto err_alloc; 14237 14238 /* 14239 * We must hold exec_update_lock across this and any potential 14240 * perf_install_in_context() call for this new event to 14241 * serialize against exec() altering our credentials (and the 14242 * perf_event_exit_task() that could imply). 14243 */ 14244 err = -EACCES; 14245 if (!perf_check_permission(&attr, task)) 14246 goto err_cred; 14247 } 14248 14249 /* 14250 * Get the target context (task or percpu): 14251 */ 14252 ctx = find_get_context(task, event); 14253 if (IS_ERR(ctx)) { 14254 err = PTR_ERR(ctx); 14255 goto err_cred; 14256 } 14257 14258 mutex_lock(&ctx->mutex); 14259 14260 if (ctx->task == TASK_TOMBSTONE) { 14261 err = -ESRCH; 14262 goto err_locked; 14263 } 14264 14265 if (!task) { 14266 /* 14267 * Check if the @cpu we're creating an event for is online. 14268 * 14269 * We use the perf_cpu_context::ctx::mutex to serialize against 14270 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 14271 */ 14272 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu); 14273 14274 if (!cpuctx->online) { 14275 err = -ENODEV; 14276 goto err_locked; 14277 } 14278 } 14279 14280 if (group_leader) { 14281 err = -EINVAL; 14282 14283 /* 14284 * Do not allow a recursive hierarchy (this new sibling 14285 * becoming part of another group-sibling): 14286 */ 14287 if (group_leader->group_leader != group_leader) 14288 goto err_locked; 14289 14290 /* All events in a group should have the same clock */ 14291 if (group_leader->clock != event->clock) 14292 goto err_locked; 14293 14294 /* 14295 * Make sure we're both events for the same CPU; 14296 * grouping events for different CPUs is broken; since 14297 * you can never concurrently schedule them anyhow. 14298 */ 14299 if (group_leader->cpu != event->cpu) 14300 goto err_locked; 14301 14302 /* 14303 * Make sure we're both on the same context; either task or cpu. 14304 */ 14305 if (group_leader->ctx != ctx) 14306 goto err_locked; 14307 14308 /* Recheck under ctx::mutex to serialize against remove-on-exec. */ 14309 if (group_leader->state <= PERF_EVENT_STATE_EXIT) { 14310 err = -ENODEV; 14311 goto err_locked; 14312 } 14313 14314 /* 14315 * Only a group leader can be exclusive or pinned 14316 */ 14317 if (attr.exclusive || attr.pinned) 14318 goto err_locked; 14319 14320 if (is_software_event(event) && 14321 !in_software_context(group_leader)) { 14322 /* 14323 * If the event is a sw event, but the group_leader 14324 * is on hw context. 14325 * 14326 * Allow the addition of software events to hw 14327 * groups, this is safe because software events 14328 * never fail to schedule. 14329 * 14330 * Note the comment that goes with struct 14331 * perf_event_pmu_context. 14332 */ 14333 pmu = group_leader->pmu_ctx->pmu; 14334 } else if (!is_software_event(event)) { 14335 if (is_software_event(group_leader) && 14336 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { 14337 /* 14338 * In case the group is a pure software group, and we 14339 * try to add a hardware event, move the whole group to 14340 * the hardware context. 14341 */ 14342 move_group = 1; 14343 } 14344 14345 /* Don't allow group of multiple hw events from different pmus */ 14346 if (!in_software_context(group_leader) && 14347 group_leader->pmu_ctx->pmu != pmu) 14348 goto err_locked; 14349 } 14350 } 14351 14352 /* 14353 * Now that we're certain of the pmu; find the pmu_ctx. 14354 */ 14355 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 14356 if (IS_ERR(pmu_ctx)) { 14357 err = PTR_ERR(pmu_ctx); 14358 goto err_locked; 14359 } 14360 event->pmu_ctx = pmu_ctx; 14361 14362 if (output_event) { 14363 err = perf_event_set_output(event, output_event); 14364 if (err) 14365 goto err_context; 14366 } 14367 14368 if (!perf_event_validate_size(event)) { 14369 err = -E2BIG; 14370 goto err_context; 14371 } 14372 14373 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) { 14374 err = -EINVAL; 14375 goto err_context; 14376 } 14377 14378 /* 14379 * Must be under the same ctx::mutex as perf_install_in_context(), 14380 * because we need to serialize with concurrent event creation. 14381 */ 14382 if (!exclusive_event_installable(event, ctx)) { 14383 err = -EBUSY; 14384 goto err_context; 14385 } 14386 14387 WARN_ON_ONCE(ctx->parent_ctx); 14388 14389 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); 14390 if (IS_ERR(event_file)) { 14391 err = PTR_ERR(event_file); 14392 event_file = NULL; 14393 goto err_context; 14394 } 14395 14396 /* 14397 * This is the point on no return; we cannot fail hereafter. This is 14398 * where we start modifying current state. 14399 */ 14400 14401 if (move_group) { 14402 perf_remove_from_context(group_leader, 0); 14403 put_pmu_ctx(group_leader->pmu_ctx); 14404 14405 for_each_sibling_event(sibling, group_leader) { 14406 perf_remove_from_context(sibling, 0); 14407 put_pmu_ctx(sibling->pmu_ctx); 14408 } 14409 14410 /* 14411 * Install the group siblings before the group leader. 14412 * 14413 * Because a group leader will try and install the entire group 14414 * (through the sibling list, which is still in-tact), we can 14415 * end up with siblings installed in the wrong context. 14416 * 14417 * By installing siblings first we NO-OP because they're not 14418 * reachable through the group lists. 14419 */ 14420 for_each_sibling_event(sibling, group_leader) { 14421 sibling->pmu_ctx = pmu_ctx; 14422 get_pmu_ctx(pmu_ctx); 14423 perf_event__state_init(sibling); 14424 perf_install_in_context(ctx, sibling, sibling->cpu); 14425 } 14426 14427 /* 14428 * Removing from the context ends up with disabled 14429 * event. What we want here is event in the initial 14430 * startup state, ready to be add into new context. 14431 */ 14432 group_leader->pmu_ctx = pmu_ctx; 14433 get_pmu_ctx(pmu_ctx); 14434 perf_event__state_init(group_leader); 14435 perf_install_in_context(ctx, group_leader, group_leader->cpu); 14436 } 14437 14438 /* 14439 * Precalculate sample_data sizes; do while holding ctx::mutex such 14440 * that we're serialized against further additions and before 14441 * perf_install_in_context() which is the point the event is active and 14442 * can use these values. 14443 */ 14444 perf_event__header_size(event); 14445 perf_event__id_header_size(event); 14446 14447 event->owner = current; 14448 14449 perf_install_in_context(ctx, event, event->cpu); 14450 perf_unpin_context(ctx); 14451 14452 mutex_unlock(&ctx->mutex); 14453 14454 /* 14455 * Publish the event on the owner's list before dropping 14456 * exec_update_lock. Otherwise a concurrent exec() can run 14457 * perf_event_remove_on_exec() and clear event->owner before 14458 * owner_entry is linked, leaving an ownerless event on 14459 * current->perf_event_list that perf_release() won't unlink. 14460 */ 14461 mutex_lock(¤t->perf_event_mutex); 14462 list_add_tail(&event->owner_entry, ¤t->perf_event_list); 14463 mutex_unlock(¤t->perf_event_mutex); 14464 14465 if (task) { 14466 up_read(&task->signal->exec_update_lock); 14467 put_task_struct(task); 14468 } 14469 14470 /* 14471 * File reference in group guarantees that group_leader has been 14472 * kept alive until we place the new event on the sibling_list. 14473 * This ensures destruction of the group leader will find 14474 * the pointer to itself in perf_group_detach(). 14475 */ 14476 fd_install(event_fd, event_file); 14477 return event_fd; 14478 14479 err_context: 14480 put_pmu_ctx(event->pmu_ctx); 14481 event->pmu_ctx = NULL; /* _free_event() */ 14482 err_locked: 14483 mutex_unlock(&ctx->mutex); 14484 perf_unpin_context(ctx); 14485 put_ctx(ctx); 14486 err_cred: 14487 if (task) 14488 up_read(&task->signal->exec_update_lock); 14489 err_alloc: 14490 put_event(event); 14491 err_task: 14492 if (task) 14493 put_task_struct(task); 14494 err_fd: 14495 put_unused_fd(event_fd); 14496 return err; 14497 } 14498 14499 /** 14500 * perf_event_create_kernel_counter 14501 * 14502 * @attr: attributes of the counter to create 14503 * @cpu: cpu in which the counter is bound 14504 * @task: task to profile (NULL for percpu) 14505 * @overflow_handler: callback to trigger when we hit the event 14506 * @context: context data could be used in overflow_handler callback 14507 */ 14508 struct perf_event * 14509 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu, 14510 struct task_struct *task, 14511 perf_overflow_handler_t overflow_handler, 14512 void *context) 14513 { 14514 struct perf_event_pmu_context *pmu_ctx; 14515 struct perf_event_context *ctx; 14516 struct perf_event *event; 14517 struct pmu *pmu; 14518 int err; 14519 14520 /* 14521 * Grouping is not supported for kernel events, neither is 'AUX', 14522 * make sure the caller's intentions are adjusted. 14523 */ 14524 if (attr->aux_output || attr->aux_action) 14525 return ERR_PTR(-EINVAL); 14526 14527 /* 14528 * Event creation should be under SRCU, see perf_pmu_unregister(). 14529 */ 14530 guard(srcu)(&pmus_srcu); 14531 14532 event = perf_event_alloc(attr, cpu, task, NULL, NULL, 14533 overflow_handler, context, -1); 14534 if (IS_ERR(event)) { 14535 err = PTR_ERR(event); 14536 goto err; 14537 } 14538 14539 /* Mark owner so we could distinguish it from user events. */ 14540 event->owner = TASK_TOMBSTONE; 14541 pmu = event->pmu; 14542 14543 if (pmu->task_ctx_nr == perf_sw_context) 14544 event->event_caps |= PERF_EV_CAP_SOFTWARE; 14545 14546 /* 14547 * Get the target context (task or percpu): 14548 */ 14549 ctx = find_get_context(task, event); 14550 if (IS_ERR(ctx)) { 14551 err = PTR_ERR(ctx); 14552 goto err_alloc; 14553 } 14554 14555 WARN_ON_ONCE(ctx->parent_ctx); 14556 mutex_lock(&ctx->mutex); 14557 if (ctx->task == TASK_TOMBSTONE) { 14558 err = -ESRCH; 14559 goto err_unlock; 14560 } 14561 14562 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 14563 if (IS_ERR(pmu_ctx)) { 14564 err = PTR_ERR(pmu_ctx); 14565 goto err_unlock; 14566 } 14567 event->pmu_ctx = pmu_ctx; 14568 14569 if (!task) { 14570 /* 14571 * Check if the @cpu we're creating an event for is online. 14572 * 14573 * We use the perf_cpu_context::ctx::mutex to serialize against 14574 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 14575 */ 14576 struct perf_cpu_context *cpuctx = 14577 container_of(ctx, struct perf_cpu_context, ctx); 14578 if (!cpuctx->online) { 14579 err = -ENODEV; 14580 goto err_pmu_ctx; 14581 } 14582 } 14583 14584 if (!exclusive_event_installable(event, ctx)) { 14585 err = -EBUSY; 14586 goto err_pmu_ctx; 14587 } 14588 14589 perf_install_in_context(ctx, event, event->cpu); 14590 perf_unpin_context(ctx); 14591 mutex_unlock(&ctx->mutex); 14592 14593 return event; 14594 14595 err_pmu_ctx: 14596 put_pmu_ctx(pmu_ctx); 14597 event->pmu_ctx = NULL; /* _free_event() */ 14598 err_unlock: 14599 mutex_unlock(&ctx->mutex); 14600 perf_unpin_context(ctx); 14601 put_ctx(ctx); 14602 err_alloc: 14603 put_event(event); 14604 err: 14605 return ERR_PTR(err); 14606 } 14607 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter); 14608 14609 static void __perf_pmu_remove(struct perf_event_context *ctx, struct pmu *pmu, 14610 struct list_head *events) 14611 { 14612 struct perf_event *event, *tmp; 14613 14614 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) { 14615 if (event->pmu_ctx->pmu != pmu) 14616 continue; 14617 14618 perf_remove_from_context(event, 0); 14619 put_pmu_ctx(event->pmu_ctx); 14620 list_add(&event->migrate_entry, events); 14621 } 14622 } 14623 14624 static void __perf_pmu_install_event(struct pmu *pmu, 14625 struct perf_event_context *ctx, 14626 int cpu, struct perf_event *event) 14627 { 14628 struct perf_event_pmu_context *epc; 14629 struct perf_event_context *old_ctx = event->ctx; 14630 14631 get_ctx(ctx); /* normally find_get_context() */ 14632 14633 event->cpu = cpu; 14634 epc = find_get_pmu_context(pmu, ctx, event); 14635 event->pmu_ctx = epc; 14636 14637 if (event->state >= PERF_EVENT_STATE_OFF) 14638 event->state = PERF_EVENT_STATE_INACTIVE; 14639 perf_install_in_context(ctx, event, cpu); 14640 14641 /* 14642 * Now that event->ctx is updated and visible, put the old ctx. 14643 */ 14644 put_ctx(old_ctx); 14645 } 14646 14647 static void __perf_pmu_install(struct perf_event_context *ctx, 14648 int cpu, struct pmu *pmu, struct list_head *events) 14649 { 14650 struct perf_event *event, *tmp; 14651 14652 /* 14653 * Re-instate events in 2 passes. 14654 * 14655 * Skip over group leaders and only install siblings on this first 14656 * pass, siblings will not get enabled without a leader, however a 14657 * leader will enable its siblings, even if those are still on the old 14658 * context. 14659 */ 14660 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 14661 if (event->group_leader == event) 14662 continue; 14663 14664 list_del(&event->migrate_entry); 14665 __perf_pmu_install_event(pmu, ctx, cpu, event); 14666 } 14667 14668 /* 14669 * Once all the siblings are setup properly, install the group leaders 14670 * to make it go. 14671 */ 14672 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 14673 list_del(&event->migrate_entry); 14674 __perf_pmu_install_event(pmu, ctx, cpu, event); 14675 } 14676 } 14677 14678 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu) 14679 { 14680 struct perf_event_context *src_ctx, *dst_ctx; 14681 LIST_HEAD(events); 14682 14683 /* 14684 * Since per-cpu context is persistent, no need to grab an extra 14685 * reference. 14686 */ 14687 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx; 14688 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx; 14689 14690 /* 14691 * See perf_event_ctx_lock() for comments on the details 14692 * of swizzling perf_event::ctx. 14693 */ 14694 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex); 14695 14696 __perf_pmu_remove(src_ctx, pmu, &events); 14697 14698 if (!list_empty(&events)) { 14699 /* 14700 * Wait for the events to quiesce before re-instating them. 14701 */ 14702 synchronize_rcu(); 14703 14704 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events); 14705 } 14706 14707 mutex_unlock(&dst_ctx->mutex); 14708 mutex_unlock(&src_ctx->mutex); 14709 } 14710 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context); 14711 14712 static void sync_child_event(struct perf_event *child_event, 14713 struct task_struct *task) 14714 { 14715 struct perf_event *parent_event = child_event->parent; 14716 u64 child_val; 14717 14718 if (child_event->attr.inherit_stat) { 14719 if (task && task != TASK_TOMBSTONE) 14720 perf_event_read_event(child_event, task); 14721 } 14722 14723 child_val = perf_event_count(child_event, false); 14724 14725 /* 14726 * Add back the child's count to the parent's count: 14727 */ 14728 atomic64_add(child_val, &parent_event->child_count); 14729 atomic64_add(child_event->total_time_enabled, 14730 &parent_event->child_total_time_enabled); 14731 atomic64_add(child_event->total_time_running, 14732 &parent_event->child_total_time_running); 14733 } 14734 14735 static void 14736 perf_event_exit_event(struct perf_event *event, 14737 struct perf_event_context *ctx, 14738 struct task_struct *task, 14739 unsigned long detach_flags) 14740 { 14741 struct perf_event *parent_event = event->parent; 14742 unsigned int attach_state; 14743 14744 detach_flags |= DETACH_EXIT; 14745 14746 if (parent_event) { 14747 /* 14748 * Do not destroy the 'original' grouping; because of the 14749 * context switch optimization the original events could've 14750 * ended up in a random child task. 14751 * 14752 * If we were to destroy the original group, all group related 14753 * operations would cease to function properly after this 14754 * random child dies. 14755 * 14756 * Do destroy all inherited groups, we don't care about those 14757 * and being thorough is better. 14758 */ 14759 detach_flags |= DETACH_GROUP | DETACH_CHILD; 14760 mutex_lock(&parent_event->child_mutex); 14761 /* PERF_ATTACH_ITRACE might be set concurrently */ 14762 attach_state = READ_ONCE(event->attach_state); 14763 14764 if (attach_state & PERF_ATTACH_CHILD) 14765 sync_child_event(event, task); 14766 } 14767 14768 if (detach_flags & DETACH_REVOKE) 14769 detach_flags |= DETACH_GROUP; 14770 14771 perf_remove_from_context(event, detach_flags); 14772 /* 14773 * Child events can be freed. 14774 */ 14775 if (parent_event) { 14776 mutex_unlock(&parent_event->child_mutex); 14777 14778 /* 14779 * Match the refcount initialization. Make sure it doesn't happen 14780 * twice if pmu_detach_event() calls it on an already exited task. 14781 */ 14782 if (attach_state & PERF_ATTACH_CHILD) { 14783 /* 14784 * Kick perf_poll() for is_event_hup(); 14785 */ 14786 perf_event_wakeup(parent_event); 14787 /* 14788 * pmu_detach_event() will have an extra refcount. 14789 * perf_pending_task() might have one too. 14790 */ 14791 put_event(event); 14792 } 14793 14794 return; 14795 } 14796 14797 /* 14798 * Parent events are governed by their filedesc, retain them. 14799 */ 14800 perf_event_wakeup(event); 14801 } 14802 14803 static void perf_event_exit_task_context(struct task_struct *task, bool exit) 14804 { 14805 struct perf_event_context *ctx, *clone_ctx = NULL; 14806 struct perf_event *child_event, *next; 14807 14808 ctx = perf_pin_task_context(task); 14809 if (!ctx) 14810 return; 14811 14812 /* 14813 * In order to reduce the amount of tricky in ctx tear-down, we hold 14814 * ctx::mutex over the entire thing. This serializes against almost 14815 * everything that wants to access the ctx. 14816 * 14817 * The exception is sys_perf_event_open() / 14818 * perf_event_create_kernel_count() which does find_get_context() 14819 * without ctx::mutex (it cannot because of the move_group double mutex 14820 * lock thing). See the comments in perf_install_in_context(). 14821 */ 14822 mutex_lock(&ctx->mutex); 14823 14824 /* 14825 * In a single ctx::lock section, de-schedule the events and detach the 14826 * context from the task such that we cannot ever get it scheduled back 14827 * in. 14828 */ 14829 raw_spin_lock_irq(&ctx->lock); 14830 if (exit) 14831 task_ctx_sched_out(ctx, NULL, EVENT_ALL); 14832 14833 /* 14834 * Now that the context is inactive, destroy the task <-> ctx relation 14835 * and mark the context dead. 14836 */ 14837 RCU_INIT_POINTER(task->perf_event_ctxp, NULL); 14838 put_ctx(ctx); /* cannot be last */ 14839 WRITE_ONCE(ctx->task, TASK_TOMBSTONE); 14840 put_task_struct(task); /* cannot be last */ 14841 14842 clone_ctx = unclone_ctx(ctx); 14843 raw_spin_unlock_irq(&ctx->lock); 14844 14845 if (clone_ctx) 14846 put_ctx(clone_ctx); 14847 14848 /* 14849 * Report the task dead after unscheduling the events so that we 14850 * won't get any samples after PERF_RECORD_EXIT. We can however still 14851 * get a few PERF_RECORD_READ events. 14852 */ 14853 if (exit) 14854 perf_event_task(task, ctx, 0); 14855 14856 list_for_each_entry_safe(child_event, next, &ctx->event_list, event_entry) 14857 perf_event_exit_event(child_event, ctx, exit ? task : NULL, 0); 14858 14859 mutex_unlock(&ctx->mutex); 14860 14861 if (!exit) { 14862 /* 14863 * perf_event_release_kernel() could still have a reference on 14864 * this context. In that case we must wait for these events to 14865 * have been freed (in particular all their references to this 14866 * task must've been dropped). 14867 * 14868 * Without this copy_process() will unconditionally free this 14869 * task (irrespective of its reference count) and 14870 * _free_event()'s put_task_struct(event->hw.target) will be a 14871 * use-after-free. 14872 * 14873 * Wait for all events to drop their context reference. 14874 */ 14875 wait_var_event(&ctx->refcount, 14876 refcount_read(&ctx->refcount) == 1); 14877 } 14878 put_ctx(ctx); 14879 } 14880 14881 /* 14882 * When a task exits, feed back event values to parent events. 14883 * 14884 * Can be called with exec_update_lock held when called from 14885 * setup_new_exec(). 14886 */ 14887 void perf_event_exit_task(struct task_struct *task) 14888 { 14889 struct perf_event *event, *tmp; 14890 14891 WARN_ON_ONCE(task != current); 14892 14893 mutex_lock(&task->perf_event_mutex); 14894 list_for_each_entry_safe(event, tmp, &task->perf_event_list, 14895 owner_entry) { 14896 list_del_init(&event->owner_entry); 14897 14898 /* 14899 * Ensure the list deletion is visible before we clear 14900 * the owner, closes a race against perf_release() where 14901 * we need to serialize on the owner->perf_event_mutex. 14902 */ 14903 smp_store_release(&event->owner, NULL); 14904 } 14905 mutex_unlock(&task->perf_event_mutex); 14906 14907 perf_event_exit_task_context(task, true); 14908 14909 /* 14910 * The perf_event_exit_task_context calls perf_event_task 14911 * with task's task_ctx, which generates EXIT events for 14912 * task contexts and sets task->perf_event_ctxp[] to NULL. 14913 * At this point we need to send EXIT events to cpu contexts. 14914 */ 14915 perf_event_task(task, NULL, 0); 14916 14917 /* 14918 * Detach the perf_ctx_data for the system-wide event. 14919 * 14920 * Done without holding global_ctx_data_rwsem; typically 14921 * attach_global_ctx_data() will skip over this task, but otherwise 14922 * attach_task_ctx_data() will observe PF_EXITING. 14923 */ 14924 detach_task_ctx_data(task); 14925 } 14926 14927 /* 14928 * Free a context as created by inheritance by perf_event_init_task() below, 14929 * used by fork() in case of fail. 14930 * 14931 * Even though the task has never lived, the context and events have been 14932 * exposed through the child_list, so we must take care tearing it all down. 14933 */ 14934 void perf_event_free_task(struct task_struct *task) 14935 { 14936 perf_event_exit_task_context(task, false); 14937 } 14938 14939 void perf_event_delayed_put(struct task_struct *task) 14940 { 14941 WARN_ON_ONCE(task->perf_event_ctxp); 14942 } 14943 14944 struct file *perf_event_get(unsigned int fd) 14945 { 14946 struct file *file = fget(fd); 14947 if (!file) 14948 return ERR_PTR(-EBADF); 14949 14950 if (file->f_op != &perf_fops) { 14951 fput(file); 14952 return ERR_PTR(-EBADF); 14953 } 14954 14955 return file; 14956 } 14957 14958 const struct perf_event *perf_get_event(struct file *file) 14959 { 14960 if (file->f_op != &perf_fops) 14961 return ERR_PTR(-EINVAL); 14962 14963 return file->private_data; 14964 } 14965 14966 const struct perf_event_attr *perf_event_attrs(struct perf_event *event) 14967 { 14968 if (!event) 14969 return ERR_PTR(-EINVAL); 14970 14971 return &event->attr; 14972 } 14973 14974 int perf_allow_kernel(void) 14975 { 14976 if (sysctl_perf_event_paranoid > 1 && !perfmon_capable()) 14977 return -EACCES; 14978 14979 return security_perf_event_open(PERF_SECURITY_KERNEL); 14980 } 14981 EXPORT_SYMBOL_GPL(perf_allow_kernel); 14982 14983 int perf_allow_cpu(void) 14984 { 14985 if (sysctl_perf_event_paranoid > 0 && !perfmon_capable()) 14986 return -EACCES; 14987 14988 return security_perf_event_open(PERF_SECURITY_CPU); 14989 } 14990 EXPORT_SYMBOL_GPL(perf_allow_cpu); 14991 14992 int perf_allow_tracepoint(void) 14993 { 14994 if (sysctl_perf_event_paranoid > -1 && !perfmon_capable()) 14995 return -EPERM; 14996 14997 return security_perf_event_open(PERF_SECURITY_TRACEPOINT); 14998 } 14999 EXPORT_SYMBOL_GPL(perf_allow_tracepoint); 15000 15001 /* 15002 * Inherit an event from parent task to child task. 15003 * 15004 * Returns: 15005 * - valid pointer on success 15006 * - NULL for orphaned events 15007 * - IS_ERR() on error 15008 */ 15009 static struct perf_event * 15010 inherit_event(struct perf_event *parent_event, 15011 struct task_struct *parent, 15012 struct perf_event_context *parent_ctx, 15013 struct task_struct *child, 15014 struct perf_event *group_leader, 15015 struct perf_event_context *child_ctx) 15016 { 15017 enum perf_event_state parent_state = parent_event->state; 15018 struct perf_event_pmu_context *pmu_ctx; 15019 struct perf_event *child_event; 15020 unsigned long flags; 15021 15022 /* 15023 * Instead of creating recursive hierarchies of events, 15024 * we link inherited events back to the original parent, 15025 * which has a filp for sure, which we use as the reference 15026 * count: 15027 */ 15028 if (parent_event->parent) 15029 parent_event = parent_event->parent; 15030 15031 if (parent_event->state <= PERF_EVENT_STATE_REVOKED) 15032 return NULL; 15033 15034 /* 15035 * Event creation should be under SRCU, see perf_pmu_unregister(). 15036 */ 15037 guard(srcu)(&pmus_srcu); 15038 15039 child_event = perf_event_alloc(&parent_event->attr, 15040 parent_event->cpu, 15041 child, 15042 group_leader, parent_event, 15043 NULL, NULL, -1); 15044 if (IS_ERR(child_event)) 15045 return child_event; 15046 15047 get_ctx(child_ctx); 15048 child_event->ctx = child_ctx; 15049 15050 pmu_ctx = find_get_pmu_context(parent_event->pmu_ctx->pmu, child_ctx, child_event); 15051 if (IS_ERR(pmu_ctx)) { 15052 free_event(child_event); 15053 return ERR_CAST(pmu_ctx); 15054 } 15055 child_event->pmu_ctx = pmu_ctx; 15056 15057 /* 15058 * is_orphaned_event() and list_add_tail(&parent_event->child_list) 15059 * must be under the same lock in order to serialize against 15060 * perf_event_release_kernel(), such that either we must observe 15061 * is_orphaned_event() or they will observe us on the child_list. 15062 */ 15063 mutex_lock(&parent_event->child_mutex); 15064 if (is_orphaned_event(parent_event) || 15065 !atomic_long_inc_not_zero(&parent_event->refcount)) { 15066 mutex_unlock(&parent_event->child_mutex); 15067 free_event(child_event); 15068 return NULL; 15069 } 15070 15071 /* 15072 * Make the child state follow the state of the parent event, 15073 * not its attr.disabled bit. We hold the parent's mutex, 15074 * so we won't race with perf_event_{en, dis}able_family. 15075 */ 15076 if (parent_state >= PERF_EVENT_STATE_INACTIVE) 15077 child_event->state = PERF_EVENT_STATE_INACTIVE; 15078 else 15079 child_event->state = PERF_EVENT_STATE_OFF; 15080 15081 if (parent_event->attr.freq) { 15082 u64 sample_period = parent_event->hw.sample_period; 15083 struct hw_perf_event *hwc = &child_event->hw; 15084 15085 hwc->sample_period = sample_period; 15086 hwc->last_period = sample_period; 15087 15088 local64_set(&hwc->period_left, sample_period); 15089 } 15090 15091 child_event->overflow_handler = parent_event->overflow_handler; 15092 child_event->overflow_handler_context 15093 = parent_event->overflow_handler_context; 15094 15095 /* 15096 * Precalculate sample_data sizes 15097 */ 15098 perf_event__header_size(child_event); 15099 perf_event__id_header_size(child_event); 15100 15101 /* 15102 * Link it up in the child's context: 15103 */ 15104 raw_spin_lock_irqsave(&child_ctx->lock, flags); 15105 add_event_to_ctx(child_event, child_ctx); 15106 child_event->attach_state |= PERF_ATTACH_CHILD; 15107 raw_spin_unlock_irqrestore(&child_ctx->lock, flags); 15108 15109 /* 15110 * Link this into the parent event's child list 15111 */ 15112 list_add_tail(&child_event->child_list, &parent_event->child_list); 15113 mutex_unlock(&parent_event->child_mutex); 15114 15115 return child_event; 15116 } 15117 15118 /* 15119 * Inherits an event group. 15120 * 15121 * This will quietly suppress orphaned events; !inherit_event() is not an error. 15122 * This matches with perf_event_release_kernel() removing all child events. 15123 * 15124 * Returns: 15125 * - 0 on success 15126 * - <0 on error 15127 */ 15128 static int inherit_group(struct perf_event *parent_event, 15129 struct task_struct *parent, 15130 struct perf_event_context *parent_ctx, 15131 struct task_struct *child, 15132 struct perf_event_context *child_ctx) 15133 { 15134 struct perf_event *leader; 15135 struct perf_event *sub; 15136 struct perf_event *child_ctr; 15137 15138 leader = inherit_event(parent_event, parent, parent_ctx, 15139 child, NULL, child_ctx); 15140 if (IS_ERR(leader)) 15141 return PTR_ERR(leader); 15142 /* 15143 * @leader can be NULL here because of is_orphaned_event(). In this 15144 * case inherit_event() will create individual events, similar to what 15145 * perf_group_detach() would do anyway. 15146 */ 15147 for_each_sibling_event(sub, parent_event) { 15148 child_ctr = inherit_event(sub, parent, parent_ctx, 15149 child, leader, child_ctx); 15150 if (IS_ERR(child_ctr)) 15151 return PTR_ERR(child_ctr); 15152 15153 if (sub->aux_event == parent_event && child_ctr && 15154 !perf_get_aux_event(child_ctr, leader)) 15155 return -EINVAL; 15156 } 15157 if (leader) 15158 leader->group_generation = parent_event->group_generation; 15159 return 0; 15160 } 15161 15162 /* 15163 * Creates the child task context and tries to inherit the event-group. 15164 * 15165 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave 15166 * inherited_all set when we 'fail' to inherit an orphaned event; this is 15167 * consistent with perf_event_release_kernel() removing all child events. 15168 * 15169 * Returns: 15170 * - 0 on success 15171 * - <0 on error 15172 */ 15173 static int 15174 inherit_task_group(struct perf_event *event, struct task_struct *parent, 15175 struct perf_event_context *parent_ctx, 15176 struct task_struct *child, 15177 u64 clone_flags, int *inherited_all) 15178 { 15179 struct perf_event_context *child_ctx; 15180 int ret; 15181 15182 if (!event->attr.inherit || 15183 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) || 15184 /* Do not inherit if sigtrap and signal handlers were cleared. */ 15185 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) { 15186 *inherited_all = 0; 15187 return 0; 15188 } 15189 15190 child_ctx = child->perf_event_ctxp; 15191 if (!child_ctx) { 15192 /* 15193 * This is executed from the parent task context, so 15194 * inherit events that have been marked for cloning. 15195 * First allocate and initialize a context for the 15196 * child. 15197 */ 15198 child_ctx = alloc_perf_context(child); 15199 if (!child_ctx) 15200 return -ENOMEM; 15201 15202 child->perf_event_ctxp = child_ctx; 15203 } 15204 15205 ret = inherit_group(event, parent, parent_ctx, child, child_ctx); 15206 if (ret) 15207 *inherited_all = 0; 15208 15209 return ret; 15210 } 15211 15212 /* 15213 * Initialize the perf_event context in task_struct 15214 */ 15215 static int perf_event_init_context(struct task_struct *child, u64 clone_flags) 15216 { 15217 struct perf_event_context *child_ctx, *parent_ctx; 15218 struct perf_event_context *cloned_ctx; 15219 struct perf_event *event; 15220 struct task_struct *parent = current; 15221 int inherited_all = 1; 15222 unsigned long flags; 15223 int ret = 0; 15224 15225 if (likely(!parent->perf_event_ctxp)) 15226 return 0; 15227 15228 /* 15229 * If the parent's context is a clone, pin it so it won't get 15230 * swapped under us. 15231 */ 15232 parent_ctx = perf_pin_task_context(parent); 15233 if (!parent_ctx) 15234 return 0; 15235 15236 /* 15237 * No need to check if parent_ctx != NULL here; since we saw 15238 * it non-NULL earlier, the only reason for it to become NULL 15239 * is if we exit, and since we're currently in the middle of 15240 * a fork we can't be exiting at the same time. 15241 */ 15242 15243 /* 15244 * Lock the parent list. No need to lock the child - not PID 15245 * hashed yet and not running, so nobody can access it. 15246 */ 15247 mutex_lock(&parent_ctx->mutex); 15248 15249 /* 15250 * We dont have to disable NMIs - we are only looking at 15251 * the list, not manipulating it: 15252 */ 15253 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) { 15254 ret = inherit_task_group(event, parent, parent_ctx, 15255 child, clone_flags, &inherited_all); 15256 if (ret) 15257 goto out_unlock; 15258 } 15259 15260 /* 15261 * We can't hold ctx->lock when iterating the ->flexible_group list due 15262 * to allocations, but we need to prevent rotation because 15263 * rotate_ctx() will change the list from interrupt context. 15264 */ 15265 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 15266 parent_ctx->rotate_disable = 1; 15267 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 15268 15269 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) { 15270 ret = inherit_task_group(event, parent, parent_ctx, 15271 child, clone_flags, &inherited_all); 15272 if (ret) 15273 goto out_unlock; 15274 } 15275 15276 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 15277 parent_ctx->rotate_disable = 0; 15278 15279 child_ctx = child->perf_event_ctxp; 15280 15281 if (child_ctx && inherited_all) { 15282 /* 15283 * Mark the child context as a clone of the parent 15284 * context, or of whatever the parent is a clone of. 15285 * 15286 * Note that if the parent is a clone, the holding of 15287 * parent_ctx->lock avoids it from being uncloned. 15288 */ 15289 cloned_ctx = parent_ctx->parent_ctx; 15290 if (cloned_ctx) { 15291 child_ctx->parent_ctx = cloned_ctx; 15292 child_ctx->parent_gen = parent_ctx->parent_gen; 15293 } else { 15294 child_ctx->parent_ctx = parent_ctx; 15295 child_ctx->parent_gen = parent_ctx->generation; 15296 } 15297 get_ctx(child_ctx->parent_ctx); 15298 } 15299 15300 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 15301 out_unlock: 15302 mutex_unlock(&parent_ctx->mutex); 15303 15304 perf_unpin_context(parent_ctx); 15305 put_ctx(parent_ctx); 15306 15307 return ret; 15308 } 15309 15310 /* 15311 * Initialize the perf_event context in task_struct 15312 */ 15313 int perf_event_init_task(struct task_struct *child, u64 clone_flags) 15314 { 15315 int ret; 15316 15317 memset(child->perf_recursion, 0, sizeof(child->perf_recursion)); 15318 child->perf_event_ctxp = NULL; 15319 mutex_init(&child->perf_event_mutex); 15320 INIT_LIST_HEAD(&child->perf_event_list); 15321 child->perf_ctx_data = NULL; 15322 15323 ret = perf_event_init_context(child, clone_flags); 15324 if (ret) { 15325 perf_event_free_task(child); 15326 return ret; 15327 } 15328 15329 return 0; 15330 } 15331 15332 static void __init perf_event_init_all_cpus(void) 15333 { 15334 struct swevent_htable *swhash; 15335 struct perf_cpu_context *cpuctx; 15336 int cpu; 15337 15338 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL); 15339 zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL); 15340 zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL); 15341 zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL); 15342 zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL); 15343 zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL); 15344 15345 15346 for_each_possible_cpu(cpu) { 15347 swhash = &per_cpu(swevent_htable, cpu); 15348 mutex_init(&swhash->hlist_mutex); 15349 15350 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu)); 15351 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu)); 15352 15353 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu)); 15354 15355 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15356 __perf_event_init_context(&cpuctx->ctx); 15357 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); 15358 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); 15359 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask); 15360 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default); 15361 cpuctx->heap = cpuctx->heap_default; 15362 } 15363 } 15364 15365 static void perf_swevent_init_cpu(unsigned int cpu) 15366 { 15367 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 15368 15369 mutex_lock(&swhash->hlist_mutex); 15370 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) { 15371 struct swevent_hlist *hlist; 15372 15373 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); 15374 WARN_ON(!hlist); 15375 rcu_assign_pointer(swhash->swevent_hlist, hlist); 15376 } 15377 mutex_unlock(&swhash->hlist_mutex); 15378 } 15379 15380 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE 15381 static void __perf_event_exit_context(void *__info) 15382 { 15383 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 15384 struct perf_event_context *ctx = __info; 15385 struct perf_event *event; 15386 15387 raw_spin_lock(&ctx->lock); 15388 ctx_sched_out(ctx, NULL, EVENT_TIME); 15389 list_for_each_entry(event, &ctx->event_list, event_entry) 15390 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP); 15391 raw_spin_unlock(&ctx->lock); 15392 } 15393 15394 static void perf_event_clear_cpumask(unsigned int cpu) 15395 { 15396 int target[PERF_PMU_MAX_SCOPE]; 15397 unsigned int scope; 15398 struct pmu *pmu; 15399 15400 cpumask_clear_cpu(cpu, perf_online_mask); 15401 15402 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15403 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 15404 struct cpumask *pmu_cpumask = perf_scope_cpumask(scope); 15405 15406 target[scope] = -1; 15407 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 15408 continue; 15409 15410 if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask)) 15411 continue; 15412 target[scope] = cpumask_any_but(cpumask, cpu); 15413 if (target[scope] < nr_cpu_ids) 15414 cpumask_set_cpu(target[scope], pmu_cpumask); 15415 } 15416 15417 /* migrate */ 15418 list_for_each_entry(pmu, &pmus, entry) { 15419 if (pmu->scope == PERF_PMU_SCOPE_NONE || 15420 WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE)) 15421 continue; 15422 15423 if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids) 15424 perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]); 15425 } 15426 } 15427 15428 static void perf_event_exit_cpu_context(int cpu) 15429 { 15430 struct perf_cpu_context *cpuctx; 15431 struct perf_event_context *ctx; 15432 15433 // XXX simplify cpuctx->online 15434 mutex_lock(&pmus_lock); 15435 /* 15436 * Clear the cpumasks, and migrate to other CPUs if possible. 15437 * Must be invoked before the __perf_event_exit_context. 15438 */ 15439 perf_event_clear_cpumask(cpu); 15440 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15441 ctx = &cpuctx->ctx; 15442 15443 mutex_lock(&ctx->mutex); 15444 if (ctx->nr_events) 15445 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1); 15446 cpuctx->online = 0; 15447 mutex_unlock(&ctx->mutex); 15448 mutex_unlock(&pmus_lock); 15449 } 15450 #else 15451 15452 static void perf_event_exit_cpu_context(int cpu) { } 15453 15454 #endif 15455 15456 static void perf_event_setup_cpumask(unsigned int cpu) 15457 { 15458 struct cpumask *pmu_cpumask; 15459 unsigned int scope; 15460 15461 /* 15462 * Early boot stage, the cpumask hasn't been set yet. 15463 * The perf_online_<domain>_masks includes the first CPU of each domain. 15464 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks. 15465 */ 15466 if (cpumask_empty(perf_online_mask)) { 15467 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15468 pmu_cpumask = perf_scope_cpumask(scope); 15469 if (WARN_ON_ONCE(!pmu_cpumask)) 15470 continue; 15471 cpumask_set_cpu(cpu, pmu_cpumask); 15472 } 15473 goto end; 15474 } 15475 15476 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15477 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 15478 15479 pmu_cpumask = perf_scope_cpumask(scope); 15480 15481 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 15482 continue; 15483 15484 if (!cpumask_empty(cpumask) && 15485 cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids) 15486 cpumask_set_cpu(cpu, pmu_cpumask); 15487 } 15488 end: 15489 cpumask_set_cpu(cpu, perf_online_mask); 15490 } 15491 15492 int perf_event_init_cpu(unsigned int cpu) 15493 { 15494 struct perf_cpu_context *cpuctx; 15495 struct perf_event_context *ctx; 15496 15497 perf_swevent_init_cpu(cpu); 15498 15499 mutex_lock(&pmus_lock); 15500 perf_event_setup_cpumask(cpu); 15501 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15502 ctx = &cpuctx->ctx; 15503 15504 mutex_lock(&ctx->mutex); 15505 cpuctx->online = 1; 15506 mutex_unlock(&ctx->mutex); 15507 mutex_unlock(&pmus_lock); 15508 15509 return 0; 15510 } 15511 15512 int perf_event_exit_cpu(unsigned int cpu) 15513 { 15514 perf_event_exit_cpu_context(cpu); 15515 return 0; 15516 } 15517 15518 static int 15519 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v) 15520 { 15521 int cpu; 15522 15523 for_each_online_cpu(cpu) 15524 perf_event_exit_cpu(cpu); 15525 15526 return NOTIFY_OK; 15527 } 15528 15529 /* 15530 * Run the perf reboot notifier at the very last possible moment so that 15531 * the generic watchdog code runs as long as possible. 15532 */ 15533 static struct notifier_block perf_reboot_notifier = { 15534 .notifier_call = perf_reboot, 15535 .priority = INT_MIN, 15536 }; 15537 15538 void __init perf_event_init(void) 15539 { 15540 int ret; 15541 15542 idr_init(&pmu_idr); 15543 15544 unwind_deferred_init(&perf_unwind_work, 15545 perf_unwind_deferred_callback); 15546 15547 perf_event_init_all_cpus(); 15548 init_srcu_struct(&pmus_srcu); 15549 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE); 15550 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1); 15551 perf_pmu_register(&perf_task_clock, "task_clock", -1); 15552 perf_tp_register(); 15553 perf_event_init_cpu(smp_processor_id()); 15554 register_reboot_notifier(&perf_reboot_notifier); 15555 15556 ret = init_hw_breakpoint(); 15557 WARN(ret, "hw_breakpoint initialization failed with: %d", ret); 15558 15559 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC); 15560 15561 /* 15562 * Build time assertion that we keep the data_head at the intended 15563 * location. IOW, validation we got the __reserved[] size right. 15564 */ 15565 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head)) 15566 != 1024); 15567 } 15568 15569 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr, 15570 char *page) 15571 { 15572 struct perf_pmu_events_attr *pmu_attr = 15573 container_of(attr, struct perf_pmu_events_attr, attr); 15574 15575 if (pmu_attr->event_str) 15576 return sprintf(page, "%s\n", pmu_attr->event_str); 15577 15578 return 0; 15579 } 15580 EXPORT_SYMBOL_GPL(perf_event_sysfs_show); 15581 15582 static int __init perf_event_sysfs_init(void) 15583 { 15584 struct pmu *pmu; 15585 int ret; 15586 15587 mutex_lock(&pmus_lock); 15588 15589 ret = bus_register(&pmu_bus); 15590 if (ret) 15591 goto unlock; 15592 15593 list_for_each_entry(pmu, &pmus, entry) { 15594 if (pmu->dev) 15595 continue; 15596 15597 ret = pmu_dev_alloc(pmu); 15598 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret); 15599 } 15600 pmu_bus_running = 1; 15601 ret = 0; 15602 15603 unlock: 15604 mutex_unlock(&pmus_lock); 15605 15606 return ret; 15607 } 15608 device_initcall(perf_event_sysfs_init); 15609 15610 #ifdef CONFIG_CGROUP_PERF 15611 static struct cgroup_subsys_state * 15612 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 15613 { 15614 struct perf_cgroup *jc; 15615 15616 jc = kzalloc_obj(*jc); 15617 if (!jc) 15618 return ERR_PTR(-ENOMEM); 15619 15620 jc->info = alloc_percpu(struct perf_cgroup_info); 15621 if (!jc->info) { 15622 kfree(jc); 15623 return ERR_PTR(-ENOMEM); 15624 } 15625 15626 return &jc->css; 15627 } 15628 15629 static void perf_cgroup_css_free(struct cgroup_subsys_state *css) 15630 { 15631 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css); 15632 15633 free_percpu(jc->info); 15634 kfree(jc); 15635 } 15636 15637 static int perf_cgroup_css_online(struct cgroup_subsys_state *css) 15638 { 15639 perf_event_cgroup(css->cgroup); 15640 return 0; 15641 } 15642 15643 static int __perf_cgroup_move(void *info) 15644 { 15645 struct task_struct *task = info; 15646 15647 preempt_disable(); 15648 perf_cgroup_switch(task); 15649 preempt_enable(); 15650 15651 return 0; 15652 } 15653 15654 static void perf_cgroup_attach(struct cgroup_taskset *tset) 15655 { 15656 struct task_struct *task; 15657 struct cgroup_subsys_state *css; 15658 15659 cgroup_taskset_for_each(task, css, tset) 15660 task_function_call(task, __perf_cgroup_move, task); 15661 } 15662 15663 struct cgroup_subsys perf_event_cgrp_subsys = { 15664 .css_alloc = perf_cgroup_css_alloc, 15665 .css_free = perf_cgroup_css_free, 15666 .css_online = perf_cgroup_css_online, 15667 .attach = perf_cgroup_attach, 15668 /* 15669 * Implicitly enable on dfl hierarchy so that perf events can 15670 * always be filtered by cgroup2 path as long as perf_event 15671 * controller is not mounted on a legacy hierarchy. 15672 */ 15673 .implicit_on_dfl = true, 15674 .threaded = true, 15675 }; 15676 #endif /* CONFIG_CGROUP_PERF */ 15677 15678 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t); 15679