1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Performance events core code: 4 * 5 * Copyright (C) 2008 Linutronix GmbH, Thomas Gleixner <tglx@kernel.org> 6 * Copyright (C) 2008-2011 Red Hat, Inc., Ingo Molnar 7 * Copyright (C) 2008-2011 Red Hat, Inc., Peter Zijlstra 8 * Copyright © 2009 Paul Mackerras, IBM Corp. <paulus@au1.ibm.com> 9 */ 10 11 #include <linux/fs.h> 12 #include <linux/mm.h> 13 #include <linux/cpu.h> 14 #include <linux/smp.h> 15 #include <linux/idr.h> 16 #include <linux/file.h> 17 #include <linux/poll.h> 18 #include <linux/slab.h> 19 #include <linux/hash.h> 20 #include <linux/tick.h> 21 #include <linux/sysfs.h> 22 #include <linux/dcache.h> 23 #include <linux/percpu.h> 24 #include <linux/ptrace.h> 25 #include <linux/reboot.h> 26 #include <linux/vmstat.h> 27 #include <linux/device.h> 28 #include <linux/export.h> 29 #include <linux/vmalloc.h> 30 #include <linux/hardirq.h> 31 #include <linux/hugetlb.h> 32 #include <linux/rculist.h> 33 #include <linux/uaccess.h> 34 #include <linux/syscalls.h> 35 #include <linux/anon_inodes.h> 36 #include <linux/kernel_stat.h> 37 #include <linux/cgroup.h> 38 #include <linux/perf_event.h> 39 #include <linux/trace_events.h> 40 #include <linux/hw_breakpoint.h> 41 #include <linux/mm_types.h> 42 #include <linux/module.h> 43 #include <linux/mman.h> 44 #include <linux/compat.h> 45 #include <linux/bpf.h> 46 #include <linux/filter.h> 47 #include <linux/namei.h> 48 #include <linux/parser.h> 49 #include <linux/sched/clock.h> 50 #include <linux/sched/mm.h> 51 #include <linux/proc_ns.h> 52 #include <linux/mount.h> 53 #include <linux/min_heap.h> 54 #include <linux/highmem.h> 55 #include <linux/pgtable.h> 56 #include <linux/buildid.h> 57 #include <linux/task_work.h> 58 #include <linux/percpu-rwsem.h> 59 #include <linux/unwind_deferred.h> 60 #include <linux/kvm_types.h> 61 #include <linux/seq_file.h> 62 63 #include "internal.h" 64 65 #include <asm/irq_regs.h> 66 67 typedef int (*remote_function_f)(void *); 68 69 struct remote_function_call { 70 struct task_struct *p; 71 remote_function_f func; 72 void *info; 73 int ret; 74 }; 75 76 static void remote_function(void *data) 77 { 78 struct remote_function_call *tfc = data; 79 struct task_struct *p = tfc->p; 80 81 if (p) { 82 /* -EAGAIN */ 83 if (task_cpu(p) != smp_processor_id()) 84 return; 85 86 /* 87 * Now that we're on right CPU with IRQs disabled, we can test 88 * if we hit the right task without races. 89 */ 90 91 tfc->ret = -ESRCH; /* No such (running) process */ 92 if (p != current) 93 return; 94 } 95 96 tfc->ret = tfc->func(tfc->info); 97 } 98 99 /** 100 * task_function_call - call a function on the cpu on which a task runs 101 * @p: the task to evaluate 102 * @func: the function to be called 103 * @info: the function call argument 104 * 105 * Calls the function @func when the task is currently running. This might 106 * be on the current CPU, which just calls the function directly. This will 107 * retry due to any failures in smp_call_function_single(), such as if the 108 * task_cpu() goes offline concurrently. 109 * 110 * returns @func return value or -ESRCH or -ENXIO when the process isn't running 111 */ 112 static int 113 task_function_call(struct task_struct *p, remote_function_f func, void *info) 114 { 115 struct remote_function_call data = { 116 .p = p, 117 .func = func, 118 .info = info, 119 .ret = -EAGAIN, 120 }; 121 int ret; 122 123 for (;;) { 124 ret = smp_call_function_single(task_cpu(p), remote_function, 125 &data, 1); 126 if (!ret) 127 ret = data.ret; 128 129 if (ret != -EAGAIN) 130 break; 131 132 cond_resched(); 133 } 134 135 return ret; 136 } 137 138 /** 139 * cpu_function_call - call a function on the cpu 140 * @cpu: target cpu to queue this function 141 * @func: the function to be called 142 * @info: the function call argument 143 * 144 * Calls the function @func on the remote cpu. 145 * 146 * returns: @func return value or -ENXIO when the cpu is offline 147 */ 148 static int cpu_function_call(int cpu, remote_function_f func, void *info) 149 { 150 struct remote_function_call data = { 151 .p = NULL, 152 .func = func, 153 .info = info, 154 .ret = -ENXIO, /* No such CPU */ 155 }; 156 157 smp_call_function_single(cpu, remote_function, &data, 1); 158 159 return data.ret; 160 } 161 162 enum event_type_t { 163 EVENT_FLEXIBLE = 0x01, 164 EVENT_PINNED = 0x02, 165 EVENT_TIME = 0x04, 166 EVENT_FROZEN = 0x08, 167 /* see ctx_resched() for details */ 168 EVENT_CPU = 0x10, 169 EVENT_CGROUP = 0x20, 170 171 /* 172 * EVENT_GUEST is set when scheduling in/out events between the host 173 * and a guest with a mediated vPMU. Among other things, EVENT_GUEST 174 * is used: 175 * 176 * - In for_each_epc() to skip PMUs that don't support events in a 177 * MEDIATED_VPMU guest, i.e. don't need to be context switched. 178 * - To indicate the start/end point of the events in a guest. Guest 179 * running time is deducted for host-only (exclude_guest) events. 180 */ 181 EVENT_GUEST = 0x40, 182 EVENT_FLAGS = EVENT_CGROUP | EVENT_GUEST, 183 /* compound helpers */ 184 EVENT_ALL = EVENT_FLEXIBLE | EVENT_PINNED, 185 EVENT_TIME_FROZEN = EVENT_TIME | EVENT_FROZEN, 186 }; 187 188 static inline void __perf_ctx_lock(struct perf_event_context *ctx) 189 { 190 raw_spin_lock(&ctx->lock); 191 WARN_ON_ONCE(ctx->is_active & EVENT_FROZEN); 192 } 193 194 static void perf_ctx_lock(struct perf_cpu_context *cpuctx, 195 struct perf_event_context *ctx) 196 { 197 __perf_ctx_lock(&cpuctx->ctx); 198 if (ctx) 199 __perf_ctx_lock(ctx); 200 } 201 202 static inline void __perf_ctx_unlock(struct perf_event_context *ctx) 203 { 204 /* 205 * If ctx_sched_in() didn't again set any ALL flags, clean up 206 * after ctx_sched_out() by clearing is_active. 207 */ 208 if (ctx->is_active & EVENT_FROZEN) { 209 if (!(ctx->is_active & EVENT_ALL)) 210 ctx->is_active = 0; 211 else 212 ctx->is_active &= ~EVENT_FROZEN; 213 } 214 raw_spin_unlock(&ctx->lock); 215 } 216 217 static void perf_ctx_unlock(struct perf_cpu_context *cpuctx, 218 struct perf_event_context *ctx) 219 { 220 if (ctx) 221 __perf_ctx_unlock(ctx); 222 __perf_ctx_unlock(&cpuctx->ctx); 223 } 224 225 typedef struct { 226 struct perf_cpu_context *cpuctx; 227 struct perf_event_context *ctx; 228 } class_perf_ctx_lock_t; 229 230 static inline void class_perf_ctx_lock_destructor(class_perf_ctx_lock_t *_T) 231 { perf_ctx_unlock(_T->cpuctx, _T->ctx); } 232 233 static inline class_perf_ctx_lock_t 234 class_perf_ctx_lock_constructor(struct perf_cpu_context *cpuctx, 235 struct perf_event_context *ctx) 236 { perf_ctx_lock(cpuctx, ctx); return (class_perf_ctx_lock_t){ cpuctx, ctx }; } 237 238 #define TASK_TOMBSTONE ((void *)-1L) 239 240 static bool is_kernel_event(struct perf_event *event) 241 { 242 return READ_ONCE(event->owner) == TASK_TOMBSTONE; 243 } 244 245 static DEFINE_PER_CPU(struct perf_cpu_context, perf_cpu_context); 246 247 struct perf_event_context *perf_cpu_task_ctx(void) 248 { 249 lockdep_assert_irqs_disabled(); 250 return this_cpu_ptr(&perf_cpu_context)->task_ctx; 251 } 252 253 /* 254 * On task ctx scheduling... 255 * 256 * When !ctx->nr_events a task context will not be scheduled. This means 257 * we can disable the scheduler hooks (for performance) without leaving 258 * pending task ctx state. 259 * 260 * This however results in two special cases: 261 * 262 * - removing the last event from a task ctx; this is relatively straight 263 * forward and is done in __perf_remove_from_context. 264 * 265 * - adding the first event to a task ctx; this is tricky because we cannot 266 * rely on ctx->is_active and therefore cannot use event_function_call(). 267 * See perf_install_in_context(). 268 * 269 * If ctx->nr_events, then ctx->is_active and cpuctx->task_ctx are set. 270 */ 271 272 typedef void (*event_f)(struct perf_event *, struct perf_cpu_context *, 273 struct perf_event_context *, void *); 274 275 struct event_function_struct { 276 struct perf_event *event; 277 event_f func; 278 void *data; 279 }; 280 281 static int event_function(void *info) 282 { 283 struct event_function_struct *efs = info; 284 struct perf_event *event = efs->event; 285 struct perf_event_context *ctx = event->ctx; 286 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 287 struct perf_event_context *task_ctx = cpuctx->task_ctx; 288 int ret = 0; 289 290 lockdep_assert_irqs_disabled(); 291 292 perf_ctx_lock(cpuctx, task_ctx); 293 /* 294 * Since we do the IPI call without holding ctx->lock things can have 295 * changed, double check we hit the task we set out to hit. 296 */ 297 if (ctx->task) { 298 if (ctx->task != current) { 299 ret = -ESRCH; 300 goto unlock; 301 } 302 303 /* 304 * We only use event_function_call() on established contexts, 305 * and event_function() is only ever called when active (or 306 * rather, we'll have bailed in task_function_call() or the 307 * above ctx->task != current test), therefore we must have 308 * ctx->is_active here. 309 */ 310 WARN_ON_ONCE(!ctx->is_active); 311 /* 312 * And since we have ctx->is_active, cpuctx->task_ctx must 313 * match. 314 */ 315 WARN_ON_ONCE(task_ctx != ctx); 316 } else { 317 WARN_ON_ONCE(&cpuctx->ctx != ctx); 318 } 319 320 efs->func(event, cpuctx, ctx, efs->data); 321 unlock: 322 perf_ctx_unlock(cpuctx, task_ctx); 323 324 return ret; 325 } 326 327 static void event_function_call(struct perf_event *event, event_f func, void *data) 328 { 329 struct perf_event_context *ctx = event->ctx; 330 struct task_struct *task = READ_ONCE(ctx->task); /* verified in event_function */ 331 struct perf_cpu_context *cpuctx; 332 struct event_function_struct efs = { 333 .event = event, 334 .func = func, 335 .data = data, 336 }; 337 338 if (!event->parent) { 339 /* 340 * If this is a !child event, we must hold ctx::mutex to 341 * stabilize the event->ctx relation. See 342 * perf_event_ctx_lock(). 343 */ 344 lockdep_assert_held(&ctx->mutex); 345 } 346 347 if (!task) { 348 cpu_function_call(event->cpu, event_function, &efs); 349 return; 350 } 351 352 if (task == TASK_TOMBSTONE) 353 return; 354 355 again: 356 if (!task_function_call(task, event_function, &efs)) 357 return; 358 359 local_irq_disable(); 360 cpuctx = this_cpu_ptr(&perf_cpu_context); 361 perf_ctx_lock(cpuctx, ctx); 362 /* 363 * Reload the task pointer, it might have been changed by 364 * a concurrent perf_event_context_sched_out(). 365 */ 366 task = ctx->task; 367 if (task == TASK_TOMBSTONE) 368 goto unlock; 369 if (ctx->is_active) { 370 perf_ctx_unlock(cpuctx, ctx); 371 local_irq_enable(); 372 goto again; 373 } 374 func(event, NULL, ctx, data); 375 unlock: 376 perf_ctx_unlock(cpuctx, ctx); 377 local_irq_enable(); 378 } 379 380 /* 381 * Similar to event_function_call() + event_function(), but hard assumes IRQs 382 * are already disabled and we're on the right CPU. 383 */ 384 static void event_function_local(struct perf_event *event, event_f func, void *data) 385 { 386 struct perf_event_context *ctx = event->ctx; 387 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 388 struct task_struct *task = READ_ONCE(ctx->task); 389 struct perf_event_context *task_ctx = NULL; 390 391 lockdep_assert_irqs_disabled(); 392 393 if (task) { 394 if (task == TASK_TOMBSTONE) 395 return; 396 397 task_ctx = ctx; 398 } 399 400 perf_ctx_lock(cpuctx, task_ctx); 401 402 task = ctx->task; 403 if (task == TASK_TOMBSTONE) 404 goto unlock; 405 406 if (task) { 407 /* 408 * We must be either inactive or active and the right task, 409 * otherwise we're screwed, since we cannot IPI to somewhere 410 * else. 411 */ 412 if (ctx->is_active) { 413 if (WARN_ON_ONCE(task != current)) 414 goto unlock; 415 416 if (WARN_ON_ONCE(cpuctx->task_ctx != ctx)) 417 goto unlock; 418 } 419 } else { 420 WARN_ON_ONCE(&cpuctx->ctx != ctx); 421 } 422 423 func(event, cpuctx, ctx, data); 424 unlock: 425 perf_ctx_unlock(cpuctx, task_ctx); 426 } 427 428 #define PERF_FLAG_ALL (PERF_FLAG_FD_NO_GROUP |\ 429 PERF_FLAG_FD_OUTPUT |\ 430 PERF_FLAG_PID_CGROUP |\ 431 PERF_FLAG_FD_CLOEXEC) 432 433 /* 434 * branch priv levels that need permission checks 435 */ 436 #define PERF_SAMPLE_BRANCH_PERM_PLM \ 437 (PERF_SAMPLE_BRANCH_KERNEL |\ 438 PERF_SAMPLE_BRANCH_HV) 439 440 /* 441 * perf_sched_events : >0 events exist 442 */ 443 444 static void perf_sched_delayed(struct work_struct *work); 445 DEFINE_STATIC_KEY_FALSE(perf_sched_events); 446 static DECLARE_DELAYED_WORK(perf_sched_work, perf_sched_delayed); 447 static DEFINE_MUTEX(perf_sched_mutex); 448 static atomic_t perf_sched_count; 449 450 static DEFINE_PER_CPU(struct pmu_event_list, pmu_sb_events); 451 452 static atomic_t nr_mmap_events __read_mostly; 453 static atomic_t nr_comm_events __read_mostly; 454 static atomic_t nr_namespaces_events __read_mostly; 455 static atomic_t nr_task_events __read_mostly; 456 static atomic_t nr_freq_events __read_mostly; 457 static atomic_t nr_switch_events __read_mostly; 458 static atomic_t nr_ksymbol_events __read_mostly; 459 static atomic_t nr_bpf_events __read_mostly; 460 static atomic_t nr_cgroup_events __read_mostly; 461 static atomic_t nr_text_poke_events __read_mostly; 462 static atomic_t nr_build_id_events __read_mostly; 463 464 static LIST_HEAD(pmus); 465 static DEFINE_MUTEX(pmus_lock); 466 static struct srcu_struct pmus_srcu; 467 static cpumask_var_t perf_online_mask; 468 static cpumask_var_t perf_online_core_mask; 469 static cpumask_var_t perf_online_die_mask; 470 static cpumask_var_t perf_online_cluster_mask; 471 static cpumask_var_t perf_online_pkg_mask; 472 static cpumask_var_t perf_online_sys_mask; 473 static struct kmem_cache *perf_event_cache; 474 475 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU 476 static DEFINE_PER_CPU(bool, guest_ctx_loaded); 477 478 static __always_inline bool is_guest_mediated_pmu_loaded(void) 479 { 480 return __this_cpu_read(guest_ctx_loaded); 481 } 482 #else 483 static __always_inline bool is_guest_mediated_pmu_loaded(void) 484 { 485 return false; 486 } 487 #endif 488 489 /* 490 * perf event paranoia level: 491 * -1 - not paranoid at all 492 * 0 - disallow raw tracepoint access for unpriv 493 * 1 - disallow cpu events for unpriv 494 * 2 - disallow kernel profiling for unpriv 495 */ 496 int sysctl_perf_event_paranoid __read_mostly = 2; 497 498 /* Minimum for 512 kiB + 1 user control page. 'free' kiB per user. */ 499 static int sysctl_perf_event_mlock __read_mostly = 512 + (PAGE_SIZE / 1024); 500 501 /* 502 * max perf event sample rate 503 */ 504 #define DEFAULT_MAX_SAMPLE_RATE 100000 505 #define DEFAULT_SAMPLE_PERIOD_NS (NSEC_PER_SEC / DEFAULT_MAX_SAMPLE_RATE) 506 #define DEFAULT_CPU_TIME_MAX_PERCENT 25 507 508 int sysctl_perf_event_sample_rate __read_mostly = DEFAULT_MAX_SAMPLE_RATE; 509 static int sysctl_perf_cpu_time_max_percent __read_mostly = DEFAULT_CPU_TIME_MAX_PERCENT; 510 511 static int max_samples_per_tick __read_mostly = DIV_ROUND_UP(DEFAULT_MAX_SAMPLE_RATE, HZ); 512 static int perf_sample_period_ns __read_mostly = DEFAULT_SAMPLE_PERIOD_NS; 513 514 static int perf_sample_allowed_ns __read_mostly = 515 DEFAULT_SAMPLE_PERIOD_NS * DEFAULT_CPU_TIME_MAX_PERCENT / 100; 516 517 static void update_perf_cpu_limits(void) 518 { 519 u64 tmp = perf_sample_period_ns; 520 521 tmp *= sysctl_perf_cpu_time_max_percent; 522 tmp = div_u64(tmp, 100); 523 if (!tmp) 524 tmp = 1; 525 526 WRITE_ONCE(perf_sample_allowed_ns, tmp); 527 } 528 529 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc); 530 531 static int perf_event_max_sample_rate_handler(const struct ctl_table *table, int write, 532 void *buffer, size_t *lenp, loff_t *ppos) 533 { 534 int ret; 535 int perf_cpu = sysctl_perf_cpu_time_max_percent; 536 /* 537 * If throttling is disabled don't allow the write: 538 */ 539 if (write && (perf_cpu == 100 || perf_cpu == 0)) 540 return -EINVAL; 541 542 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 543 if (ret || !write) 544 return ret; 545 546 max_samples_per_tick = DIV_ROUND_UP(sysctl_perf_event_sample_rate, HZ); 547 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; 548 update_perf_cpu_limits(); 549 550 return 0; 551 } 552 553 static int perf_cpu_time_max_percent_handler(const struct ctl_table *table, int write, 554 void *buffer, size_t *lenp, loff_t *ppos) 555 { 556 int ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); 557 558 if (ret || !write) 559 return ret; 560 561 if (sysctl_perf_cpu_time_max_percent == 100 || 562 sysctl_perf_cpu_time_max_percent == 0) { 563 printk(KERN_WARNING 564 "perf: Dynamic interrupt throttling disabled, can hang your system!\n"); 565 WRITE_ONCE(perf_sample_allowed_ns, 0); 566 } else { 567 update_perf_cpu_limits(); 568 } 569 570 return 0; 571 } 572 573 static const struct ctl_table events_core_sysctl_table[] = { 574 /* 575 * User-space relies on this file as a feature check for 576 * perf_events being enabled. It's an ABI, do not remove! 577 */ 578 { 579 .procname = "perf_event_paranoid", 580 .data = &sysctl_perf_event_paranoid, 581 .maxlen = sizeof(sysctl_perf_event_paranoid), 582 .mode = 0644, 583 .proc_handler = proc_dointvec, 584 }, 585 { 586 .procname = "perf_event_mlock_kb", 587 .data = &sysctl_perf_event_mlock, 588 .maxlen = sizeof(sysctl_perf_event_mlock), 589 .mode = 0644, 590 .proc_handler = proc_dointvec, 591 }, 592 { 593 .procname = "perf_event_max_sample_rate", 594 .data = &sysctl_perf_event_sample_rate, 595 .maxlen = sizeof(sysctl_perf_event_sample_rate), 596 .mode = 0644, 597 .proc_handler = perf_event_max_sample_rate_handler, 598 .extra1 = SYSCTL_ONE, 599 }, 600 { 601 .procname = "perf_cpu_time_max_percent", 602 .data = &sysctl_perf_cpu_time_max_percent, 603 .maxlen = sizeof(sysctl_perf_cpu_time_max_percent), 604 .mode = 0644, 605 .proc_handler = perf_cpu_time_max_percent_handler, 606 .extra1 = SYSCTL_ZERO, 607 .extra2 = SYSCTL_ONE_HUNDRED, 608 }, 609 }; 610 611 static int __init init_events_core_sysctls(void) 612 { 613 register_sysctl_init("kernel", events_core_sysctl_table); 614 return 0; 615 } 616 core_initcall(init_events_core_sysctls); 617 618 619 /* 620 * perf samples are done in some very critical code paths (NMIs). 621 * If they take too much CPU time, the system can lock up and not 622 * get any real work done. This will drop the sample rate when 623 * we detect that events are taking too long. 624 */ 625 #define NR_ACCUMULATED_SAMPLES 128 626 static DEFINE_PER_CPU(u64, running_sample_length); 627 628 static u64 __report_avg; 629 static u64 __report_allowed; 630 631 static void perf_duration_warn(struct irq_work *w) 632 { 633 printk_ratelimited(KERN_INFO 634 "perf: interrupt took too long (%lld > %lld), lowering " 635 "kernel.perf_event_max_sample_rate to %d\n", 636 __report_avg, __report_allowed, 637 sysctl_perf_event_sample_rate); 638 } 639 640 static DEFINE_IRQ_WORK(perf_duration_work, perf_duration_warn); 641 642 void perf_sample_event_took(u64 sample_len_ns) 643 { 644 u64 max_len = READ_ONCE(perf_sample_allowed_ns); 645 u64 running_len; 646 u64 avg_len; 647 u32 max; 648 649 if (max_len == 0) 650 return; 651 652 /* Decay the counter by 1 average sample. */ 653 running_len = __this_cpu_read(running_sample_length); 654 running_len -= running_len/NR_ACCUMULATED_SAMPLES; 655 running_len += sample_len_ns; 656 __this_cpu_write(running_sample_length, running_len); 657 658 /* 659 * Note: this will be biased artificially low until we have 660 * seen NR_ACCUMULATED_SAMPLES. Doing it this way keeps us 661 * from having to maintain a count. 662 */ 663 avg_len = running_len/NR_ACCUMULATED_SAMPLES; 664 if (avg_len <= max_len) 665 return; 666 667 __report_avg = avg_len; 668 __report_allowed = max_len; 669 670 /* 671 * Compute a throttle threshold 25% below the current duration. 672 */ 673 avg_len += avg_len / 4; 674 max = (TICK_NSEC / 100) * sysctl_perf_cpu_time_max_percent; 675 if (avg_len < max) 676 max /= (u32)avg_len; 677 else 678 max = 1; 679 680 WRITE_ONCE(perf_sample_allowed_ns, avg_len); 681 WRITE_ONCE(max_samples_per_tick, max); 682 683 sysctl_perf_event_sample_rate = max * HZ; 684 perf_sample_period_ns = NSEC_PER_SEC / sysctl_perf_event_sample_rate; 685 686 if (!irq_work_queue(&perf_duration_work)) { 687 early_printk("perf: interrupt took too long (%lld > %lld), lowering " 688 "kernel.perf_event_max_sample_rate to %d\n", 689 __report_avg, __report_allowed, 690 sysctl_perf_event_sample_rate); 691 } 692 } 693 694 static atomic64_t perf_event_id; 695 696 static void update_context_time(struct perf_event_context *ctx); 697 static u64 perf_event_time(struct perf_event *event); 698 699 void __weak perf_event_print_debug(void) { } 700 701 static inline u64 perf_clock(void) 702 { 703 return local_clock(); 704 } 705 706 static inline u64 perf_event_clock(struct perf_event *event) 707 { 708 return event->clock(); 709 } 710 711 /* 712 * State based event timekeeping... 713 * 714 * The basic idea is to use event->state to determine which (if any) time 715 * fields to increment with the current delta. This means we only need to 716 * update timestamps when we change state or when they are explicitly requested 717 * (read). 718 * 719 * Event groups make things a little more complicated, but not terribly so. The 720 * rules for a group are that if the group leader is OFF the entire group is 721 * OFF, irrespective of what the group member states are. This results in 722 * __perf_effective_state(). 723 * 724 * A further ramification is that when a group leader flips between OFF and 725 * !OFF, we need to update all group member times. 726 * 727 * 728 * NOTE: perf_event_time() is based on the (cgroup) context time, and thus we 729 * need to make sure the relevant context time is updated before we try and 730 * update our timestamps. 731 */ 732 733 static __always_inline enum perf_event_state 734 __perf_effective_state(struct perf_event *event) 735 { 736 struct perf_event *leader = event->group_leader; 737 738 if (leader->state <= PERF_EVENT_STATE_OFF) 739 return leader->state; 740 741 return event->state; 742 } 743 744 static __always_inline void 745 __perf_update_times(struct perf_event *event, u64 now, u64 *enabled, u64 *running) 746 { 747 enum perf_event_state state = __perf_effective_state(event); 748 u64 delta = now - event->tstamp; 749 750 *enabled = event->total_time_enabled; 751 if (state >= PERF_EVENT_STATE_INACTIVE) 752 *enabled += delta; 753 754 *running = event->total_time_running; 755 if (state >= PERF_EVENT_STATE_ACTIVE) 756 *running += delta; 757 } 758 759 static void perf_event_update_time(struct perf_event *event) 760 { 761 u64 now = perf_event_time(event); 762 763 __perf_update_times(event, now, &event->total_time_enabled, 764 &event->total_time_running); 765 event->tstamp = now; 766 } 767 768 static void perf_event_update_sibling_time(struct perf_event *leader) 769 { 770 struct perf_event *sibling; 771 772 for_each_sibling_event(sibling, leader) 773 perf_event_update_time(sibling); 774 } 775 776 static void 777 perf_event_set_state(struct perf_event *event, enum perf_event_state state) 778 { 779 if (event->state == state) 780 return; 781 782 perf_event_update_time(event); 783 /* 784 * If a group leader gets enabled/disabled all its siblings 785 * are affected too. 786 */ 787 if ((event->state < 0) ^ (state < 0)) 788 perf_event_update_sibling_time(event); 789 790 WRITE_ONCE(event->state, state); 791 } 792 793 /* 794 * UP store-release, load-acquire 795 */ 796 797 #define __store_release(ptr, val) \ 798 do { \ 799 barrier(); \ 800 WRITE_ONCE(*(ptr), (val)); \ 801 } while (0) 802 803 #define __load_acquire(ptr) \ 804 ({ \ 805 __unqual_scalar_typeof(*(ptr)) ___p = READ_ONCE(*(ptr)); \ 806 barrier(); \ 807 ___p; \ 808 }) 809 810 static bool perf_skip_pmu_ctx(struct perf_event_pmu_context *pmu_ctx, 811 enum event_type_t event_type) 812 { 813 if ((event_type & EVENT_CGROUP) && !pmu_ctx->nr_cgroups) 814 return true; 815 if ((event_type & EVENT_GUEST) && 816 !(pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU)) 817 return true; 818 return false; 819 } 820 821 #define for_each_epc(_epc, _ctx, _pmu, _event_type) \ 822 list_for_each_entry(_epc, &((_ctx)->pmu_ctx_list), pmu_ctx_entry) \ 823 if (perf_skip_pmu_ctx(_epc, _event_type)) \ 824 continue; \ 825 else if (_pmu && _epc->pmu != _pmu) \ 826 continue; \ 827 else 828 829 static void perf_ctx_disable(struct perf_event_context *ctx, 830 enum event_type_t event_type) 831 { 832 struct perf_event_pmu_context *pmu_ctx; 833 834 for_each_epc(pmu_ctx, ctx, NULL, event_type) 835 perf_pmu_disable(pmu_ctx->pmu); 836 } 837 838 static void perf_ctx_enable(struct perf_event_context *ctx, 839 enum event_type_t event_type) 840 { 841 struct perf_event_pmu_context *pmu_ctx; 842 843 for_each_epc(pmu_ctx, ctx, NULL, event_type) 844 perf_pmu_enable(pmu_ctx->pmu); 845 } 846 847 static void ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type); 848 static void ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type); 849 850 static inline void update_perf_time_ctx(struct perf_time_ctx *time, u64 now, bool adv) 851 { 852 if (adv) 853 time->time += now - time->stamp; 854 time->stamp = now; 855 856 /* 857 * The above: time' = time + (now - timestamp), can be re-arranged 858 * into: time` = now + (time - timestamp), which gives a single value 859 * offset to compute future time without locks on. 860 * 861 * See perf_event_time_now(), which can be used from NMI context where 862 * it's (obviously) not possible to acquire ctx->lock in order to read 863 * both the above values in a consistent manner. 864 */ 865 WRITE_ONCE(time->offset, time->time - time->stamp); 866 } 867 868 static_assert(offsetof(struct perf_event_context, timeguest) - 869 offsetof(struct perf_event_context, time) == 870 sizeof(struct perf_time_ctx)); 871 872 #define T_TOTAL 0 873 #define T_GUEST 1 874 875 static inline u64 __perf_event_time_ctx(struct perf_event *event, 876 struct perf_time_ctx *times) 877 { 878 u64 time = times[T_TOTAL].time; 879 880 if (event->attr.exclude_guest) 881 time -= times[T_GUEST].time; 882 883 return time; 884 } 885 886 static inline u64 __perf_event_time_ctx_now(struct perf_event *event, 887 struct perf_time_ctx *times, 888 u64 now) 889 { 890 if (is_guest_mediated_pmu_loaded() && event->attr.exclude_guest) { 891 /* 892 * (now + times[total].offset) - (now + times[guest].offset) := 893 * times[total].offset - times[guest].offset 894 */ 895 return READ_ONCE(times[T_TOTAL].offset) - READ_ONCE(times[T_GUEST].offset); 896 } 897 898 return now + READ_ONCE(times[T_TOTAL].offset); 899 } 900 901 #ifdef CONFIG_CGROUP_PERF 902 903 static inline bool 904 perf_cgroup_match(struct perf_event *event) 905 { 906 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 907 908 /* @event doesn't care about cgroup */ 909 if (!event->cgrp) 910 return true; 911 912 /* wants specific cgroup scope but @cpuctx isn't associated with any */ 913 if (!cpuctx->cgrp) 914 return false; 915 916 /* 917 * Cgroup scoping is recursive. An event enabled for a cgroup is 918 * also enabled for all its descendant cgroups. If @cpuctx's 919 * cgroup is a descendant of @event's (the test covers identity 920 * case), it's a match. 921 */ 922 return cgroup_is_descendant(cpuctx->cgrp->css.cgroup, 923 event->cgrp->css.cgroup); 924 } 925 926 static inline void perf_detach_cgroup(struct perf_event *event) 927 { 928 css_put(&event->cgrp->css); 929 event->cgrp = NULL; 930 } 931 932 static inline int is_cgroup_event(struct perf_event *event) 933 { 934 return event->cgrp != NULL; 935 } 936 937 static_assert(offsetof(struct perf_cgroup_info, timeguest) - 938 offsetof(struct perf_cgroup_info, time) == 939 sizeof(struct perf_time_ctx)); 940 941 static inline u64 perf_cgroup_event_time(struct perf_event *event) 942 { 943 struct perf_cgroup_info *t; 944 945 t = per_cpu_ptr(event->cgrp->info, event->cpu); 946 return __perf_event_time_ctx(event, &t->time); 947 } 948 949 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now) 950 { 951 struct perf_cgroup_info *t; 952 953 t = per_cpu_ptr(event->cgrp->info, event->cpu); 954 if (!__load_acquire(&t->active)) 955 return __perf_event_time_ctx(event, &t->time); 956 957 return __perf_event_time_ctx_now(event, &t->time, now); 958 } 959 960 static inline void __update_cgrp_guest_time(struct perf_cgroup_info *info, u64 now, bool adv) 961 { 962 update_perf_time_ctx(&info->timeguest, now, adv); 963 } 964 965 static inline void update_cgrp_time(struct perf_cgroup_info *info, u64 now) 966 { 967 update_perf_time_ctx(&info->time, now, true); 968 if (is_guest_mediated_pmu_loaded()) 969 __update_cgrp_guest_time(info, now, true); 970 } 971 972 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, bool final) 973 { 974 struct perf_cgroup *cgrp = cpuctx->cgrp; 975 struct cgroup_subsys_state *css; 976 struct perf_cgroup_info *info; 977 978 if (cgrp) { 979 u64 now = perf_clock(); 980 981 for (css = &cgrp->css; css; css = css->parent) { 982 cgrp = container_of(css, struct perf_cgroup, css); 983 info = this_cpu_ptr(cgrp->info); 984 985 update_cgrp_time(info, now); 986 if (final) 987 __store_release(&info->active, 0); 988 } 989 } 990 } 991 992 static inline void update_cgrp_time_from_event(struct perf_event *event) 993 { 994 struct perf_cgroup_info *info; 995 996 /* 997 * ensure we access cgroup data only when needed and 998 * when we know the cgroup is pinned (css_get) 999 */ 1000 if (!is_cgroup_event(event)) 1001 return; 1002 1003 info = this_cpu_ptr(event->cgrp->info); 1004 /* 1005 * Do not update time when cgroup is not active 1006 */ 1007 if (info->active) 1008 update_cgrp_time(info, perf_clock()); 1009 } 1010 1011 static inline void 1012 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx, bool guest) 1013 { 1014 struct perf_event_context *ctx = &cpuctx->ctx; 1015 struct perf_cgroup *cgrp = cpuctx->cgrp; 1016 struct perf_cgroup_info *info; 1017 struct cgroup_subsys_state *css; 1018 1019 /* 1020 * ctx->lock held by caller 1021 * ensure we do not access cgroup data 1022 * unless we have the cgroup pinned (css_get) 1023 */ 1024 if (!cgrp) 1025 return; 1026 1027 WARN_ON_ONCE(!ctx->nr_cgroups); 1028 1029 for (css = &cgrp->css; css; css = css->parent) { 1030 cgrp = container_of(css, struct perf_cgroup, css); 1031 info = this_cpu_ptr(cgrp->info); 1032 if (guest) { 1033 __update_cgrp_guest_time(info, ctx->time.stamp, false); 1034 } else { 1035 update_perf_time_ctx(&info->time, ctx->time.stamp, false); 1036 __store_release(&info->active, 1); 1037 } 1038 } 1039 } 1040 1041 /* 1042 * reschedule events based on the cgroup constraint of task. 1043 */ 1044 static void perf_cgroup_switch(struct task_struct *task) 1045 { 1046 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 1047 struct perf_cgroup *cgrp; 1048 1049 /* 1050 * cpuctx->cgrp is set when the first cgroup event enabled, 1051 * and is cleared when the last cgroup event disabled. 1052 */ 1053 if (READ_ONCE(cpuctx->cgrp) == NULL) 1054 return; 1055 1056 cgrp = perf_cgroup_from_task(task, NULL); 1057 if (READ_ONCE(cpuctx->cgrp) == cgrp) 1058 return; 1059 1060 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx); 1061 /* 1062 * Re-check, could've raced vs perf_remove_from_context(). 1063 */ 1064 if (READ_ONCE(cpuctx->cgrp) == NULL) 1065 return; 1066 1067 WARN_ON_ONCE(cpuctx->ctx.nr_cgroups == 0); 1068 perf_ctx_disable(&cpuctx->ctx, EVENT_CGROUP); 1069 1070 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP); 1071 /* 1072 * must not be done before ctxswout due 1073 * to update_cgrp_time_from_cpuctx() in 1074 * ctx_sched_out() 1075 */ 1076 cpuctx->cgrp = cgrp; 1077 /* 1078 * set cgrp before ctxsw in to allow 1079 * perf_cgroup_set_timestamp() in ctx_sched_in() 1080 * to not have to pass task around 1081 */ 1082 ctx_sched_in(&cpuctx->ctx, NULL, EVENT_ALL|EVENT_CGROUP); 1083 1084 perf_ctx_enable(&cpuctx->ctx, EVENT_CGROUP); 1085 } 1086 1087 static int perf_cgroup_ensure_storage(struct perf_event *event, 1088 struct cgroup_subsys_state *css) 1089 { 1090 struct perf_cpu_context *cpuctx; 1091 struct perf_event **storage; 1092 int cpu, heap_size, ret = 0; 1093 1094 /* 1095 * Allow storage to have sufficient space for an iterator for each 1096 * possibly nested cgroup plus an iterator for events with no cgroup. 1097 */ 1098 for (heap_size = 1; css; css = css->parent) 1099 heap_size++; 1100 1101 for_each_possible_cpu(cpu) { 1102 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 1103 if (heap_size <= cpuctx->heap_size) 1104 continue; 1105 1106 storage = kmalloc_node(heap_size * sizeof(struct perf_event *), 1107 GFP_KERNEL, cpu_to_node(cpu)); 1108 if (!storage) { 1109 ret = -ENOMEM; 1110 break; 1111 } 1112 1113 raw_spin_lock_irq(&cpuctx->ctx.lock); 1114 if (cpuctx->heap_size < heap_size) { 1115 swap(cpuctx->heap, storage); 1116 if (storage == cpuctx->heap_default) 1117 storage = NULL; 1118 cpuctx->heap_size = heap_size; 1119 } 1120 raw_spin_unlock_irq(&cpuctx->ctx.lock); 1121 1122 kfree(storage); 1123 } 1124 1125 return ret; 1126 } 1127 1128 static inline int perf_cgroup_connect(int fd, struct perf_event *event, 1129 struct perf_event_attr *attr, 1130 struct perf_event *group_leader) 1131 { 1132 struct perf_cgroup *cgrp; 1133 struct cgroup_subsys_state *css; 1134 CLASS(fd, f)(fd); 1135 int ret = 0; 1136 1137 if (fd_empty(f)) 1138 return -EBADF; 1139 1140 css = css_tryget_online_from_dir(fd_file(f)->f_path.dentry, 1141 &perf_event_cgrp_subsys); 1142 if (IS_ERR(css)) 1143 return PTR_ERR(css); 1144 1145 ret = perf_cgroup_ensure_storage(event, css); 1146 if (ret) 1147 return ret; 1148 1149 cgrp = container_of(css, struct perf_cgroup, css); 1150 event->cgrp = cgrp; 1151 1152 /* 1153 * all events in a group must monitor 1154 * the same cgroup because a task belongs 1155 * to only one perf cgroup at a time 1156 */ 1157 if (group_leader && group_leader->cgrp != cgrp) { 1158 perf_detach_cgroup(event); 1159 ret = -EINVAL; 1160 } 1161 return ret; 1162 } 1163 1164 static inline void 1165 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx) 1166 { 1167 struct perf_cpu_context *cpuctx; 1168 1169 if (!is_cgroup_event(event)) 1170 return; 1171 1172 event->pmu_ctx->nr_cgroups++; 1173 1174 /* 1175 * Because cgroup events are always per-cpu events, 1176 * @ctx == &cpuctx->ctx. 1177 */ 1178 cpuctx = container_of(ctx, struct perf_cpu_context, ctx); 1179 1180 if (ctx->nr_cgroups++) 1181 return; 1182 1183 cpuctx->cgrp = perf_cgroup_from_task(current, ctx); 1184 } 1185 1186 static inline void 1187 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx) 1188 { 1189 struct perf_cpu_context *cpuctx; 1190 1191 if (!is_cgroup_event(event)) 1192 return; 1193 1194 event->pmu_ctx->nr_cgroups--; 1195 1196 /* 1197 * Because cgroup events are always per-cpu events, 1198 * @ctx == &cpuctx->ctx. 1199 */ 1200 cpuctx = container_of(ctx, struct perf_cpu_context, ctx); 1201 1202 if (--ctx->nr_cgroups) 1203 return; 1204 1205 cpuctx->cgrp = NULL; 1206 } 1207 1208 #else /* !CONFIG_CGROUP_PERF */ 1209 1210 static inline bool 1211 perf_cgroup_match(struct perf_event *event) 1212 { 1213 return true; 1214 } 1215 1216 static inline void perf_detach_cgroup(struct perf_event *event) 1217 {} 1218 1219 static inline int is_cgroup_event(struct perf_event *event) 1220 { 1221 return 0; 1222 } 1223 1224 static inline void update_cgrp_time_from_event(struct perf_event *event) 1225 { 1226 } 1227 1228 static inline void update_cgrp_time_from_cpuctx(struct perf_cpu_context *cpuctx, 1229 bool final) 1230 { 1231 } 1232 1233 static inline int perf_cgroup_connect(pid_t pid, struct perf_event *event, 1234 struct perf_event_attr *attr, 1235 struct perf_event *group_leader) 1236 { 1237 return -EINVAL; 1238 } 1239 1240 static inline void 1241 perf_cgroup_set_timestamp(struct perf_cpu_context *cpuctx, bool guest) 1242 { 1243 } 1244 1245 static inline u64 perf_cgroup_event_time(struct perf_event *event) 1246 { 1247 return 0; 1248 } 1249 1250 static inline u64 perf_cgroup_event_time_now(struct perf_event *event, u64 now) 1251 { 1252 return 0; 1253 } 1254 1255 static inline void 1256 perf_cgroup_event_enable(struct perf_event *event, struct perf_event_context *ctx) 1257 { 1258 } 1259 1260 static inline void 1261 perf_cgroup_event_disable(struct perf_event *event, struct perf_event_context *ctx) 1262 { 1263 } 1264 1265 static void perf_cgroup_switch(struct task_struct *task) 1266 { 1267 } 1268 #endif 1269 1270 /* 1271 * set default to be dependent on timer tick just 1272 * like original code 1273 */ 1274 #define PERF_CPU_HRTIMER (1000 / HZ) 1275 /* 1276 * function must be called with interrupts disabled 1277 */ 1278 static enum hrtimer_restart perf_mux_hrtimer_handler(struct hrtimer *hr) 1279 { 1280 struct perf_cpu_pmu_context *cpc; 1281 bool rotations; 1282 1283 lockdep_assert_irqs_disabled(); 1284 1285 cpc = container_of(hr, struct perf_cpu_pmu_context, hrtimer); 1286 rotations = perf_rotate_context(cpc); 1287 1288 raw_spin_lock(&cpc->hrtimer_lock); 1289 if (rotations) 1290 hrtimer_forward_now(hr, cpc->hrtimer_interval); 1291 else 1292 cpc->hrtimer_active = 0; 1293 raw_spin_unlock(&cpc->hrtimer_lock); 1294 1295 return rotations ? HRTIMER_RESTART : HRTIMER_NORESTART; 1296 } 1297 1298 static void __perf_mux_hrtimer_init(struct perf_cpu_pmu_context *cpc, int cpu) 1299 { 1300 struct hrtimer *timer = &cpc->hrtimer; 1301 struct pmu *pmu = cpc->epc.pmu; 1302 u64 interval; 1303 1304 /* 1305 * check default is sane, if not set then force to 1306 * default interval (1/tick) 1307 */ 1308 interval = pmu->hrtimer_interval_ms; 1309 if (interval < 1) 1310 interval = pmu->hrtimer_interval_ms = PERF_CPU_HRTIMER; 1311 1312 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * interval); 1313 1314 raw_spin_lock_init(&cpc->hrtimer_lock); 1315 hrtimer_setup(timer, perf_mux_hrtimer_handler, CLOCK_MONOTONIC, 1316 HRTIMER_MODE_ABS_PINNED_HARD); 1317 } 1318 1319 static int perf_mux_hrtimer_restart(struct perf_cpu_pmu_context *cpc) 1320 { 1321 struct hrtimer *timer = &cpc->hrtimer; 1322 unsigned long flags; 1323 1324 raw_spin_lock_irqsave(&cpc->hrtimer_lock, flags); 1325 if (!cpc->hrtimer_active) { 1326 cpc->hrtimer_active = 1; 1327 hrtimer_forward_now(timer, cpc->hrtimer_interval); 1328 hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED_HARD); 1329 } 1330 raw_spin_unlock_irqrestore(&cpc->hrtimer_lock, flags); 1331 1332 return 0; 1333 } 1334 1335 static int perf_mux_hrtimer_restart_ipi(void *arg) 1336 { 1337 return perf_mux_hrtimer_restart(arg); 1338 } 1339 1340 static __always_inline struct perf_cpu_pmu_context *this_cpc(struct pmu *pmu) 1341 { 1342 return *this_cpu_ptr(pmu->cpu_pmu_context); 1343 } 1344 1345 void perf_pmu_disable(struct pmu *pmu) 1346 { 1347 int *count = &this_cpc(pmu)->pmu_disable_count; 1348 if (!(*count)++) 1349 pmu->pmu_disable(pmu); 1350 } 1351 1352 void perf_pmu_enable(struct pmu *pmu) 1353 { 1354 int *count = &this_cpc(pmu)->pmu_disable_count; 1355 if (!--(*count)) 1356 pmu->pmu_enable(pmu); 1357 } 1358 1359 static void perf_assert_pmu_disabled(struct pmu *pmu) 1360 { 1361 int *count = &this_cpc(pmu)->pmu_disable_count; 1362 WARN_ON_ONCE(*count == 0); 1363 } 1364 1365 static inline void perf_pmu_read(struct perf_event *event) 1366 { 1367 if (event->state == PERF_EVENT_STATE_ACTIVE) 1368 event->pmu->read(event); 1369 } 1370 1371 static void get_ctx(struct perf_event_context *ctx) 1372 { 1373 refcount_inc(&ctx->refcount); 1374 } 1375 1376 static void free_ctx(struct rcu_head *head) 1377 { 1378 struct perf_event_context *ctx; 1379 1380 ctx = container_of(head, struct perf_event_context, rcu_head); 1381 kfree(ctx); 1382 } 1383 1384 static void put_ctx(struct perf_event_context *ctx) 1385 { 1386 if (refcount_dec_and_test(&ctx->refcount)) { 1387 if (ctx->parent_ctx) 1388 put_ctx(ctx->parent_ctx); 1389 if (ctx->task && ctx->task != TASK_TOMBSTONE) 1390 put_task_struct(ctx->task); 1391 call_rcu(&ctx->rcu_head, free_ctx); 1392 } else { 1393 smp_mb__after_atomic(); /* pairs with wait_var_event() */ 1394 if (ctx->task == TASK_TOMBSTONE) 1395 wake_up_var(&ctx->refcount); 1396 } 1397 } 1398 1399 /* 1400 * Because of perf_event::ctx migration in sys_perf_event_open::move_group and 1401 * perf_pmu_migrate_context() we need some magic. 1402 * 1403 * Those places that change perf_event::ctx will hold both 1404 * perf_event_ctx::mutex of the 'old' and 'new' ctx value. 1405 * 1406 * Lock ordering is by mutex address. There are two other sites where 1407 * perf_event_context::mutex nests and those are: 1408 * 1409 * - perf_event_exit_task_context() [ child , 0 ] 1410 * perf_event_exit_event() 1411 * put_event() [ parent, 1 ] 1412 * 1413 * - perf_event_init_context() [ parent, 0 ] 1414 * inherit_task_group() 1415 * inherit_group() 1416 * inherit_event() 1417 * perf_event_alloc() 1418 * perf_init_event() 1419 * perf_try_init_event() [ child , 1 ] 1420 * 1421 * While it appears there is an obvious deadlock here -- the parent and child 1422 * nesting levels are inverted between the two. This is in fact safe because 1423 * life-time rules separate them. That is an exiting task cannot fork, and a 1424 * spawning task cannot (yet) exit. 1425 * 1426 * But remember that these are parent<->child context relations, and 1427 * migration does not affect children, therefore these two orderings should not 1428 * interact. 1429 * 1430 * The change in perf_event::ctx does not affect children (as claimed above) 1431 * because the sys_perf_event_open() case will install a new event and break 1432 * the ctx parent<->child relation, and perf_pmu_migrate_context() is only 1433 * concerned with cpuctx and that doesn't have children. 1434 * 1435 * The places that change perf_event::ctx will issue: 1436 * 1437 * perf_remove_from_context(); 1438 * synchronize_rcu(); 1439 * perf_install_in_context(); 1440 * 1441 * to affect the change. The remove_from_context() + synchronize_rcu() should 1442 * quiesce the event, after which we can install it in the new location. This 1443 * means that only external vectors (perf_fops, prctl) can perturb the event 1444 * while in transit. Therefore all such accessors should also acquire 1445 * perf_event_context::mutex to serialize against this. 1446 * 1447 * However; because event->ctx can change while we're waiting to acquire 1448 * ctx->mutex we must be careful and use the below perf_event_ctx_lock() 1449 * function. 1450 * 1451 * Lock order: 1452 * exec_update_lock 1453 * task_struct::perf_event_mutex 1454 * perf_event_context::mutex 1455 * perf_event::child_mutex; 1456 * perf_event_context::lock 1457 * mmap_lock 1458 * perf_event::mmap_mutex 1459 * perf_buffer::aux_mutex 1460 * perf_addr_filters_head::lock 1461 * 1462 * cpu_hotplug_lock 1463 * pmus_lock 1464 * cpuctx->mutex / perf_event_context::mutex 1465 */ 1466 static struct perf_event_context * 1467 perf_event_ctx_lock_nested(struct perf_event *event, int nesting) 1468 { 1469 struct perf_event_context *ctx; 1470 1471 again: 1472 rcu_read_lock(); 1473 ctx = READ_ONCE(event->ctx); 1474 if (!refcount_inc_not_zero(&ctx->refcount)) { 1475 rcu_read_unlock(); 1476 goto again; 1477 } 1478 rcu_read_unlock(); 1479 1480 mutex_lock_nested(&ctx->mutex, nesting); 1481 if (event->ctx != ctx) { 1482 mutex_unlock(&ctx->mutex); 1483 put_ctx(ctx); 1484 goto again; 1485 } 1486 1487 return ctx; 1488 } 1489 1490 static inline struct perf_event_context * 1491 perf_event_ctx_lock(struct perf_event *event) 1492 { 1493 return perf_event_ctx_lock_nested(event, 0); 1494 } 1495 1496 static void perf_event_ctx_unlock(struct perf_event *event, 1497 struct perf_event_context *ctx) 1498 { 1499 mutex_unlock(&ctx->mutex); 1500 put_ctx(ctx); 1501 } 1502 1503 /* 1504 * This must be done under the ctx->lock, such as to serialize against 1505 * context_equiv(), therefore we cannot call put_ctx() since that might end up 1506 * calling scheduler related locks and ctx->lock nests inside those. 1507 */ 1508 static __must_check struct perf_event_context * 1509 unclone_ctx(struct perf_event_context *ctx) 1510 { 1511 struct perf_event_context *parent_ctx = ctx->parent_ctx; 1512 1513 lockdep_assert_held(&ctx->lock); 1514 1515 if (parent_ctx) 1516 ctx->parent_ctx = NULL; 1517 ctx->generation++; 1518 1519 return parent_ctx; 1520 } 1521 1522 static u32 perf_event_pid_type(struct perf_event *event, struct task_struct *p, 1523 enum pid_type type) 1524 { 1525 u32 nr; 1526 /* 1527 * only top level events have the pid namespace they were created in 1528 */ 1529 if (event->parent) 1530 event = event->parent; 1531 1532 nr = __task_pid_nr_ns(p, type, event->ns); 1533 /* avoid -1 if it is idle thread or runs in another ns */ 1534 if (!nr && !pid_alive(p)) 1535 nr = -1; 1536 return nr; 1537 } 1538 1539 static u32 perf_event_pid(struct perf_event *event, struct task_struct *p) 1540 { 1541 return perf_event_pid_type(event, p, PIDTYPE_TGID); 1542 } 1543 1544 static u32 perf_event_tid(struct perf_event *event, struct task_struct *p) 1545 { 1546 return perf_event_pid_type(event, p, PIDTYPE_PID); 1547 } 1548 1549 /* 1550 * If we inherit events we want to return the parent event id 1551 * to userspace. 1552 */ 1553 static u64 primary_event_id(struct perf_event *event) 1554 { 1555 u64 id = event->id; 1556 1557 if (event->parent) 1558 id = event->parent->id; 1559 1560 return id; 1561 } 1562 1563 /* 1564 * Get the perf_event_context for a task and lock it. 1565 * 1566 * This has to cope with the fact that until it is locked, 1567 * the context could get moved to another task. 1568 */ 1569 static struct perf_event_context * 1570 perf_lock_task_context(struct task_struct *task, unsigned long *flags) 1571 { 1572 struct perf_event_context *ctx; 1573 1574 retry: 1575 /* 1576 * One of the few rules of preemptible RCU is that one cannot do 1577 * rcu_read_unlock() while holding a scheduler (or nested) lock when 1578 * part of the read side critical section was irqs-enabled -- see 1579 * rcu_read_unlock_special(). 1580 * 1581 * Since ctx->lock nests under rq->lock we must ensure the entire read 1582 * side critical section has interrupts disabled. 1583 */ 1584 local_irq_save(*flags); 1585 rcu_read_lock(); 1586 ctx = rcu_dereference(task->perf_event_ctxp); 1587 if (ctx) { 1588 /* 1589 * If this context is a clone of another, it might 1590 * get swapped for another underneath us by 1591 * perf_event_task_sched_out, though the 1592 * rcu_read_lock() protects us from any context 1593 * getting freed. Lock the context and check if it 1594 * got swapped before we could get the lock, and retry 1595 * if so. If we locked the right context, then it 1596 * can't get swapped on us any more. 1597 */ 1598 raw_spin_lock(&ctx->lock); 1599 if (ctx != rcu_dereference(task->perf_event_ctxp)) { 1600 raw_spin_unlock(&ctx->lock); 1601 rcu_read_unlock(); 1602 local_irq_restore(*flags); 1603 goto retry; 1604 } 1605 1606 if (ctx->task == TASK_TOMBSTONE || 1607 !refcount_inc_not_zero(&ctx->refcount)) { 1608 raw_spin_unlock(&ctx->lock); 1609 ctx = NULL; 1610 } else { 1611 WARN_ON_ONCE(ctx->task != task); 1612 } 1613 } 1614 rcu_read_unlock(); 1615 if (!ctx) 1616 local_irq_restore(*flags); 1617 return ctx; 1618 } 1619 1620 /* 1621 * Get the context for a task and increment its pin_count so it 1622 * can't get swapped to another task. This also increments its 1623 * reference count so that the context can't get freed. 1624 */ 1625 static struct perf_event_context * 1626 perf_pin_task_context(struct task_struct *task) 1627 { 1628 struct perf_event_context *ctx; 1629 unsigned long flags; 1630 1631 ctx = perf_lock_task_context(task, &flags); 1632 if (ctx) { 1633 ++ctx->pin_count; 1634 raw_spin_unlock_irqrestore(&ctx->lock, flags); 1635 } 1636 return ctx; 1637 } 1638 1639 static void perf_unpin_context(struct perf_event_context *ctx) 1640 { 1641 unsigned long flags; 1642 1643 raw_spin_lock_irqsave(&ctx->lock, flags); 1644 --ctx->pin_count; 1645 raw_spin_unlock_irqrestore(&ctx->lock, flags); 1646 } 1647 1648 /* 1649 * Update the record of the current time in a context. 1650 */ 1651 static void __update_context_time(struct perf_event_context *ctx, bool adv) 1652 { 1653 lockdep_assert_held(&ctx->lock); 1654 1655 update_perf_time_ctx(&ctx->time, perf_clock(), adv); 1656 } 1657 1658 static void __update_context_guest_time(struct perf_event_context *ctx, bool adv) 1659 { 1660 lockdep_assert_held(&ctx->lock); 1661 1662 /* must be called after __update_context_time(); */ 1663 update_perf_time_ctx(&ctx->timeguest, ctx->time.stamp, adv); 1664 } 1665 1666 static void update_context_time(struct perf_event_context *ctx) 1667 { 1668 __update_context_time(ctx, true); 1669 if (is_guest_mediated_pmu_loaded()) 1670 __update_context_guest_time(ctx, true); 1671 } 1672 1673 static u64 perf_event_time(struct perf_event *event) 1674 { 1675 struct perf_event_context *ctx = event->ctx; 1676 1677 if (unlikely(!ctx)) 1678 return 0; 1679 1680 if (is_cgroup_event(event)) 1681 return perf_cgroup_event_time(event); 1682 1683 return __perf_event_time_ctx(event, &ctx->time); 1684 } 1685 1686 static u64 perf_event_time_now(struct perf_event *event, u64 now) 1687 { 1688 struct perf_event_context *ctx = event->ctx; 1689 1690 if (unlikely(!ctx)) 1691 return 0; 1692 1693 if (is_cgroup_event(event)) 1694 return perf_cgroup_event_time_now(event, now); 1695 1696 if (!(__load_acquire(&ctx->is_active) & EVENT_TIME)) 1697 return __perf_event_time_ctx(event, &ctx->time); 1698 1699 return __perf_event_time_ctx_now(event, &ctx->time, now); 1700 } 1701 1702 static enum event_type_t get_event_type(struct perf_event *event) 1703 { 1704 struct perf_event_context *ctx = event->ctx; 1705 enum event_type_t event_type; 1706 1707 lockdep_assert_held(&ctx->lock); 1708 1709 /* 1710 * It's 'group type', really, because if our group leader is 1711 * pinned, so are we. 1712 */ 1713 if (event->group_leader != event) 1714 event = event->group_leader; 1715 1716 event_type = event->attr.pinned ? EVENT_PINNED : EVENT_FLEXIBLE; 1717 if (!ctx->task) 1718 event_type |= EVENT_CPU; 1719 1720 return event_type; 1721 } 1722 1723 /* 1724 * Helper function to initialize event group nodes. 1725 */ 1726 static void init_event_group(struct perf_event *event) 1727 { 1728 RB_CLEAR_NODE(&event->group_node); 1729 event->group_index = 0; 1730 } 1731 1732 /* 1733 * Extract pinned or flexible groups from the context 1734 * based on event attrs bits. 1735 */ 1736 static struct perf_event_groups * 1737 get_event_groups(struct perf_event *event, struct perf_event_context *ctx) 1738 { 1739 if (event->attr.pinned) 1740 return &ctx->pinned_groups; 1741 else 1742 return &ctx->flexible_groups; 1743 } 1744 1745 /* 1746 * Helper function to initializes perf_event_group trees. 1747 */ 1748 static void perf_event_groups_init(struct perf_event_groups *groups) 1749 { 1750 groups->tree = RB_ROOT; 1751 groups->index = 0; 1752 } 1753 1754 static inline struct cgroup *event_cgroup(const struct perf_event *event) 1755 { 1756 struct cgroup *cgroup = NULL; 1757 1758 #ifdef CONFIG_CGROUP_PERF 1759 if (event->cgrp) 1760 cgroup = event->cgrp->css.cgroup; 1761 #endif 1762 1763 return cgroup; 1764 } 1765 1766 /* 1767 * Compare function for event groups; 1768 * 1769 * Implements complex key that first sorts by CPU and then by virtual index 1770 * which provides ordering when rotating groups for the same CPU. 1771 */ 1772 static __always_inline int 1773 perf_event_groups_cmp(const int left_cpu, const struct pmu *left_pmu, 1774 const struct cgroup *left_cgroup, const u64 left_group_index, 1775 const struct perf_event *right) 1776 { 1777 if (left_cpu < right->cpu) 1778 return -1; 1779 if (left_cpu > right->cpu) 1780 return 1; 1781 1782 if (left_pmu) { 1783 if (left_pmu < right->pmu_ctx->pmu) 1784 return -1; 1785 if (left_pmu > right->pmu_ctx->pmu) 1786 return 1; 1787 } 1788 1789 #ifdef CONFIG_CGROUP_PERF 1790 { 1791 const struct cgroup *right_cgroup = event_cgroup(right); 1792 1793 if (left_cgroup != right_cgroup) { 1794 if (!left_cgroup) { 1795 /* 1796 * Left has no cgroup but right does, no 1797 * cgroups come first. 1798 */ 1799 return -1; 1800 } 1801 if (!right_cgroup) { 1802 /* 1803 * Right has no cgroup but left does, no 1804 * cgroups come first. 1805 */ 1806 return 1; 1807 } 1808 /* Two dissimilar cgroups, order by id. */ 1809 if (cgroup_id(left_cgroup) < cgroup_id(right_cgroup)) 1810 return -1; 1811 1812 return 1; 1813 } 1814 } 1815 #endif 1816 1817 if (left_group_index < right->group_index) 1818 return -1; 1819 if (left_group_index > right->group_index) 1820 return 1; 1821 1822 return 0; 1823 } 1824 1825 #define __node_2_pe(node) \ 1826 rb_entry((node), struct perf_event, group_node) 1827 1828 static inline bool __group_less(struct rb_node *a, const struct rb_node *b) 1829 { 1830 struct perf_event *e = __node_2_pe(a); 1831 return perf_event_groups_cmp(e->cpu, e->pmu_ctx->pmu, event_cgroup(e), 1832 e->group_index, __node_2_pe(b)) < 0; 1833 } 1834 1835 struct __group_key { 1836 int cpu; 1837 struct pmu *pmu; 1838 struct cgroup *cgroup; 1839 }; 1840 1841 static inline int __group_cmp(const void *key, const struct rb_node *node) 1842 { 1843 const struct __group_key *a = key; 1844 const struct perf_event *b = __node_2_pe(node); 1845 1846 /* partial/subtree match: @cpu, @pmu, @cgroup; ignore: @group_index */ 1847 return perf_event_groups_cmp(a->cpu, a->pmu, a->cgroup, b->group_index, b); 1848 } 1849 1850 static inline int 1851 __group_cmp_ignore_cgroup(const void *key, const struct rb_node *node) 1852 { 1853 const struct __group_key *a = key; 1854 const struct perf_event *b = __node_2_pe(node); 1855 1856 /* partial/subtree match: @cpu, @pmu, ignore: @cgroup, @group_index */ 1857 return perf_event_groups_cmp(a->cpu, a->pmu, event_cgroup(b), 1858 b->group_index, b); 1859 } 1860 1861 /* 1862 * Insert @event into @groups' tree; using 1863 * {@event->cpu, @event->pmu_ctx->pmu, event_cgroup(@event), ++@groups->index} 1864 * as key. This places it last inside the {cpu,pmu,cgroup} subtree. 1865 */ 1866 static void 1867 perf_event_groups_insert(struct perf_event_groups *groups, 1868 struct perf_event *event) 1869 { 1870 event->group_index = ++groups->index; 1871 1872 rb_add(&event->group_node, &groups->tree, __group_less); 1873 } 1874 1875 /* 1876 * Helper function to insert event into the pinned or flexible groups. 1877 */ 1878 static void 1879 add_event_to_groups(struct perf_event *event, struct perf_event_context *ctx) 1880 { 1881 struct perf_event_groups *groups; 1882 1883 groups = get_event_groups(event, ctx); 1884 perf_event_groups_insert(groups, event); 1885 } 1886 1887 /* 1888 * Delete a group from a tree. 1889 */ 1890 static void 1891 perf_event_groups_delete(struct perf_event_groups *groups, 1892 struct perf_event *event) 1893 { 1894 WARN_ON_ONCE(RB_EMPTY_NODE(&event->group_node) || 1895 RB_EMPTY_ROOT(&groups->tree)); 1896 1897 rb_erase(&event->group_node, &groups->tree); 1898 init_event_group(event); 1899 } 1900 1901 /* 1902 * Helper function to delete event from its groups. 1903 */ 1904 static void 1905 del_event_from_groups(struct perf_event *event, struct perf_event_context *ctx) 1906 { 1907 struct perf_event_groups *groups; 1908 1909 groups = get_event_groups(event, ctx); 1910 perf_event_groups_delete(groups, event); 1911 } 1912 1913 /* 1914 * Get the leftmost event in the {cpu,pmu,cgroup} subtree. 1915 */ 1916 static struct perf_event * 1917 perf_event_groups_first(struct perf_event_groups *groups, int cpu, 1918 struct pmu *pmu, struct cgroup *cgrp) 1919 { 1920 struct __group_key key = { 1921 .cpu = cpu, 1922 .pmu = pmu, 1923 .cgroup = cgrp, 1924 }; 1925 struct rb_node *node; 1926 1927 node = rb_find_first(&key, &groups->tree, __group_cmp); 1928 if (node) 1929 return __node_2_pe(node); 1930 1931 return NULL; 1932 } 1933 1934 static struct perf_event * 1935 perf_event_groups_next(struct perf_event *event, struct pmu *pmu) 1936 { 1937 struct __group_key key = { 1938 .cpu = event->cpu, 1939 .pmu = pmu, 1940 .cgroup = event_cgroup(event), 1941 }; 1942 struct rb_node *next; 1943 1944 next = rb_next_match(&key, &event->group_node, __group_cmp); 1945 if (next) 1946 return __node_2_pe(next); 1947 1948 return NULL; 1949 } 1950 1951 #define perf_event_groups_for_cpu_pmu(event, groups, cpu, pmu) \ 1952 for (event = perf_event_groups_first(groups, cpu, pmu, NULL); \ 1953 event; event = perf_event_groups_next(event, pmu)) 1954 1955 /* 1956 * Iterate through the whole groups tree. 1957 */ 1958 #define perf_event_groups_for_each(event, groups) \ 1959 for (event = rb_entry_safe(rb_first(&((groups)->tree)), \ 1960 typeof(*event), group_node); event; \ 1961 event = rb_entry_safe(rb_next(&event->group_node), \ 1962 typeof(*event), group_node)) 1963 1964 /* 1965 * Does the event attribute request inherit with PERF_SAMPLE_READ 1966 */ 1967 static inline bool has_inherit_and_sample_read(struct perf_event_attr *attr) 1968 { 1969 return attr->inherit && (attr->sample_type & PERF_SAMPLE_READ); 1970 } 1971 1972 /* 1973 * Add an event from the lists for its context. 1974 * Must be called with ctx->mutex and ctx->lock held. 1975 */ 1976 static void 1977 list_add_event(struct perf_event *event, struct perf_event_context *ctx) 1978 { 1979 lockdep_assert_held(&ctx->lock); 1980 1981 WARN_ON_ONCE(event->attach_state & PERF_ATTACH_CONTEXT); 1982 event->attach_state |= PERF_ATTACH_CONTEXT; 1983 1984 event->tstamp = perf_event_time(event); 1985 1986 /* 1987 * If we're a stand alone event or group leader, we go to the context 1988 * list, group events are kept attached to the group so that 1989 * perf_group_detach can, at all times, locate all siblings. 1990 */ 1991 if (event->group_leader == event) { 1992 event->group_caps = event->event_caps; 1993 add_event_to_groups(event, ctx); 1994 } 1995 1996 list_add_rcu(&event->event_entry, &ctx->event_list); 1997 ctx->nr_events++; 1998 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT) 1999 ctx->nr_user++; 2000 if (event->attr.inherit_stat) 2001 ctx->nr_stat++; 2002 if (has_inherit_and_sample_read(&event->attr)) 2003 local_inc(&ctx->nr_no_switch_fast); 2004 2005 if (event->state > PERF_EVENT_STATE_OFF) 2006 perf_cgroup_event_enable(event, ctx); 2007 2008 ctx->generation++; 2009 event->pmu_ctx->nr_events++; 2010 } 2011 2012 /* 2013 * Initialize event state based on the perf_event_attr::disabled. 2014 */ 2015 static inline void perf_event__state_init(struct perf_event *event) 2016 { 2017 event->state = event->attr.disabled ? PERF_EVENT_STATE_OFF : 2018 PERF_EVENT_STATE_INACTIVE; 2019 } 2020 2021 static int __perf_event_read_size(u64 read_format, int nr_siblings) 2022 { 2023 int entry = sizeof(u64); /* value */ 2024 int size = 0; 2025 int nr = 1; 2026 2027 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 2028 size += sizeof(u64); 2029 2030 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 2031 size += sizeof(u64); 2032 2033 if (read_format & PERF_FORMAT_ID) 2034 entry += sizeof(u64); 2035 2036 if (read_format & PERF_FORMAT_LOST) 2037 entry += sizeof(u64); 2038 2039 if (read_format & PERF_FORMAT_GROUP) { 2040 nr += nr_siblings; 2041 size += sizeof(u64); 2042 } 2043 2044 /* 2045 * Since perf_event_validate_size() limits this to 16k and inhibits 2046 * adding more siblings, this will never overflow. 2047 */ 2048 return size + nr * entry; 2049 } 2050 2051 static void __perf_event_header_size(struct perf_event *event, u64 sample_type) 2052 { 2053 struct perf_sample_data *data; 2054 u16 size = 0; 2055 2056 if (sample_type & PERF_SAMPLE_IP) 2057 size += sizeof(data->ip); 2058 2059 if (sample_type & PERF_SAMPLE_ADDR) 2060 size += sizeof(data->addr); 2061 2062 if (sample_type & PERF_SAMPLE_PERIOD) 2063 size += sizeof(data->period); 2064 2065 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) 2066 size += sizeof(data->weight.full); 2067 2068 if (sample_type & PERF_SAMPLE_READ) 2069 size += event->read_size; 2070 2071 if (sample_type & PERF_SAMPLE_DATA_SRC) 2072 size += sizeof(data->data_src.val); 2073 2074 if (sample_type & PERF_SAMPLE_TRANSACTION) 2075 size += sizeof(data->txn); 2076 2077 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 2078 size += sizeof(data->phys_addr); 2079 2080 if (sample_type & PERF_SAMPLE_CGROUP) 2081 size += sizeof(data->cgroup); 2082 2083 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) 2084 size += sizeof(data->data_page_size); 2085 2086 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) 2087 size += sizeof(data->code_page_size); 2088 2089 event->header_size = size; 2090 } 2091 2092 /* 2093 * Called at perf_event creation and when events are attached/detached from a 2094 * group. 2095 */ 2096 static void perf_event__header_size(struct perf_event *event) 2097 { 2098 event->read_size = 2099 __perf_event_read_size(event->attr.read_format, 2100 event->group_leader->nr_siblings); 2101 __perf_event_header_size(event, event->attr.sample_type); 2102 } 2103 2104 static void perf_event__id_header_size(struct perf_event *event) 2105 { 2106 struct perf_sample_data *data; 2107 u64 sample_type = event->attr.sample_type; 2108 u16 size = 0; 2109 2110 if (sample_type & PERF_SAMPLE_TID) 2111 size += sizeof(data->tid_entry); 2112 2113 if (sample_type & PERF_SAMPLE_TIME) 2114 size += sizeof(data->time); 2115 2116 if (sample_type & PERF_SAMPLE_IDENTIFIER) 2117 size += sizeof(data->id); 2118 2119 if (sample_type & PERF_SAMPLE_ID) 2120 size += sizeof(data->id); 2121 2122 if (sample_type & PERF_SAMPLE_STREAM_ID) 2123 size += sizeof(data->stream_id); 2124 2125 if (sample_type & PERF_SAMPLE_CPU) 2126 size += sizeof(data->cpu_entry); 2127 2128 event->id_header_size = size; 2129 } 2130 2131 /* 2132 * Check that adding an event to the group does not result in anybody 2133 * overflowing the 64k event limit imposed by the output buffer. 2134 * 2135 * Specifically, check that the read_size for the event does not exceed 16k, 2136 * read_size being the one term that grows with groups size. Since read_size 2137 * depends on per-event read_format, also (re)check the existing events. 2138 * 2139 * This leaves 48k for the constant size fields and things like callchains, 2140 * branch stacks and register sets. 2141 */ 2142 static bool perf_event_validate_size(struct perf_event *event) 2143 { 2144 struct perf_event *sibling, *group_leader = event->group_leader; 2145 2146 if (__perf_event_read_size(event->attr.read_format, 2147 group_leader->nr_siblings + 1) > 16*1024) 2148 return false; 2149 2150 if (__perf_event_read_size(group_leader->attr.read_format, 2151 group_leader->nr_siblings + 1) > 16*1024) 2152 return false; 2153 2154 /* 2155 * When creating a new group leader, group_leader->ctx is initialized 2156 * after the size has been validated, but we cannot safely use 2157 * for_each_sibling_event() until group_leader->ctx is set. A new group 2158 * leader cannot have any siblings yet, so we can safely skip checking 2159 * the non-existent siblings. 2160 */ 2161 if (event == group_leader) 2162 return true; 2163 2164 for_each_sibling_event(sibling, group_leader) { 2165 if (__perf_event_read_size(sibling->attr.read_format, 2166 group_leader->nr_siblings + 1) > 16*1024) 2167 return false; 2168 } 2169 2170 return true; 2171 } 2172 2173 static void perf_group_attach(struct perf_event *event) 2174 { 2175 struct perf_event *group_leader = event->group_leader, *pos; 2176 2177 lockdep_assert_held(&event->ctx->lock); 2178 2179 /* 2180 * We can have double attach due to group movement (move_group) in 2181 * perf_event_open(). 2182 */ 2183 if (event->attach_state & PERF_ATTACH_GROUP) 2184 return; 2185 2186 event->attach_state |= PERF_ATTACH_GROUP; 2187 2188 if (group_leader == event) 2189 return; 2190 2191 WARN_ON_ONCE(group_leader->ctx != event->ctx); 2192 2193 group_leader->group_caps &= event->event_caps; 2194 2195 list_add_tail(&event->sibling_list, &group_leader->sibling_list); 2196 group_leader->nr_siblings++; 2197 group_leader->group_generation++; 2198 2199 perf_event__header_size(group_leader); 2200 2201 for_each_sibling_event(pos, group_leader) 2202 perf_event__header_size(pos); 2203 } 2204 2205 /* 2206 * Remove an event from the lists for its context. 2207 * Must be called with ctx->mutex and ctx->lock held. 2208 */ 2209 static void 2210 list_del_event(struct perf_event *event, struct perf_event_context *ctx) 2211 { 2212 WARN_ON_ONCE(event->ctx != ctx); 2213 lockdep_assert_held(&ctx->lock); 2214 2215 /* 2216 * We can have double detach due to exit/hot-unplug + close. 2217 */ 2218 if (!(event->attach_state & PERF_ATTACH_CONTEXT)) 2219 return; 2220 2221 event->attach_state &= ~PERF_ATTACH_CONTEXT; 2222 2223 ctx->nr_events--; 2224 if (event->hw.flags & PERF_EVENT_FLAG_USER_READ_CNT) 2225 ctx->nr_user--; 2226 if (event->attr.inherit_stat) 2227 ctx->nr_stat--; 2228 if (has_inherit_and_sample_read(&event->attr)) 2229 local_dec(&ctx->nr_no_switch_fast); 2230 2231 list_del_rcu(&event->event_entry); 2232 2233 if (event->group_leader == event) 2234 del_event_from_groups(event, ctx); 2235 2236 ctx->generation++; 2237 event->pmu_ctx->nr_events--; 2238 } 2239 2240 static int 2241 perf_aux_output_match(struct perf_event *event, struct perf_event *aux_event) 2242 { 2243 if (!has_aux(aux_event)) 2244 return 0; 2245 2246 if (!event->pmu->aux_output_match) 2247 return 0; 2248 2249 return event->pmu->aux_output_match(aux_event); 2250 } 2251 2252 static void put_event(struct perf_event *event); 2253 static void __event_disable(struct perf_event *event, 2254 struct perf_event_context *ctx, 2255 enum perf_event_state state); 2256 2257 static void perf_put_aux_event(struct perf_event *event) 2258 { 2259 struct perf_event_context *ctx = event->ctx; 2260 struct perf_event *iter; 2261 2262 /* 2263 * If event uses aux_event tear down the link 2264 */ 2265 if (event->aux_event) { 2266 iter = event->aux_event; 2267 event->aux_event = NULL; 2268 put_event(iter); 2269 return; 2270 } 2271 2272 /* 2273 * If the event is an aux_event, tear down all links to 2274 * it from other events. 2275 */ 2276 for_each_sibling_event(iter, event) { 2277 if (iter->aux_event != event) 2278 continue; 2279 2280 iter->aux_event = NULL; 2281 put_event(event); 2282 2283 /* 2284 * If it's ACTIVE, schedule it out and put it into ERROR 2285 * state so that we don't try to schedule it again. Note 2286 * that perf_event_enable() will clear the ERROR status. 2287 */ 2288 __event_disable(iter, ctx, PERF_EVENT_STATE_ERROR); 2289 } 2290 } 2291 2292 static bool perf_need_aux_event(struct perf_event *event) 2293 { 2294 return event->attr.aux_output || has_aux_action(event); 2295 } 2296 2297 static int perf_get_aux_event(struct perf_event *event, 2298 struct perf_event *group_leader) 2299 { 2300 /* 2301 * Our group leader must be an aux event if we want to be 2302 * an aux_output. This way, the aux event will precede its 2303 * aux_output events in the group, and therefore will always 2304 * schedule first. 2305 */ 2306 if (!group_leader) 2307 return 0; 2308 2309 /* 2310 * aux_output and aux_sample_size are mutually exclusive. 2311 */ 2312 if (event->attr.aux_output && event->attr.aux_sample_size) 2313 return 0; 2314 2315 if (event->attr.aux_output && 2316 !perf_aux_output_match(event, group_leader)) 2317 return 0; 2318 2319 if ((event->attr.aux_pause || event->attr.aux_resume) && 2320 !(group_leader->pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) 2321 return 0; 2322 2323 if (event->attr.aux_sample_size && !group_leader->pmu->snapshot_aux) 2324 return 0; 2325 2326 if (!atomic_long_inc_not_zero(&group_leader->refcount)) 2327 return 0; 2328 2329 /* 2330 * Link aux_outputs to their aux event; this is undone in 2331 * perf_group_detach() by perf_put_aux_event(). When the 2332 * group in torn down, the aux_output events loose their 2333 * link to the aux_event and can't schedule any more. 2334 */ 2335 event->aux_event = group_leader; 2336 2337 return 1; 2338 } 2339 2340 static inline struct list_head *get_event_list(struct perf_event *event) 2341 { 2342 return event->attr.pinned ? &event->pmu_ctx->pinned_active : 2343 &event->pmu_ctx->flexible_active; 2344 } 2345 2346 /* @sibling must already be unlinked from its old leader's sibling_list. */ 2347 static void perf_promote_sibling_to_leader(struct perf_event *sibling, 2348 struct perf_event_context *ctx, 2349 int group_caps) 2350 { 2351 /* 2352 * Events that have PERF_EV_CAP_SIBLING require being part of 2353 * a group and cannot exist on their own, schedule them out 2354 * and move them into the ERROR state. Also see 2355 * _perf_event_enable(), it will not be able to recover this 2356 * ERROR state. 2357 */ 2358 if (sibling->event_caps & PERF_EV_CAP_SIBLING) 2359 __event_disable(sibling, ctx, PERF_EVENT_STATE_ERROR); 2360 2361 sibling->group_leader = sibling; 2362 sibling->group_caps = group_caps; 2363 2364 if (sibling->attach_state & PERF_ATTACH_CONTEXT) { 2365 add_event_to_groups(sibling, ctx); 2366 2367 if (sibling->state == PERF_EVENT_STATE_ACTIVE) 2368 list_add_tail(&sibling->active_list, get_event_list(sibling)); 2369 } 2370 2371 perf_event__header_size(sibling); 2372 } 2373 2374 static void perf_group_detach(struct perf_event *event) 2375 { 2376 struct perf_event *leader = event->group_leader; 2377 struct perf_event *sibling, *tmp; 2378 struct perf_event_context *ctx = event->ctx; 2379 2380 lockdep_assert_held(&ctx->lock); 2381 2382 /* 2383 * We can have double detach due to exit/hot-unplug + close. 2384 */ 2385 if (!(event->attach_state & PERF_ATTACH_GROUP)) 2386 return; 2387 2388 event->attach_state &= ~PERF_ATTACH_GROUP; 2389 2390 perf_put_aux_event(event); 2391 2392 /* 2393 * If this is a sibling, remove it from its group. 2394 */ 2395 if (leader != event) { 2396 list_del_init(&event->sibling_list); 2397 leader->nr_siblings--; 2398 leader->group_generation++; 2399 perf_promote_sibling_to_leader(event, ctx, event->event_caps); 2400 goto out; 2401 } 2402 2403 /* 2404 * If this was a group event with sibling events then 2405 * upgrade the siblings to singleton events by adding them 2406 * to whatever list we are on. 2407 */ 2408 list_for_each_entry_safe(sibling, tmp, &event->sibling_list, sibling_list) { 2409 list_del_init(&sibling->sibling_list); 2410 2411 /* Inherit group flags from the previous leader */ 2412 perf_promote_sibling_to_leader(sibling, ctx, event->group_caps); 2413 2414 WARN_ON_ONCE(sibling->ctx != event->ctx); 2415 } 2416 event->nr_siblings = 0; 2417 2418 out: 2419 for_each_sibling_event(tmp, leader) 2420 perf_event__header_size(tmp); 2421 2422 perf_event__header_size(leader); 2423 } 2424 2425 static void perf_child_detach(struct perf_event *event) 2426 { 2427 struct perf_event *parent_event = event->parent; 2428 2429 if (!(event->attach_state & PERF_ATTACH_CHILD)) 2430 return; 2431 2432 event->attach_state &= ~PERF_ATTACH_CHILD; 2433 2434 if (WARN_ON_ONCE(!parent_event)) 2435 return; 2436 2437 /* 2438 * Can't check this from an IPI, the holder is likey another CPU. 2439 * 2440 lockdep_assert_held(&parent_event->child_mutex); 2441 */ 2442 2443 list_del_init(&event->child_list); 2444 } 2445 2446 static bool is_orphaned_event(struct perf_event *event) 2447 { 2448 return event->state == PERF_EVENT_STATE_DEAD; 2449 } 2450 2451 static inline int 2452 event_filter_match(struct perf_event *event) 2453 { 2454 return (event->cpu == -1 || event->cpu == smp_processor_id()) && 2455 perf_cgroup_match(event); 2456 } 2457 2458 static inline bool is_event_in_freq_mode(struct perf_event *event) 2459 { 2460 return event->attr.freq && event->attr.sample_freq; 2461 } 2462 2463 static void 2464 event_sched_out(struct perf_event *event, struct perf_event_context *ctx) 2465 { 2466 struct perf_event_pmu_context *epc = event->pmu_ctx; 2467 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu); 2468 enum perf_event_state state = PERF_EVENT_STATE_INACTIVE; 2469 2470 // XXX cpc serialization, probably per-cpu IRQ disabled 2471 2472 WARN_ON_ONCE(event->ctx != ctx); 2473 lockdep_assert_held(&ctx->lock); 2474 2475 if (event->state != PERF_EVENT_STATE_ACTIVE) 2476 return; 2477 2478 /* 2479 * Asymmetry; we only schedule events _IN_ through ctx_sched_in(), but 2480 * we can schedule events _OUT_ individually through things like 2481 * __perf_remove_from_context(). 2482 */ 2483 list_del_init(&event->active_list); 2484 2485 perf_pmu_disable(event->pmu); 2486 2487 event->pmu->del(event, 0); 2488 event->oncpu = -1; 2489 2490 if (event->pending_disable) { 2491 event->pending_disable = 0; 2492 perf_cgroup_event_disable(event, ctx); 2493 state = PERF_EVENT_STATE_OFF; 2494 } 2495 2496 perf_event_set_state(event, state); 2497 2498 if (!is_software_event(event)) 2499 cpc->active_oncpu--; 2500 if (is_event_in_freq_mode(event)) { 2501 ctx->nr_freq--; 2502 epc->nr_freq--; 2503 } 2504 if (event->attr.exclusive || !cpc->active_oncpu) 2505 cpc->exclusive = 0; 2506 2507 perf_pmu_enable(event->pmu); 2508 } 2509 2510 static void 2511 group_sched_out(struct perf_event *group_event, struct perf_event_context *ctx) 2512 { 2513 struct perf_event *event; 2514 2515 if (group_event->state != PERF_EVENT_STATE_ACTIVE) 2516 return; 2517 2518 perf_assert_pmu_disabled(group_event->pmu_ctx->pmu); 2519 2520 event_sched_out(group_event, ctx); 2521 2522 /* 2523 * Schedule out siblings (if any): 2524 */ 2525 for_each_sibling_event(event, group_event) 2526 event_sched_out(event, ctx); 2527 } 2528 2529 static inline void 2530 __ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx, 2531 bool final, enum event_type_t event_type) 2532 { 2533 if (ctx->is_active & EVENT_TIME) { 2534 if (ctx->is_active & EVENT_FROZEN) 2535 return; 2536 2537 update_context_time(ctx); 2538 /* vPMU should not stop time */ 2539 update_cgrp_time_from_cpuctx(cpuctx, !(event_type & EVENT_GUEST) && final); 2540 } 2541 } 2542 2543 static inline void 2544 ctx_time_update(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) 2545 { 2546 __ctx_time_update(cpuctx, ctx, false, 0); 2547 } 2548 2549 /* 2550 * To be used inside perf_ctx_lock() / perf_ctx_unlock(). Lasts until perf_ctx_unlock(). 2551 */ 2552 static inline void 2553 ctx_time_freeze(struct perf_cpu_context *cpuctx, struct perf_event_context *ctx) 2554 { 2555 ctx_time_update(cpuctx, ctx); 2556 if (ctx->is_active & EVENT_TIME) 2557 ctx->is_active |= EVENT_FROZEN; 2558 } 2559 2560 static inline void 2561 ctx_time_update_event(struct perf_event_context *ctx, struct perf_event *event) 2562 { 2563 if (ctx->is_active & EVENT_TIME) { 2564 if (ctx->is_active & EVENT_FROZEN) 2565 return; 2566 update_context_time(ctx); 2567 update_cgrp_time_from_event(event); 2568 } 2569 } 2570 2571 #define DETACH_GROUP 0x01UL 2572 #define DETACH_CHILD 0x02UL 2573 #define DETACH_EXIT 0x04UL 2574 #define DETACH_REVOKE 0x08UL 2575 #define DETACH_DEAD 0x10UL 2576 2577 /* 2578 * Cross CPU call to remove a performance event 2579 * 2580 * We disable the event on the hardware level first. After that we 2581 * remove it from the context list. 2582 */ 2583 static void 2584 __perf_remove_from_context(struct perf_event *event, 2585 struct perf_cpu_context *cpuctx, 2586 struct perf_event_context *ctx, 2587 void *info) 2588 { 2589 struct perf_event_pmu_context *pmu_ctx = event->pmu_ctx; 2590 enum perf_event_state state = PERF_EVENT_STATE_OFF; 2591 unsigned long flags = (unsigned long)info; 2592 2593 perf_pmu_disable(pmu_ctx->pmu); 2594 ctx_time_update(cpuctx, ctx); 2595 2596 /* 2597 * Ensure event_sched_out() switches to OFF, at the very least 2598 * this avoids raising perf_pending_task() at this time. 2599 */ 2600 if (flags & DETACH_EXIT) 2601 state = PERF_EVENT_STATE_EXIT; 2602 if (flags & DETACH_REVOKE) 2603 state = PERF_EVENT_STATE_REVOKED; 2604 if (flags & DETACH_DEAD) 2605 state = PERF_EVENT_STATE_DEAD; 2606 2607 /* 2608 * When disabling a group leader, the whole group becomes ineligible 2609 * to run, so schedule out the full group. 2610 */ 2611 if (!(flags & DETACH_GROUP) && event == event->group_leader) 2612 group_sched_out(event, ctx); 2613 2614 __event_disable(event, ctx, state); 2615 2616 if (flags & DETACH_GROUP) 2617 perf_group_detach(event); 2618 if (flags & DETACH_CHILD) 2619 perf_child_detach(event); 2620 list_del_event(event, ctx); 2621 2622 if (!pmu_ctx->nr_events) { 2623 pmu_ctx->rotate_necessary = 0; 2624 2625 if (ctx->task && ctx->is_active) { 2626 struct perf_cpu_pmu_context *cpc = this_cpc(pmu_ctx->pmu); 2627 2628 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx); 2629 cpc->task_epc = NULL; 2630 } 2631 } 2632 2633 if (!ctx->nr_events && ctx->is_active) { 2634 if (ctx == &cpuctx->ctx) 2635 update_cgrp_time_from_cpuctx(cpuctx, true); 2636 2637 ctx->is_active = 0; 2638 if (ctx->task) { 2639 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 2640 cpuctx->task_ctx = NULL; 2641 } 2642 } 2643 perf_pmu_enable(pmu_ctx->pmu); 2644 } 2645 2646 /* 2647 * Remove the event from a task's (or a CPU's) list of events. 2648 * 2649 * If event->ctx is a cloned context, callers must make sure that 2650 * every task struct that event->ctx->task could possibly point to 2651 * remains valid. This is OK when called from perf_release since 2652 * that only calls us on the top-level context, which can't be a clone. 2653 * When called from perf_event_exit_task, it's OK because the 2654 * context has been detached from its task. 2655 */ 2656 static void perf_remove_from_context(struct perf_event *event, unsigned long flags) 2657 { 2658 struct perf_event_context *ctx = event->ctx; 2659 2660 lockdep_assert_held(&ctx->mutex); 2661 2662 /* 2663 * Because of perf_event_exit_task(), perf_remove_from_context() ought 2664 * to work in the face of TASK_TOMBSTONE, unlike every other 2665 * event_function_call() user. 2666 */ 2667 raw_spin_lock_irq(&ctx->lock); 2668 if (!ctx->is_active) { 2669 __perf_remove_from_context(event, this_cpu_ptr(&perf_cpu_context), 2670 ctx, (void *)flags); 2671 raw_spin_unlock_irq(&ctx->lock); 2672 return; 2673 } 2674 raw_spin_unlock_irq(&ctx->lock); 2675 2676 event_function_call(event, __perf_remove_from_context, (void *)flags); 2677 } 2678 2679 static void __event_disable(struct perf_event *event, 2680 struct perf_event_context *ctx, 2681 enum perf_event_state state) 2682 { 2683 event_sched_out(event, ctx); 2684 if (event->state > PERF_EVENT_STATE_OFF) 2685 perf_cgroup_event_disable(event, ctx); 2686 perf_event_set_state(event, min(event->state, state)); 2687 } 2688 2689 /* 2690 * Cross CPU call to disable a performance event 2691 */ 2692 static void __perf_event_disable(struct perf_event *event, 2693 struct perf_cpu_context *cpuctx, 2694 struct perf_event_context *ctx, 2695 void *info) 2696 { 2697 if (event->state < PERF_EVENT_STATE_INACTIVE) 2698 return; 2699 2700 perf_pmu_disable(event->pmu_ctx->pmu); 2701 ctx_time_update_event(ctx, event); 2702 2703 /* 2704 * When disabling a group leader, the whole group becomes ineligible 2705 * to run, so schedule out the full group. 2706 */ 2707 if (event == event->group_leader) 2708 group_sched_out(event, ctx); 2709 2710 /* 2711 * But only mark the leader OFF; the siblings will remain 2712 * INACTIVE. 2713 */ 2714 __event_disable(event, ctx, PERF_EVENT_STATE_OFF); 2715 2716 perf_pmu_enable(event->pmu_ctx->pmu); 2717 } 2718 2719 /* 2720 * Disable an event. 2721 * 2722 * If event->ctx is a cloned context, callers must make sure that 2723 * every task struct that event->ctx->task could possibly point to 2724 * remains valid. This condition is satisfied when called through 2725 * perf_event_for_each_child or perf_event_for_each because they 2726 * hold the top-level event's child_mutex, so any descendant that 2727 * goes to exit will block in perf_event_exit_event(). 2728 * 2729 * When called from perf_pending_disable it's OK because event->ctx 2730 * is the current context on this CPU and preemption is disabled, 2731 * hence we can't get into perf_event_task_sched_out for this context. 2732 */ 2733 static void _perf_event_disable(struct perf_event *event) 2734 { 2735 struct perf_event_context *ctx = event->ctx; 2736 2737 raw_spin_lock_irq(&ctx->lock); 2738 if (event->state <= PERF_EVENT_STATE_OFF) { 2739 raw_spin_unlock_irq(&ctx->lock); 2740 return; 2741 } 2742 raw_spin_unlock_irq(&ctx->lock); 2743 2744 event_function_call(event, __perf_event_disable, NULL); 2745 } 2746 2747 void perf_event_disable_local(struct perf_event *event) 2748 { 2749 event_function_local(event, __perf_event_disable, NULL); 2750 } 2751 2752 /* 2753 * Strictly speaking kernel users cannot create groups and therefore this 2754 * interface does not need the perf_event_ctx_lock() magic. 2755 */ 2756 void perf_event_disable(struct perf_event *event) 2757 { 2758 struct perf_event_context *ctx; 2759 2760 ctx = perf_event_ctx_lock(event); 2761 _perf_event_disable(event); 2762 perf_event_ctx_unlock(event, ctx); 2763 } 2764 EXPORT_SYMBOL_GPL(perf_event_disable); 2765 2766 void perf_event_disable_inatomic(struct perf_event *event) 2767 { 2768 event->pending_disable = 1; 2769 irq_work_queue(&event->pending_disable_irq); 2770 } 2771 2772 #define MAX_INTERRUPTS (~0ULL) 2773 2774 static void perf_log_throttle(struct perf_event *event, int enable); 2775 static void perf_log_itrace_start(struct perf_event *event); 2776 2777 static void perf_event_unthrottle(struct perf_event *event, bool start) 2778 { 2779 if (event->state != PERF_EVENT_STATE_ACTIVE) 2780 return; 2781 2782 event->hw.interrupts = 0; 2783 if (start) 2784 event->pmu->start(event, 0); 2785 if (event == event->group_leader) 2786 perf_log_throttle(event, 1); 2787 } 2788 2789 static void perf_event_throttle(struct perf_event *event) 2790 { 2791 if (event->state != PERF_EVENT_STATE_ACTIVE) 2792 return; 2793 2794 event->hw.interrupts = MAX_INTERRUPTS; 2795 event->pmu->stop(event, 0); 2796 if (event == event->group_leader) 2797 perf_log_throttle(event, 0); 2798 } 2799 2800 static void perf_event_unthrottle_group(struct perf_event *event, bool skip_start_event) 2801 { 2802 struct perf_event *sibling, *leader = event->group_leader; 2803 2804 perf_event_unthrottle(leader, skip_start_event ? leader != event : true); 2805 for_each_sibling_event(sibling, leader) 2806 perf_event_unthrottle(sibling, skip_start_event ? sibling != event : true); 2807 } 2808 2809 static void perf_event_throttle_group(struct perf_event *event) 2810 { 2811 struct perf_event *sibling, *leader = event->group_leader; 2812 2813 perf_event_throttle(leader); 2814 for_each_sibling_event(sibling, leader) 2815 perf_event_throttle(sibling); 2816 } 2817 2818 static int 2819 event_sched_in(struct perf_event *event, struct perf_event_context *ctx) 2820 { 2821 struct perf_event_pmu_context *epc = event->pmu_ctx; 2822 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu); 2823 int ret = 0; 2824 2825 WARN_ON_ONCE(event->ctx != ctx); 2826 2827 lockdep_assert_held(&ctx->lock); 2828 2829 if (event->state <= PERF_EVENT_STATE_OFF) 2830 return 0; 2831 2832 WRITE_ONCE(event->oncpu, smp_processor_id()); 2833 /* 2834 * Order event::oncpu write to happen before the ACTIVE state is 2835 * visible. This allows perf_event_{stop,read}() to observe the correct 2836 * ->oncpu if it sees ACTIVE. 2837 */ 2838 smp_wmb(); 2839 perf_event_set_state(event, PERF_EVENT_STATE_ACTIVE); 2840 2841 /* 2842 * Unthrottle events, since we scheduled we might have missed several 2843 * ticks already, also for a heavily scheduling task there is little 2844 * guarantee it'll get a tick in a timely manner. 2845 */ 2846 if (unlikely(event->hw.interrupts == MAX_INTERRUPTS)) 2847 perf_event_unthrottle(event, false); 2848 2849 perf_pmu_disable(event->pmu); 2850 2851 perf_log_itrace_start(event); 2852 2853 if (event->pmu->add(event, PERF_EF_START)) { 2854 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 2855 event->oncpu = -1; 2856 ret = -EAGAIN; 2857 goto out; 2858 } 2859 2860 if (!is_software_event(event)) 2861 cpc->active_oncpu++; 2862 if (is_event_in_freq_mode(event)) { 2863 ctx->nr_freq++; 2864 epc->nr_freq++; 2865 } 2866 if (event->attr.exclusive) 2867 cpc->exclusive = 1; 2868 2869 out: 2870 perf_pmu_enable(event->pmu); 2871 2872 return ret; 2873 } 2874 2875 static int 2876 group_sched_in(struct perf_event *group_event, struct perf_event_context *ctx) 2877 { 2878 struct perf_event *event, *partial_group = NULL; 2879 struct pmu *pmu = group_event->pmu_ctx->pmu; 2880 2881 if (group_event->state == PERF_EVENT_STATE_OFF) 2882 return 0; 2883 2884 pmu->start_txn(pmu, PERF_PMU_TXN_ADD); 2885 2886 if (event_sched_in(group_event, ctx)) 2887 goto error; 2888 2889 /* 2890 * Schedule in siblings as one group (if any): 2891 */ 2892 for_each_sibling_event(event, group_event) { 2893 if (event_sched_in(event, ctx)) { 2894 partial_group = event; 2895 goto group_error; 2896 } 2897 } 2898 2899 if (!pmu->commit_txn(pmu)) 2900 return 0; 2901 2902 group_error: 2903 /* 2904 * Groups can be scheduled in as one unit only, so undo any 2905 * partial group before returning: 2906 * The events up to the failed event are scheduled out normally. 2907 */ 2908 for_each_sibling_event(event, group_event) { 2909 if (event == partial_group) 2910 break; 2911 2912 event_sched_out(event, ctx); 2913 } 2914 event_sched_out(group_event, ctx); 2915 2916 error: 2917 pmu->cancel_txn(pmu); 2918 return -EAGAIN; 2919 } 2920 2921 /* 2922 * Work out whether we can put this event group on the CPU now. 2923 */ 2924 static int group_can_go_on(struct perf_event *event, int can_add_hw) 2925 { 2926 struct perf_event_pmu_context *epc = event->pmu_ctx; 2927 struct perf_cpu_pmu_context *cpc = this_cpc(epc->pmu); 2928 2929 /* 2930 * Groups consisting entirely of software events can always go on. 2931 */ 2932 if (event->group_caps & PERF_EV_CAP_SOFTWARE) 2933 return 1; 2934 /* 2935 * If an exclusive group is already on, no other hardware 2936 * events can go on. 2937 */ 2938 if (cpc->exclusive) 2939 return 0; 2940 /* 2941 * If this group is exclusive and there are already 2942 * events on the CPU, it can't go on. 2943 */ 2944 if (event->attr.exclusive && !list_empty(get_event_list(event))) 2945 return 0; 2946 /* 2947 * Otherwise, try to add it if all previous groups were able 2948 * to go on. 2949 */ 2950 return can_add_hw; 2951 } 2952 2953 static void add_event_to_ctx(struct perf_event *event, 2954 struct perf_event_context *ctx) 2955 { 2956 list_add_event(event, ctx); 2957 perf_group_attach(event); 2958 } 2959 2960 static void task_ctx_sched_out(struct perf_event_context *ctx, 2961 struct pmu *pmu, 2962 enum event_type_t event_type) 2963 { 2964 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 2965 2966 if (!cpuctx->task_ctx) 2967 return; 2968 2969 if (WARN_ON_ONCE(ctx != cpuctx->task_ctx)) 2970 return; 2971 2972 ctx_sched_out(ctx, pmu, event_type); 2973 } 2974 2975 static void perf_event_sched_in(struct perf_cpu_context *cpuctx, 2976 struct perf_event_context *ctx, 2977 struct pmu *pmu, 2978 enum event_type_t event_type) 2979 { 2980 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_PINNED | event_type); 2981 if (ctx) 2982 ctx_sched_in(ctx, pmu, EVENT_PINNED | event_type); 2983 ctx_sched_in(&cpuctx->ctx, pmu, EVENT_FLEXIBLE | event_type); 2984 if (ctx) 2985 ctx_sched_in(ctx, pmu, EVENT_FLEXIBLE | event_type); 2986 } 2987 2988 /* 2989 * We want to maintain the following priority of scheduling: 2990 * - CPU pinned (EVENT_CPU | EVENT_PINNED) 2991 * - task pinned (EVENT_PINNED) 2992 * - CPU flexible (EVENT_CPU | EVENT_FLEXIBLE) 2993 * - task flexible (EVENT_FLEXIBLE). 2994 * 2995 * In order to avoid unscheduling and scheduling back in everything every 2996 * time an event is added, only do it for the groups of equal priority and 2997 * below. 2998 * 2999 * This can be called after a batch operation on task events, in which case 3000 * event_type is a bit mask of the types of events involved. For CPU events, 3001 * event_type is only either EVENT_PINNED or EVENT_FLEXIBLE. 3002 */ 3003 static void ctx_resched(struct perf_cpu_context *cpuctx, 3004 struct perf_event_context *task_ctx, 3005 struct pmu *pmu, enum event_type_t event_type) 3006 { 3007 bool cpu_event = !!(event_type & EVENT_CPU); 3008 struct perf_event_pmu_context *epc; 3009 3010 /* 3011 * If pinned groups are involved, flexible groups also need to be 3012 * scheduled out. 3013 */ 3014 if (event_type & EVENT_PINNED) 3015 event_type |= EVENT_FLEXIBLE; 3016 3017 event_type &= EVENT_ALL; 3018 3019 for_each_epc(epc, &cpuctx->ctx, pmu, 0) 3020 perf_pmu_disable(epc->pmu); 3021 3022 if (task_ctx) { 3023 for_each_epc(epc, task_ctx, pmu, 0) 3024 perf_pmu_disable(epc->pmu); 3025 3026 task_ctx_sched_out(task_ctx, pmu, event_type); 3027 } 3028 3029 /* 3030 * Decide which cpu ctx groups to schedule out based on the types 3031 * of events that caused rescheduling: 3032 * - EVENT_CPU: schedule out corresponding groups; 3033 * - EVENT_PINNED task events: schedule out EVENT_FLEXIBLE groups; 3034 * - otherwise, do nothing more. 3035 */ 3036 if (cpu_event) 3037 ctx_sched_out(&cpuctx->ctx, pmu, event_type); 3038 else if (event_type & EVENT_PINNED) 3039 ctx_sched_out(&cpuctx->ctx, pmu, EVENT_FLEXIBLE); 3040 3041 perf_event_sched_in(cpuctx, task_ctx, pmu, 0); 3042 3043 for_each_epc(epc, &cpuctx->ctx, pmu, 0) 3044 perf_pmu_enable(epc->pmu); 3045 3046 if (task_ctx) { 3047 for_each_epc(epc, task_ctx, pmu, 0) 3048 perf_pmu_enable(epc->pmu); 3049 } 3050 } 3051 3052 void perf_pmu_resched(struct pmu *pmu) 3053 { 3054 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3055 struct perf_event_context *task_ctx = cpuctx->task_ctx; 3056 3057 perf_ctx_lock(cpuctx, task_ctx); 3058 ctx_resched(cpuctx, task_ctx, pmu, EVENT_ALL|EVENT_CPU); 3059 perf_ctx_unlock(cpuctx, task_ctx); 3060 } 3061 3062 /* 3063 * Cross CPU call to install and enable a performance event 3064 * 3065 * Very similar to remote_function() + event_function() but cannot assume that 3066 * things like ctx->is_active and cpuctx->task_ctx are set. 3067 */ 3068 static int __perf_install_in_context(void *info) 3069 { 3070 struct perf_event *event = info; 3071 struct perf_event_context *ctx = event->ctx; 3072 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3073 struct perf_event_context *task_ctx = cpuctx->task_ctx; 3074 bool reprogram = true; 3075 int ret = 0; 3076 3077 raw_spin_lock(&cpuctx->ctx.lock); 3078 if (ctx->task) { 3079 raw_spin_lock(&ctx->lock); 3080 task_ctx = ctx; 3081 3082 reprogram = (ctx->task == current); 3083 3084 /* 3085 * If the task is running, it must be running on this CPU, 3086 * otherwise we cannot reprogram things. 3087 * 3088 * If its not running, we don't care, ctx->lock will 3089 * serialize against it becoming runnable. 3090 */ 3091 if (task_curr(ctx->task) && !reprogram) { 3092 ret = -ESRCH; 3093 goto unlock; 3094 } 3095 3096 WARN_ON_ONCE(reprogram && cpuctx->task_ctx && cpuctx->task_ctx != ctx); 3097 } else if (task_ctx) { 3098 raw_spin_lock(&task_ctx->lock); 3099 } 3100 3101 #ifdef CONFIG_CGROUP_PERF 3102 if (event->state > PERF_EVENT_STATE_OFF && is_cgroup_event(event)) { 3103 /* 3104 * If the current cgroup doesn't match the event's 3105 * cgroup, we should not try to schedule it. 3106 */ 3107 struct perf_cgroup *cgrp = perf_cgroup_from_task(current, ctx); 3108 reprogram = cgroup_is_descendant(cgrp->css.cgroup, 3109 event->cgrp->css.cgroup); 3110 } 3111 #endif 3112 3113 if (reprogram) { 3114 ctx_time_freeze(cpuctx, ctx); 3115 add_event_to_ctx(event, ctx); 3116 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, 3117 get_event_type(event)); 3118 } else { 3119 add_event_to_ctx(event, ctx); 3120 } 3121 3122 unlock: 3123 perf_ctx_unlock(cpuctx, task_ctx); 3124 3125 return ret; 3126 } 3127 3128 static bool exclusive_event_installable(struct perf_event *event, 3129 struct perf_event_context *ctx); 3130 3131 /* 3132 * Attach a performance event to a context. 3133 * 3134 * Very similar to event_function_call, see comment there. 3135 */ 3136 static void 3137 perf_install_in_context(struct perf_event_context *ctx, 3138 struct perf_event *event, 3139 int cpu) 3140 { 3141 struct task_struct *task = READ_ONCE(ctx->task); 3142 3143 lockdep_assert_held(&ctx->mutex); 3144 3145 WARN_ON_ONCE(!exclusive_event_installable(event, ctx)); 3146 3147 if (event->cpu != -1) 3148 WARN_ON_ONCE(event->cpu != cpu); 3149 3150 /* 3151 * Ensures that if we can observe event->ctx, both the event and ctx 3152 * will be 'complete'. See perf_iterate_sb_cpu(). 3153 */ 3154 smp_store_release(&event->ctx, ctx); 3155 3156 /* 3157 * perf_event_attr::disabled events will not run and can be initialized 3158 * without IPI. Except when this is the first event for the context, in 3159 * that case we need the magic of the IPI to set ctx->is_active. 3160 * 3161 * The IOC_ENABLE that is sure to follow the creation of a disabled 3162 * event will issue the IPI and reprogram the hardware. 3163 */ 3164 if (__perf_effective_state(event) == PERF_EVENT_STATE_OFF && 3165 ctx->nr_events && !is_cgroup_event(event)) { 3166 raw_spin_lock_irq(&ctx->lock); 3167 if (ctx->task == TASK_TOMBSTONE) { 3168 raw_spin_unlock_irq(&ctx->lock); 3169 return; 3170 } 3171 add_event_to_ctx(event, ctx); 3172 raw_spin_unlock_irq(&ctx->lock); 3173 return; 3174 } 3175 3176 if (!task) { 3177 cpu_function_call(cpu, __perf_install_in_context, event); 3178 return; 3179 } 3180 3181 /* 3182 * Should not happen, we validate the ctx is still alive before calling. 3183 */ 3184 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) 3185 return; 3186 3187 /* 3188 * Installing events is tricky because we cannot rely on ctx->is_active 3189 * to be set in case this is the nr_events 0 -> 1 transition. 3190 * 3191 * Instead we use task_curr(), which tells us if the task is running. 3192 * However, since we use task_curr() outside of rq::lock, we can race 3193 * against the actual state. This means the result can be wrong. 3194 * 3195 * If we get a false positive, we retry, this is harmless. 3196 * 3197 * If we get a false negative, things are complicated. If we are after 3198 * perf_event_context_sched_in() ctx::lock will serialize us, and the 3199 * value must be correct. If we're before, it doesn't matter since 3200 * perf_event_context_sched_in() will program the counter. 3201 * 3202 * However, this hinges on the remote context switch having observed 3203 * our task->perf_event_ctxp[] store, such that it will in fact take 3204 * ctx::lock in perf_event_context_sched_in(). 3205 * 3206 * We do this by task_function_call(), if the IPI fails to hit the task 3207 * we know any future context switch of task must see the 3208 * perf_event_ctpx[] store. 3209 */ 3210 3211 /* 3212 * This smp_mb() orders the task->perf_event_ctxp[] store with the 3213 * task_cpu() load, such that if the IPI then does not find the task 3214 * running, a future context switch of that task must observe the 3215 * store. 3216 */ 3217 smp_mb(); 3218 again: 3219 if (!task_function_call(task, __perf_install_in_context, event)) 3220 return; 3221 3222 raw_spin_lock_irq(&ctx->lock); 3223 task = ctx->task; 3224 if (WARN_ON_ONCE(task == TASK_TOMBSTONE)) { 3225 /* 3226 * Cannot happen because we already checked above (which also 3227 * cannot happen), and we hold ctx->mutex, which serializes us 3228 * against perf_event_exit_task_context(). 3229 */ 3230 raw_spin_unlock_irq(&ctx->lock); 3231 return; 3232 } 3233 /* 3234 * If the task is not running, ctx->lock will avoid it becoming so, 3235 * thus we can safely install the event. 3236 */ 3237 if (task_curr(task)) { 3238 raw_spin_unlock_irq(&ctx->lock); 3239 goto again; 3240 } 3241 add_event_to_ctx(event, ctx); 3242 raw_spin_unlock_irq(&ctx->lock); 3243 } 3244 3245 /* 3246 * Cross CPU call to enable a performance event 3247 */ 3248 static void __perf_event_enable(struct perf_event *event, 3249 struct perf_cpu_context *cpuctx, 3250 struct perf_event_context *ctx, 3251 void *info) 3252 { 3253 struct perf_event *leader = event->group_leader; 3254 struct perf_event_context *task_ctx; 3255 3256 if (event->state >= PERF_EVENT_STATE_INACTIVE || 3257 event->state <= PERF_EVENT_STATE_ERROR) 3258 return; 3259 3260 ctx_time_freeze(cpuctx, ctx); 3261 3262 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 3263 perf_cgroup_event_enable(event, ctx); 3264 3265 if (!ctx->is_active) 3266 return; 3267 3268 if (!event_filter_match(event)) 3269 return; 3270 3271 /* 3272 * If the event is in a group and isn't the group leader, 3273 * then don't put it on unless the group is on. 3274 */ 3275 if (leader != event && leader->state != PERF_EVENT_STATE_ACTIVE) 3276 return; 3277 3278 task_ctx = cpuctx->task_ctx; 3279 if (ctx->task) 3280 WARN_ON_ONCE(task_ctx != ctx); 3281 3282 ctx_resched(cpuctx, task_ctx, event->pmu_ctx->pmu, get_event_type(event)); 3283 } 3284 3285 /* 3286 * Enable an event. 3287 * 3288 * If event->ctx is a cloned context, callers must make sure that 3289 * every task struct that event->ctx->task could possibly point to 3290 * remains valid. This condition is satisfied when called through 3291 * perf_event_for_each_child or perf_event_for_each as described 3292 * for perf_event_disable. 3293 */ 3294 static void _perf_event_enable(struct perf_event *event) 3295 { 3296 struct perf_event_context *ctx = event->ctx; 3297 3298 raw_spin_lock_irq(&ctx->lock); 3299 if (event->state >= PERF_EVENT_STATE_INACTIVE || 3300 event->state < PERF_EVENT_STATE_ERROR) { 3301 out: 3302 raw_spin_unlock_irq(&ctx->lock); 3303 return; 3304 } 3305 3306 /* 3307 * If the event is in error state, clear that first. 3308 * 3309 * That way, if we see the event in error state below, we know that it 3310 * has gone back into error state, as distinct from the task having 3311 * been scheduled away before the cross-call arrived. 3312 */ 3313 if (event->state == PERF_EVENT_STATE_ERROR) { 3314 /* 3315 * Detached SIBLING events cannot leave ERROR state. 3316 */ 3317 if (event->event_caps & PERF_EV_CAP_SIBLING && 3318 event->group_leader == event) 3319 goto out; 3320 3321 event->state = PERF_EVENT_STATE_OFF; 3322 } 3323 raw_spin_unlock_irq(&ctx->lock); 3324 3325 event_function_call(event, __perf_event_enable, NULL); 3326 } 3327 3328 /* 3329 * See perf_event_disable(); 3330 */ 3331 void perf_event_enable(struct perf_event *event) 3332 { 3333 struct perf_event_context *ctx; 3334 3335 ctx = perf_event_ctx_lock(event); 3336 _perf_event_enable(event); 3337 perf_event_ctx_unlock(event, ctx); 3338 } 3339 EXPORT_SYMBOL_GPL(perf_event_enable); 3340 3341 struct stop_event_data { 3342 struct perf_event *event; 3343 unsigned int restart; 3344 }; 3345 3346 static int __perf_event_stop(void *info) 3347 { 3348 struct stop_event_data *sd = info; 3349 struct perf_event *event = sd->event; 3350 3351 /* if it's already INACTIVE, do nothing */ 3352 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) 3353 return 0; 3354 3355 /* matches smp_wmb() in event_sched_in() */ 3356 smp_rmb(); 3357 3358 /* 3359 * There is a window with interrupts enabled before we get here, 3360 * so we need to check again lest we try to stop another CPU's event. 3361 */ 3362 if (READ_ONCE(event->oncpu) != smp_processor_id()) 3363 return -EAGAIN; 3364 3365 event->pmu->stop(event, PERF_EF_UPDATE); 3366 3367 /* 3368 * May race with the actual stop (through perf_pmu_output_stop()), 3369 * but it is only used for events with AUX ring buffer, and such 3370 * events will refuse to restart because of rb::aux_mmap_count==0, 3371 * see comments in perf_aux_output_begin(). 3372 * 3373 * Since this is happening on an event-local CPU, no trace is lost 3374 * while restarting. 3375 */ 3376 if (sd->restart) 3377 event->pmu->start(event, 0); 3378 3379 return 0; 3380 } 3381 3382 static int perf_event_stop(struct perf_event *event, int restart) 3383 { 3384 struct stop_event_data sd = { 3385 .event = event, 3386 .restart = restart, 3387 }; 3388 int ret = 0; 3389 3390 do { 3391 if (READ_ONCE(event->state) != PERF_EVENT_STATE_ACTIVE) 3392 return 0; 3393 3394 /* matches smp_wmb() in event_sched_in() */ 3395 smp_rmb(); 3396 3397 /* 3398 * We only want to restart ACTIVE events, so if the event goes 3399 * inactive here (event->oncpu==-1), there's nothing more to do; 3400 * fall through with ret==-ENXIO. 3401 */ 3402 ret = cpu_function_call(READ_ONCE(event->oncpu), 3403 __perf_event_stop, &sd); 3404 } while (ret == -EAGAIN); 3405 3406 return ret; 3407 } 3408 3409 /* 3410 * In order to contain the amount of racy and tricky in the address filter 3411 * configuration management, it is a two part process: 3412 * 3413 * (p1) when userspace mappings change as a result of (1) or (2) or (3) below, 3414 * we update the addresses of corresponding vmas in 3415 * event::addr_filter_ranges array and bump the event::addr_filters_gen; 3416 * (p2) when an event is scheduled in (pmu::add), it calls 3417 * perf_event_addr_filters_sync() which calls pmu::addr_filters_sync() 3418 * if the generation has changed since the previous call. 3419 * 3420 * If (p1) happens while the event is active, we restart it to force (p2). 3421 * 3422 * (1) perf_addr_filters_apply(): adjusting filters' offsets based on 3423 * pre-existing mappings, called once when new filters arrive via SET_FILTER 3424 * ioctl; 3425 * (2) perf_addr_filters_adjust(): adjusting filters' offsets based on newly 3426 * registered mapping, called for every new mmap(), with mm::mmap_lock down 3427 * for reading; 3428 * (3) perf_event_addr_filters_exec(): clearing filters' offsets in the process 3429 * of exec. 3430 */ 3431 void perf_event_addr_filters_sync(struct perf_event *event) 3432 { 3433 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 3434 3435 if (!has_addr_filter(event)) 3436 return; 3437 3438 raw_spin_lock(&ifh->lock); 3439 if (event->addr_filters_gen != event->hw.addr_filters_gen) { 3440 event->pmu->addr_filters_sync(event); 3441 event->hw.addr_filters_gen = event->addr_filters_gen; 3442 } 3443 raw_spin_unlock(&ifh->lock); 3444 } 3445 EXPORT_SYMBOL_GPL(perf_event_addr_filters_sync); 3446 3447 static int _perf_event_refresh(struct perf_event *event, int refresh) 3448 { 3449 /* 3450 * not supported on inherited events 3451 */ 3452 if (event->attr.inherit || !is_sampling_event(event)) 3453 return -EINVAL; 3454 3455 atomic_add(refresh, &event->event_limit); 3456 _perf_event_enable(event); 3457 3458 return 0; 3459 } 3460 3461 /* 3462 * See perf_event_disable() 3463 */ 3464 int perf_event_refresh(struct perf_event *event, int refresh) 3465 { 3466 struct perf_event_context *ctx; 3467 int ret; 3468 3469 ctx = perf_event_ctx_lock(event); 3470 ret = _perf_event_refresh(event, refresh); 3471 perf_event_ctx_unlock(event, ctx); 3472 3473 return ret; 3474 } 3475 EXPORT_SYMBOL_GPL(perf_event_refresh); 3476 3477 static int perf_event_modify_breakpoint(struct perf_event *bp, 3478 struct perf_event_attr *attr) 3479 { 3480 int err; 3481 3482 _perf_event_disable(bp); 3483 3484 err = modify_user_hw_breakpoint_check(bp, attr, true); 3485 3486 if (!bp->attr.disabled) 3487 _perf_event_enable(bp); 3488 3489 return err; 3490 } 3491 3492 /* 3493 * Copy event-type-independent attributes that may be modified. 3494 */ 3495 static void perf_event_modify_copy_attr(struct perf_event_attr *to, 3496 const struct perf_event_attr *from) 3497 { 3498 to->sig_data = from->sig_data; 3499 } 3500 3501 static int perf_event_modify_attr(struct perf_event *event, 3502 struct perf_event_attr *attr) 3503 { 3504 int (*func)(struct perf_event *, struct perf_event_attr *); 3505 struct perf_event *child; 3506 int err; 3507 3508 if (event->attr.type != attr->type) 3509 return -EINVAL; 3510 3511 switch (event->attr.type) { 3512 case PERF_TYPE_BREAKPOINT: 3513 func = perf_event_modify_breakpoint; 3514 break; 3515 default: 3516 /* Place holder for future additions. */ 3517 return -EOPNOTSUPP; 3518 } 3519 3520 WARN_ON_ONCE(event->ctx->parent_ctx); 3521 3522 mutex_lock(&event->child_mutex); 3523 /* 3524 * Event-type-independent attributes must be copied before event-type 3525 * modification, which will validate that final attributes match the 3526 * source attributes after all relevant attributes have been copied. 3527 */ 3528 perf_event_modify_copy_attr(&event->attr, attr); 3529 err = func(event, attr); 3530 if (err) 3531 goto out; 3532 list_for_each_entry(child, &event->child_list, child_list) { 3533 perf_event_modify_copy_attr(&child->attr, attr); 3534 err = func(child, attr); 3535 if (err) 3536 goto out; 3537 } 3538 out: 3539 mutex_unlock(&event->child_mutex); 3540 return err; 3541 } 3542 3543 static void __pmu_ctx_sched_out(struct perf_event_pmu_context *pmu_ctx, 3544 enum event_type_t event_type) 3545 { 3546 struct perf_event_context *ctx = pmu_ctx->ctx; 3547 struct perf_event *event, *tmp; 3548 struct pmu *pmu = pmu_ctx->pmu; 3549 3550 if (ctx->task && !(ctx->is_active & EVENT_ALL)) { 3551 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 3552 3553 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx); 3554 cpc->task_epc = NULL; 3555 } 3556 3557 if (!(event_type & EVENT_ALL)) 3558 return; 3559 3560 perf_pmu_disable(pmu); 3561 if (event_type & EVENT_PINNED) { 3562 list_for_each_entry_safe(event, tmp, 3563 &pmu_ctx->pinned_active, 3564 active_list) 3565 group_sched_out(event, ctx); 3566 } 3567 3568 if (event_type & EVENT_FLEXIBLE) { 3569 list_for_each_entry_safe(event, tmp, 3570 &pmu_ctx->flexible_active, 3571 active_list) 3572 group_sched_out(event, ctx); 3573 /* 3574 * Since we cleared EVENT_FLEXIBLE, also clear 3575 * rotate_necessary, is will be reset by 3576 * ctx_flexible_sched_in() when needed. 3577 */ 3578 pmu_ctx->rotate_necessary = 0; 3579 } 3580 perf_pmu_enable(pmu); 3581 } 3582 3583 /* 3584 * Be very careful with the @pmu argument since this will change ctx state. 3585 * The @pmu argument works for ctx_resched(), because that is symmetric in 3586 * ctx_sched_out() / ctx_sched_in() usage and the ctx state ends up invariant. 3587 * 3588 * However, if you were to be asymmetrical, you could end up with messed up 3589 * state, eg. ctx->is_active cleared even though most EPCs would still actually 3590 * be active. 3591 */ 3592 static void 3593 ctx_sched_out(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type) 3594 { 3595 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3596 enum event_type_t active_type = event_type & ~EVENT_FLAGS; 3597 struct perf_event_pmu_context *pmu_ctx; 3598 int is_active = ctx->is_active; 3599 3600 3601 lockdep_assert_held(&ctx->lock); 3602 3603 if (likely(!ctx->nr_events)) { 3604 /* 3605 * See __perf_remove_from_context(). 3606 */ 3607 WARN_ON_ONCE(ctx->is_active); 3608 if (ctx->task) 3609 WARN_ON_ONCE(cpuctx->task_ctx); 3610 return; 3611 } 3612 3613 /* 3614 * Always update time if it was set; not only when it changes. 3615 * Otherwise we can 'forget' to update time for any but the last 3616 * context we sched out. For example: 3617 * 3618 * ctx_sched_out(.event_type = EVENT_FLEXIBLE) 3619 * ctx_sched_out(.event_type = EVENT_PINNED) 3620 * 3621 * would only update time for the pinned events. 3622 */ 3623 __ctx_time_update(cpuctx, ctx, ctx == &cpuctx->ctx, event_type); 3624 3625 /* 3626 * CPU-release for the below ->is_active store, 3627 * see __load_acquire() in perf_event_time_now() 3628 */ 3629 barrier(); 3630 ctx->is_active &= ~active_type; 3631 3632 if (!(ctx->is_active & EVENT_ALL)) { 3633 /* 3634 * For FROZEN, preserve TIME|FROZEN such that perf_event_time_now() 3635 * does not observe a hole. perf_ctx_unlock() will clean up. 3636 */ 3637 if (ctx->is_active & EVENT_FROZEN) 3638 ctx->is_active &= EVENT_TIME_FROZEN; 3639 else 3640 ctx->is_active = 0; 3641 } 3642 3643 if (ctx->task) { 3644 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 3645 if (!(ctx->is_active & EVENT_ALL)) 3646 cpuctx->task_ctx = NULL; 3647 } 3648 3649 if (event_type & EVENT_GUEST) { 3650 /* 3651 * Schedule out all exclude_guest events of PMU 3652 * with PERF_PMU_CAP_MEDIATED_VPMU. 3653 */ 3654 is_active = EVENT_ALL; 3655 __update_context_guest_time(ctx, false); 3656 perf_cgroup_set_timestamp(cpuctx, true); 3657 barrier(); 3658 } else { 3659 is_active ^= ctx->is_active; /* changed bits */ 3660 } 3661 3662 for_each_epc(pmu_ctx, ctx, pmu, event_type) 3663 __pmu_ctx_sched_out(pmu_ctx, is_active); 3664 } 3665 3666 /* 3667 * Test whether two contexts are equivalent, i.e. whether they have both been 3668 * cloned from the same version of the same context. 3669 * 3670 * Equivalence is measured using a generation number in the context that is 3671 * incremented on each modification to it; see unclone_ctx(), list_add_event() 3672 * and list_del_event(). 3673 */ 3674 static int context_equiv(struct perf_event_context *ctx1, 3675 struct perf_event_context *ctx2) 3676 { 3677 lockdep_assert_held(&ctx1->lock); 3678 lockdep_assert_held(&ctx2->lock); 3679 3680 /* Pinning disables the swap optimization */ 3681 if (ctx1->pin_count || ctx2->pin_count) 3682 return 0; 3683 3684 /* If ctx1 is the parent of ctx2 */ 3685 if (ctx1 == ctx2->parent_ctx && ctx1->generation == ctx2->parent_gen) 3686 return 1; 3687 3688 /* If ctx2 is the parent of ctx1 */ 3689 if (ctx1->parent_ctx == ctx2 && ctx1->parent_gen == ctx2->generation) 3690 return 1; 3691 3692 /* 3693 * If ctx1 and ctx2 have the same parent; we flatten the parent 3694 * hierarchy, see perf_event_init_context(). 3695 */ 3696 if (ctx1->parent_ctx && ctx1->parent_ctx == ctx2->parent_ctx && 3697 ctx1->parent_gen == ctx2->parent_gen) 3698 return 1; 3699 3700 /* Unmatched */ 3701 return 0; 3702 } 3703 3704 static void __perf_event_sync_stat(struct perf_event *event, 3705 struct perf_event *next_event) 3706 { 3707 u64 value; 3708 3709 if (!event->attr.inherit_stat) 3710 return; 3711 3712 /* 3713 * Update the event value, we cannot use perf_event_read() 3714 * because we're in the middle of a context switch and have IRQs 3715 * disabled, which upsets smp_call_function_single(), however 3716 * we know the event must be on the current CPU, therefore we 3717 * don't need to use it. 3718 */ 3719 perf_pmu_read(event); 3720 3721 perf_event_update_time(event); 3722 3723 /* 3724 * In order to keep per-task stats reliable we need to flip the event 3725 * values when we flip the contexts. 3726 */ 3727 value = local64_read(&next_event->count); 3728 value = local64_xchg(&event->count, value); 3729 local64_set(&next_event->count, value); 3730 3731 swap(event->total_time_enabled, next_event->total_time_enabled); 3732 swap(event->total_time_running, next_event->total_time_running); 3733 3734 /* 3735 * Since we swizzled the values, update the user visible data too. 3736 */ 3737 perf_event_update_userpage(event); 3738 perf_event_update_userpage(next_event); 3739 } 3740 3741 static void perf_event_sync_stat(struct perf_event_context *ctx, 3742 struct perf_event_context *next_ctx) 3743 { 3744 struct perf_event *event, *next_event; 3745 3746 if (!ctx->nr_stat) 3747 return; 3748 3749 update_context_time(ctx); 3750 3751 event = list_first_entry(&ctx->event_list, 3752 struct perf_event, event_entry); 3753 3754 next_event = list_first_entry(&next_ctx->event_list, 3755 struct perf_event, event_entry); 3756 3757 while (&event->event_entry != &ctx->event_list && 3758 &next_event->event_entry != &next_ctx->event_list) { 3759 3760 __perf_event_sync_stat(event, next_event); 3761 3762 event = list_next_entry(event, event_entry); 3763 next_event = list_next_entry(next_event, event_entry); 3764 } 3765 } 3766 3767 static void perf_ctx_sched_task_cb(struct perf_event_context *ctx, 3768 struct task_struct *task, bool sched_in) 3769 { 3770 struct perf_event_pmu_context *pmu_ctx; 3771 struct perf_cpu_pmu_context *cpc; 3772 3773 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) { 3774 cpc = this_cpc(pmu_ctx->pmu); 3775 3776 if (cpc->task_epc != pmu_ctx) 3777 continue; 3778 3779 if (cpc->sched_cb_usage && pmu_ctx->pmu->sched_task) 3780 pmu_ctx->pmu->sched_task(pmu_ctx, task, sched_in); 3781 } 3782 } 3783 3784 static void 3785 perf_event_context_sched_out(struct task_struct *task, struct task_struct *next) 3786 { 3787 struct perf_event_context *ctx = task->perf_event_ctxp; 3788 struct perf_event_context *next_ctx; 3789 struct perf_event_context *parent, *next_parent; 3790 int do_switch = 1; 3791 3792 if (likely(!ctx)) 3793 return; 3794 3795 rcu_read_lock(); 3796 next_ctx = rcu_dereference(next->perf_event_ctxp); 3797 if (!next_ctx) 3798 goto unlock; 3799 3800 parent = rcu_dereference(ctx->parent_ctx); 3801 next_parent = rcu_dereference(next_ctx->parent_ctx); 3802 3803 /* If neither context have a parent context; they cannot be clones. */ 3804 if (!parent && !next_parent) 3805 goto unlock; 3806 3807 if (next_parent == ctx || next_ctx == parent || next_parent == parent) { 3808 /* 3809 * Looks like the two contexts are clones, so we might be 3810 * able to optimize the context switch. We lock both 3811 * contexts and check that they are clones under the 3812 * lock (including re-checking that neither has been 3813 * uncloned in the meantime). It doesn't matter which 3814 * order we take the locks because no other cpu could 3815 * be trying to lock both of these tasks. 3816 */ 3817 raw_spin_lock(&ctx->lock); 3818 raw_spin_lock_nested(&next_ctx->lock, SINGLE_DEPTH_NESTING); 3819 if (context_equiv(ctx, next_ctx)) { 3820 3821 perf_ctx_disable(ctx, 0); 3822 3823 /* PMIs are disabled; ctx->nr_no_switch_fast is stable. */ 3824 if (local_read(&ctx->nr_no_switch_fast) || 3825 local_read(&next_ctx->nr_no_switch_fast)) { 3826 /* 3827 * Must not swap out ctx when there's pending 3828 * events that rely on the ctx->task relation. 3829 * 3830 * Likewise, when a context contains inherit + 3831 * SAMPLE_READ events they should be switched 3832 * out using the slow path so that they are 3833 * treated as if they were distinct contexts. 3834 */ 3835 raw_spin_unlock(&next_ctx->lock); 3836 rcu_read_unlock(); 3837 goto inside_switch; 3838 } 3839 3840 WRITE_ONCE(ctx->task, next); 3841 WRITE_ONCE(next_ctx->task, task); 3842 3843 perf_ctx_sched_task_cb(ctx, task, false); 3844 3845 perf_ctx_enable(ctx, 0); 3846 3847 /* 3848 * RCU_INIT_POINTER here is safe because we've not 3849 * modified the ctx and the above modification of 3850 * ctx->task is immaterial since this value is 3851 * always verified under ctx->lock which we're now 3852 * holding. 3853 */ 3854 RCU_INIT_POINTER(task->perf_event_ctxp, next_ctx); 3855 RCU_INIT_POINTER(next->perf_event_ctxp, ctx); 3856 3857 do_switch = 0; 3858 3859 perf_event_sync_stat(ctx, next_ctx); 3860 } 3861 raw_spin_unlock(&next_ctx->lock); 3862 raw_spin_unlock(&ctx->lock); 3863 } 3864 unlock: 3865 rcu_read_unlock(); 3866 3867 if (do_switch) { 3868 raw_spin_lock(&ctx->lock); 3869 perf_ctx_disable(ctx, 0); 3870 3871 inside_switch: 3872 perf_ctx_sched_task_cb(ctx, task, false); 3873 task_ctx_sched_out(ctx, NULL, EVENT_ALL); 3874 3875 perf_ctx_enable(ctx, 0); 3876 raw_spin_unlock(&ctx->lock); 3877 } 3878 } 3879 3880 static DEFINE_PER_CPU(struct list_head, sched_cb_list); 3881 static DEFINE_PER_CPU(int, perf_sched_cb_usages); 3882 3883 void perf_sched_cb_dec(struct pmu *pmu) 3884 { 3885 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 3886 3887 this_cpu_dec(perf_sched_cb_usages); 3888 barrier(); 3889 3890 if (!--cpc->sched_cb_usage) 3891 list_del(&cpc->sched_cb_entry); 3892 } 3893 3894 3895 void perf_sched_cb_inc(struct pmu *pmu) 3896 { 3897 struct perf_cpu_pmu_context *cpc = this_cpc(pmu); 3898 3899 if (!cpc->sched_cb_usage++) 3900 list_add(&cpc->sched_cb_entry, this_cpu_ptr(&sched_cb_list)); 3901 3902 barrier(); 3903 this_cpu_inc(perf_sched_cb_usages); 3904 } 3905 3906 /* 3907 * This function provides the context switch callback to the lower code 3908 * layer. It is invoked ONLY when the context switch callback is enabled. 3909 * 3910 * This callback is relevant even to per-cpu events; for example multi event 3911 * PEBS requires this to provide PID/TID information. This requires we flush 3912 * all queued PEBS records before we context switch to a new task. 3913 */ 3914 static void __perf_pmu_sched_task(struct perf_cpu_pmu_context *cpc, 3915 struct task_struct *task, bool sched_in) 3916 { 3917 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 3918 struct pmu *pmu; 3919 3920 pmu = cpc->epc.pmu; 3921 3922 /* software PMUs will not have sched_task */ 3923 if (WARN_ON_ONCE(!pmu->sched_task)) 3924 return; 3925 3926 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 3927 perf_pmu_disable(pmu); 3928 3929 pmu->sched_task(&cpc->epc, task, sched_in); 3930 3931 perf_pmu_enable(pmu); 3932 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 3933 } 3934 3935 static void perf_pmu_sched_task(struct task_struct *prev, 3936 struct task_struct *next, 3937 bool sched_in) 3938 { 3939 struct perf_cpu_pmu_context *cpc, *cpc2; 3940 3941 if (prev == next) 3942 return; 3943 3944 list_for_each_entry_safe(cpc, cpc2, this_cpu_ptr(&sched_cb_list), sched_cb_entry) { 3945 if (cpc->task_epc) 3946 continue; 3947 3948 __perf_pmu_sched_task(cpc, sched_in ? next : prev, sched_in); 3949 } 3950 } 3951 3952 static void perf_event_switch(struct task_struct *task, 3953 struct task_struct *next_prev, bool sched_in); 3954 3955 /* 3956 * Called from scheduler to remove the events of the current task, 3957 * with interrupts disabled. 3958 * 3959 * We stop each event and update the event value in event->count. 3960 * 3961 * This does not protect us against NMI, but disable() 3962 * sets the disabled bit in the control field of event _before_ 3963 * accessing the event control register. If a NMI hits, then it will 3964 * not restart the event. 3965 */ 3966 void __perf_event_task_sched_out(struct task_struct *task, 3967 struct task_struct *next) 3968 { 3969 if (__this_cpu_read(perf_sched_cb_usages)) 3970 perf_pmu_sched_task(task, next, false); 3971 3972 if (atomic_read(&nr_switch_events)) 3973 perf_event_switch(task, next, false); 3974 3975 perf_event_context_sched_out(task, next); 3976 3977 /* 3978 * if cgroup events exist on this CPU, then we need 3979 * to check if we have to switch out PMU state. 3980 * cgroup event are system-wide mode only 3981 */ 3982 perf_cgroup_switch(next); 3983 } 3984 3985 static bool perf_less_group_idx(const void *l, const void *r, void __always_unused *args) 3986 { 3987 const struct perf_event *le = *(const struct perf_event **)l; 3988 const struct perf_event *re = *(const struct perf_event **)r; 3989 3990 return le->group_index < re->group_index; 3991 } 3992 3993 DEFINE_MIN_HEAP(struct perf_event *, perf_event_min_heap); 3994 3995 static const struct min_heap_callbacks perf_min_heap = { 3996 .less = perf_less_group_idx, 3997 .swp = NULL, 3998 }; 3999 4000 static void __heap_add(struct perf_event_min_heap *heap, struct perf_event *event) 4001 { 4002 struct perf_event **itrs = heap->data; 4003 4004 if (event) { 4005 itrs[heap->nr] = event; 4006 heap->nr++; 4007 } 4008 } 4009 4010 static void __link_epc(struct perf_event_pmu_context *pmu_ctx) 4011 { 4012 struct perf_cpu_pmu_context *cpc; 4013 4014 if (!pmu_ctx->ctx->task) 4015 return; 4016 4017 cpc = this_cpc(pmu_ctx->pmu); 4018 WARN_ON_ONCE(cpc->task_epc && cpc->task_epc != pmu_ctx); 4019 cpc->task_epc = pmu_ctx; 4020 } 4021 4022 static noinline int visit_groups_merge(struct perf_event_context *ctx, 4023 struct perf_event_groups *groups, int cpu, 4024 struct pmu *pmu, 4025 int (*func)(struct perf_event *, void *), 4026 void *data) 4027 { 4028 #ifdef CONFIG_CGROUP_PERF 4029 struct cgroup_subsys_state *css = NULL; 4030 #endif 4031 struct perf_cpu_context *cpuctx = NULL; 4032 /* Space for per CPU and/or any CPU event iterators. */ 4033 struct perf_event *itrs[2]; 4034 struct perf_event_min_heap event_heap; 4035 struct perf_event **evt; 4036 int ret; 4037 4038 if (pmu->filter && pmu->filter(pmu, cpu)) 4039 return 0; 4040 4041 if (!ctx->task) { 4042 cpuctx = this_cpu_ptr(&perf_cpu_context); 4043 event_heap = (struct perf_event_min_heap){ 4044 .data = cpuctx->heap, 4045 .nr = 0, 4046 .size = cpuctx->heap_size, 4047 }; 4048 4049 lockdep_assert_held(&cpuctx->ctx.lock); 4050 4051 #ifdef CONFIG_CGROUP_PERF 4052 if (cpuctx->cgrp) 4053 css = &cpuctx->cgrp->css; 4054 #endif 4055 } else { 4056 event_heap = (struct perf_event_min_heap){ 4057 .data = itrs, 4058 .nr = 0, 4059 .size = ARRAY_SIZE(itrs), 4060 }; 4061 /* Events not within a CPU context may be on any CPU. */ 4062 __heap_add(&event_heap, perf_event_groups_first(groups, -1, pmu, NULL)); 4063 } 4064 evt = event_heap.data; 4065 4066 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, NULL)); 4067 4068 #ifdef CONFIG_CGROUP_PERF 4069 for (; css; css = css->parent) 4070 __heap_add(&event_heap, perf_event_groups_first(groups, cpu, pmu, css->cgroup)); 4071 #endif 4072 4073 if (event_heap.nr) { 4074 __link_epc((*evt)->pmu_ctx); 4075 perf_assert_pmu_disabled((*evt)->pmu_ctx->pmu); 4076 } 4077 4078 min_heapify_all_inline(&event_heap, &perf_min_heap, NULL); 4079 4080 while (event_heap.nr) { 4081 ret = func(*evt, data); 4082 if (ret) 4083 return ret; 4084 4085 *evt = perf_event_groups_next(*evt, pmu); 4086 if (*evt) 4087 min_heap_sift_down_inline(&event_heap, 0, &perf_min_heap, NULL); 4088 else 4089 min_heap_pop_inline(&event_heap, &perf_min_heap, NULL); 4090 } 4091 4092 return 0; 4093 } 4094 4095 /* 4096 * Because the userpage is strictly per-event (there is no concept of context, 4097 * so there cannot be a context indirection), every userpage must be updated 4098 * when context time starts :-( 4099 * 4100 * IOW, we must not miss EVENT_TIME edges. 4101 */ 4102 static inline bool event_update_userpage(struct perf_event *event) 4103 { 4104 if (likely(!refcount_read(&event->mmap_count))) 4105 return false; 4106 4107 perf_event_update_time(event); 4108 perf_event_update_userpage(event); 4109 4110 return true; 4111 } 4112 4113 static inline void group_update_userpage(struct perf_event *group_event) 4114 { 4115 struct perf_event *event; 4116 4117 if (!event_update_userpage(group_event)) 4118 return; 4119 4120 for_each_sibling_event(event, group_event) 4121 event_update_userpage(event); 4122 } 4123 4124 struct merge_sched_data { 4125 int can_add_hw; 4126 enum event_type_t event_type; 4127 }; 4128 4129 static int merge_sched_in(struct perf_event *event, void *data) 4130 { 4131 struct perf_event_context *ctx = event->ctx; 4132 struct merge_sched_data *msd = data; 4133 4134 if (event->state <= PERF_EVENT_STATE_OFF) 4135 return 0; 4136 4137 if (!event_filter_match(event)) 4138 return 0; 4139 4140 /* 4141 * Don't schedule in any host events from PMU with 4142 * PERF_PMU_CAP_MEDIATED_VPMU, while a guest is running. 4143 */ 4144 if (is_guest_mediated_pmu_loaded() && 4145 event->pmu_ctx->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU && 4146 !(msd->event_type & EVENT_GUEST)) 4147 return 0; 4148 4149 if (group_can_go_on(event, msd->can_add_hw)) { 4150 if (!group_sched_in(event, ctx)) 4151 list_add_tail(&event->active_list, get_event_list(event)); 4152 } 4153 4154 if (event->state == PERF_EVENT_STATE_INACTIVE) { 4155 msd->can_add_hw = 0; 4156 if (event->attr.pinned) { 4157 perf_cgroup_event_disable(event, ctx); 4158 perf_event_set_state(event, PERF_EVENT_STATE_ERROR); 4159 4160 if (*perf_event_fasync(event)) 4161 event->pending_kill = POLL_ERR; 4162 4163 event->pending_wakeup = 1; 4164 irq_work_queue(&event->pending_irq); 4165 } else { 4166 struct perf_cpu_pmu_context *cpc = this_cpc(event->pmu_ctx->pmu); 4167 4168 event->pmu_ctx->rotate_necessary = 1; 4169 perf_mux_hrtimer_restart(cpc); 4170 group_update_userpage(event); 4171 } 4172 } 4173 4174 return 0; 4175 } 4176 4177 static void pmu_groups_sched_in(struct perf_event_context *ctx, 4178 struct perf_event_groups *groups, 4179 struct pmu *pmu, 4180 enum event_type_t event_type) 4181 { 4182 struct merge_sched_data msd = { 4183 .can_add_hw = 1, 4184 .event_type = event_type, 4185 }; 4186 visit_groups_merge(ctx, groups, smp_processor_id(), pmu, 4187 merge_sched_in, &msd); 4188 } 4189 4190 static void __pmu_ctx_sched_in(struct perf_event_pmu_context *pmu_ctx, 4191 enum event_type_t event_type) 4192 { 4193 struct perf_event_context *ctx = pmu_ctx->ctx; 4194 4195 if (event_type & EVENT_PINNED) 4196 pmu_groups_sched_in(ctx, &ctx->pinned_groups, pmu_ctx->pmu, event_type); 4197 if (event_type & EVENT_FLEXIBLE) 4198 pmu_groups_sched_in(ctx, &ctx->flexible_groups, pmu_ctx->pmu, event_type); 4199 } 4200 4201 static void 4202 ctx_sched_in(struct perf_event_context *ctx, struct pmu *pmu, enum event_type_t event_type) 4203 { 4204 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4205 enum event_type_t active_type = event_type & ~EVENT_FLAGS; 4206 struct perf_event_pmu_context *pmu_ctx; 4207 int is_active = ctx->is_active; 4208 4209 lockdep_assert_held(&ctx->lock); 4210 4211 if (likely(!ctx->nr_events)) 4212 return; 4213 4214 if (!(is_active & EVENT_TIME)) { 4215 /* EVENT_TIME should be active while the guest runs */ 4216 WARN_ON_ONCE(event_type & EVENT_GUEST); 4217 /* start ctx time */ 4218 __update_context_time(ctx, false); 4219 perf_cgroup_set_timestamp(cpuctx, false); 4220 /* 4221 * CPU-release for the below ->is_active store, 4222 * see __load_acquire() in perf_event_time_now() 4223 */ 4224 barrier(); 4225 } 4226 4227 ctx->is_active |= active_type | EVENT_TIME; 4228 if (ctx->task) { 4229 if (!(is_active & EVENT_ALL)) 4230 cpuctx->task_ctx = ctx; 4231 else 4232 WARN_ON_ONCE(cpuctx->task_ctx != ctx); 4233 } 4234 4235 if (event_type & EVENT_GUEST) { 4236 /* 4237 * Schedule in the required exclude_guest events of PMU 4238 * with PERF_PMU_CAP_MEDIATED_VPMU. 4239 */ 4240 is_active = event_type & EVENT_ALL; 4241 4242 /* 4243 * Update ctx time to set the new start time for 4244 * the exclude_guest events. 4245 */ 4246 update_context_time(ctx); 4247 update_cgrp_time_from_cpuctx(cpuctx, false); 4248 barrier(); 4249 } else { 4250 is_active ^= ctx->is_active; /* changed bits */ 4251 } 4252 4253 /* 4254 * First go through the list and put on any pinned groups 4255 * in order to give them the best chance of going on. 4256 */ 4257 if (is_active & EVENT_PINNED) { 4258 for_each_epc(pmu_ctx, ctx, pmu, event_type) 4259 __pmu_ctx_sched_in(pmu_ctx, EVENT_PINNED | (event_type & EVENT_GUEST)); 4260 } 4261 4262 /* Then walk through the lower prio flexible groups */ 4263 if (is_active & EVENT_FLEXIBLE) { 4264 for_each_epc(pmu_ctx, ctx, pmu, event_type) 4265 __pmu_ctx_sched_in(pmu_ctx, EVENT_FLEXIBLE | (event_type & EVENT_GUEST)); 4266 } 4267 } 4268 4269 static void perf_event_context_sched_in(struct task_struct *task) 4270 { 4271 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4272 struct perf_event_context *ctx; 4273 4274 rcu_read_lock(); 4275 ctx = rcu_dereference(task->perf_event_ctxp); 4276 if (!ctx) 4277 goto rcu_unlock; 4278 4279 if (cpuctx->task_ctx == ctx) { 4280 perf_ctx_lock(cpuctx, ctx); 4281 perf_ctx_disable(ctx, 0); 4282 4283 perf_ctx_sched_task_cb(ctx, task, true); 4284 4285 perf_ctx_enable(ctx, 0); 4286 perf_ctx_unlock(cpuctx, ctx); 4287 goto rcu_unlock; 4288 } 4289 4290 perf_ctx_lock(cpuctx, ctx); 4291 /* 4292 * We must check ctx->nr_events while holding ctx->lock, such 4293 * that we serialize against perf_install_in_context(). 4294 */ 4295 if (!ctx->nr_events) 4296 goto unlock; 4297 4298 perf_ctx_disable(ctx, 0); 4299 /* 4300 * We want to keep the following priority order: 4301 * cpu pinned (that don't need to move), task pinned, 4302 * cpu flexible, task flexible. 4303 * 4304 * However, if task's ctx is not carrying any pinned 4305 * events, no need to flip the cpuctx's events around. 4306 */ 4307 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) { 4308 perf_ctx_disable(&cpuctx->ctx, 0); 4309 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_FLEXIBLE); 4310 } 4311 4312 perf_event_sched_in(cpuctx, ctx, NULL, 0); 4313 4314 perf_ctx_sched_task_cb(cpuctx->task_ctx, task, true); 4315 4316 if (!RB_EMPTY_ROOT(&ctx->pinned_groups.tree)) 4317 perf_ctx_enable(&cpuctx->ctx, 0); 4318 4319 perf_ctx_enable(ctx, 0); 4320 4321 unlock: 4322 perf_ctx_unlock(cpuctx, ctx); 4323 rcu_unlock: 4324 rcu_read_unlock(); 4325 } 4326 4327 /* 4328 * Called from scheduler to add the events of the current task 4329 * with interrupts disabled. 4330 * 4331 * We restore the event value and then enable it. 4332 * 4333 * This does not protect us against NMI, but enable() 4334 * sets the enabled bit in the control field of event _before_ 4335 * accessing the event control register. If a NMI hits, then it will 4336 * keep the event running. 4337 */ 4338 void __perf_event_task_sched_in(struct task_struct *prev, 4339 struct task_struct *task) 4340 { 4341 perf_event_context_sched_in(task); 4342 4343 if (atomic_read(&nr_switch_events)) 4344 perf_event_switch(task, prev, true); 4345 4346 if (__this_cpu_read(perf_sched_cb_usages)) 4347 perf_pmu_sched_task(prev, task, true); 4348 } 4349 4350 static u64 perf_calculate_period(struct perf_event *event, u64 nsec, u64 count) 4351 { 4352 u64 frequency = event->attr.sample_freq; 4353 u64 sec = NSEC_PER_SEC; 4354 u64 divisor, dividend; 4355 4356 int count_fls, nsec_fls, frequency_fls, sec_fls; 4357 4358 count_fls = fls64(count); 4359 nsec_fls = fls64(nsec); 4360 frequency_fls = fls64(frequency); 4361 sec_fls = 30; 4362 4363 /* 4364 * We got @count in @nsec, with a target of sample_freq HZ 4365 * the target period becomes: 4366 * 4367 * @count * 10^9 4368 * period = ------------------- 4369 * @nsec * sample_freq 4370 * 4371 */ 4372 4373 /* 4374 * Reduce accuracy by one bit such that @a and @b converge 4375 * to a similar magnitude. 4376 */ 4377 #define REDUCE_FLS(a, b) \ 4378 do { \ 4379 if (a##_fls > b##_fls) { \ 4380 a >>= 1; \ 4381 a##_fls--; \ 4382 } else { \ 4383 b >>= 1; \ 4384 b##_fls--; \ 4385 } \ 4386 } while (0) 4387 4388 /* 4389 * Reduce accuracy until either term fits in a u64, then proceed with 4390 * the other, so that finally we can do a u64/u64 division. 4391 */ 4392 while (count_fls + sec_fls > 64 && nsec_fls + frequency_fls > 64) { 4393 REDUCE_FLS(nsec, frequency); 4394 REDUCE_FLS(sec, count); 4395 } 4396 4397 if (count_fls + sec_fls > 64) { 4398 divisor = nsec * frequency; 4399 4400 while (count_fls + sec_fls > 64) { 4401 REDUCE_FLS(count, sec); 4402 divisor >>= 1; 4403 } 4404 4405 dividend = count * sec; 4406 } else { 4407 dividend = count * sec; 4408 4409 while (nsec_fls + frequency_fls > 64) { 4410 REDUCE_FLS(nsec, frequency); 4411 dividend >>= 1; 4412 } 4413 4414 divisor = nsec * frequency; 4415 } 4416 4417 if (!divisor) 4418 return dividend; 4419 4420 return div64_u64(dividend, divisor); 4421 } 4422 4423 static DEFINE_PER_CPU(int, perf_throttled_count); 4424 static DEFINE_PER_CPU(u64, perf_throttled_seq); 4425 4426 static void perf_adjust_period(struct perf_event *event, u64 nsec, u64 count, bool disable) 4427 { 4428 struct hw_perf_event *hwc = &event->hw; 4429 s64 period, sample_period; 4430 s64 delta; 4431 4432 period = perf_calculate_period(event, nsec, count); 4433 4434 delta = (s64)(period - hwc->sample_period); 4435 if (delta >= 0) 4436 delta += 7; 4437 else 4438 delta -= 7; 4439 delta /= 8; /* low pass filter */ 4440 4441 sample_period = hwc->sample_period + delta; 4442 4443 if (!sample_period) 4444 sample_period = 1; 4445 4446 hwc->sample_period = sample_period; 4447 4448 if (local64_read(&hwc->period_left) > 8*sample_period) { 4449 if (disable) 4450 event->pmu->stop(event, PERF_EF_UPDATE); 4451 4452 local64_set(&hwc->period_left, 0); 4453 4454 if (disable) 4455 event->pmu->start(event, PERF_EF_RELOAD); 4456 } 4457 } 4458 4459 static void perf_adjust_freq_unthr_events(struct list_head *event_list) 4460 { 4461 struct perf_event *event; 4462 struct hw_perf_event *hwc; 4463 u64 now, period = TICK_NSEC; 4464 s64 delta; 4465 4466 list_for_each_entry(event, event_list, active_list) { 4467 if (event->state != PERF_EVENT_STATE_ACTIVE) 4468 continue; 4469 4470 // XXX use visit thingy to avoid the -1,cpu match 4471 if (!event_filter_match(event)) 4472 continue; 4473 4474 hwc = &event->hw; 4475 4476 if (hwc->interrupts == MAX_INTERRUPTS) 4477 perf_event_unthrottle_group(event, is_event_in_freq_mode(event)); 4478 4479 if (!is_event_in_freq_mode(event)) 4480 continue; 4481 4482 /* 4483 * stop the event and update event->count 4484 */ 4485 event->pmu->stop(event, PERF_EF_UPDATE); 4486 4487 now = local64_read(&event->count); 4488 delta = now - hwc->freq_count_stamp; 4489 hwc->freq_count_stamp = now; 4490 4491 /* 4492 * restart the event 4493 * reload only if value has changed 4494 * we have stopped the event so tell that 4495 * to perf_adjust_period() to avoid stopping it 4496 * twice. 4497 */ 4498 if (delta > 0) 4499 perf_adjust_period(event, period, delta, false); 4500 4501 event->pmu->start(event, delta > 0 ? PERF_EF_RELOAD : 0); 4502 } 4503 } 4504 4505 /* 4506 * combine freq adjustment with unthrottling to avoid two passes over the 4507 * events. At the same time, make sure, having freq events does not change 4508 * the rate of unthrottling as that would introduce bias. 4509 */ 4510 static void 4511 perf_adjust_freq_unthr_context(struct perf_event_context *ctx, bool unthrottle) 4512 { 4513 struct perf_event_pmu_context *pmu_ctx; 4514 4515 /* 4516 * only need to iterate over all events iff: 4517 * - context have events in frequency mode (needs freq adjust) 4518 * - there are events to unthrottle on this cpu 4519 */ 4520 if (!(ctx->nr_freq || unthrottle)) 4521 return; 4522 4523 raw_spin_lock(&ctx->lock); 4524 4525 list_for_each_entry(pmu_ctx, &ctx->pmu_ctx_list, pmu_ctx_entry) { 4526 if (!(pmu_ctx->nr_freq || unthrottle)) 4527 continue; 4528 if (!perf_pmu_ctx_is_active(pmu_ctx)) 4529 continue; 4530 if (pmu_ctx->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) 4531 continue; 4532 4533 perf_pmu_disable(pmu_ctx->pmu); 4534 perf_adjust_freq_unthr_events(&pmu_ctx->pinned_active); 4535 perf_adjust_freq_unthr_events(&pmu_ctx->flexible_active); 4536 perf_pmu_enable(pmu_ctx->pmu); 4537 } 4538 4539 raw_spin_unlock(&ctx->lock); 4540 } 4541 4542 /* 4543 * Move @event to the tail of the @ctx's elegible events. 4544 */ 4545 static void rotate_ctx(struct perf_event_context *ctx, struct perf_event *event) 4546 { 4547 /* 4548 * Rotate the first entry last of non-pinned groups. Rotation might be 4549 * disabled by the inheritance code. 4550 */ 4551 if (ctx->rotate_disable) 4552 return; 4553 4554 perf_event_groups_delete(&ctx->flexible_groups, event); 4555 perf_event_groups_insert(&ctx->flexible_groups, event); 4556 } 4557 4558 /* pick an event from the flexible_groups to rotate */ 4559 static inline struct perf_event * 4560 ctx_event_to_rotate(struct perf_event_pmu_context *pmu_ctx) 4561 { 4562 struct perf_event *event; 4563 struct rb_node *node; 4564 struct rb_root *tree; 4565 struct __group_key key = { 4566 .pmu = pmu_ctx->pmu, 4567 }; 4568 4569 /* pick the first active flexible event */ 4570 event = list_first_entry_or_null(&pmu_ctx->flexible_active, 4571 struct perf_event, active_list); 4572 if (event) 4573 goto out; 4574 4575 /* if no active flexible event, pick the first event */ 4576 tree = &pmu_ctx->ctx->flexible_groups.tree; 4577 4578 if (!pmu_ctx->ctx->task) { 4579 key.cpu = smp_processor_id(); 4580 4581 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup); 4582 if (node) 4583 event = __node_2_pe(node); 4584 goto out; 4585 } 4586 4587 key.cpu = -1; 4588 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup); 4589 if (node) { 4590 event = __node_2_pe(node); 4591 goto out; 4592 } 4593 4594 key.cpu = smp_processor_id(); 4595 node = rb_find_first(&key, tree, __group_cmp_ignore_cgroup); 4596 if (node) 4597 event = __node_2_pe(node); 4598 4599 out: 4600 /* 4601 * Unconditionally clear rotate_necessary; if ctx_flexible_sched_in() 4602 * finds there are unschedulable events, it will set it again. 4603 */ 4604 pmu_ctx->rotate_necessary = 0; 4605 4606 return event; 4607 } 4608 4609 static bool perf_rotate_context(struct perf_cpu_pmu_context *cpc) 4610 { 4611 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4612 struct perf_event_pmu_context *cpu_epc, *task_epc = NULL; 4613 struct perf_event *cpu_event = NULL, *task_event = NULL; 4614 int cpu_rotate, task_rotate; 4615 struct pmu *pmu; 4616 4617 /* 4618 * Since we run this from IRQ context, nobody can install new 4619 * events, thus the event count values are stable. 4620 */ 4621 4622 cpu_epc = &cpc->epc; 4623 pmu = cpu_epc->pmu; 4624 task_epc = cpc->task_epc; 4625 4626 cpu_rotate = cpu_epc->rotate_necessary; 4627 task_rotate = task_epc ? task_epc->rotate_necessary : 0; 4628 4629 if (!(cpu_rotate || task_rotate)) 4630 return false; 4631 4632 perf_ctx_lock(cpuctx, cpuctx->task_ctx); 4633 perf_pmu_disable(pmu); 4634 4635 if (task_rotate) 4636 task_event = ctx_event_to_rotate(task_epc); 4637 if (cpu_rotate) 4638 cpu_event = ctx_event_to_rotate(cpu_epc); 4639 4640 /* 4641 * As per the order given at ctx_resched() first 'pop' task flexible 4642 * and then, if needed CPU flexible. 4643 */ 4644 if (task_event || (task_epc && cpu_event)) { 4645 update_context_time(task_epc->ctx); 4646 __pmu_ctx_sched_out(task_epc, EVENT_FLEXIBLE); 4647 } 4648 4649 if (cpu_event) { 4650 update_context_time(&cpuctx->ctx); 4651 update_cgrp_time_from_cpuctx(cpuctx, false); 4652 __pmu_ctx_sched_out(cpu_epc, EVENT_FLEXIBLE); 4653 rotate_ctx(&cpuctx->ctx, cpu_event); 4654 __pmu_ctx_sched_in(cpu_epc, EVENT_FLEXIBLE); 4655 } 4656 4657 if (task_event) 4658 rotate_ctx(task_epc->ctx, task_event); 4659 4660 if (task_event || (task_epc && cpu_event)) 4661 __pmu_ctx_sched_in(task_epc, EVENT_FLEXIBLE); 4662 4663 perf_pmu_enable(pmu); 4664 perf_ctx_unlock(cpuctx, cpuctx->task_ctx); 4665 4666 return true; 4667 } 4668 4669 void perf_event_task_tick(void) 4670 { 4671 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4672 struct perf_event_context *ctx; 4673 int throttled; 4674 4675 lockdep_assert_irqs_disabled(); 4676 4677 __this_cpu_inc(perf_throttled_seq); 4678 throttled = __this_cpu_xchg(perf_throttled_count, 0); 4679 tick_dep_clear_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 4680 4681 perf_adjust_freq_unthr_context(&cpuctx->ctx, !!throttled); 4682 4683 rcu_read_lock(); 4684 ctx = rcu_dereference(current->perf_event_ctxp); 4685 if (ctx) 4686 perf_adjust_freq_unthr_context(ctx, !!throttled); 4687 rcu_read_unlock(); 4688 } 4689 4690 static int event_enable_on_exec(struct perf_event *event, 4691 struct perf_event_context *ctx) 4692 { 4693 if (!event->attr.enable_on_exec) 4694 return 0; 4695 4696 event->attr.enable_on_exec = 0; 4697 if (event->state >= PERF_EVENT_STATE_INACTIVE) 4698 return 0; 4699 4700 perf_event_set_state(event, PERF_EVENT_STATE_INACTIVE); 4701 4702 return 1; 4703 } 4704 4705 /* 4706 * Enable all of a task's events that have been marked enable-on-exec. 4707 * This expects task == current. 4708 */ 4709 static void perf_event_enable_on_exec(struct perf_event_context *ctx) 4710 { 4711 struct perf_event_context *clone_ctx = NULL; 4712 enum event_type_t event_type = 0; 4713 struct perf_cpu_context *cpuctx; 4714 struct perf_event *event; 4715 unsigned long flags; 4716 int enabled = 0; 4717 4718 local_irq_save(flags); 4719 if (WARN_ON_ONCE(current->perf_event_ctxp != ctx)) 4720 goto out; 4721 4722 if (!ctx->nr_events) 4723 goto out; 4724 4725 cpuctx = this_cpu_ptr(&perf_cpu_context); 4726 perf_ctx_lock(cpuctx, ctx); 4727 ctx_time_freeze(cpuctx, ctx); 4728 4729 list_for_each_entry(event, &ctx->event_list, event_entry) { 4730 enabled |= event_enable_on_exec(event, ctx); 4731 event_type |= get_event_type(event); 4732 } 4733 4734 /* 4735 * Unclone and reschedule this context if we enabled any event. 4736 */ 4737 if (enabled) { 4738 clone_ctx = unclone_ctx(ctx); 4739 ctx_resched(cpuctx, ctx, NULL, event_type); 4740 } 4741 perf_ctx_unlock(cpuctx, ctx); 4742 4743 out: 4744 local_irq_restore(flags); 4745 4746 if (clone_ctx) 4747 put_ctx(clone_ctx); 4748 } 4749 4750 static void perf_remove_from_owner(struct perf_event *event); 4751 static void perf_event_exit_event(struct perf_event *event, 4752 struct perf_event_context *ctx, 4753 struct task_struct *task, 4754 unsigned long detach_flags); 4755 4756 /* 4757 * Removes all events from the current task that have been marked 4758 * remove-on-exec, and feeds their values back to parent events. 4759 */ 4760 static void perf_event_remove_on_exec(struct perf_event_context *ctx) 4761 { 4762 struct perf_event_context *clone_ctx = NULL; 4763 struct perf_event *event, *next; 4764 unsigned long flags; 4765 bool modified = false; 4766 4767 mutex_lock(&ctx->mutex); 4768 4769 if (WARN_ON_ONCE(ctx->task != current)) 4770 goto unlock; 4771 4772 list_for_each_entry_safe(event, next, &ctx->event_list, event_entry) { 4773 if (!event->attr.remove_on_exec) 4774 continue; 4775 4776 if (!is_kernel_event(event)) 4777 perf_remove_from_owner(event); 4778 4779 modified = true; 4780 4781 perf_event_exit_event(event, ctx, ctx->task, DETACH_GROUP); 4782 } 4783 4784 raw_spin_lock_irqsave(&ctx->lock, flags); 4785 if (modified) 4786 clone_ctx = unclone_ctx(ctx); 4787 raw_spin_unlock_irqrestore(&ctx->lock, flags); 4788 4789 unlock: 4790 mutex_unlock(&ctx->mutex); 4791 4792 if (clone_ctx) 4793 put_ctx(clone_ctx); 4794 } 4795 4796 struct perf_read_data { 4797 struct perf_event *event; 4798 bool group; 4799 int ret; 4800 }; 4801 4802 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu); 4803 4804 static int __perf_event_read_cpu(struct perf_event *event, int event_cpu) 4805 { 4806 int local_cpu = smp_processor_id(); 4807 u16 local_pkg, event_pkg; 4808 4809 if ((unsigned)event_cpu >= nr_cpu_ids) 4810 return event_cpu; 4811 4812 if (event->group_caps & PERF_EV_CAP_READ_SCOPE) { 4813 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(event->pmu->scope, event_cpu); 4814 4815 if (cpumask && cpumask_test_cpu(local_cpu, cpumask)) 4816 return local_cpu; 4817 } 4818 4819 if (event->group_caps & PERF_EV_CAP_READ_ACTIVE_PKG) { 4820 event_pkg = topology_physical_package_id(event_cpu); 4821 local_pkg = topology_physical_package_id(local_cpu); 4822 4823 if (event_pkg == local_pkg) 4824 return local_cpu; 4825 } 4826 4827 return event_cpu; 4828 } 4829 4830 /* 4831 * Cross CPU call to read the hardware event 4832 */ 4833 static void __perf_event_read(void *info) 4834 { 4835 struct perf_read_data *data = info; 4836 struct perf_event *sub, *event = data->event; 4837 struct perf_event_context *ctx = event->ctx; 4838 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 4839 struct pmu *pmu; 4840 4841 /* 4842 * If this is a task context, we need to check whether it is 4843 * the current task context of this cpu. If not it has been 4844 * scheduled out before the smp call arrived. In that case 4845 * event->count would have been updated to a recent sample 4846 * when the event was scheduled out. 4847 */ 4848 if (ctx->task && cpuctx->task_ctx != ctx) 4849 return; 4850 4851 guard(raw_spinlock)(&ctx->lock); 4852 ctx_time_update_event(ctx, event); 4853 4854 perf_event_update_time(event); 4855 if (data->group) 4856 perf_event_update_sibling_time(event); 4857 4858 if (event->state != PERF_EVENT_STATE_ACTIVE) 4859 return; 4860 4861 if (!data->group) { 4862 perf_pmu_read(event); 4863 data->ret = 0; 4864 return; 4865 } 4866 4867 pmu = event->pmu_ctx->pmu; 4868 pmu->start_txn(pmu, PERF_PMU_TXN_READ); 4869 4870 perf_pmu_read(event); 4871 for_each_sibling_event(sub, event) 4872 perf_pmu_read(sub); 4873 4874 data->ret = pmu->commit_txn(pmu); 4875 } 4876 4877 static inline u64 perf_event_count(struct perf_event *event, bool self) 4878 { 4879 if (self) 4880 return local64_read(&event->count); 4881 4882 return local64_read(&event->count) + atomic64_read(&event->child_count); 4883 } 4884 4885 static void calc_timer_values(struct perf_event *event, 4886 u64 *now, 4887 u64 *enabled, 4888 u64 *running) 4889 { 4890 u64 ctx_time; 4891 4892 *now = perf_clock(); 4893 ctx_time = perf_event_time_now(event, *now); 4894 __perf_update_times(event, ctx_time, enabled, running); 4895 } 4896 4897 /* 4898 * NMI-safe method to read a local event, that is an event that 4899 * is: 4900 * - either for the current task, or for this CPU 4901 * - does not have inherit set, for inherited task events 4902 * will not be local and we cannot read them atomically 4903 * - must not have a pmu::count method 4904 */ 4905 int perf_event_read_local(struct perf_event *event, u64 *value, 4906 u64 *enabled, u64 *running) 4907 { 4908 unsigned long flags; 4909 int event_oncpu; 4910 int event_cpu; 4911 int ret = 0; 4912 4913 /* 4914 * Disabling interrupts avoids all counter scheduling (context 4915 * switches, timer based rotation and IPIs). 4916 */ 4917 local_irq_save(flags); 4918 4919 /* 4920 * It must not be an event with inherit set, we cannot read 4921 * all child counters from atomic context. 4922 */ 4923 if (event->attr.inherit) { 4924 ret = -EOPNOTSUPP; 4925 goto out; 4926 } 4927 4928 /* If this is a per-task event, it must be for current */ 4929 if ((event->attach_state & PERF_ATTACH_TASK) && 4930 event->hw.target != current) { 4931 ret = -EINVAL; 4932 goto out; 4933 } 4934 4935 /* 4936 * Get the event CPU numbers, and adjust them to local if the event is 4937 * a per-package event that can be read locally 4938 */ 4939 event_oncpu = __perf_event_read_cpu(event, event->oncpu); 4940 event_cpu = __perf_event_read_cpu(event, event->cpu); 4941 4942 /* If this is a per-CPU event, it must be for this CPU */ 4943 if (!(event->attach_state & PERF_ATTACH_TASK) && 4944 event_cpu != smp_processor_id()) { 4945 ret = -EINVAL; 4946 goto out; 4947 } 4948 4949 /* If this is a pinned event it must be running on this CPU */ 4950 if (event->attr.pinned && event_oncpu != smp_processor_id()) { 4951 ret = -EBUSY; 4952 goto out; 4953 } 4954 4955 /* 4956 * If the event is currently on this CPU, its either a per-task event, 4957 * or local to this CPU. Furthermore it means its ACTIVE (otherwise 4958 * oncpu == -1). 4959 */ 4960 if (event_oncpu == smp_processor_id()) 4961 event->pmu->read(event); 4962 4963 *value = local64_read(&event->count); 4964 if (enabled || running) { 4965 u64 __enabled, __running, __now; 4966 4967 calc_timer_values(event, &__now, &__enabled, &__running); 4968 if (enabled) 4969 *enabled = __enabled; 4970 if (running) 4971 *running = __running; 4972 } 4973 out: 4974 local_irq_restore(flags); 4975 4976 return ret; 4977 } 4978 4979 static int perf_event_read(struct perf_event *event, bool group) 4980 { 4981 enum perf_event_state state = READ_ONCE(event->state); 4982 int event_cpu, ret = 0; 4983 4984 /* 4985 * If event is enabled and currently active on a CPU, update the 4986 * value in the event structure: 4987 */ 4988 again: 4989 if (state == PERF_EVENT_STATE_ACTIVE) { 4990 struct perf_read_data data; 4991 4992 /* 4993 * Orders the ->state and ->oncpu loads such that if we see 4994 * ACTIVE we must also see the right ->oncpu. 4995 * 4996 * Matches the smp_wmb() from event_sched_in(). 4997 */ 4998 smp_rmb(); 4999 5000 event_cpu = READ_ONCE(event->oncpu); 5001 if ((unsigned)event_cpu >= nr_cpu_ids) 5002 return 0; 5003 5004 data = (struct perf_read_data){ 5005 .event = event, 5006 .group = group, 5007 .ret = 0, 5008 }; 5009 5010 preempt_disable(); 5011 event_cpu = __perf_event_read_cpu(event, event_cpu); 5012 5013 /* 5014 * Purposely ignore the smp_call_function_single() return 5015 * value. 5016 * 5017 * If event_cpu isn't a valid CPU it means the event got 5018 * scheduled out and that will have updated the event count. 5019 * 5020 * Therefore, either way, we'll have an up-to-date event count 5021 * after this. 5022 */ 5023 (void)smp_call_function_single(event_cpu, __perf_event_read, &data, 1); 5024 preempt_enable(); 5025 ret = data.ret; 5026 5027 } else if (state == PERF_EVENT_STATE_INACTIVE) { 5028 struct perf_event_context *ctx = event->ctx; 5029 unsigned long flags; 5030 5031 raw_spin_lock_irqsave(&ctx->lock, flags); 5032 state = event->state; 5033 if (state != PERF_EVENT_STATE_INACTIVE) { 5034 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5035 goto again; 5036 } 5037 5038 /* 5039 * May read while context is not active (e.g., thread is 5040 * blocked), in that case we cannot update context time 5041 */ 5042 ctx_time_update_event(ctx, event); 5043 5044 perf_event_update_time(event); 5045 if (group) 5046 perf_event_update_sibling_time(event); 5047 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5048 } 5049 5050 return ret; 5051 } 5052 5053 /* 5054 * Initialize the perf_event context in a task_struct: 5055 */ 5056 static void __perf_event_init_context(struct perf_event_context *ctx) 5057 { 5058 raw_spin_lock_init(&ctx->lock); 5059 mutex_init(&ctx->mutex); 5060 INIT_LIST_HEAD(&ctx->pmu_ctx_list); 5061 perf_event_groups_init(&ctx->pinned_groups); 5062 perf_event_groups_init(&ctx->flexible_groups); 5063 INIT_LIST_HEAD(&ctx->event_list); 5064 refcount_set(&ctx->refcount, 1); 5065 } 5066 5067 static void 5068 __perf_init_event_pmu_context(struct perf_event_pmu_context *epc, struct pmu *pmu) 5069 { 5070 epc->pmu = pmu; 5071 INIT_LIST_HEAD(&epc->pmu_ctx_entry); 5072 INIT_LIST_HEAD(&epc->pinned_active); 5073 INIT_LIST_HEAD(&epc->flexible_active); 5074 atomic_set(&epc->refcount, 1); 5075 } 5076 5077 static struct perf_event_context * 5078 alloc_perf_context(struct task_struct *task) 5079 { 5080 struct perf_event_context *ctx; 5081 5082 ctx = kzalloc_obj(struct perf_event_context); 5083 if (!ctx) 5084 return NULL; 5085 5086 __perf_event_init_context(ctx); 5087 if (task) 5088 ctx->task = get_task_struct(task); 5089 5090 return ctx; 5091 } 5092 5093 static struct task_struct * 5094 find_lively_task_by_vpid(pid_t vpid) 5095 { 5096 struct task_struct *task; 5097 5098 rcu_read_lock(); 5099 if (!vpid) 5100 task = current; 5101 else 5102 task = find_task_by_vpid(vpid); 5103 if (task) 5104 get_task_struct(task); 5105 rcu_read_unlock(); 5106 5107 if (!task) 5108 return ERR_PTR(-ESRCH); 5109 5110 return task; 5111 } 5112 5113 /* 5114 * Returns a matching context with refcount and pincount. 5115 */ 5116 static struct perf_event_context * 5117 find_get_context(struct task_struct *task, struct perf_event *event) 5118 { 5119 struct perf_event_context *ctx, *clone_ctx = NULL; 5120 struct perf_cpu_context *cpuctx; 5121 unsigned long flags; 5122 int err; 5123 5124 if (!task) { 5125 /* Must be root to operate on a CPU event: */ 5126 err = perf_allow_cpu(); 5127 if (err) 5128 return ERR_PTR(err); 5129 5130 cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu); 5131 ctx = &cpuctx->ctx; 5132 get_ctx(ctx); 5133 raw_spin_lock_irqsave(&ctx->lock, flags); 5134 ++ctx->pin_count; 5135 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5136 5137 return ctx; 5138 } 5139 5140 err = -EINVAL; 5141 retry: 5142 ctx = perf_lock_task_context(task, &flags); 5143 if (ctx) { 5144 clone_ctx = unclone_ctx(ctx); 5145 ++ctx->pin_count; 5146 5147 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5148 5149 if (clone_ctx) 5150 put_ctx(clone_ctx); 5151 } else { 5152 ctx = alloc_perf_context(task); 5153 err = -ENOMEM; 5154 if (!ctx) 5155 goto errout; 5156 5157 err = 0; 5158 mutex_lock(&task->perf_event_mutex); 5159 /* 5160 * If it has already passed perf_event_exit_task(). 5161 * we must see PF_EXITING, it takes this mutex too. 5162 */ 5163 if (task->flags & PF_EXITING) 5164 err = -ESRCH; 5165 else if (task->perf_event_ctxp) 5166 err = -EAGAIN; 5167 else { 5168 get_ctx(ctx); 5169 ++ctx->pin_count; 5170 rcu_assign_pointer(task->perf_event_ctxp, ctx); 5171 } 5172 mutex_unlock(&task->perf_event_mutex); 5173 5174 if (unlikely(err)) { 5175 put_ctx(ctx); 5176 5177 if (err == -EAGAIN) 5178 goto retry; 5179 goto errout; 5180 } 5181 } 5182 5183 return ctx; 5184 5185 errout: 5186 return ERR_PTR(err); 5187 } 5188 5189 static struct perf_event_pmu_context * 5190 find_get_pmu_context(struct pmu *pmu, struct perf_event_context *ctx, 5191 struct perf_event *event) 5192 { 5193 struct perf_event_pmu_context *new = NULL, *pos = NULL, *epc; 5194 5195 if (!ctx->task) { 5196 /* 5197 * perf_pmu_migrate_context() / __perf_pmu_install_event() 5198 * relies on the fact that find_get_pmu_context() cannot fail 5199 * for CPU contexts. 5200 */ 5201 struct perf_cpu_pmu_context *cpc; 5202 5203 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, event->cpu); 5204 epc = &cpc->epc; 5205 raw_spin_lock_irq(&ctx->lock); 5206 if (!epc->ctx) { 5207 /* 5208 * One extra reference for the pmu; see perf_pmu_free(). 5209 */ 5210 atomic_set(&epc->refcount, 2); 5211 epc->embedded = 1; 5212 list_add(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list); 5213 epc->ctx = ctx; 5214 } else { 5215 WARN_ON_ONCE(epc->ctx != ctx); 5216 atomic_inc(&epc->refcount); 5217 } 5218 raw_spin_unlock_irq(&ctx->lock); 5219 return epc; 5220 } 5221 5222 new = kzalloc_obj(*epc); 5223 if (!new) 5224 return ERR_PTR(-ENOMEM); 5225 5226 __perf_init_event_pmu_context(new, pmu); 5227 5228 /* 5229 * XXX 5230 * 5231 * lockdep_assert_held(&ctx->mutex); 5232 * 5233 * can't because perf_event_init_task() doesn't actually hold the 5234 * child_ctx->mutex. 5235 */ 5236 5237 raw_spin_lock_irq(&ctx->lock); 5238 list_for_each_entry(epc, &ctx->pmu_ctx_list, pmu_ctx_entry) { 5239 if (epc->pmu == pmu) { 5240 WARN_ON_ONCE(epc->ctx != ctx); 5241 atomic_inc(&epc->refcount); 5242 goto found_epc; 5243 } 5244 /* Make sure the pmu_ctx_list is sorted by PMU type: */ 5245 if (!pos && epc->pmu->type > pmu->type) 5246 pos = epc; 5247 } 5248 5249 epc = new; 5250 new = NULL; 5251 5252 if (!pos) 5253 list_add_tail(&epc->pmu_ctx_entry, &ctx->pmu_ctx_list); 5254 else 5255 list_add(&epc->pmu_ctx_entry, pos->pmu_ctx_entry.prev); 5256 5257 epc->ctx = ctx; 5258 5259 found_epc: 5260 raw_spin_unlock_irq(&ctx->lock); 5261 kfree(new); 5262 5263 return epc; 5264 } 5265 5266 static void get_pmu_ctx(struct perf_event_pmu_context *epc) 5267 { 5268 WARN_ON_ONCE(!atomic_inc_not_zero(&epc->refcount)); 5269 } 5270 5271 static void free_cpc_rcu(struct rcu_head *head) 5272 { 5273 struct perf_cpu_pmu_context *cpc = 5274 container_of(head, typeof(*cpc), epc.rcu_head); 5275 5276 kfree(cpc); 5277 } 5278 5279 static void free_epc_rcu(struct rcu_head *head) 5280 { 5281 struct perf_event_pmu_context *epc = container_of(head, typeof(*epc), rcu_head); 5282 5283 kfree(epc); 5284 } 5285 5286 static void put_pmu_ctx(struct perf_event_pmu_context *epc) 5287 { 5288 struct perf_event_context *ctx = epc->ctx; 5289 unsigned long flags; 5290 5291 /* 5292 * XXX 5293 * 5294 * lockdep_assert_held(&ctx->mutex); 5295 * 5296 * can't because of the call-site in _free_event()/put_event() 5297 * which isn't always called under ctx->mutex. 5298 */ 5299 if (!atomic_dec_and_raw_lock_irqsave(&epc->refcount, &ctx->lock, flags)) 5300 return; 5301 5302 WARN_ON_ONCE(list_empty(&epc->pmu_ctx_entry)); 5303 5304 list_del_init(&epc->pmu_ctx_entry); 5305 epc->ctx = NULL; 5306 5307 WARN_ON_ONCE(!list_empty(&epc->pinned_active)); 5308 WARN_ON_ONCE(!list_empty(&epc->flexible_active)); 5309 5310 raw_spin_unlock_irqrestore(&ctx->lock, flags); 5311 5312 if (epc->embedded) { 5313 call_rcu(&epc->rcu_head, free_cpc_rcu); 5314 return; 5315 } 5316 5317 call_rcu(&epc->rcu_head, free_epc_rcu); 5318 } 5319 5320 static void perf_event_free_filter(struct perf_event *event); 5321 5322 static void free_event_rcu(struct rcu_head *head) 5323 { 5324 struct perf_event *event = container_of(head, typeof(*event), rcu_head); 5325 5326 if (event->ns) 5327 put_pid_ns(event->ns); 5328 perf_event_free_filter(event); 5329 kfree(event->addr_filter_ranges); 5330 kmem_cache_free(perf_event_cache, event); 5331 } 5332 5333 static void ring_buffer_attach(struct perf_event *event, 5334 struct perf_buffer *rb); 5335 5336 static void detach_sb_event(struct perf_event *event) 5337 { 5338 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 5339 5340 raw_spin_lock(&pel->lock); 5341 list_del_rcu(&event->sb_list); 5342 raw_spin_unlock(&pel->lock); 5343 } 5344 5345 static bool is_sb_event(struct perf_event *event) 5346 { 5347 struct perf_event_attr *attr = &event->attr; 5348 5349 if (event->parent) 5350 return false; 5351 5352 if (event->attach_state & PERF_ATTACH_TASK) 5353 return false; 5354 5355 if (attr->mmap || attr->mmap_data || attr->mmap2 || 5356 attr->comm || attr->comm_exec || 5357 attr->task || attr->ksymbol || 5358 attr->context_switch || attr->text_poke || 5359 attr->bpf_event || attr->defer_output) 5360 return true; 5361 5362 return false; 5363 } 5364 5365 static void unaccount_pmu_sb_event(struct perf_event *event) 5366 { 5367 if (is_sb_event(event)) 5368 detach_sb_event(event); 5369 } 5370 5371 #ifdef CONFIG_NO_HZ_FULL 5372 static DEFINE_SPINLOCK(nr_freq_lock); 5373 #endif 5374 5375 static void unaccount_freq_event_nohz(void) 5376 { 5377 #ifdef CONFIG_NO_HZ_FULL 5378 spin_lock(&nr_freq_lock); 5379 if (atomic_dec_and_test(&nr_freq_events)) 5380 tick_nohz_dep_clear(TICK_DEP_BIT_PERF_EVENTS); 5381 spin_unlock(&nr_freq_lock); 5382 #endif 5383 } 5384 5385 static void unaccount_freq_event(void) 5386 { 5387 if (tick_nohz_full_enabled()) 5388 unaccount_freq_event_nohz(); 5389 else 5390 atomic_dec(&nr_freq_events); 5391 } 5392 5393 5394 static struct perf_ctx_data * 5395 alloc_perf_ctx_data(struct kmem_cache *ctx_cache, bool global, gfp_t gfp_flags) 5396 { 5397 struct perf_ctx_data *cd; 5398 5399 cd = kzalloc_obj(*cd, gfp_flags); 5400 if (!cd) 5401 return NULL; 5402 5403 cd->data = kmem_cache_zalloc(ctx_cache, gfp_flags); 5404 if (!cd->data) { 5405 kfree(cd); 5406 return NULL; 5407 } 5408 5409 cd->global = global; 5410 cd->ctx_cache = ctx_cache; 5411 refcount_set(&cd->refcount, 1); 5412 5413 return cd; 5414 } 5415 5416 static void free_perf_ctx_data(struct perf_ctx_data *cd) 5417 { 5418 kmem_cache_free(cd->ctx_cache, cd->data); 5419 kfree(cd); 5420 } 5421 5422 static void __free_perf_ctx_data_rcu(struct rcu_head *rcu_head) 5423 { 5424 struct perf_ctx_data *cd; 5425 5426 cd = container_of(rcu_head, struct perf_ctx_data, rcu_head); 5427 free_perf_ctx_data(cd); 5428 } 5429 5430 static inline void perf_free_ctx_data_rcu(struct perf_ctx_data *cd) 5431 { 5432 call_rcu(&cd->rcu_head, __free_perf_ctx_data_rcu); 5433 } 5434 5435 static int 5436 attach_task_ctx_data(struct task_struct *task, struct kmem_cache *ctx_cache, 5437 bool global, gfp_t gfp_flags) 5438 { 5439 struct perf_ctx_data *cd, *old = NULL; 5440 5441 cd = alloc_perf_ctx_data(ctx_cache, global, gfp_flags); 5442 if (!cd) 5443 return -ENOMEM; 5444 5445 for (;;) { 5446 /* Protect @old until inc_not_zero(&old->refcount) */ 5447 guard(rcu)(); 5448 5449 if (try_cmpxchg(&task->perf_ctx_data, &old, cd)) { 5450 if (old) 5451 perf_free_ctx_data_rcu(old); 5452 /* 5453 * Above try_cmpxchg() pairs with try_cmpxchg() from 5454 * detach_task_ctx_data() such that 5455 * if we race with perf_event_exit_task(), we must 5456 * observe PF_EXITING. 5457 */ 5458 if (task->flags & PF_EXITING) { 5459 /* detach_task_ctx_data() may free it already */ 5460 if (try_cmpxchg(&task->perf_ctx_data, &cd, NULL)) 5461 perf_free_ctx_data_rcu(cd); 5462 } 5463 return 0; 5464 } 5465 5466 if (!old) { 5467 /* 5468 * After seeing a dead @old, we raced with 5469 * removal and lost, try again to install @cd. 5470 */ 5471 continue; 5472 } 5473 5474 if (refcount_inc_not_zero(&old->refcount)) { 5475 if (global) 5476 old->global = true; 5477 free_perf_ctx_data(cd); /* unused */ 5478 return 0; 5479 } 5480 5481 /* 5482 * @old is a dead object, refcount==0 is stable, try and 5483 * replace it with @cd. 5484 */ 5485 } 5486 return 0; 5487 } 5488 5489 static void __detach_global_ctx_data(void); 5490 DEFINE_STATIC_PERCPU_RWSEM(global_ctx_data_rwsem); 5491 static refcount_t global_ctx_data_ref; 5492 5493 static int 5494 attach_global_ctx_data(struct kmem_cache *ctx_cache) 5495 { 5496 struct task_struct *g, *p; 5497 struct perf_ctx_data *cd; 5498 int ret; 5499 5500 if (refcount_inc_not_zero(&global_ctx_data_ref)) 5501 return 0; 5502 5503 guard(percpu_write)(&global_ctx_data_rwsem); 5504 if (refcount_inc_not_zero(&global_ctx_data_ref)) 5505 return 0; 5506 again: 5507 /* Allocate everything */ 5508 scoped_guard (rcu) { 5509 for_each_process_thread(g, p) { 5510 if (p->flags & PF_EXITING) 5511 continue; 5512 cd = rcu_dereference(p->perf_ctx_data); 5513 if (cd && !cd->global) { 5514 cd->global = 1; 5515 if (!refcount_inc_not_zero(&cd->refcount)) 5516 cd = NULL; 5517 } 5518 if (!cd) { 5519 /* 5520 * Try to allocate context quickly before 5521 * traversing the whole thread list again. 5522 */ 5523 if (!attach_task_ctx_data(p, ctx_cache, true, GFP_NOWAIT)) 5524 continue; 5525 get_task_struct(p); 5526 goto alloc; 5527 } 5528 } 5529 } 5530 5531 refcount_set(&global_ctx_data_ref, 1); 5532 5533 return 0; 5534 alloc: 5535 ret = attach_task_ctx_data(p, ctx_cache, true, GFP_KERNEL); 5536 put_task_struct(p); 5537 if (ret) { 5538 __detach_global_ctx_data(); 5539 return ret; 5540 } 5541 goto again; 5542 } 5543 5544 static int 5545 attach_perf_ctx_data(struct perf_event *event) 5546 { 5547 struct task_struct *task = event->hw.target; 5548 struct kmem_cache *ctx_cache = event->pmu->task_ctx_cache; 5549 int ret; 5550 5551 if (!ctx_cache) 5552 return -ENOMEM; 5553 5554 if (task) 5555 return attach_task_ctx_data(task, ctx_cache, false, GFP_KERNEL); 5556 5557 ret = attach_global_ctx_data(ctx_cache); 5558 if (ret) 5559 return ret; 5560 5561 event->attach_state |= PERF_ATTACH_GLOBAL_DATA; 5562 return 0; 5563 } 5564 5565 static void 5566 detach_task_ctx_data(struct task_struct *p) 5567 { 5568 struct perf_ctx_data *cd; 5569 5570 scoped_guard (rcu) { 5571 cd = rcu_dereference(p->perf_ctx_data); 5572 if (!cd || !refcount_dec_and_test(&cd->refcount)) 5573 return; 5574 } 5575 5576 /* 5577 * The old ctx_data may be lost because of the race. 5578 * Nothing is required to do for the case. 5579 * See attach_task_ctx_data(). 5580 */ 5581 if (try_cmpxchg((struct perf_ctx_data **)&p->perf_ctx_data, &cd, NULL)) 5582 perf_free_ctx_data_rcu(cd); 5583 } 5584 5585 static void __detach_global_ctx_data(void) 5586 { 5587 struct task_struct *g, *p; 5588 struct perf_ctx_data *cd; 5589 5590 scoped_guard (rcu) { 5591 for_each_process_thread(g, p) { 5592 cd = rcu_dereference(p->perf_ctx_data); 5593 if (cd && cd->global) { 5594 cd->global = 0; 5595 detach_task_ctx_data(p); 5596 } 5597 } 5598 } 5599 } 5600 5601 static void detach_global_ctx_data(void) 5602 { 5603 if (refcount_dec_not_one(&global_ctx_data_ref)) 5604 return; 5605 5606 guard(percpu_write)(&global_ctx_data_rwsem); 5607 if (!refcount_dec_and_test(&global_ctx_data_ref)) 5608 return; 5609 5610 /* remove everything */ 5611 __detach_global_ctx_data(); 5612 } 5613 5614 static void detach_perf_ctx_data(struct perf_event *event) 5615 { 5616 struct task_struct *task = event->hw.target; 5617 5618 event->attach_state &= ~PERF_ATTACH_TASK_DATA; 5619 5620 if (task) 5621 return detach_task_ctx_data(task); 5622 5623 if (event->attach_state & PERF_ATTACH_GLOBAL_DATA) { 5624 detach_global_ctx_data(); 5625 event->attach_state &= ~PERF_ATTACH_GLOBAL_DATA; 5626 } 5627 } 5628 5629 static void unaccount_event(struct perf_event *event) 5630 { 5631 bool dec = false; 5632 5633 if (event->parent) 5634 return; 5635 5636 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB)) 5637 dec = true; 5638 if (event->attr.mmap || event->attr.mmap_data) 5639 atomic_dec(&nr_mmap_events); 5640 if (event->attr.build_id) 5641 atomic_dec(&nr_build_id_events); 5642 if (event->attr.comm) 5643 atomic_dec(&nr_comm_events); 5644 if (event->attr.namespaces) 5645 atomic_dec(&nr_namespaces_events); 5646 if (event->attr.cgroup) 5647 atomic_dec(&nr_cgroup_events); 5648 if (event->attr.task) 5649 atomic_dec(&nr_task_events); 5650 if (event->attr.freq) 5651 unaccount_freq_event(); 5652 if (event->attr.context_switch) { 5653 dec = true; 5654 atomic_dec(&nr_switch_events); 5655 } 5656 if (is_cgroup_event(event)) 5657 dec = true; 5658 if (has_branch_stack(event)) 5659 dec = true; 5660 if (event->attr.ksymbol) 5661 atomic_dec(&nr_ksymbol_events); 5662 if (event->attr.bpf_event) 5663 atomic_dec(&nr_bpf_events); 5664 if (event->attr.text_poke) 5665 atomic_dec(&nr_text_poke_events); 5666 5667 if (dec) { 5668 if (!atomic_add_unless(&perf_sched_count, -1, 1)) 5669 schedule_delayed_work(&perf_sched_work, HZ); 5670 } 5671 5672 unaccount_pmu_sb_event(event); 5673 } 5674 5675 static void perf_sched_delayed(struct work_struct *work) 5676 { 5677 mutex_lock(&perf_sched_mutex); 5678 if (atomic_dec_and_test(&perf_sched_count)) 5679 static_branch_disable(&perf_sched_events); 5680 mutex_unlock(&perf_sched_mutex); 5681 } 5682 5683 /* 5684 * The following implement mutual exclusion of events on "exclusive" pmus 5685 * (PERF_PMU_CAP_EXCLUSIVE). Such pmus can only have one event scheduled 5686 * at a time, so we disallow creating events that might conflict, namely: 5687 * 5688 * 1) cpu-wide events in the presence of per-task events, 5689 * 2) per-task events in the presence of cpu-wide events, 5690 * 3) two matching events on the same perf_event_context. 5691 * 5692 * The former two cases are handled in the allocation path (perf_event_alloc(), 5693 * _free_event()), the latter -- before the first perf_install_in_context(). 5694 */ 5695 static int exclusive_event_init(struct perf_event *event) 5696 { 5697 struct pmu *pmu = event->pmu; 5698 5699 if (!is_exclusive_pmu(pmu)) 5700 return 0; 5701 5702 /* 5703 * Prevent co-existence of per-task and cpu-wide events on the 5704 * same exclusive pmu. 5705 * 5706 * Negative pmu::exclusive_cnt means there are cpu-wide 5707 * events on this "exclusive" pmu, positive means there are 5708 * per-task events. 5709 * 5710 * Since this is called in perf_event_alloc() path, event::ctx 5711 * doesn't exist yet; it is, however, safe to use PERF_ATTACH_TASK 5712 * to mean "per-task event", because unlike other attach states it 5713 * never gets cleared. 5714 */ 5715 if (event->attach_state & PERF_ATTACH_TASK) { 5716 if (!atomic_inc_unless_negative(&pmu->exclusive_cnt)) 5717 return -EBUSY; 5718 } else { 5719 if (!atomic_dec_unless_positive(&pmu->exclusive_cnt)) 5720 return -EBUSY; 5721 } 5722 5723 event->attach_state |= PERF_ATTACH_EXCLUSIVE; 5724 5725 return 0; 5726 } 5727 5728 static void exclusive_event_destroy(struct perf_event *event) 5729 { 5730 struct pmu *pmu = event->pmu; 5731 5732 /* see comment in exclusive_event_init() */ 5733 if (event->attach_state & PERF_ATTACH_TASK) 5734 atomic_dec(&pmu->exclusive_cnt); 5735 else 5736 atomic_inc(&pmu->exclusive_cnt); 5737 5738 event->attach_state &= ~PERF_ATTACH_EXCLUSIVE; 5739 } 5740 5741 static bool exclusive_event_match(struct perf_event *e1, struct perf_event *e2) 5742 { 5743 if ((e1->pmu == e2->pmu) && 5744 (e1->cpu == e2->cpu || 5745 e1->cpu == -1 || 5746 e2->cpu == -1)) 5747 return true; 5748 return false; 5749 } 5750 5751 static bool exclusive_event_installable(struct perf_event *event, 5752 struct perf_event_context *ctx) 5753 { 5754 struct perf_event *iter_event; 5755 struct pmu *pmu = event->pmu; 5756 5757 lockdep_assert_held(&ctx->mutex); 5758 5759 if (!is_exclusive_pmu(pmu)) 5760 return true; 5761 5762 list_for_each_entry(iter_event, &ctx->event_list, event_entry) { 5763 if (exclusive_event_match(iter_event, event)) 5764 return false; 5765 } 5766 5767 return true; 5768 } 5769 5770 static void perf_free_addr_filters(struct perf_event *event); 5771 5772 /* vs perf_event_alloc() error */ 5773 static void __free_event(struct perf_event *event) 5774 { 5775 struct pmu *pmu = event->pmu; 5776 5777 security_perf_event_free(event); 5778 5779 if (event->attach_state & PERF_ATTACH_CALLCHAIN) 5780 put_callchain_buffers(); 5781 5782 if (event->attach_state & PERF_ATTACH_EXCLUSIVE) 5783 exclusive_event_destroy(event); 5784 5785 if (is_cgroup_event(event)) 5786 perf_detach_cgroup(event); 5787 5788 if (event->attach_state & PERF_ATTACH_TASK_DATA) 5789 detach_perf_ctx_data(event); 5790 5791 if (event->destroy) 5792 event->destroy(event); 5793 5794 /* 5795 * Must be after ->destroy(), due to uprobe_perf_close() using 5796 * hw.target. 5797 */ 5798 if (event->hw.target) 5799 put_task_struct(event->hw.target); 5800 5801 if (event->pmu_ctx) { 5802 /* 5803 * put_pmu_ctx() needs an event->ctx reference, because of 5804 * epc->ctx. 5805 */ 5806 WARN_ON_ONCE(!pmu); 5807 WARN_ON_ONCE(!event->ctx); 5808 WARN_ON_ONCE(event->pmu_ctx->ctx != event->ctx); 5809 put_pmu_ctx(event->pmu_ctx); 5810 } 5811 5812 /* 5813 * perf_event_free_task() relies on put_ctx() being 'last', in 5814 * particular all task references must be cleaned up. 5815 */ 5816 if (event->ctx) 5817 put_ctx(event->ctx); 5818 5819 if (pmu) { 5820 module_put(pmu->module); 5821 scoped_guard (spinlock, &pmu->events_lock) { 5822 list_del(&event->pmu_list); 5823 wake_up_var(pmu); 5824 } 5825 } 5826 5827 call_rcu(&event->rcu_head, free_event_rcu); 5828 } 5829 5830 static void mediated_pmu_unaccount_event(struct perf_event *event); 5831 5832 DEFINE_FREE(__free_event, struct perf_event *, if (_T) __free_event(_T)) 5833 5834 /* vs perf_event_alloc() success */ 5835 static void _free_event(struct perf_event *event) 5836 { 5837 irq_work_sync(&event->pending_irq); 5838 irq_work_sync(&event->pending_disable_irq); 5839 5840 unaccount_event(event); 5841 mediated_pmu_unaccount_event(event); 5842 5843 if (event->rb) { 5844 /* 5845 * Can happen when we close an event with re-directed output. 5846 * 5847 * Since we have a 0 refcount, perf_mmap_close() will skip 5848 * over us; possibly making our ring_buffer_put() the last. 5849 */ 5850 mutex_lock(&event->mmap_mutex); 5851 ring_buffer_attach(event, NULL); 5852 mutex_unlock(&event->mmap_mutex); 5853 } 5854 5855 perf_event_free_bpf_prog(event); 5856 perf_free_addr_filters(event); 5857 5858 __free_event(event); 5859 } 5860 5861 /* 5862 * Used to free events which have a known refcount of 1, such as in error paths 5863 * of inherited events. 5864 */ 5865 static void free_event(struct perf_event *event) 5866 { 5867 if (WARN(atomic_long_cmpxchg(&event->refcount, 1, 0) != 1, 5868 "unexpected event refcount: %ld; ptr=%p\n", 5869 atomic_long_read(&event->refcount), event)) { 5870 /* leak to avoid use-after-free */ 5871 return; 5872 } 5873 5874 _free_event(event); 5875 } 5876 5877 /* 5878 * Remove user event from the owner task. 5879 */ 5880 static void perf_remove_from_owner(struct perf_event *event) 5881 { 5882 struct task_struct *owner; 5883 5884 rcu_read_lock(); 5885 /* 5886 * Matches the smp_store_release() in perf_event_exit_task(). If we 5887 * observe !owner it means the list deletion is complete and we can 5888 * indeed free this event, otherwise we need to serialize on 5889 * owner->perf_event_mutex. 5890 */ 5891 owner = READ_ONCE(event->owner); 5892 if (owner) { 5893 /* 5894 * Since delayed_put_task_struct() also drops the last 5895 * task reference we can safely take a new reference 5896 * while holding the rcu_read_lock(). 5897 */ 5898 get_task_struct(owner); 5899 } 5900 rcu_read_unlock(); 5901 5902 if (owner) { 5903 /* 5904 * If we're here through perf_event_exit_task() we're already 5905 * holding ctx->mutex which would be an inversion wrt. the 5906 * normal lock order. 5907 * 5908 * However we can safely take this lock because its the child 5909 * ctx->mutex. 5910 */ 5911 mutex_lock_nested(&owner->perf_event_mutex, SINGLE_DEPTH_NESTING); 5912 5913 /* 5914 * We have to re-check the event->owner field, if it is cleared 5915 * we raced with perf_event_exit_task(), acquiring the mutex 5916 * ensured they're done, and we can proceed with freeing the 5917 * event. 5918 */ 5919 if (event->owner) { 5920 list_del_init(&event->owner_entry); 5921 smp_store_release(&event->owner, NULL); 5922 } 5923 mutex_unlock(&owner->perf_event_mutex); 5924 put_task_struct(owner); 5925 } 5926 } 5927 5928 static void put_event(struct perf_event *event) 5929 { 5930 struct perf_event *parent; 5931 5932 if (!atomic_long_dec_and_test(&event->refcount)) 5933 return; 5934 5935 parent = event->parent; 5936 _free_event(event); 5937 5938 /* Matches the refcount bump in inherit_event() */ 5939 if (parent) 5940 put_event(parent); 5941 } 5942 5943 /* 5944 * Kill an event dead; while event:refcount will preserve the event 5945 * object, it will not preserve its functionality. Once the last 'user' 5946 * gives up the object, we'll destroy the thing. 5947 */ 5948 int perf_event_release_kernel(struct perf_event *event) 5949 { 5950 struct perf_event_context *ctx = event->ctx; 5951 struct perf_event *child, *tmp; 5952 5953 /* 5954 * If we got here through err_alloc: free_event(event); we will not 5955 * have attached to a context yet. 5956 */ 5957 if (!ctx) { 5958 WARN_ON_ONCE(event->attach_state & 5959 (PERF_ATTACH_CONTEXT|PERF_ATTACH_GROUP)); 5960 goto no_ctx; 5961 } 5962 5963 if (!is_kernel_event(event)) 5964 perf_remove_from_owner(event); 5965 5966 ctx = perf_event_ctx_lock(event); 5967 WARN_ON_ONCE(ctx->parent_ctx); 5968 5969 /* 5970 * Mark this event as STATE_DEAD, there is no external reference to it 5971 * anymore. 5972 * 5973 * Anybody acquiring event->child_mutex after the below loop _must_ 5974 * also see this, most importantly inherit_event() which will avoid 5975 * placing more children on the list. 5976 * 5977 * Thus this guarantees that we will in fact observe and kill _ALL_ 5978 * child events. 5979 */ 5980 if (event->state > PERF_EVENT_STATE_REVOKED) { 5981 perf_remove_from_context(event, DETACH_GROUP|DETACH_DEAD); 5982 } else { 5983 event->state = PERF_EVENT_STATE_DEAD; 5984 } 5985 5986 perf_event_ctx_unlock(event, ctx); 5987 5988 again: 5989 mutex_lock(&event->child_mutex); 5990 list_for_each_entry(child, &event->child_list, child_list) { 5991 /* 5992 * Cannot change, child events are not migrated, see the 5993 * comment with perf_event_ctx_lock_nested(). 5994 */ 5995 ctx = READ_ONCE(child->ctx); 5996 /* 5997 * Since child_mutex nests inside ctx::mutex, we must jump 5998 * through hoops. We start by grabbing a reference on the ctx. 5999 * 6000 * Since the event cannot get freed while we hold the 6001 * child_mutex, the context must also exist and have a !0 6002 * reference count. 6003 */ 6004 get_ctx(ctx); 6005 6006 /* 6007 * Now that we have a ctx ref, we can drop child_mutex, and 6008 * acquire ctx::mutex without fear of it going away. Then we 6009 * can re-acquire child_mutex. 6010 */ 6011 mutex_unlock(&event->child_mutex); 6012 mutex_lock(&ctx->mutex); 6013 mutex_lock(&event->child_mutex); 6014 6015 /* 6016 * Now that we hold ctx::mutex and child_mutex, revalidate our 6017 * state, if child is still the first entry, it didn't get freed 6018 * and we can continue doing so. 6019 */ 6020 tmp = list_first_entry_or_null(&event->child_list, 6021 struct perf_event, child_list); 6022 if (tmp == child) { 6023 perf_remove_from_context(child, DETACH_GROUP | DETACH_CHILD); 6024 } else { 6025 child = NULL; 6026 } 6027 6028 mutex_unlock(&event->child_mutex); 6029 mutex_unlock(&ctx->mutex); 6030 6031 if (child) { 6032 /* Last reference unless ->pending_task work is pending */ 6033 put_event(child); 6034 } 6035 put_ctx(ctx); 6036 6037 goto again; 6038 } 6039 mutex_unlock(&event->child_mutex); 6040 6041 no_ctx: 6042 /* 6043 * Last reference unless ->pending_task work is pending on this event 6044 * or any of its children. 6045 */ 6046 put_event(event); 6047 return 0; 6048 } 6049 EXPORT_SYMBOL_GPL(perf_event_release_kernel); 6050 6051 /* 6052 * Called when the last reference to the file is gone. 6053 */ 6054 static int perf_release(struct inode *inode, struct file *file) 6055 { 6056 perf_event_release_kernel(file->private_data); 6057 return 0; 6058 } 6059 6060 static u64 __perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 6061 { 6062 struct perf_event *child; 6063 u64 total = 0; 6064 6065 *enabled = 0; 6066 *running = 0; 6067 6068 mutex_lock(&event->child_mutex); 6069 6070 (void)perf_event_read(event, false); 6071 total += perf_event_count(event, false); 6072 6073 *enabled += event->total_time_enabled + 6074 atomic64_read(&event->child_total_time_enabled); 6075 *running += event->total_time_running + 6076 atomic64_read(&event->child_total_time_running); 6077 6078 list_for_each_entry(child, &event->child_list, child_list) { 6079 (void)perf_event_read(child, false); 6080 total += perf_event_count(child, false); 6081 *enabled += child->total_time_enabled; 6082 *running += child->total_time_running; 6083 } 6084 mutex_unlock(&event->child_mutex); 6085 6086 return total; 6087 } 6088 6089 u64 perf_event_read_value(struct perf_event *event, u64 *enabled, u64 *running) 6090 { 6091 struct perf_event_context *ctx; 6092 u64 count; 6093 6094 ctx = perf_event_ctx_lock(event); 6095 count = __perf_event_read_value(event, enabled, running); 6096 perf_event_ctx_unlock(event, ctx); 6097 6098 return count; 6099 } 6100 EXPORT_SYMBOL_GPL(perf_event_read_value); 6101 6102 static int __perf_read_group_add(struct perf_event *leader, 6103 u64 read_format, u64 *values) 6104 { 6105 struct perf_event_context *ctx = leader->ctx; 6106 struct perf_event *sub, *parent; 6107 unsigned long flags; 6108 int n = 1; /* skip @nr */ 6109 int ret; 6110 6111 ret = perf_event_read(leader, true); 6112 if (ret) 6113 return ret; 6114 6115 raw_spin_lock_irqsave(&ctx->lock, flags); 6116 /* 6117 * Verify the grouping between the parent and child (inherited) 6118 * events is still in tact. 6119 * 6120 * Specifically: 6121 * - leader->ctx->lock pins leader->sibling_list 6122 * - parent->child_mutex pins parent->child_list 6123 * - parent->ctx->mutex pins parent->sibling_list 6124 * 6125 * Because parent->ctx != leader->ctx (and child_list nests inside 6126 * ctx->mutex), group destruction is not atomic between children, also 6127 * see perf_event_release_kernel(). Additionally, parent can grow the 6128 * group. 6129 * 6130 * Therefore it is possible to have parent and child groups in a 6131 * different configuration and summing over such a beast makes no sense 6132 * what so ever. 6133 * 6134 * Reject this. 6135 */ 6136 parent = leader->parent; 6137 if (parent && 6138 (parent->group_generation != leader->group_generation || 6139 parent->nr_siblings != leader->nr_siblings)) { 6140 ret = -ECHILD; 6141 goto unlock; 6142 } 6143 6144 /* 6145 * Since we co-schedule groups, {enabled,running} times of siblings 6146 * will be identical to those of the leader, so we only publish one 6147 * set. 6148 */ 6149 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 6150 values[n++] += leader->total_time_enabled + 6151 atomic64_read(&leader->child_total_time_enabled); 6152 } 6153 6154 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 6155 values[n++] += leader->total_time_running + 6156 atomic64_read(&leader->child_total_time_running); 6157 } 6158 6159 /* 6160 * Write {count,id} tuples for every sibling. 6161 */ 6162 values[n++] += perf_event_count(leader, false); 6163 if (read_format & PERF_FORMAT_ID) 6164 values[n++] = primary_event_id(leader); 6165 if (read_format & PERF_FORMAT_LOST) 6166 values[n++] = atomic64_read(&leader->lost_samples); 6167 6168 for_each_sibling_event(sub, leader) { 6169 values[n++] += perf_event_count(sub, false); 6170 if (read_format & PERF_FORMAT_ID) 6171 values[n++] = primary_event_id(sub); 6172 if (read_format & PERF_FORMAT_LOST) 6173 values[n++] = atomic64_read(&sub->lost_samples); 6174 } 6175 6176 unlock: 6177 raw_spin_unlock_irqrestore(&ctx->lock, flags); 6178 return ret; 6179 } 6180 6181 static int perf_read_group(struct perf_event *event, 6182 u64 read_format, char __user *buf) 6183 { 6184 struct perf_event *leader = event->group_leader, *child; 6185 struct perf_event_context *ctx = leader->ctx; 6186 int ret; 6187 u64 *values; 6188 6189 lockdep_assert_held(&ctx->mutex); 6190 6191 values = kzalloc(event->read_size, GFP_KERNEL); 6192 if (!values) 6193 return -ENOMEM; 6194 6195 values[0] = 1 + leader->nr_siblings; 6196 6197 mutex_lock(&leader->child_mutex); 6198 6199 ret = __perf_read_group_add(leader, read_format, values); 6200 if (ret) 6201 goto unlock; 6202 6203 list_for_each_entry(child, &leader->child_list, child_list) { 6204 ret = __perf_read_group_add(child, read_format, values); 6205 if (ret) 6206 goto unlock; 6207 } 6208 6209 mutex_unlock(&leader->child_mutex); 6210 6211 ret = event->read_size; 6212 if (copy_to_user(buf, values, event->read_size)) 6213 ret = -EFAULT; 6214 goto out; 6215 6216 unlock: 6217 mutex_unlock(&leader->child_mutex); 6218 out: 6219 kfree(values); 6220 return ret; 6221 } 6222 6223 static int perf_read_one(struct perf_event *event, 6224 u64 read_format, char __user *buf) 6225 { 6226 u64 enabled, running; 6227 u64 values[5]; 6228 int n = 0; 6229 6230 values[n++] = __perf_event_read_value(event, &enabled, &running); 6231 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 6232 values[n++] = enabled; 6233 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 6234 values[n++] = running; 6235 if (read_format & PERF_FORMAT_ID) 6236 values[n++] = primary_event_id(event); 6237 if (read_format & PERF_FORMAT_LOST) 6238 values[n++] = atomic64_read(&event->lost_samples); 6239 6240 if (copy_to_user(buf, values, n * sizeof(u64))) 6241 return -EFAULT; 6242 6243 return n * sizeof(u64); 6244 } 6245 6246 static bool is_event_hup(struct perf_event *event) 6247 { 6248 bool no_children; 6249 6250 if (event->state > PERF_EVENT_STATE_EXIT) 6251 return false; 6252 6253 mutex_lock(&event->child_mutex); 6254 no_children = list_empty(&event->child_list); 6255 mutex_unlock(&event->child_mutex); 6256 return no_children; 6257 } 6258 6259 /* 6260 * Read the performance event - simple non blocking version for now 6261 */ 6262 static ssize_t 6263 __perf_read(struct perf_event *event, char __user *buf, size_t count) 6264 { 6265 u64 read_format = event->attr.read_format; 6266 int ret; 6267 6268 /* 6269 * Return end-of-file for a read on an event that is in 6270 * error state (i.e. because it was pinned but it couldn't be 6271 * scheduled on to the CPU at some point). 6272 */ 6273 if (event->state == PERF_EVENT_STATE_ERROR) 6274 return 0; 6275 6276 if (count < event->read_size) 6277 return -ENOSPC; 6278 6279 WARN_ON_ONCE(event->ctx->parent_ctx); 6280 if (read_format & PERF_FORMAT_GROUP) 6281 ret = perf_read_group(event, read_format, buf); 6282 else 6283 ret = perf_read_one(event, read_format, buf); 6284 6285 return ret; 6286 } 6287 6288 static ssize_t 6289 perf_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) 6290 { 6291 struct perf_event *event = file->private_data; 6292 struct perf_event_context *ctx; 6293 int ret; 6294 6295 ret = security_perf_event_read(event); 6296 if (ret) 6297 return ret; 6298 6299 ctx = perf_event_ctx_lock(event); 6300 ret = __perf_read(event, buf, count); 6301 perf_event_ctx_unlock(event, ctx); 6302 6303 return ret; 6304 } 6305 6306 static __poll_t perf_poll(struct file *file, poll_table *wait) 6307 { 6308 struct perf_event *event = file->private_data; 6309 struct perf_buffer *rb; 6310 __poll_t events = EPOLLHUP; 6311 6312 if (event->state <= PERF_EVENT_STATE_REVOKED) 6313 return EPOLLERR; 6314 6315 poll_wait(file, &event->waitq, wait); 6316 6317 if (event->state <= PERF_EVENT_STATE_REVOKED) 6318 return EPOLLERR; 6319 6320 if (is_event_hup(event)) 6321 return events; 6322 6323 if (unlikely(READ_ONCE(event->state) == PERF_EVENT_STATE_ERROR && 6324 event->attr.pinned)) 6325 return EPOLLERR; 6326 6327 /* 6328 * Pin the event->rb by taking event->mmap_mutex; otherwise 6329 * perf_event_set_output() can swizzle our rb and make us miss wakeups. 6330 */ 6331 mutex_lock(&event->mmap_mutex); 6332 rb = event->rb; 6333 if (rb) 6334 events = atomic_xchg(&rb->poll, 0); 6335 mutex_unlock(&event->mmap_mutex); 6336 return events; 6337 } 6338 6339 static void _perf_event_reset(struct perf_event *event) 6340 { 6341 (void)perf_event_read(event, false); 6342 local64_set(&event->count, 0); 6343 perf_event_update_userpage(event); 6344 } 6345 6346 /* Assume it's not an event with inherit set. */ 6347 u64 perf_event_pause(struct perf_event *event, bool reset) 6348 { 6349 struct perf_event_context *ctx; 6350 u64 count; 6351 6352 ctx = perf_event_ctx_lock(event); 6353 WARN_ON_ONCE(event->attr.inherit); 6354 _perf_event_disable(event); 6355 count = local64_read(&event->count); 6356 if (reset) 6357 local64_set(&event->count, 0); 6358 perf_event_ctx_unlock(event, ctx); 6359 6360 return count; 6361 } 6362 EXPORT_SYMBOL_GPL(perf_event_pause); 6363 6364 #ifdef CONFIG_PERF_GUEST_MEDIATED_PMU 6365 static atomic_t nr_include_guest_events __read_mostly; 6366 6367 static atomic_t nr_mediated_pmu_vms __read_mostly; 6368 static DEFINE_MUTEX(perf_mediated_pmu_mutex); 6369 6370 /* !exclude_guest event of PMU with PERF_PMU_CAP_MEDIATED_VPMU */ 6371 static inline bool is_include_guest_event(struct perf_event *event) 6372 { 6373 if (!event->pmu) 6374 return false; 6375 6376 if ((event->pmu->capabilities & PERF_PMU_CAP_MEDIATED_VPMU) && 6377 !event->attr.exclude_guest) 6378 return true; 6379 6380 return false; 6381 } 6382 6383 static int mediated_pmu_account_event(struct perf_event *event) 6384 { 6385 if (!is_include_guest_event(event)) 6386 return 0; 6387 6388 if (atomic_inc_not_zero(&nr_include_guest_events)) 6389 return 0; 6390 6391 guard(mutex)(&perf_mediated_pmu_mutex); 6392 if (atomic_read(&nr_mediated_pmu_vms)) 6393 return -EOPNOTSUPP; 6394 6395 atomic_inc(&nr_include_guest_events); 6396 return 0; 6397 } 6398 6399 static void mediated_pmu_unaccount_event(struct perf_event *event) 6400 { 6401 if (!is_include_guest_event(event)) 6402 return; 6403 6404 if (WARN_ON_ONCE(!atomic_read(&nr_include_guest_events))) 6405 return; 6406 6407 atomic_dec(&nr_include_guest_events); 6408 } 6409 6410 /* 6411 * Currently invoked at VM creation to 6412 * - Check whether there are existing !exclude_guest events of PMU with 6413 * PERF_PMU_CAP_MEDIATED_VPMU 6414 * - Set nr_mediated_pmu_vms to prevent !exclude_guest event creation on 6415 * PMUs with PERF_PMU_CAP_MEDIATED_VPMU 6416 * 6417 * No impact for the PMU without PERF_PMU_CAP_MEDIATED_VPMU. The perf 6418 * still owns all the PMU resources. 6419 */ 6420 int perf_create_mediated_pmu(void) 6421 { 6422 if (atomic_inc_not_zero(&nr_mediated_pmu_vms)) 6423 return 0; 6424 6425 guard(mutex)(&perf_mediated_pmu_mutex); 6426 if (atomic_read(&nr_include_guest_events)) 6427 return -EBUSY; 6428 6429 atomic_inc(&nr_mediated_pmu_vms); 6430 return 0; 6431 } 6432 EXPORT_SYMBOL_FOR_KVM(perf_create_mediated_pmu); 6433 6434 void perf_release_mediated_pmu(void) 6435 { 6436 if (WARN_ON_ONCE(!atomic_read(&nr_mediated_pmu_vms))) 6437 return; 6438 6439 atomic_dec(&nr_mediated_pmu_vms); 6440 } 6441 EXPORT_SYMBOL_FOR_KVM(perf_release_mediated_pmu); 6442 6443 /* When loading a guest's mediated PMU, schedule out all exclude_guest events. */ 6444 void perf_load_guest_context(void) 6445 { 6446 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 6447 6448 lockdep_assert_irqs_disabled(); 6449 6450 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx); 6451 6452 if (WARN_ON_ONCE(__this_cpu_read(guest_ctx_loaded))) 6453 return; 6454 6455 perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST); 6456 ctx_sched_out(&cpuctx->ctx, NULL, EVENT_GUEST); 6457 if (cpuctx->task_ctx) { 6458 perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST); 6459 task_ctx_sched_out(cpuctx->task_ctx, NULL, EVENT_GUEST); 6460 } 6461 6462 perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST); 6463 if (cpuctx->task_ctx) 6464 perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST); 6465 6466 __this_cpu_write(guest_ctx_loaded, true); 6467 } 6468 EXPORT_SYMBOL_GPL(perf_load_guest_context); 6469 6470 void perf_put_guest_context(void) 6471 { 6472 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 6473 6474 lockdep_assert_irqs_disabled(); 6475 6476 guard(perf_ctx_lock)(cpuctx, cpuctx->task_ctx); 6477 6478 if (WARN_ON_ONCE(!__this_cpu_read(guest_ctx_loaded))) 6479 return; 6480 6481 perf_ctx_disable(&cpuctx->ctx, EVENT_GUEST); 6482 if (cpuctx->task_ctx) 6483 perf_ctx_disable(cpuctx->task_ctx, EVENT_GUEST); 6484 6485 perf_event_sched_in(cpuctx, cpuctx->task_ctx, NULL, EVENT_GUEST); 6486 6487 if (cpuctx->task_ctx) 6488 perf_ctx_enable(cpuctx->task_ctx, EVENT_GUEST); 6489 perf_ctx_enable(&cpuctx->ctx, EVENT_GUEST); 6490 6491 __this_cpu_write(guest_ctx_loaded, false); 6492 } 6493 EXPORT_SYMBOL_GPL(perf_put_guest_context); 6494 #else 6495 static int mediated_pmu_account_event(struct perf_event *event) { return 0; } 6496 static void mediated_pmu_unaccount_event(struct perf_event *event) {} 6497 #endif 6498 6499 /* 6500 * Holding the top-level event's child_mutex means that any 6501 * descendant process that has inherited this event will block 6502 * in perf_event_exit_event() if it goes to exit, thus satisfying the 6503 * task existence requirements of perf_event_enable/disable. 6504 */ 6505 static void perf_event_for_each_child(struct perf_event *event, 6506 void (*func)(struct perf_event *)) 6507 { 6508 struct perf_event *child; 6509 6510 WARN_ON_ONCE(event->ctx->parent_ctx); 6511 6512 mutex_lock(&event->child_mutex); 6513 func(event); 6514 list_for_each_entry(child, &event->child_list, child_list) 6515 func(child); 6516 mutex_unlock(&event->child_mutex); 6517 } 6518 6519 static void perf_event_for_each(struct perf_event *event, 6520 void (*func)(struct perf_event *)) 6521 { 6522 struct perf_event_context *ctx = event->ctx; 6523 struct perf_event *sibling; 6524 6525 lockdep_assert_held(&ctx->mutex); 6526 6527 event = event->group_leader; 6528 6529 perf_event_for_each_child(event, func); 6530 for_each_sibling_event(sibling, event) 6531 perf_event_for_each_child(sibling, func); 6532 } 6533 6534 static void __perf_event_period(struct perf_event *event, 6535 struct perf_cpu_context *cpuctx, 6536 struct perf_event_context *ctx, 6537 void *info) 6538 { 6539 u64 value = *((u64 *)info); 6540 bool active; 6541 6542 if (event->attr.freq) { 6543 event->attr.sample_freq = value; 6544 } else { 6545 event->attr.sample_period = value; 6546 event->hw.sample_period = value; 6547 } 6548 6549 active = (event->state == PERF_EVENT_STATE_ACTIVE); 6550 if (active) { 6551 perf_pmu_disable(event->pmu); 6552 event->pmu->stop(event, PERF_EF_UPDATE); 6553 } 6554 6555 local64_set(&event->hw.period_left, 0); 6556 6557 if (active) { 6558 event->pmu->start(event, PERF_EF_RELOAD); 6559 /* 6560 * Once the period is force-reset, the event starts immediately. 6561 * But the event/group could be throttled. Unthrottle the 6562 * event/group now to avoid the next tick trying to unthrottle 6563 * while we already re-started the event/group. 6564 */ 6565 if (event->hw.interrupts == MAX_INTERRUPTS) 6566 perf_event_unthrottle_group(event, true); 6567 perf_pmu_enable(event->pmu); 6568 } 6569 } 6570 6571 static int perf_event_check_period(struct perf_event *event, u64 value) 6572 { 6573 return event->pmu->check_period(event, value); 6574 } 6575 6576 static int _perf_event_period(struct perf_event *event, u64 value) 6577 { 6578 if (!is_sampling_event(event)) 6579 return -EINVAL; 6580 6581 if (!value) 6582 return -EINVAL; 6583 6584 if (event->attr.freq) { 6585 if (value > sysctl_perf_event_sample_rate) 6586 return -EINVAL; 6587 } else { 6588 if (perf_event_check_period(event, value)) 6589 return -EINVAL; 6590 if (value & (1ULL << 63)) 6591 return -EINVAL; 6592 } 6593 6594 event_function_call(event, __perf_event_period, &value); 6595 6596 return 0; 6597 } 6598 6599 int perf_event_period(struct perf_event *event, u64 value) 6600 { 6601 struct perf_event_context *ctx; 6602 int ret; 6603 6604 ctx = perf_event_ctx_lock(event); 6605 ret = _perf_event_period(event, value); 6606 perf_event_ctx_unlock(event, ctx); 6607 6608 return ret; 6609 } 6610 EXPORT_SYMBOL_GPL(perf_event_period); 6611 6612 static const struct file_operations perf_fops; 6613 6614 static inline bool is_perf_file(struct fd f) 6615 { 6616 return !fd_empty(f) && fd_file(f)->f_op == &perf_fops; 6617 } 6618 6619 static int perf_event_set_output(struct perf_event *event, 6620 struct perf_event *output_event); 6621 static int perf_event_set_filter(struct perf_event *event, void __user *arg); 6622 static int perf_copy_attr(struct perf_event_attr __user *uattr, 6623 struct perf_event_attr *attr); 6624 static int __perf_event_set_bpf_prog(struct perf_event *event, 6625 struct bpf_prog *prog, 6626 u64 bpf_cookie); 6627 6628 static long _perf_ioctl(struct perf_event *event, unsigned int cmd, unsigned long arg) 6629 { 6630 void (*func)(struct perf_event *); 6631 u32 flags = arg; 6632 6633 if (event->state <= PERF_EVENT_STATE_REVOKED) 6634 return -ENODEV; 6635 6636 switch (cmd) { 6637 case PERF_EVENT_IOC_ENABLE: 6638 func = _perf_event_enable; 6639 break; 6640 case PERF_EVENT_IOC_DISABLE: 6641 func = _perf_event_disable; 6642 break; 6643 case PERF_EVENT_IOC_RESET: 6644 func = _perf_event_reset; 6645 break; 6646 6647 case PERF_EVENT_IOC_REFRESH: 6648 return _perf_event_refresh(event, arg); 6649 6650 case PERF_EVENT_IOC_PERIOD: 6651 { 6652 u64 value; 6653 6654 if (copy_from_user(&value, (u64 __user *)arg, sizeof(value))) 6655 return -EFAULT; 6656 6657 return _perf_event_period(event, value); 6658 } 6659 case PERF_EVENT_IOC_ID: 6660 { 6661 u64 id = primary_event_id(event); 6662 6663 if (copy_to_user((void __user *)arg, &id, sizeof(id))) 6664 return -EFAULT; 6665 return 0; 6666 } 6667 6668 case PERF_EVENT_IOC_SET_OUTPUT: 6669 { 6670 CLASS(fd, output)(arg); // arg == -1 => empty 6671 struct perf_event *output_event = NULL; 6672 if (arg != -1) { 6673 if (!is_perf_file(output)) 6674 return -EBADF; 6675 output_event = fd_file(output)->private_data; 6676 } 6677 return perf_event_set_output(event, output_event); 6678 } 6679 6680 case PERF_EVENT_IOC_SET_FILTER: 6681 return perf_event_set_filter(event, (void __user *)arg); 6682 6683 case PERF_EVENT_IOC_SET_BPF: 6684 { 6685 struct bpf_prog *prog; 6686 int err; 6687 6688 prog = bpf_prog_get(arg); 6689 if (IS_ERR(prog)) 6690 return PTR_ERR(prog); 6691 6692 err = __perf_event_set_bpf_prog(event, prog, 0); 6693 if (err) { 6694 bpf_prog_put(prog); 6695 return err; 6696 } 6697 6698 return 0; 6699 } 6700 6701 case PERF_EVENT_IOC_PAUSE_OUTPUT: { 6702 struct perf_buffer *rb; 6703 6704 rcu_read_lock(); 6705 rb = rcu_dereference(event->rb); 6706 if (!rb || !rb->nr_pages) { 6707 rcu_read_unlock(); 6708 return -EINVAL; 6709 } 6710 rb_toggle_paused(rb, !!arg); 6711 rcu_read_unlock(); 6712 return 0; 6713 } 6714 6715 case PERF_EVENT_IOC_QUERY_BPF: 6716 return perf_event_query_prog_array(event, (void __user *)arg); 6717 6718 case PERF_EVENT_IOC_MODIFY_ATTRIBUTES: { 6719 struct perf_event_attr new_attr; 6720 int err = perf_copy_attr((struct perf_event_attr __user *)arg, 6721 &new_attr); 6722 6723 if (err) 6724 return err; 6725 6726 return perf_event_modify_attr(event, &new_attr); 6727 } 6728 default: 6729 return -ENOTTY; 6730 } 6731 6732 if (flags & PERF_IOC_FLAG_GROUP) 6733 perf_event_for_each(event, func); 6734 else 6735 perf_event_for_each_child(event, func); 6736 6737 return 0; 6738 } 6739 6740 static long perf_ioctl(struct file *file, unsigned int cmd, unsigned long arg) 6741 { 6742 struct perf_event *event = file->private_data; 6743 struct perf_event_context *ctx; 6744 long ret; 6745 6746 /* Treat ioctl like writes as it is likely a mutating operation. */ 6747 ret = security_perf_event_write(event); 6748 if (ret) 6749 return ret; 6750 6751 ctx = perf_event_ctx_lock(event); 6752 ret = _perf_ioctl(event, cmd, arg); 6753 perf_event_ctx_unlock(event, ctx); 6754 6755 return ret; 6756 } 6757 6758 #ifdef CONFIG_COMPAT 6759 static long perf_compat_ioctl(struct file *file, unsigned int cmd, 6760 unsigned long arg) 6761 { 6762 switch (_IOC_NR(cmd)) { 6763 case _IOC_NR(PERF_EVENT_IOC_SET_FILTER): 6764 case _IOC_NR(PERF_EVENT_IOC_ID): 6765 case _IOC_NR(PERF_EVENT_IOC_QUERY_BPF): 6766 case _IOC_NR(PERF_EVENT_IOC_MODIFY_ATTRIBUTES): 6767 /* Fix up pointer size (usually 4 -> 8 in 32-on-64-bit case */ 6768 if (_IOC_SIZE(cmd) == sizeof(compat_uptr_t)) { 6769 cmd &= ~IOCSIZE_MASK; 6770 cmd |= sizeof(void *) << IOCSIZE_SHIFT; 6771 } 6772 break; 6773 } 6774 return perf_ioctl(file, cmd, arg); 6775 } 6776 #else 6777 # define perf_compat_ioctl NULL 6778 #endif 6779 6780 int perf_event_task_enable(void) 6781 { 6782 struct perf_event_context *ctx; 6783 struct perf_event *event; 6784 6785 mutex_lock(¤t->perf_event_mutex); 6786 list_for_each_entry(event, ¤t->perf_event_list, owner_entry) { 6787 ctx = perf_event_ctx_lock(event); 6788 perf_event_for_each_child(event, _perf_event_enable); 6789 perf_event_ctx_unlock(event, ctx); 6790 } 6791 mutex_unlock(¤t->perf_event_mutex); 6792 6793 return 0; 6794 } 6795 6796 int perf_event_task_disable(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_disable); 6805 perf_event_ctx_unlock(event, ctx); 6806 } 6807 mutex_unlock(¤t->perf_event_mutex); 6808 6809 return 0; 6810 } 6811 6812 static int perf_event_index(struct perf_event *event) 6813 { 6814 if (event->hw.state & PERF_HES_STOPPED) 6815 return 0; 6816 6817 if (event->state != PERF_EVENT_STATE_ACTIVE) 6818 return 0; 6819 6820 return event->pmu->event_idx(event); 6821 } 6822 6823 static void perf_event_init_userpage(struct perf_event *event) 6824 { 6825 struct perf_event_mmap_page *userpg; 6826 struct perf_buffer *rb; 6827 6828 rcu_read_lock(); 6829 rb = rcu_dereference(event->rb); 6830 if (!rb) 6831 goto unlock; 6832 6833 userpg = rb->user_page; 6834 6835 /* Allow new userspace to detect that bit 0 is deprecated */ 6836 userpg->cap_bit0_is_deprecated = 1; 6837 userpg->size = offsetof(struct perf_event_mmap_page, __reserved); 6838 userpg->data_offset = PAGE_SIZE; 6839 userpg->data_size = perf_data_size(rb); 6840 6841 unlock: 6842 rcu_read_unlock(); 6843 } 6844 6845 void __weak arch_perf_update_userpage( 6846 struct perf_event *event, struct perf_event_mmap_page *userpg, u64 now) 6847 { 6848 } 6849 6850 /* 6851 * Callers need to ensure there can be no nesting of this function, otherwise 6852 * the seqlock logic goes bad. We can not serialize this because the arch 6853 * code calls this from NMI context. 6854 */ 6855 void perf_event_update_userpage(struct perf_event *event) 6856 { 6857 struct perf_event_mmap_page *userpg; 6858 struct perf_buffer *rb; 6859 u64 enabled, running, now; 6860 6861 rcu_read_lock(); 6862 rb = rcu_dereference(event->rb); 6863 if (!rb) 6864 goto unlock; 6865 6866 /* 6867 * Disable preemption to guarantee consistent time stamps are stored to 6868 * the user page. 6869 */ 6870 preempt_disable(); 6871 6872 /* 6873 * Compute total_time_enabled, total_time_running based on snapshot 6874 * values taken when the event was last scheduled in. 6875 * 6876 * We cannot simply call update_context_time() because doing so would 6877 * lead to deadlock when called from NMI context. 6878 */ 6879 calc_timer_values(event, &now, &enabled, &running); 6880 6881 userpg = rb->user_page; 6882 6883 ++userpg->lock; 6884 barrier(); 6885 userpg->index = perf_event_index(event); 6886 userpg->offset = perf_event_count(event, false); 6887 if (userpg->index) 6888 userpg->offset -= local64_read(&event->hw.prev_count); 6889 6890 userpg->time_enabled = enabled + 6891 atomic64_read(&event->child_total_time_enabled); 6892 6893 userpg->time_running = running + 6894 atomic64_read(&event->child_total_time_running); 6895 6896 arch_perf_update_userpage(event, userpg, now); 6897 6898 barrier(); 6899 ++userpg->lock; 6900 preempt_enable(); 6901 unlock: 6902 rcu_read_unlock(); 6903 } 6904 EXPORT_SYMBOL_GPL(perf_event_update_userpage); 6905 6906 static void ring_buffer_attach(struct perf_event *event, 6907 struct perf_buffer *rb) 6908 { 6909 struct perf_buffer *old_rb = NULL; 6910 unsigned long flags; 6911 6912 WARN_ON_ONCE(event->parent); 6913 6914 if (event->rb) { 6915 /* 6916 * Should be impossible, we set this when removing 6917 * event->rb_entry and wait/clear when adding event->rb_entry. 6918 */ 6919 WARN_ON_ONCE(event->rcu_pending); 6920 6921 old_rb = event->rb; 6922 spin_lock_irqsave(&old_rb->event_lock, flags); 6923 list_del_rcu(&event->rb_entry); 6924 spin_unlock_irqrestore(&old_rb->event_lock, flags); 6925 6926 event->rcu_batches = get_state_synchronize_rcu(); 6927 event->rcu_pending = 1; 6928 } 6929 6930 if (rb) { 6931 if (event->rcu_pending) { 6932 cond_synchronize_rcu(event->rcu_batches); 6933 event->rcu_pending = 0; 6934 } 6935 6936 spin_lock_irqsave(&rb->event_lock, flags); 6937 list_add_rcu(&event->rb_entry, &rb->event_list); 6938 spin_unlock_irqrestore(&rb->event_lock, flags); 6939 } 6940 6941 /* 6942 * Avoid racing with perf_mmap_close(AUX): stop the event 6943 * before swizzling the event::rb pointer; if it's getting 6944 * unmapped, its aux_mmap_count will be 0 and it won't 6945 * restart. See the comment in __perf_pmu_output_stop(). 6946 * 6947 * Data will inevitably be lost when set_output is done in 6948 * mid-air, but then again, whoever does it like this is 6949 * not in for the data anyway. 6950 */ 6951 if (has_aux(event)) 6952 perf_event_stop(event, 0); 6953 6954 rcu_assign_pointer(event->rb, rb); 6955 6956 if (old_rb) { 6957 ring_buffer_put(old_rb); 6958 /* 6959 * Since we detached before setting the new rb, so that we 6960 * could attach the new rb, we could have missed a wakeup. 6961 * Provide it now. 6962 */ 6963 wake_up_all(&event->waitq); 6964 } 6965 } 6966 6967 static void ring_buffer_wakeup(struct perf_event *event) 6968 { 6969 struct perf_buffer *rb; 6970 6971 if (event->parent) 6972 event = event->parent; 6973 6974 rcu_read_lock(); 6975 rb = rcu_dereference(event->rb); 6976 if (rb) { 6977 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) 6978 wake_up_all(&event->waitq); 6979 } 6980 rcu_read_unlock(); 6981 } 6982 6983 struct perf_buffer *ring_buffer_get(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 if (!refcount_inc_not_zero(&rb->refcount)) 6994 rb = NULL; 6995 } 6996 rcu_read_unlock(); 6997 6998 return rb; 6999 } 7000 7001 void ring_buffer_put(struct perf_buffer *rb) 7002 { 7003 if (!refcount_dec_and_test(&rb->refcount)) 7004 return; 7005 7006 WARN_ON_ONCE(!list_empty(&rb->event_list)); 7007 7008 call_rcu(&rb->rcu_head, rb_free_rcu); 7009 } 7010 7011 typedef void (*mapped_f)(struct perf_event *event, struct mm_struct *mm); 7012 7013 #define get_mapped(event, func) \ 7014 ({ struct pmu *pmu; \ 7015 mapped_f f = NULL; \ 7016 guard(rcu)(); \ 7017 pmu = READ_ONCE(event->pmu); \ 7018 if (pmu) \ 7019 f = pmu->func; \ 7020 f; \ 7021 }) 7022 7023 static void perf_mmap_open(struct vm_area_struct *vma) 7024 { 7025 struct perf_event *event = vma->vm_file->private_data; 7026 mapped_f mapped = get_mapped(event, event_mapped); 7027 7028 refcount_inc(&event->mmap_count); 7029 refcount_inc(&event->rb->mmap_count); 7030 7031 if (vma_start_pgoff(vma)) 7032 refcount_inc(&event->rb->aux_mmap_count); 7033 7034 if (mapped) 7035 mapped(event, vma->vm_mm); 7036 } 7037 7038 static void perf_pmu_output_stop(struct perf_event *event); 7039 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb); 7040 7041 /* 7042 * A buffer can be mmap()ed multiple times; either directly through the same 7043 * event, or through other events by use of perf_event_set_output(). 7044 * 7045 * In order to undo the VM accounting done by perf_mmap() we need to destroy 7046 * the buffer here, where we still have a VM context. This means we need 7047 * to detach all events redirecting to us. 7048 */ 7049 static void perf_mmap_close(struct vm_area_struct *vma) 7050 { 7051 struct perf_event *event = vma->vm_file->private_data; 7052 mapped_f unmapped = get_mapped(event, event_unmapped); 7053 struct perf_buffer *rb = ring_buffer_get(event); 7054 struct user_struct *mmap_user = rb->mmap_user; 7055 7056 /* FIXIES vs perf_pmu_unregister() */ 7057 if (unmapped) 7058 unmapped(event, vma->vm_mm); 7059 7060 /* 7061 * The AUX buffer is strictly a sub-buffer, serialize using aux_mutex 7062 * to avoid complications. 7063 */ 7064 if (rb_has_aux(rb) && vma_start_pgoff(vma) == rb->aux_pgoff && 7065 refcount_dec_and_mutex_lock(&rb->aux_mmap_count, &rb->aux_mutex)) { 7066 /* 7067 * Stop all AUX events that are writing to this buffer, 7068 * so that we can free its AUX pages and corresponding PMU 7069 * data. Note that after rb::aux_mmap_count dropped to zero, 7070 * they won't start any more (see perf_aux_output_begin()). 7071 */ 7072 perf_pmu_output_stop(event); 7073 7074 /* now it's safe to free the pages */ 7075 atomic_long_sub(rb->aux_nr_pages - rb->aux_mmap_locked, &mmap_user->perf_mlock); 7076 atomic64_sub(rb->aux_mmap_locked, &vma->vm_mm->pinned_vm); 7077 7078 /* this has to be the last one */ 7079 rb_free_aux(rb); 7080 WARN_ON_ONCE(refcount_read(&rb->aux_refcount)); 7081 7082 mutex_unlock(&rb->aux_mutex); 7083 } 7084 7085 /* 7086 * Drop references in reverse order of perf_mmap() to prevent 7087 * rb revival after rb->mmap_count reaches zero. 7088 */ 7089 if (refcount_dec_and_mutex_lock(&event->mmap_count, 7090 &event->mmap_mutex)) { 7091 ring_buffer_attach(event, NULL); 7092 mutex_unlock(&event->mmap_mutex); 7093 } 7094 7095 /* If there's still other mmap()s of this buffer, we're done. */ 7096 if (!refcount_dec_and_test(&rb->mmap_count)) 7097 goto out_put; 7098 7099 /* 7100 * No other mmap()s, detach from all other events that might redirect 7101 * into the now unreachable buffer. Somewhat complicated by the 7102 * fact that rb::event_lock otherwise nests inside mmap_mutex. 7103 */ 7104 again: 7105 rcu_read_lock(); 7106 list_for_each_entry_rcu(event, &rb->event_list, rb_entry) { 7107 if (!atomic_long_inc_not_zero(&event->refcount)) { 7108 /* 7109 * This event is en-route to free_event() which will 7110 * detach it and remove it from the list. 7111 */ 7112 continue; 7113 } 7114 rcu_read_unlock(); 7115 7116 mutex_lock(&event->mmap_mutex); 7117 /* 7118 * Check we didn't race with perf_event_set_output() which can 7119 * swizzle the rb from under us while we were waiting to 7120 * acquire mmap_mutex. 7121 * 7122 * If we find a different rb; ignore this event, a next 7123 * iteration will no longer find it on the list. We have to 7124 * still restart the iteration to make sure we're not now 7125 * iterating the wrong list. 7126 */ 7127 if (event->rb == rb) 7128 ring_buffer_attach(event, NULL); 7129 7130 mutex_unlock(&event->mmap_mutex); 7131 put_event(event); 7132 7133 /* 7134 * Restart the iteration; either we're on the wrong list or 7135 * destroyed its integrity by doing a deletion. 7136 */ 7137 goto again; 7138 } 7139 rcu_read_unlock(); 7140 7141 /* 7142 * It could be there's still a few 0-ref events on the list; they'll 7143 * get cleaned up by free_event() -- they'll also still have their 7144 * ref on the rb and will free it whenever they are done with it. 7145 * 7146 * Aside from that, this buffer is 'fully' detached and unmapped, 7147 * undo the VM accounting. 7148 */ 7149 perf_mmap_unaccount(vma, rb); 7150 7151 out_put: 7152 ring_buffer_put(rb); /* could be last */ 7153 } 7154 7155 static vm_fault_t perf_mmap_pfn_mkwrite(struct vm_fault *vmf) 7156 { 7157 /* The first page is the user control page, others are read-only. */ 7158 return vmf->pgoff == 0 ? 0 : VM_FAULT_SIGBUS; 7159 } 7160 7161 static int perf_mmap_may_split(struct vm_area_struct *vma, unsigned long addr) 7162 { 7163 /* 7164 * Forbid splitting perf mappings to prevent refcount leaks due to 7165 * the resulting non-matching offsets and sizes. See open()/close(). 7166 */ 7167 return -EINVAL; 7168 } 7169 7170 static const struct vm_operations_struct perf_mmap_vmops = { 7171 .open = perf_mmap_open, 7172 .close = perf_mmap_close, /* non mergeable */ 7173 .pfn_mkwrite = perf_mmap_pfn_mkwrite, 7174 .may_split = perf_mmap_may_split, 7175 }; 7176 7177 static int map_range(struct perf_buffer *rb, struct vm_area_struct *vma) 7178 { 7179 unsigned long nr_pages = vma_pages(vma); 7180 int err = 0; 7181 unsigned long pagenum; 7182 7183 guard(mutex)(&rb->aux_mutex); 7184 7185 /* 7186 * We map this as a VM_PFNMAP VMA. 7187 * 7188 * This is not ideal as this is designed broadly for mappings of PFNs 7189 * referencing memory-mapped I/O ranges or non-system RAM i.e. for which 7190 * !pfn_valid(pfn). 7191 * 7192 * We are mapping kernel-allocated memory (memory we manage ourselves) 7193 * which would more ideally be mapped using vm_insert_page() or a 7194 * similar mechanism, that is as a VM_MIXEDMAP mapping. 7195 * 7196 * However this won't work here, because: 7197 * 7198 * 1. It uses vma->vm_page_prot, but this field has not been completely 7199 * setup at the point of the f_op->mmp() hook, so we are unable to 7200 * indicate that this should be mapped CoW in order that the 7201 * mkwrite() hook can be invoked to make the first page R/W and the 7202 * rest R/O as desired. 7203 * 7204 * 2. Anything other than a VM_PFNMAP of valid PFNs will result in 7205 * vm_normal_page() returning a struct page * pointer, which means 7206 * vm_ops->page_mkwrite() will be invoked rather than 7207 * vm_ops->pfn_mkwrite(), and this means we have to set page->mapping 7208 * to work around retry logic in the fault handler, however this 7209 * field is no longer allowed to be used within struct page. 7210 * 7211 * 3. Having a struct page * made available in the fault logic also 7212 * means that the page gets put on the rmap and becomes 7213 * inappropriately accessible and subject to map and ref counting. 7214 * 7215 * Ideally we would have a mechanism that could explicitly express our 7216 * desires, but this is not currently the case, so we instead use 7217 * VM_PFNMAP. 7218 * 7219 * We manage the lifetime of these mappings with internal refcounts (see 7220 * perf_mmap_open() and perf_mmap_close()) so we ensure the lifetime of 7221 * this mapping is maintained correctly. 7222 */ 7223 for (pagenum = 0; pagenum < nr_pages; pagenum++) { 7224 unsigned long va = vma->vm_start + PAGE_SIZE * pagenum; 7225 struct page *page = perf_mmap_to_page(rb, 7226 vma_start_pgoff(vma) + pagenum); 7227 7228 if (page == NULL) { 7229 err = -EINVAL; 7230 break; 7231 } 7232 7233 /* Map readonly, perf_mmap_pfn_mkwrite() called on write fault. */ 7234 err = remap_pfn_range(vma, va, page_to_pfn(page), PAGE_SIZE, 7235 vm_get_page_prot(vma->vm_flags & ~VM_SHARED)); 7236 if (err) 7237 break; 7238 } 7239 7240 #ifdef CONFIG_MMU 7241 /* Clear any partial mappings on error. */ 7242 if (err) 7243 zap_vma_range(vma, vma->vm_start, nr_pages * PAGE_SIZE); 7244 #endif 7245 7246 return err; 7247 } 7248 7249 static bool perf_mmap_calc_limits(struct vm_area_struct *vma, long *user_extra, long *extra) 7250 { 7251 unsigned long user_locked, user_lock_limit, locked, lock_limit; 7252 struct user_struct *user = current_user(); 7253 7254 user_lock_limit = sysctl_perf_event_mlock >> (PAGE_SHIFT - 10); 7255 /* Increase the limit linearly with more CPUs */ 7256 user_lock_limit *= num_online_cpus(); 7257 7258 user_locked = atomic_long_read(&user->perf_mlock); 7259 7260 /* 7261 * sysctl_perf_event_mlock may have changed, so that 7262 * user->perf_mlock > user_lock_limit 7263 */ 7264 if (user_locked > user_lock_limit) 7265 user_locked = user_lock_limit; 7266 user_locked += *user_extra; 7267 7268 if (user_locked > user_lock_limit) { 7269 /* 7270 * charge perf_mlock until it hits user_lock_limit; 7271 * charge the rest from pinned_vm 7272 */ 7273 *extra = user_locked - user_lock_limit; 7274 *user_extra -= *extra; 7275 } 7276 7277 lock_limit = rlimit(RLIMIT_MEMLOCK); 7278 lock_limit >>= PAGE_SHIFT; 7279 locked = atomic64_read(&vma->vm_mm->pinned_vm) + *extra; 7280 7281 return locked <= lock_limit || !perf_is_paranoid() || capable(CAP_IPC_LOCK); 7282 } 7283 7284 static void perf_mmap_account(struct vm_area_struct *vma, long user_extra, long extra) 7285 { 7286 struct user_struct *user = current_user(); 7287 7288 atomic_long_add(user_extra, &user->perf_mlock); 7289 atomic64_add(extra, &vma->vm_mm->pinned_vm); 7290 } 7291 7292 static void perf_mmap_unaccount(struct vm_area_struct *vma, struct perf_buffer *rb) 7293 { 7294 struct user_struct *user = rb->mmap_user; 7295 7296 atomic_long_sub((perf_data_size(rb) >> PAGE_SHIFT) + 1 - rb->mmap_locked, 7297 &user->perf_mlock); 7298 atomic64_sub(rb->mmap_locked, &vma->vm_mm->pinned_vm); 7299 } 7300 7301 static int perf_mmap_rb(struct vm_area_struct *vma, struct perf_event *event, 7302 unsigned long nr_pages) 7303 { 7304 long extra = 0, user_extra = nr_pages; 7305 struct perf_buffer *rb; 7306 int rb_flags = 0; 7307 7308 nr_pages -= 1; 7309 7310 /* 7311 * If we have rb pages ensure they're a power-of-two number, so we 7312 * can do bitmasks instead of modulo. 7313 */ 7314 if (nr_pages != 0 && !is_power_of_2(nr_pages)) 7315 return -EINVAL; 7316 7317 WARN_ON_ONCE(event->ctx->parent_ctx); 7318 7319 if (event->rb) { 7320 if (data_page_nr(event->rb) != nr_pages) 7321 return -EINVAL; 7322 7323 /* 7324 * If this event doesn't have mmap_count, we're attempting to 7325 * create an alias of another event's mmap(); this would mean 7326 * both events will end up scribbling the same user_page; 7327 * which makes no sense. 7328 */ 7329 if (!refcount_read(&event->mmap_count)) 7330 return -EBUSY; 7331 7332 if (refcount_inc_not_zero(&event->rb->mmap_count)) { 7333 /* 7334 * Success -- managed to mmap() the same buffer 7335 * multiple times. 7336 */ 7337 perf_mmap_account(vma, user_extra, extra); 7338 refcount_inc(&event->mmap_count); 7339 return 0; 7340 } 7341 7342 /* 7343 * Raced against perf_mmap_close()'s 7344 * refcount_dec_and_mutex_lock() remove the 7345 * event and continue as if !event->rb 7346 */ 7347 ring_buffer_attach(event, NULL); 7348 } 7349 7350 if (!perf_mmap_calc_limits(vma, &user_extra, &extra)) 7351 return -EPERM; 7352 7353 if (vma->vm_flags & VM_WRITE) 7354 rb_flags |= RING_BUFFER_WRITABLE; 7355 7356 rb = rb_alloc(nr_pages, 7357 event->attr.watermark ? event->attr.wakeup_watermark : 0, 7358 event->cpu, rb_flags); 7359 7360 if (!rb) 7361 return -ENOMEM; 7362 7363 rb->mmap_locked = extra; 7364 7365 ring_buffer_attach(event, rb); 7366 7367 perf_event_update_time(event); 7368 perf_event_init_userpage(event); 7369 perf_event_update_userpage(event); 7370 7371 perf_mmap_account(vma, user_extra, extra); 7372 refcount_set(&event->mmap_count, 1); 7373 7374 return 0; 7375 } 7376 7377 static int perf_mmap_aux(struct vm_area_struct *vma, struct perf_event *event, 7378 unsigned long nr_pages) 7379 { 7380 const pgoff_t pgoff_start = vma_start_pgoff(vma); 7381 long extra = 0, user_extra = nr_pages; 7382 u64 aux_offset, aux_size; 7383 struct perf_buffer *rb; 7384 int ret, rb_flags = 0; 7385 7386 rb = event->rb; 7387 if (!rb) 7388 return -EINVAL; 7389 7390 guard(mutex)(&rb->aux_mutex); 7391 7392 /* 7393 * AUX area mapping: if rb->aux_nr_pages != 0, it's already 7394 * mapped, all subsequent mappings should have the same size 7395 * and offset. Must be above the normal perf buffer. 7396 */ 7397 aux_offset = READ_ONCE(rb->user_page->aux_offset); 7398 aux_size = READ_ONCE(rb->user_page->aux_size); 7399 7400 if (aux_offset < perf_data_size(rb) + PAGE_SIZE) 7401 return -EINVAL; 7402 7403 if (aux_offset != pgoff_start << PAGE_SHIFT) 7404 return -EINVAL; 7405 7406 /* already mapped with a different offset */ 7407 if (rb_has_aux(rb) && rb->aux_pgoff != pgoff_start) 7408 return -EINVAL; 7409 7410 if (aux_size != nr_pages * PAGE_SIZE) 7411 return -EINVAL; 7412 7413 /* already mapped with a different size */ 7414 if (rb_has_aux(rb) && rb->aux_nr_pages != nr_pages) 7415 return -EINVAL; 7416 7417 if (!is_power_of_2(nr_pages)) 7418 return -EINVAL; 7419 7420 if (!refcount_inc_not_zero(&rb->mmap_count)) 7421 return -EINVAL; 7422 7423 if (rb_has_aux(rb)) { 7424 refcount_inc(&rb->aux_mmap_count); 7425 7426 } else { 7427 if (!perf_mmap_calc_limits(vma, &user_extra, &extra)) { 7428 refcount_dec(&rb->mmap_count); 7429 return -EPERM; 7430 } 7431 7432 WARN_ON(!rb && event->rb); 7433 7434 if (vma->vm_flags & VM_WRITE) 7435 rb_flags |= RING_BUFFER_WRITABLE; 7436 7437 ret = rb_alloc_aux(rb, event, pgoff_start, nr_pages, 7438 event->attr.aux_watermark, rb_flags); 7439 if (ret) { 7440 refcount_dec(&rb->mmap_count); 7441 return ret; 7442 } 7443 7444 refcount_set(&rb->aux_mmap_count, 1); 7445 rb->aux_mmap_locked = extra; 7446 } 7447 7448 perf_mmap_account(vma, user_extra, extra); 7449 refcount_inc(&event->mmap_count); 7450 7451 return 0; 7452 } 7453 7454 static int perf_mmap(struct file *file, struct vm_area_struct *vma) 7455 { 7456 struct perf_event *event = file->private_data; 7457 unsigned long vma_size, nr_pages; 7458 mapped_f mapped; 7459 int ret; 7460 7461 /* 7462 * Don't allow mmap() of inherited per-task counters. This would 7463 * create a performance issue due to all children writing to the 7464 * same rb. 7465 */ 7466 if (event->cpu == -1 && event->attr.inherit) 7467 return -EINVAL; 7468 7469 if (!(vma->vm_flags & VM_SHARED)) 7470 return -EINVAL; 7471 7472 ret = security_perf_event_read(event); 7473 if (ret) 7474 return ret; 7475 7476 vma_size = vma->vm_end - vma->vm_start; 7477 nr_pages = vma_size / PAGE_SIZE; 7478 7479 if (nr_pages > INT_MAX) 7480 return -ENOMEM; 7481 7482 if (vma_size != PAGE_SIZE * nr_pages) 7483 return -EINVAL; 7484 7485 scoped_guard (mutex, &event->mmap_mutex) { 7486 /* 7487 * This relies on __pmu_detach_event() taking mmap_mutex after marking 7488 * the event REVOKED. Either we observe the state, or __pmu_detach_event() 7489 * will detach the rb created here. 7490 */ 7491 if (event->state <= PERF_EVENT_STATE_REVOKED) 7492 return -ENODEV; 7493 7494 if (!vma_start_pgoff(vma)) 7495 ret = perf_mmap_rb(vma, event, nr_pages); 7496 else 7497 ret = perf_mmap_aux(vma, event, nr_pages); 7498 if (ret) 7499 return ret; 7500 7501 /* 7502 * Since pinned accounting is per vm we cannot allow fork() to copy our 7503 * vma. 7504 */ 7505 vm_flags_set(vma, VM_DONTCOPY | VM_DONTEXPAND | VM_DONTDUMP); 7506 vma->vm_ops = &perf_mmap_vmops; 7507 7508 mapped = get_mapped(event, event_mapped); 7509 if (mapped) 7510 mapped(event, vma->vm_mm); 7511 7512 /* 7513 * Try to map it into the page table. On fail undo the above, 7514 * as the callsite expects full cleanup in this case and 7515 * therefore does not invoke vmops::close(). 7516 */ 7517 ret = map_range(event->rb, vma); 7518 if (likely(!ret)) 7519 return 0; 7520 7521 /* Error path */ 7522 7523 /* 7524 * If this is the first mmap(), then event->mmap_count should 7525 * be stable at 1. It is only modified by: 7526 * perf_mmap_{open,close}() and perf_mmap(). 7527 * 7528 * The former are not possible because this mmap() hasn't been 7529 * successful yet, and the latter is serialized by 7530 * event->mmap_mutex which we still hold (note that mmap_lock 7531 * is not strictly sufficient here, because the event fd can 7532 * be passed to another process through trivial means like 7533 * fork(), leading to concurrent mmap() from different mm). 7534 * 7535 * Make sure to remove event->rb before releasing 7536 * event->mmap_mutex, such that any concurrent mmap() will not 7537 * attempt use this failed buffer. 7538 */ 7539 if (refcount_read(&event->mmap_count) == 1) { 7540 /* 7541 * Minimal perf_mmap_close(); there can't be AUX or 7542 * other events on account of this being the first. 7543 */ 7544 mapped = get_mapped(event, event_unmapped); 7545 if (mapped) 7546 mapped(event, vma->vm_mm); 7547 perf_mmap_unaccount(vma, event->rb); 7548 ring_buffer_attach(event, NULL); /* drops last rb->refcount */ 7549 refcount_set(&event->mmap_count, 0); 7550 return ret; 7551 } 7552 7553 /* 7554 * Otherwise this is an already existing buffer, and there is 7555 * no race vs first exposure, so fall-through and call 7556 * perf_mmap_close(). 7557 */ 7558 } 7559 7560 perf_mmap_close(vma); 7561 return ret; 7562 } 7563 7564 static int perf_fasync(int fd, struct file *filp, int on) 7565 { 7566 struct inode *inode = file_inode(filp); 7567 struct perf_event *event = filp->private_data; 7568 int retval; 7569 7570 if (event->state <= PERF_EVENT_STATE_REVOKED) 7571 return -ENODEV; 7572 7573 inode_lock(inode); 7574 retval = fasync_helper(fd, filp, on, &event->fasync); 7575 inode_unlock(inode); 7576 7577 if (retval < 0) 7578 return retval; 7579 7580 return 0; 7581 } 7582 7583 static void perf_show_fdinfo(struct seq_file *m, struct file *f) 7584 { 7585 struct perf_event *event = f->private_data; 7586 struct perf_event_context *ctx; 7587 struct mutex *child_mutex; 7588 7589 ctx = perf_event_ctx_lock(event); 7590 child_mutex = event->parent ? &event->parent->child_mutex : &event->child_mutex; 7591 mutex_lock(child_mutex); 7592 7593 seq_printf(m, "perf_event_attr.type:\t%u\n", event->orig_type); 7594 if (event->pmu) 7595 seq_printf(m, "pmu_type:\t%u\n", event->pmu->type); 7596 seq_printf(m, "perf_event_attr.config:\t0x%llx\n", (unsigned long long)event->attr.config); 7597 seq_printf(m, "perf_event_attr.config1:\t0x%llx\n", 7598 (unsigned long long)event->attr.config1); 7599 seq_printf(m, "perf_event_attr.config2:\t0x%llx\n", 7600 (unsigned long long)event->attr.config2); 7601 seq_printf(m, "perf_event_attr.config3:\t0x%llx\n", 7602 (unsigned long long)event->attr.config3); 7603 seq_printf(m, "perf_event_attr.config4:\t0x%llx\n", 7604 (unsigned long long)event->attr.config4); 7605 7606 mutex_unlock(child_mutex); 7607 perf_event_ctx_unlock(event, ctx); 7608 } 7609 7610 static const struct file_operations perf_fops = { 7611 .release = perf_release, 7612 .read = perf_read, 7613 .poll = perf_poll, 7614 .unlocked_ioctl = perf_ioctl, 7615 .compat_ioctl = perf_compat_ioctl, 7616 .mmap = perf_mmap, 7617 .fasync = perf_fasync, 7618 .show_fdinfo = perf_show_fdinfo, 7619 }; 7620 7621 /* 7622 * Perf event wakeup 7623 * 7624 * If there's data, ensure we set the poll() state and publish everything 7625 * to user-space before waking everybody up. 7626 */ 7627 7628 void perf_event_wakeup(struct perf_event *event) 7629 { 7630 ring_buffer_wakeup(event); 7631 7632 if (event->pending_kill) { 7633 kill_fasync(perf_event_fasync(event), SIGIO, event->pending_kill); 7634 event->pending_kill = 0; 7635 } 7636 } 7637 7638 static void perf_sigtrap(struct perf_event *event) 7639 { 7640 /* 7641 * Both perf_pending_task() and perf_pending_irq() can race with the 7642 * task exiting or exec-ing. We can determine if such a race has 7643 * occurred by checking if perf_event_exit_task(), which will set 7644 * ctx->task to TASK_TOMBSTONE, has already been called. 7645 */ 7646 if (event->ctx->task == TASK_TOMBSTONE) 7647 return; 7648 7649 /* 7650 * The event was removed after this signal was queued, e.g. by exec() 7651 * (remove_on_exec), which may also have closed its fd (close-on-exec). 7652 * The new program has default signal handlers, so a SIGTRAP would 7653 * kill it. 7654 */ 7655 if (READ_ONCE(event->state) <= PERF_EVENT_STATE_EXIT) 7656 return; 7657 7658 /* 7659 * We'd expect this to only occur if the irq_work is delayed and either 7660 * ctx->task or current has changed in the meantime. This can be the 7661 * case on architectures that do not implement arch_irq_work_raise(). 7662 */ 7663 if (WARN_ON_ONCE(event->ctx->task != current)) 7664 return; 7665 7666 send_sig_perf((void __user *)event->pending_addr, 7667 event->orig_type, event->attr.sig_data); 7668 } 7669 7670 /* 7671 * Deliver the pending work in-event-context or follow the context. 7672 */ 7673 static void __perf_pending_disable(struct perf_event *event) 7674 { 7675 int cpu = READ_ONCE(event->oncpu); 7676 7677 /* 7678 * If the event isn't running; we done. event_sched_out() will have 7679 * taken care of things. 7680 */ 7681 if (cpu < 0) 7682 return; 7683 7684 /* 7685 * Yay, we hit home and are in the context of the event. 7686 */ 7687 if (cpu == smp_processor_id()) { 7688 if (event->pending_disable) { 7689 event->pending_disable = 0; 7690 perf_event_disable_local(event); 7691 } 7692 return; 7693 } 7694 7695 /* 7696 * CPU-A CPU-B 7697 * 7698 * perf_event_disable_inatomic() 7699 * @pending_disable = 1; 7700 * irq_work_queue(); 7701 * 7702 * sched-out 7703 * @pending_disable = 0; 7704 * 7705 * sched-in 7706 * perf_event_disable_inatomic() 7707 * @pending_disable = 1; 7708 * irq_work_queue(); // FAILS 7709 * 7710 * irq_work_run() 7711 * perf_pending_disable() 7712 * 7713 * But the event runs on CPU-B and wants disabling there. 7714 */ 7715 irq_work_queue_on(&event->pending_disable_irq, cpu); 7716 } 7717 7718 static void perf_pending_disable(struct irq_work *entry) 7719 { 7720 struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq); 7721 int rctx; 7722 7723 /* 7724 * If we 'fail' here, that's OK, it means recursion is already disabled 7725 * and we won't recurse 'further'. 7726 */ 7727 rctx = perf_swevent_get_recursion_context(); 7728 __perf_pending_disable(event); 7729 if (rctx >= 0) 7730 perf_swevent_put_recursion_context(rctx); 7731 } 7732 7733 static void perf_pending_irq(struct irq_work *entry) 7734 { 7735 struct perf_event *event = container_of(entry, struct perf_event, pending_irq); 7736 int rctx; 7737 7738 /* 7739 * If we 'fail' here, that's OK, it means recursion is already disabled 7740 * and we won't recurse 'further'. 7741 */ 7742 rctx = perf_swevent_get_recursion_context(); 7743 7744 /* 7745 * The wakeup isn't bound to the context of the event -- it can happen 7746 * irrespective of where the event is. 7747 */ 7748 if (event->pending_wakeup) { 7749 event->pending_wakeup = 0; 7750 perf_event_wakeup(event); 7751 } 7752 7753 if (rctx >= 0) 7754 perf_swevent_put_recursion_context(rctx); 7755 } 7756 7757 static void perf_pending_task(struct callback_head *head) 7758 { 7759 struct perf_event *event = container_of(head, struct perf_event, pending_task); 7760 int rctx; 7761 7762 /* 7763 * If we 'fail' here, that's OK, it means recursion is already disabled 7764 * and we won't recurse 'further'. 7765 */ 7766 rctx = perf_swevent_get_recursion_context(); 7767 7768 if (event->pending_work) { 7769 event->pending_work = 0; 7770 perf_sigtrap(event); 7771 local_dec(&event->ctx->nr_no_switch_fast); 7772 } 7773 put_event(event); 7774 7775 if (rctx >= 0) 7776 perf_swevent_put_recursion_context(rctx); 7777 } 7778 7779 #ifdef CONFIG_GUEST_PERF_EVENTS 7780 struct perf_guest_info_callbacks __rcu *perf_guest_cbs; 7781 7782 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state); 7783 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip); 7784 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr); 7785 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi); 7786 7787 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7788 { 7789 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs))) 7790 return; 7791 7792 rcu_assign_pointer(perf_guest_cbs, cbs); 7793 static_call_update(__perf_guest_state, cbs->state); 7794 static_call_update(__perf_guest_get_ip, cbs->get_ip); 7795 7796 /* Implementing ->handle_intel_pt_intr is optional. */ 7797 if (cbs->handle_intel_pt_intr) 7798 static_call_update(__perf_guest_handle_intel_pt_intr, 7799 cbs->handle_intel_pt_intr); 7800 7801 if (cbs->handle_mediated_pmi) 7802 static_call_update(__perf_guest_handle_mediated_pmi, 7803 cbs->handle_mediated_pmi); 7804 } 7805 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks); 7806 7807 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7808 { 7809 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs)) 7810 return; 7811 7812 rcu_assign_pointer(perf_guest_cbs, NULL); 7813 static_call_update(__perf_guest_state, (void *)&__static_call_return0); 7814 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0); 7815 static_call_update(__perf_guest_handle_intel_pt_intr, (void *)&__static_call_return0); 7816 static_call_update(__perf_guest_handle_mediated_pmi, (void *)&__static_call_return0); 7817 synchronize_rcu(); 7818 } 7819 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks); 7820 #endif 7821 7822 static bool should_sample_guest(struct perf_event *event) 7823 { 7824 return !event->attr.exclude_guest && perf_guest_state(); 7825 } 7826 7827 unsigned long perf_misc_flags(struct perf_event *event, 7828 struct pt_regs *regs) 7829 { 7830 if (should_sample_guest(event)) 7831 return perf_arch_guest_misc_flags(regs); 7832 7833 return perf_arch_misc_flags(regs); 7834 } 7835 7836 unsigned long perf_instruction_pointer(struct perf_event *event, 7837 struct pt_regs *regs) 7838 { 7839 /* 7840 * Hardware skid can lead to a scenario where a PMI is 7841 * delivered after the CPU has already entered kernel mode. 7842 * In that case, user-space sampling must not expose kernel 7843 * register state. 7844 */ 7845 if (should_sample_guest(event)) { 7846 return event->attr.exclude_kernel && 7847 !(perf_guest_state() & PERF_GUEST_USER) ? 7848 0 : perf_guest_get_ip(); 7849 } 7850 7851 return event->attr.exclude_kernel && !user_mode(regs) ? 7852 0 : perf_arch_instruction_pointer(regs); 7853 } 7854 7855 u64 __weak perf_reg_value(struct pt_regs *regs, int idx) 7856 { 7857 return 0; 7858 } 7859 7860 int __weak perf_reg_validate(u64 mask, bool simd_enabled) 7861 { 7862 return mask ? -ENOSYS : 0; 7863 } 7864 7865 u64 __weak perf_reg_abi(struct task_struct *task) 7866 { 7867 return PERF_SAMPLE_REGS_ABI_NONE; 7868 } 7869 7870 void __weak perf_get_regs_user(struct perf_regs *regs_user, 7871 struct pt_regs *regs) 7872 { 7873 regs_user->regs = task_pt_regs(current); 7874 regs_user->abi = perf_reg_abi(current); 7875 } 7876 7877 #define word_for_each_set_bit(bit, val) \ 7878 for (unsigned long long __v = (val); \ 7879 __v && ((bit = __builtin_ctzll(__v)), 1); \ 7880 __v &= __v - 1) 7881 7882 static void 7883 perf_output_sample_regs(struct perf_output_handle *handle, 7884 struct pt_regs *regs, u64 mask) 7885 { 7886 int bit; 7887 7888 word_for_each_set_bit(bit, mask) { 7889 u64 val = perf_reg_value(regs, bit); 7890 perf_output_put(handle, val); 7891 } 7892 } 7893 7894 static void 7895 perf_output_sample_simd_regs(struct perf_output_handle *handle, 7896 struct perf_event *event, 7897 struct pt_regs *regs, 7898 u64 mask, u32 pred_mask) 7899 { 7900 u64 pred_qwords = event->attr.sample_simd_pred_reg_qwords; 7901 u64 vec_qwords = event->attr.sample_simd_vec_reg_qwords; 7902 u64 nr_vectors = hweight64(mask); 7903 u64 nr_pred = hweight32(pred_mask); 7904 int bit; 7905 7906 perf_output_put(handle, nr_vectors); 7907 perf_output_put(handle, vec_qwords); 7908 perf_output_put(handle, nr_pred); 7909 perf_output_put(handle, pred_qwords); 7910 7911 if (nr_vectors) { 7912 word_for_each_set_bit(bit, mask) { 7913 for (int i = 0; i < vec_qwords; i++) { 7914 u64 val = perf_simd_reg_value(regs, bit, 7915 i, false); 7916 perf_output_put(handle, val); 7917 } 7918 } 7919 } 7920 if (nr_pred) { 7921 word_for_each_set_bit(bit, pred_mask) { 7922 for (int i = 0; i < pred_qwords; i++) { 7923 u64 val = perf_simd_reg_value(regs, bit, 7924 i, true); 7925 perf_output_put(handle, val); 7926 } 7927 } 7928 } 7929 } 7930 7931 void perf_sample_regs_user(struct perf_regs *regs_user, 7932 struct pt_regs *regs) 7933 { 7934 if (user_mode(regs)) { 7935 regs_user->abi = perf_reg_abi(current); 7936 regs_user->regs = regs; 7937 } else if (is_user_task(current)) { 7938 perf_get_regs_user(regs_user, regs); 7939 } else { 7940 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE; 7941 regs_user->regs = NULL; 7942 } 7943 } 7944 7945 void perf_sample_regs_intr(struct perf_regs *regs_intr, 7946 struct pt_regs *regs, 7947 bool exclude_kernel) 7948 { 7949 /* 7950 * Hardware skid can lead to a scenario where a PMI is 7951 * delivered after the CPU has already entered kernel mode. 7952 * In that case, user-space sampling must not expose kernel 7953 * register state. 7954 */ 7955 if (exclude_kernel && !user_mode(regs)) { 7956 regs_intr->abi = PERF_SAMPLE_REGS_ABI_NONE; 7957 regs_intr->regs = NULL; 7958 } else { 7959 regs_intr->regs = regs; 7960 regs_intr->abi = perf_reg_abi(current); 7961 } 7962 } 7963 7964 int __weak perf_simd_reg_validate(u16 vec_qwords, u64 vec_mask, 7965 u16 pred_qwords, u32 pred_mask) 7966 { 7967 return -EINVAL; 7968 } 7969 7970 u64 __weak perf_simd_reg_value(struct pt_regs *regs, int idx, 7971 u16 qwords_idx, bool pred) 7972 { 7973 return 0; 7974 } 7975 7976 /* 7977 * Get remaining task size from user stack pointer. 7978 * 7979 * It'd be better to take stack vma map and limit this more 7980 * precisely, but there's no way to get it safely under interrupt, 7981 * so using TASK_SIZE as limit. 7982 */ 7983 static u64 perf_ustack_task_size(struct pt_regs *regs) 7984 { 7985 unsigned long addr = perf_user_stack_pointer(regs); 7986 7987 if (!addr || addr >= TASK_SIZE) 7988 return 0; 7989 7990 return TASK_SIZE - addr; 7991 } 7992 7993 static u16 7994 perf_sample_ustack_size(u16 stack_size, u16 header_size, 7995 struct pt_regs *regs) 7996 { 7997 u64 task_size; 7998 7999 /* No regs, no stack pointer, no dump. */ 8000 if (!regs) 8001 return 0; 8002 8003 /* No mm, no stack, no dump. */ 8004 if (!current->mm) 8005 return 0; 8006 8007 /* 8008 * Check if we fit in with the requested stack size into the: 8009 * - TASK_SIZE 8010 * If we don't, we limit the size to the TASK_SIZE. 8011 * 8012 * - remaining sample size 8013 * If we don't, we customize the stack size to 8014 * fit in to the remaining sample size. 8015 */ 8016 8017 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs)); 8018 stack_size = min(stack_size, (u16) task_size); 8019 8020 /* Current header size plus static size and dynamic size. */ 8021 header_size += 2 * sizeof(u64); 8022 8023 /* Do we fit in with the current stack dump size? */ 8024 if ((u16) (header_size + stack_size) < header_size) { 8025 /* 8026 * If we overflow the maximum size for the sample, 8027 * we customize the stack dump size to fit in. 8028 */ 8029 stack_size = USHRT_MAX - header_size - sizeof(u64); 8030 stack_size = round_up(stack_size, sizeof(u64)); 8031 } 8032 8033 return stack_size; 8034 } 8035 8036 static void 8037 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size, 8038 struct pt_regs *regs) 8039 { 8040 /* Case of a kernel thread, nothing to dump */ 8041 if (!regs) { 8042 u64 size = 0; 8043 perf_output_put(handle, size); 8044 } else { 8045 unsigned long sp; 8046 unsigned int rem; 8047 u64 dyn_size; 8048 8049 /* 8050 * We dump: 8051 * static size 8052 * - the size requested by user or the best one we can fit 8053 * in to the sample max size 8054 * data 8055 * - user stack dump data 8056 * dynamic size 8057 * - the actual dumped size 8058 */ 8059 8060 /* Static size. */ 8061 perf_output_put(handle, dump_size); 8062 8063 /* Data. */ 8064 sp = perf_user_stack_pointer(regs); 8065 rem = __output_copy_user(handle, (void *) sp, dump_size); 8066 dyn_size = dump_size - rem; 8067 8068 perf_output_skip(handle, rem); 8069 8070 /* Dynamic size. */ 8071 perf_output_put(handle, dyn_size); 8072 } 8073 } 8074 8075 static unsigned long perf_prepare_sample_aux(struct perf_event *event, 8076 struct perf_sample_data *data, 8077 size_t size) 8078 { 8079 struct perf_event *sampler = event->aux_event; 8080 struct perf_buffer *rb; 8081 8082 data->aux_size = 0; 8083 8084 if (!sampler) 8085 goto out; 8086 8087 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE)) 8088 goto out; 8089 8090 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id())) 8091 goto out; 8092 8093 rb = ring_buffer_get(sampler); 8094 if (!rb) 8095 goto out; 8096 8097 /* 8098 * If this is an NMI hit inside sampling code, don't take 8099 * the sample. See also perf_aux_sample_output(). 8100 */ 8101 if (READ_ONCE(rb->aux_in_sampling)) { 8102 data->aux_size = 0; 8103 } else { 8104 size = min_t(size_t, size, perf_aux_size(rb)); 8105 data->aux_size = ALIGN(size, sizeof(u64)); 8106 } 8107 ring_buffer_put(rb); 8108 8109 out: 8110 return data->aux_size; 8111 } 8112 8113 static long perf_pmu_snapshot_aux(struct perf_buffer *rb, 8114 struct perf_event *event, 8115 struct perf_output_handle *handle, 8116 unsigned long size) 8117 { 8118 unsigned long flags; 8119 long ret; 8120 8121 /* 8122 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler 8123 * paths. If we start calling them in NMI context, they may race with 8124 * the IRQ ones, that is, for example, re-starting an event that's just 8125 * been stopped, which is why we're using a separate callback that 8126 * doesn't change the event state. 8127 * 8128 * IRQs need to be disabled to prevent IPIs from racing with us. 8129 */ 8130 local_irq_save(flags); 8131 /* 8132 * Guard against NMI hits inside the critical section; 8133 * see also perf_prepare_sample_aux(). 8134 */ 8135 WRITE_ONCE(rb->aux_in_sampling, 1); 8136 barrier(); 8137 8138 ret = event->pmu->snapshot_aux(event, handle, size); 8139 8140 barrier(); 8141 WRITE_ONCE(rb->aux_in_sampling, 0); 8142 local_irq_restore(flags); 8143 8144 return ret; 8145 } 8146 8147 static void perf_aux_sample_output(struct perf_event *event, 8148 struct perf_output_handle *handle, 8149 struct perf_sample_data *data) 8150 { 8151 struct perf_event *sampler = event->aux_event; 8152 struct perf_buffer *rb; 8153 unsigned long pad; 8154 long size; 8155 8156 if (WARN_ON_ONCE(!sampler || !data->aux_size)) 8157 return; 8158 8159 rb = ring_buffer_get(sampler); 8160 if (!rb) 8161 return; 8162 8163 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size); 8164 8165 /* 8166 * An error here means that perf_output_copy() failed (returned a 8167 * non-zero surplus that it didn't copy), which in its current 8168 * enlightened implementation is not possible. If that changes, we'd 8169 * like to know. 8170 */ 8171 if (WARN_ON_ONCE(size < 0)) 8172 goto out_put; 8173 8174 /* 8175 * The pad comes from ALIGN()ing data->aux_size up to u64 in 8176 * perf_prepare_sample_aux(), so should not be more than that. 8177 */ 8178 pad = data->aux_size - size; 8179 if (WARN_ON_ONCE(pad >= sizeof(u64))) 8180 pad = 8; 8181 8182 if (pad) { 8183 u64 zero = 0; 8184 perf_output_copy(handle, &zero, pad); 8185 } 8186 8187 out_put: 8188 ring_buffer_put(rb); 8189 } 8190 8191 /* 8192 * A set of common sample data types saved even for non-sample records 8193 * when event->attr.sample_id_all is set. 8194 */ 8195 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \ 8196 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \ 8197 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER) 8198 8199 static void __perf_event_header__init_id(struct perf_sample_data *data, 8200 struct perf_event *event, 8201 u64 sample_type) 8202 { 8203 data->type = event->attr.sample_type; 8204 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL; 8205 8206 if (sample_type & PERF_SAMPLE_TID) { 8207 /* namespace issues */ 8208 data->tid_entry.pid = perf_event_pid(event, current); 8209 data->tid_entry.tid = perf_event_tid(event, current); 8210 } 8211 8212 if (sample_type & PERF_SAMPLE_TIME) 8213 data->time = perf_event_clock(event); 8214 8215 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) 8216 data->id = primary_event_id(event); 8217 8218 if (sample_type & PERF_SAMPLE_STREAM_ID) 8219 data->stream_id = event->id; 8220 8221 if (sample_type & PERF_SAMPLE_CPU) { 8222 data->cpu_entry.cpu = raw_smp_processor_id(); 8223 data->cpu_entry.reserved = 0; 8224 } 8225 } 8226 8227 void perf_event_header__init(struct perf_event_header *header, 8228 struct perf_sample_data *data, 8229 u32 type, u16 misc, u16 size, 8230 struct perf_event *event) 8231 { 8232 header->type = type; 8233 header->misc = misc; 8234 header->size = size; 8235 8236 if (event->attr.sample_id_all) { 8237 header->size += event->id_header_size; 8238 __perf_event_header__init_id(data, event, event->attr.sample_type); 8239 } 8240 } 8241 8242 static void __perf_event__output_id_sample(struct perf_output_handle *handle, 8243 struct perf_sample_data *data) 8244 { 8245 u64 sample_type = data->type; 8246 8247 if (sample_type & PERF_SAMPLE_TID) 8248 perf_output_put(handle, data->tid_entry); 8249 8250 if (sample_type & PERF_SAMPLE_TIME) 8251 perf_output_put(handle, data->time); 8252 8253 if (sample_type & PERF_SAMPLE_ID) 8254 perf_output_put(handle, data->id); 8255 8256 if (sample_type & PERF_SAMPLE_STREAM_ID) 8257 perf_output_put(handle, data->stream_id); 8258 8259 if (sample_type & PERF_SAMPLE_CPU) 8260 perf_output_put(handle, data->cpu_entry); 8261 8262 if (sample_type & PERF_SAMPLE_IDENTIFIER) 8263 perf_output_put(handle, data->id); 8264 } 8265 8266 void perf_event__output_id_sample(struct perf_event *event, 8267 struct perf_output_handle *handle, 8268 struct perf_sample_data *sample) 8269 { 8270 if (event->attr.sample_id_all) 8271 __perf_event__output_id_sample(handle, sample); 8272 } 8273 8274 static void perf_output_read_one(struct perf_output_handle *handle, 8275 struct perf_event *event, 8276 u64 enabled, u64 running) 8277 { 8278 u64 read_format = event->attr.read_format; 8279 u64 values[5]; 8280 int n = 0; 8281 8282 values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr)); 8283 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 8284 values[n++] = enabled + 8285 atomic64_read(&event->child_total_time_enabled); 8286 } 8287 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 8288 values[n++] = running + 8289 atomic64_read(&event->child_total_time_running); 8290 } 8291 if (read_format & PERF_FORMAT_ID) 8292 values[n++] = primary_event_id(event); 8293 if (read_format & PERF_FORMAT_LOST) 8294 values[n++] = atomic64_read(&event->lost_samples); 8295 8296 __output_copy(handle, values, n * sizeof(u64)); 8297 } 8298 8299 static void perf_output_read_group(struct perf_output_handle *handle, 8300 struct perf_event *event, 8301 u64 enabled, u64 running) 8302 { 8303 struct perf_event *leader = event->group_leader, *sub; 8304 u64 read_format = event->attr.read_format; 8305 unsigned long flags; 8306 u64 values[6]; 8307 int n = 0; 8308 bool self = has_inherit_and_sample_read(&event->attr); 8309 8310 /* 8311 * Disabling interrupts avoids all counter scheduling 8312 * (context switches, timer based rotation and IPIs). 8313 */ 8314 local_irq_save(flags); 8315 8316 values[n++] = 1 + leader->nr_siblings; 8317 8318 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 8319 values[n++] = enabled; 8320 8321 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 8322 values[n++] = running; 8323 8324 if ((leader != event) && !handle->skip_read) 8325 perf_pmu_read(leader); 8326 8327 values[n++] = perf_event_count(leader, self); 8328 if (read_format & PERF_FORMAT_ID) 8329 values[n++] = primary_event_id(leader); 8330 if (read_format & PERF_FORMAT_LOST) 8331 values[n++] = atomic64_read(&leader->lost_samples); 8332 8333 __output_copy(handle, values, n * sizeof(u64)); 8334 8335 for_each_sibling_event(sub, leader) { 8336 n = 0; 8337 8338 if ((sub != event) && !handle->skip_read) 8339 perf_pmu_read(sub); 8340 8341 values[n++] = perf_event_count(sub, self); 8342 if (read_format & PERF_FORMAT_ID) 8343 values[n++] = primary_event_id(sub); 8344 if (read_format & PERF_FORMAT_LOST) 8345 values[n++] = atomic64_read(&sub->lost_samples); 8346 8347 __output_copy(handle, values, n * sizeof(u64)); 8348 } 8349 8350 local_irq_restore(flags); 8351 } 8352 8353 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\ 8354 PERF_FORMAT_TOTAL_TIME_RUNNING) 8355 8356 /* 8357 * XXX PERF_SAMPLE_READ vs inherited events seems difficult. 8358 * 8359 * The problem is that its both hard and excessively expensive to iterate the 8360 * child list, not to mention that its impossible to IPI the children running 8361 * on another CPU, from interrupt/NMI context. 8362 * 8363 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread 8364 * counts rather than attempting to accumulate some value across all children on 8365 * all cores. 8366 */ 8367 static void perf_output_read(struct perf_output_handle *handle, 8368 struct perf_event *event) 8369 { 8370 u64 enabled = 0, running = 0, now; 8371 u64 read_format = event->attr.read_format; 8372 8373 /* 8374 * Compute total_time_enabled, total_time_running based on snapshot 8375 * values taken when the event was last scheduled in. 8376 * 8377 * We cannot simply call update_context_time() because doing so would 8378 * lead to deadlock when called from NMI context. 8379 */ 8380 if (read_format & PERF_FORMAT_TOTAL_TIMES) 8381 calc_timer_values(event, &now, &enabled, &running); 8382 8383 if (event->attr.read_format & PERF_FORMAT_GROUP) 8384 perf_output_read_group(handle, event, enabled, running); 8385 else 8386 perf_output_read_one(handle, event, enabled, running); 8387 } 8388 8389 void perf_output_sample(struct perf_output_handle *handle, 8390 struct perf_event_header *header, 8391 struct perf_sample_data *data, 8392 struct perf_event *event) 8393 { 8394 u64 sample_type = data->type; 8395 8396 if (data->sample_flags & PERF_SAMPLE_READ) 8397 handle->skip_read = 1; 8398 8399 perf_output_put(handle, *header); 8400 8401 if (sample_type & PERF_SAMPLE_IDENTIFIER) 8402 perf_output_put(handle, data->id); 8403 8404 if (sample_type & PERF_SAMPLE_IP) 8405 perf_output_put(handle, data->ip); 8406 8407 if (sample_type & PERF_SAMPLE_TID) 8408 perf_output_put(handle, data->tid_entry); 8409 8410 if (sample_type & PERF_SAMPLE_TIME) 8411 perf_output_put(handle, data->time); 8412 8413 if (sample_type & PERF_SAMPLE_ADDR) 8414 perf_output_put(handle, data->addr); 8415 8416 if (sample_type & PERF_SAMPLE_ID) 8417 perf_output_put(handle, data->id); 8418 8419 if (sample_type & PERF_SAMPLE_STREAM_ID) 8420 perf_output_put(handle, data->stream_id); 8421 8422 if (sample_type & PERF_SAMPLE_CPU) 8423 perf_output_put(handle, data->cpu_entry); 8424 8425 if (sample_type & PERF_SAMPLE_PERIOD) 8426 perf_output_put(handle, data->period); 8427 8428 if (sample_type & PERF_SAMPLE_READ) 8429 perf_output_read(handle, event); 8430 8431 if (sample_type & PERF_SAMPLE_CALLCHAIN) { 8432 int size = 1; 8433 8434 size += data->callchain->nr; 8435 size *= sizeof(u64); 8436 __output_copy(handle, data->callchain, size); 8437 } 8438 8439 if (sample_type & PERF_SAMPLE_RAW) { 8440 struct perf_raw_record *raw = data->raw; 8441 8442 if (raw) { 8443 struct perf_raw_frag *frag = &raw->frag; 8444 8445 perf_output_put(handle, raw->size); 8446 do { 8447 if (frag->copy) { 8448 __output_custom(handle, frag->copy, 8449 frag->data, frag->size); 8450 } else { 8451 __output_copy(handle, frag->data, 8452 frag->size); 8453 } 8454 if (perf_raw_frag_last(frag)) 8455 break; 8456 frag = frag->next; 8457 } while (1); 8458 if (frag->pad) 8459 __output_skip(handle, NULL, frag->pad); 8460 } else { 8461 struct { 8462 u32 size; 8463 u32 data; 8464 } raw = { 8465 .size = sizeof(u32), 8466 .data = 0, 8467 }; 8468 perf_output_put(handle, raw); 8469 } 8470 } 8471 8472 if (sample_type & PERF_SAMPLE_BRANCH_STACK) { 8473 if (data->br_stack) { 8474 size_t size; 8475 8476 size = data->br_stack->nr 8477 * sizeof(struct perf_branch_entry); 8478 8479 perf_output_put(handle, data->br_stack->nr); 8480 if (branch_sample_hw_index(event)) 8481 perf_output_put(handle, data->br_stack->hw_idx); 8482 perf_output_copy(handle, data->br_stack->entries, size); 8483 /* 8484 * Add the extension space which is appended 8485 * right after the struct perf_branch_stack. 8486 */ 8487 if (data->br_stack_cntr) { 8488 size = data->br_stack->nr * sizeof(u64); 8489 perf_output_copy(handle, data->br_stack_cntr, size); 8490 } 8491 } else { 8492 /* 8493 * we always store at least the value of nr 8494 */ 8495 u64 nr = 0; 8496 perf_output_put(handle, nr); 8497 } 8498 } 8499 8500 if (sample_type & PERF_SAMPLE_REGS_USER) { 8501 u64 abi = data->regs_user.abi; 8502 8503 /* 8504 * If there are no regs to dump, notice it through 8505 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 8506 */ 8507 perf_output_put(handle, abi); 8508 8509 if (abi) { 8510 struct perf_event_attr *attr = &event->attr; 8511 u64 mask = attr->sample_regs_user; 8512 perf_output_sample_regs(handle, 8513 data->regs_user.regs, 8514 mask); 8515 if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { 8516 perf_output_sample_simd_regs(handle, event, 8517 data->regs_user.regs, 8518 attr->sample_simd_vec_reg_user, 8519 attr->sample_simd_pred_reg_user); 8520 } 8521 } 8522 } 8523 8524 if (sample_type & PERF_SAMPLE_STACK_USER) { 8525 perf_output_sample_ustack(handle, 8526 data->stack_user_size, 8527 data->regs_user.regs); 8528 } 8529 8530 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) 8531 perf_output_put(handle, data->weight.full); 8532 8533 if (sample_type & PERF_SAMPLE_DATA_SRC) 8534 perf_output_put(handle, data->data_src.val); 8535 8536 if (sample_type & PERF_SAMPLE_TRANSACTION) 8537 perf_output_put(handle, data->txn); 8538 8539 if (sample_type & PERF_SAMPLE_REGS_INTR) { 8540 u64 abi = data->regs_intr.abi; 8541 /* 8542 * If there are no regs to dump, notice it through 8543 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 8544 */ 8545 perf_output_put(handle, abi); 8546 8547 if (abi) { 8548 struct perf_event_attr *attr = &event->attr; 8549 u64 mask = attr->sample_regs_intr; 8550 8551 perf_output_sample_regs(handle, 8552 data->regs_intr.regs, 8553 mask); 8554 if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { 8555 perf_output_sample_simd_regs(handle, event, 8556 data->regs_intr.regs, 8557 attr->sample_simd_vec_reg_intr, 8558 attr->sample_simd_pred_reg_intr); 8559 } 8560 } 8561 } 8562 8563 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 8564 perf_output_put(handle, data->phys_addr); 8565 8566 if (sample_type & PERF_SAMPLE_CGROUP) 8567 perf_output_put(handle, data->cgroup); 8568 8569 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) 8570 perf_output_put(handle, data->data_page_size); 8571 8572 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) 8573 perf_output_put(handle, data->code_page_size); 8574 8575 if (sample_type & PERF_SAMPLE_AUX) { 8576 perf_output_put(handle, data->aux_size); 8577 8578 if (data->aux_size) 8579 perf_aux_sample_output(event, handle, data); 8580 } 8581 8582 if (!event->attr.watermark) { 8583 int wakeup_events = event->attr.wakeup_events; 8584 8585 if (wakeup_events) { 8586 struct perf_buffer *rb = handle->rb; 8587 int events = local_inc_return(&rb->events); 8588 8589 if (events >= wakeup_events) { 8590 local_sub(wakeup_events, &rb->events); 8591 local_inc(&rb->wakeup); 8592 } 8593 } 8594 } 8595 } 8596 8597 static u64 perf_virt_to_phys(u64 virt) 8598 { 8599 u64 phys_addr = 0; 8600 8601 if (!virt) 8602 return 0; 8603 8604 if (virt >= TASK_SIZE) { 8605 /* If it's vmalloc()d memory, leave phys_addr as 0 */ 8606 if (virt_addr_valid((void *)(uintptr_t)virt) && 8607 !(virt >= VMALLOC_START && virt < VMALLOC_END)) 8608 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt); 8609 } else { 8610 /* 8611 * Walking the pages tables for user address. 8612 * Interrupts are disabled, so it prevents any tear down 8613 * of the page tables. 8614 * Try IRQ-safe get_user_page_fast_only first. 8615 * If failed, leave phys_addr as 0. 8616 */ 8617 if (is_user_task(current)) { 8618 struct page *p; 8619 8620 pagefault_disable(); 8621 if (get_user_page_fast_only(virt, 0, &p)) { 8622 phys_addr = page_to_phys(p) + virt % PAGE_SIZE; 8623 put_page(p); 8624 } 8625 pagefault_enable(); 8626 } 8627 } 8628 8629 return phys_addr; 8630 } 8631 8632 /* 8633 * Return the pagetable size of a given virtual address. 8634 */ 8635 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr) 8636 { 8637 u64 size = 0; 8638 8639 #ifdef CONFIG_HAVE_GUP_FAST 8640 pgd_t *pgdp, pgd; 8641 p4d_t *p4dp, p4d; 8642 pud_t *pudp, pud; 8643 pmd_t *pmdp, pmd; 8644 pte_t *ptep, pte; 8645 8646 pgdp = pgd_offset(mm, addr); 8647 pgd = pgdp_get(pgdp); 8648 if (pgd_none(pgd)) 8649 return 0; 8650 8651 if (pgd_leaf(pgd)) 8652 return pgd_leaf_size(pgd); 8653 8654 p4dp = p4d_offset_lockless(pgdp, pgd, addr); 8655 p4d = p4dp_get(p4dp); 8656 if (!p4d_present(p4d)) 8657 return 0; 8658 8659 if (p4d_leaf(p4d)) 8660 return p4d_leaf_size(p4d); 8661 8662 pudp = pud_offset_lockless(p4dp, p4d, addr); 8663 pud = pudp_get(pudp); 8664 if (!pud_present(pud)) 8665 return 0; 8666 8667 if (pud_leaf(pud)) 8668 return pud_leaf_size(pud); 8669 8670 pmdp = pmd_offset_lockless(pudp, pud, addr); 8671 again: 8672 pmd = pmdp_get_lockless(pmdp); 8673 if (!pmd_present(pmd)) 8674 return 0; 8675 8676 if (pmd_leaf(pmd)) 8677 return pmd_leaf_size(pmd); 8678 8679 ptep = pte_offset_map(&pmd, addr); 8680 if (!ptep) 8681 goto again; 8682 8683 pte = ptep_get_lockless(ptep); 8684 if (pte_present(pte)) 8685 size = __pte_leaf_size(pmd, pte); 8686 pte_unmap(ptep); 8687 #endif /* CONFIG_HAVE_GUP_FAST */ 8688 8689 return size; 8690 } 8691 8692 static u64 perf_get_page_size(unsigned long addr) 8693 { 8694 struct mm_struct *mm; 8695 unsigned long flags; 8696 u64 size; 8697 8698 if (!addr) 8699 return 0; 8700 8701 /* 8702 * Software page-table walkers must disable IRQs, 8703 * which prevents any tear down of the page tables. 8704 */ 8705 local_irq_save(flags); 8706 8707 mm = current->mm; 8708 if (!mm) { 8709 /* 8710 * For kernel threads and the like, use init_mm so that 8711 * we can find kernel memory. 8712 */ 8713 mm = &init_mm; 8714 } 8715 8716 size = perf_get_pgtable_size(mm, addr); 8717 8718 local_irq_restore(flags); 8719 8720 return size; 8721 } 8722 8723 static struct perf_callchain_entry __empty_callchain = { .nr = 0, }; 8724 8725 static struct unwind_work perf_unwind_work; 8726 8727 struct perf_callchain_entry * 8728 perf_callchain(struct perf_event *event, struct pt_regs *regs) 8729 { 8730 bool kernel = !event->attr.exclude_callchain_kernel; 8731 bool user = !event->attr.exclude_callchain_user && 8732 is_user_task(current); 8733 /* Disallow cross-task user callchains. */ 8734 bool crosstask = event->ctx->task && event->ctx->task != current; 8735 bool defer_user = IS_ENABLED(CONFIG_UNWIND_USER) && user && 8736 event->attr.defer_callchain; 8737 const u32 max_stack = event->attr.sample_max_stack; 8738 struct perf_callchain_entry *callchain; 8739 u64 defer_cookie; 8740 8741 if (!current->mm) 8742 user = false; 8743 8744 if (!kernel && !user) 8745 return &__empty_callchain; 8746 8747 if (!(user && defer_user && !crosstask && 8748 unwind_deferred_request(&perf_unwind_work, &defer_cookie) >= 0)) 8749 defer_cookie = 0; 8750 8751 callchain = get_perf_callchain(regs, kernel, user, max_stack, 8752 crosstask, true, defer_cookie); 8753 8754 return callchain ?: &__empty_callchain; 8755 } 8756 8757 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d) 8758 { 8759 return d * !!(flags & s); 8760 } 8761 8762 u64 perf_update_xregs_size(struct perf_event *event, bool intr) 8763 { 8764 u16 pred_qwords = event->attr.sample_simd_pred_reg_qwords; 8765 u16 vec_qwords = event->attr.sample_simd_vec_reg_qwords; 8766 u64 pred_mask; 8767 u64 mask; 8768 int size; 8769 8770 if (intr) { 8771 mask = event->attr.sample_simd_vec_reg_intr; 8772 pred_mask = event->attr.sample_simd_pred_reg_intr; 8773 } else { 8774 mask = event->attr.sample_simd_vec_reg_user; 8775 pred_mask = event->attr.sample_simd_pred_reg_user; 8776 } 8777 8778 size = sizeof(u64) * 4; 8779 size += (hweight64(mask) * vec_qwords + 8780 hweight64(pred_mask) * pred_qwords) * sizeof(u64); 8781 8782 return size; 8783 } 8784 8785 void perf_prepare_sample(struct perf_sample_data *data, 8786 struct perf_event *event, 8787 struct pt_regs *regs) 8788 { 8789 u64 sample_type = event->attr.sample_type; 8790 u64 filtered_sample_type; 8791 8792 /* 8793 * Add the sample flags that are dependent to others. And clear the 8794 * sample flags that have already been done by the PMU driver. 8795 */ 8796 filtered_sample_type = sample_type; 8797 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE, 8798 PERF_SAMPLE_IP); 8799 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE | 8800 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR); 8801 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER, 8802 PERF_SAMPLE_REGS_USER); 8803 filtered_sample_type &= ~data->sample_flags; 8804 8805 if (filtered_sample_type == 0) { 8806 /* Make sure it has the correct data->type for output */ 8807 data->type = event->attr.sample_type; 8808 return; 8809 } 8810 8811 __perf_event_header__init_id(data, event, filtered_sample_type); 8812 8813 if (filtered_sample_type & PERF_SAMPLE_IP) { 8814 data->ip = perf_instruction_pointer(event, regs); 8815 data->sample_flags |= PERF_SAMPLE_IP; 8816 } 8817 8818 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN) 8819 perf_sample_save_callchain(data, event, regs); 8820 8821 if (filtered_sample_type & PERF_SAMPLE_RAW) { 8822 data->raw = NULL; 8823 data->dyn_size += sizeof(u64); 8824 data->sample_flags |= PERF_SAMPLE_RAW; 8825 } 8826 8827 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) { 8828 data->br_stack = NULL; 8829 data->dyn_size += sizeof(u64); 8830 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK; 8831 } 8832 8833 if (filtered_sample_type & PERF_SAMPLE_REGS_USER) 8834 perf_sample_regs_user(&data->regs_user, regs); 8835 8836 /* 8837 * It cannot use the filtered_sample_type here as REGS_USER can be set 8838 * by STACK_USER (using __cond_set() above) and we don't want to update 8839 * the dyn_size if it's not requested by users. 8840 */ 8841 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) { 8842 /* regs dump ABI info */ 8843 int size = sizeof(u64); 8844 8845 if (data->regs_user.regs) { 8846 u64 mask = event->attr.sample_regs_user; 8847 8848 size += hweight64(mask) * sizeof(u64); 8849 if (event_has_simd_regs(event)) { 8850 size += perf_update_xregs_size(event, false); 8851 data->regs_user.abi |= PERF_SAMPLE_REGS_ABI_SIMD; 8852 } 8853 } 8854 8855 data->dyn_size += size; 8856 data->sample_flags |= PERF_SAMPLE_REGS_USER; 8857 } 8858 8859 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) { 8860 /* 8861 * Either we need PERF_SAMPLE_STACK_USER bit to be always 8862 * processed as the last one or have additional check added 8863 * in case new sample type is added, because we could eat 8864 * up the rest of the sample size. 8865 */ 8866 u16 stack_size = event->attr.sample_stack_user; 8867 u16 header_size = perf_sample_data_size(data, event); 8868 u16 size = sizeof(u64); 8869 8870 stack_size = perf_sample_ustack_size(stack_size, header_size, 8871 data->regs_user.regs); 8872 8873 /* 8874 * If there is something to dump, add space for the dump 8875 * itself and for the field that tells the dynamic size, 8876 * which is how many have been actually dumped. 8877 */ 8878 if (stack_size) 8879 size += sizeof(u64) + stack_size; 8880 8881 data->stack_user_size = stack_size; 8882 data->dyn_size += size; 8883 data->sample_flags |= PERF_SAMPLE_STACK_USER; 8884 } 8885 8886 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) { 8887 data->weight.full = 0; 8888 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE; 8889 } 8890 8891 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) { 8892 data->data_src.val = PERF_MEM_NA; 8893 data->sample_flags |= PERF_SAMPLE_DATA_SRC; 8894 } 8895 8896 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) { 8897 data->txn = 0; 8898 data->sample_flags |= PERF_SAMPLE_TRANSACTION; 8899 } 8900 8901 if (filtered_sample_type & PERF_SAMPLE_ADDR) { 8902 data->addr = 0; 8903 data->sample_flags |= PERF_SAMPLE_ADDR; 8904 } 8905 8906 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) { 8907 /* regs dump ABI info */ 8908 int size = sizeof(u64); 8909 8910 perf_sample_regs_intr(&data->regs_intr, regs, 8911 event->attr.exclude_kernel); 8912 8913 if (data->regs_intr.regs) { 8914 u64 mask = event->attr.sample_regs_intr; 8915 8916 size += hweight64(mask) * sizeof(u64); 8917 if (event_has_simd_regs(event)) { 8918 size += perf_update_xregs_size(event, true); 8919 data->regs_intr.abi |= PERF_SAMPLE_REGS_ABI_SIMD; 8920 } 8921 } 8922 8923 data->dyn_size += size; 8924 data->sample_flags |= PERF_SAMPLE_REGS_INTR; 8925 } 8926 8927 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) { 8928 data->phys_addr = perf_virt_to_phys(data->addr); 8929 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR; 8930 } 8931 8932 #ifdef CONFIG_CGROUP_PERF 8933 if (filtered_sample_type & PERF_SAMPLE_CGROUP) { 8934 struct cgroup *cgrp; 8935 8936 /* protected by RCU */ 8937 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup; 8938 data->cgroup = cgroup_id(cgrp); 8939 data->sample_flags |= PERF_SAMPLE_CGROUP; 8940 } 8941 #endif 8942 8943 /* 8944 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't 8945 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr, 8946 * but the value will not dump to the userspace. 8947 */ 8948 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) { 8949 data->data_page_size = perf_get_page_size(data->addr); 8950 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE; 8951 } 8952 8953 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) { 8954 data->code_page_size = perf_get_page_size(data->ip); 8955 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE; 8956 } 8957 8958 if (filtered_sample_type & PERF_SAMPLE_AUX) { 8959 u64 size; 8960 u16 header_size = perf_sample_data_size(data, event); 8961 8962 header_size += sizeof(u64); /* size */ 8963 8964 /* 8965 * Given the 16bit nature of header::size, an AUX sample can 8966 * easily overflow it, what with all the preceding sample bits. 8967 * Make sure this doesn't happen by using up to U16_MAX bytes 8968 * per sample in total (rounded down to 8 byte boundary). 8969 */ 8970 size = min_t(size_t, U16_MAX - header_size, 8971 event->attr.aux_sample_size); 8972 size = rounddown(size, 8); 8973 size = perf_prepare_sample_aux(event, data, size); 8974 8975 WARN_ON_ONCE(size + header_size > U16_MAX); 8976 data->dyn_size += size + sizeof(u64); /* size above */ 8977 data->sample_flags |= PERF_SAMPLE_AUX; 8978 } 8979 } 8980 8981 void perf_prepare_header(struct perf_event_header *header, 8982 struct perf_sample_data *data, 8983 struct perf_event *event, 8984 struct pt_regs *regs) 8985 { 8986 header->type = PERF_RECORD_SAMPLE; 8987 header->size = perf_sample_data_size(data, event); 8988 header->misc = perf_misc_flags(event, regs); 8989 8990 /* 8991 * If you're adding more sample types here, you likely need to do 8992 * something about the overflowing header::size, like repurpose the 8993 * lowest 3 bits of size, which should be always zero at the moment. 8994 * This raises a more important question, do we really need 512k sized 8995 * samples and why, so good argumentation is in order for whatever you 8996 * do here next. 8997 */ 8998 WARN_ON_ONCE(header->size & 7); 8999 } 9000 9001 static void __perf_event_aux_pause(struct perf_event *event, bool pause) 9002 { 9003 if (pause) { 9004 if (!event->hw.aux_paused) { 9005 event->hw.aux_paused = 1; 9006 event->pmu->stop(event, PERF_EF_PAUSE); 9007 } 9008 } else { 9009 if (event->hw.aux_paused) { 9010 event->hw.aux_paused = 0; 9011 event->pmu->start(event, PERF_EF_RESUME); 9012 } 9013 } 9014 } 9015 9016 static void perf_event_aux_pause(struct perf_event *event, bool pause) 9017 { 9018 struct perf_buffer *rb; 9019 9020 if (WARN_ON_ONCE(!event)) 9021 return; 9022 9023 rb = ring_buffer_get(event); 9024 if (!rb) 9025 return; 9026 9027 scoped_guard (irqsave) { 9028 /* 9029 * Guard against self-recursion here. Another event could trip 9030 * this same from NMI context. 9031 */ 9032 if (READ_ONCE(rb->aux_in_pause_resume)) 9033 break; 9034 9035 WRITE_ONCE(rb->aux_in_pause_resume, 1); 9036 barrier(); 9037 __perf_event_aux_pause(event, pause); 9038 barrier(); 9039 WRITE_ONCE(rb->aux_in_pause_resume, 0); 9040 } 9041 ring_buffer_put(rb); 9042 } 9043 9044 static __always_inline int 9045 __perf_event_output(struct perf_event *event, 9046 struct perf_sample_data *data, 9047 struct pt_regs *regs, 9048 int (*output_begin)(struct perf_output_handle *, 9049 struct perf_sample_data *, 9050 struct perf_event *, 9051 unsigned int)) 9052 { 9053 struct perf_output_handle handle; 9054 struct perf_event_header header; 9055 int err; 9056 9057 /* protect the callchain buffers */ 9058 rcu_read_lock(); 9059 9060 perf_prepare_sample(data, event, regs); 9061 perf_prepare_header(&header, data, event, regs); 9062 9063 err = output_begin(&handle, data, event, header.size); 9064 if (err) 9065 goto exit; 9066 9067 perf_output_sample(&handle, &header, data, event); 9068 9069 perf_output_end(&handle); 9070 9071 exit: 9072 rcu_read_unlock(); 9073 return err; 9074 } 9075 9076 void 9077 perf_event_output_forward(struct perf_event *event, 9078 struct perf_sample_data *data, 9079 struct pt_regs *regs) 9080 { 9081 __perf_event_output(event, data, regs, perf_output_begin_forward); 9082 } 9083 9084 void 9085 perf_event_output_backward(struct perf_event *event, 9086 struct perf_sample_data *data, 9087 struct pt_regs *regs) 9088 { 9089 __perf_event_output(event, data, regs, perf_output_begin_backward); 9090 } 9091 9092 int 9093 perf_event_output(struct perf_event *event, 9094 struct perf_sample_data *data, 9095 struct pt_regs *regs) 9096 { 9097 return __perf_event_output(event, data, regs, perf_output_begin); 9098 } 9099 9100 /* 9101 * read event_id 9102 */ 9103 9104 struct perf_read_event { 9105 struct perf_event_header header; 9106 9107 u32 pid; 9108 u32 tid; 9109 }; 9110 9111 static void 9112 perf_event_read_event(struct perf_event *event, 9113 struct task_struct *task) 9114 { 9115 struct perf_output_handle handle; 9116 struct perf_sample_data sample; 9117 struct perf_read_event read_event = { 9118 .pid = perf_event_pid(event, task), 9119 .tid = perf_event_tid(event, task), 9120 }; 9121 int ret; 9122 9123 perf_event_header__init(&read_event.header, &sample, 9124 PERF_RECORD_READ, 9125 /* misc= */ 0, 9126 sizeof(read_event) + event->read_size, 9127 event); 9128 ret = perf_output_begin(&handle, &sample, event, read_event.header.size); 9129 if (ret) 9130 return; 9131 9132 perf_output_put(&handle, read_event); 9133 perf_output_read(&handle, event); 9134 perf_event__output_id_sample(event, &handle, &sample); 9135 9136 perf_output_end(&handle); 9137 } 9138 9139 typedef void (perf_iterate_f)(struct perf_event *event, void *data); 9140 9141 static void 9142 perf_iterate_ctx(struct perf_event_context *ctx, 9143 perf_iterate_f output, 9144 void *data, bool all) 9145 { 9146 struct perf_event *event; 9147 9148 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { 9149 if (!all) { 9150 if (event->state < PERF_EVENT_STATE_INACTIVE) 9151 continue; 9152 if (!event_filter_match(event)) 9153 continue; 9154 } 9155 9156 output(event, data); 9157 } 9158 } 9159 9160 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data) 9161 { 9162 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events); 9163 struct perf_event *event; 9164 9165 list_for_each_entry_rcu(event, &pel->list, sb_list) { 9166 /* 9167 * Skip events that are not fully formed yet; ensure that 9168 * if we observe event->ctx, both event and ctx will be 9169 * complete enough. See perf_install_in_context(). 9170 */ 9171 if (!smp_load_acquire(&event->ctx)) 9172 continue; 9173 9174 if (event->state < PERF_EVENT_STATE_INACTIVE) 9175 continue; 9176 if (!event_filter_match(event)) 9177 continue; 9178 output(event, data); 9179 } 9180 } 9181 9182 /* 9183 * Iterate all events that need to receive side-band events. 9184 * 9185 * For new callers; ensure that account_pmu_sb_event() includes 9186 * your event, otherwise it might not get delivered. 9187 */ 9188 static void 9189 perf_iterate_sb(perf_iterate_f output, void *data, 9190 struct perf_event_context *task_ctx) 9191 { 9192 struct perf_event_context *ctx; 9193 9194 rcu_read_lock(); 9195 preempt_disable(); 9196 9197 /* 9198 * If we have task_ctx != NULL we only notify the task context itself. 9199 * The task_ctx is set only for EXIT events before releasing task 9200 * context. 9201 */ 9202 if (task_ctx) { 9203 perf_iterate_ctx(task_ctx, output, data, false); 9204 goto done; 9205 } 9206 9207 perf_iterate_sb_cpu(output, data); 9208 9209 ctx = rcu_dereference(current->perf_event_ctxp); 9210 if (ctx) 9211 perf_iterate_ctx(ctx, output, data, false); 9212 done: 9213 preempt_enable(); 9214 rcu_read_unlock(); 9215 } 9216 9217 /* 9218 * Clear all file-based filters at exec, they'll have to be 9219 * re-instated when/if these objects are mmapped again. 9220 */ 9221 static void perf_event_addr_filters_exec(struct perf_event *event, void *data) 9222 { 9223 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 9224 struct perf_addr_filter *filter; 9225 unsigned int restart = 0, count = 0; 9226 unsigned long flags; 9227 9228 if (!has_addr_filter(event)) 9229 return; 9230 9231 raw_spin_lock_irqsave(&ifh->lock, flags); 9232 list_for_each_entry(filter, &ifh->list, entry) { 9233 if (filter->path.dentry) { 9234 event->addr_filter_ranges[count].start = 0; 9235 event->addr_filter_ranges[count].size = 0; 9236 restart++; 9237 } 9238 9239 count++; 9240 } 9241 9242 if (restart) 9243 event->addr_filters_gen++; 9244 raw_spin_unlock_irqrestore(&ifh->lock, flags); 9245 9246 if (restart) 9247 perf_event_stop(event, 1); 9248 } 9249 9250 void perf_event_exec(void) 9251 { 9252 struct perf_event_context *ctx; 9253 9254 ctx = perf_pin_task_context(current); 9255 if (!ctx) 9256 return; 9257 9258 perf_event_enable_on_exec(ctx); 9259 perf_event_remove_on_exec(ctx); 9260 scoped_guard(rcu) 9261 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true); 9262 9263 perf_unpin_context(ctx); 9264 put_ctx(ctx); 9265 } 9266 9267 struct remote_output { 9268 struct perf_buffer *rb; 9269 int err; 9270 }; 9271 9272 static void __perf_event_output_stop(struct perf_event *event, void *data) 9273 { 9274 struct perf_event *parent = event->parent; 9275 struct remote_output *ro = data; 9276 struct perf_buffer *rb = ro->rb; 9277 struct stop_event_data sd = { 9278 .event = event, 9279 }; 9280 9281 if (!has_aux(event)) 9282 return; 9283 9284 if (!parent) 9285 parent = event; 9286 9287 /* 9288 * In case of inheritance, it will be the parent that links to the 9289 * ring-buffer, but it will be the child that's actually using it. 9290 * 9291 * We are using event::rb to determine if the event should be stopped, 9292 * however this may race with ring_buffer_attach() (through set_output), 9293 * which will make us skip the event that actually needs to be stopped. 9294 * So ring_buffer_attach() has to stop an aux event before re-assigning 9295 * its rb pointer. 9296 */ 9297 if (rcu_dereference(parent->rb) == rb) 9298 ro->err = __perf_event_stop(&sd); 9299 } 9300 9301 static int __perf_pmu_output_stop(void *info) 9302 { 9303 struct perf_event *event = info; 9304 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 9305 struct remote_output ro = { 9306 .rb = event->rb, 9307 }; 9308 9309 rcu_read_lock(); 9310 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false); 9311 if (cpuctx->task_ctx) 9312 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop, 9313 &ro, false); 9314 rcu_read_unlock(); 9315 9316 return ro.err; 9317 } 9318 9319 static void perf_pmu_output_stop(struct perf_event *event) 9320 { 9321 struct perf_event *iter; 9322 int err, cpu; 9323 9324 restart: 9325 rcu_read_lock(); 9326 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) { 9327 /* 9328 * For per-CPU events, we need to make sure that neither they 9329 * nor their children are running; for cpu==-1 events it's 9330 * sufficient to stop the event itself if it's active, since 9331 * it can't have children. 9332 */ 9333 cpu = iter->cpu; 9334 if (cpu == -1) 9335 cpu = READ_ONCE(iter->oncpu); 9336 9337 if (cpu == -1) 9338 continue; 9339 9340 err = cpu_function_call(cpu, __perf_pmu_output_stop, event); 9341 if (err == -EAGAIN) { 9342 rcu_read_unlock(); 9343 goto restart; 9344 } 9345 } 9346 rcu_read_unlock(); 9347 } 9348 9349 /* 9350 * task tracking -- fork/exit 9351 * 9352 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task 9353 */ 9354 9355 struct perf_task_event { 9356 struct task_struct *task; 9357 struct perf_event_context *task_ctx; 9358 9359 struct { 9360 struct perf_event_header header; 9361 9362 u32 pid; 9363 u32 ppid; 9364 u32 tid; 9365 u32 ptid; 9366 u64 time; 9367 } event_id; 9368 int new; 9369 }; 9370 9371 static int perf_event_task_match(struct perf_event *event) 9372 { 9373 return event->attr.comm || event->attr.mmap || 9374 event->attr.mmap2 || event->attr.mmap_data || 9375 event->attr.task; 9376 } 9377 9378 static void perf_event_task_output(struct perf_event *event, 9379 void *data) 9380 { 9381 struct perf_task_event *task_event = data; 9382 struct perf_output_handle handle; 9383 struct perf_sample_data sample; 9384 struct task_struct *task = task_event->task; 9385 int ret; 9386 9387 if (!perf_event_task_match(event)) 9388 return; 9389 9390 perf_event_header__init(&task_event->event_id.header, &sample, 9391 task_event->new ? PERF_RECORD_FORK : PERF_RECORD_EXIT, 9392 /* misc= */ 0, 9393 sizeof(task_event->event_id), 9394 event); 9395 9396 ret = perf_output_begin(&handle, &sample, event, 9397 task_event->event_id.header.size); 9398 if (ret) 9399 return; 9400 9401 task_event->event_id.pid = perf_event_pid(event, task); 9402 task_event->event_id.tid = perf_event_tid(event, task); 9403 9404 if (task_event->event_id.header.type == PERF_RECORD_EXIT) { 9405 task_event->event_id.ppid = perf_event_pid(event, 9406 task->real_parent); 9407 task_event->event_id.ptid = perf_event_pid(event, 9408 task->real_parent); 9409 } else { /* PERF_RECORD_FORK */ 9410 task_event->event_id.ppid = perf_event_pid(event, current); 9411 task_event->event_id.ptid = perf_event_tid(event, current); 9412 } 9413 9414 task_event->event_id.time = perf_event_clock(event); 9415 9416 perf_output_put(&handle, task_event->event_id); 9417 9418 perf_event__output_id_sample(event, &handle, &sample); 9419 9420 perf_output_end(&handle); 9421 } 9422 9423 static void perf_event_task(struct task_struct *task, 9424 struct perf_event_context *task_ctx, 9425 int new) 9426 { 9427 struct perf_task_event task_event; 9428 9429 if (!atomic_read(&nr_comm_events) && 9430 !atomic_read(&nr_mmap_events) && 9431 !atomic_read(&nr_task_events)) 9432 return; 9433 9434 task_event = (struct perf_task_event){ 9435 .task = task, 9436 .task_ctx = task_ctx, 9437 .new = new, 9438 }; 9439 9440 perf_iterate_sb(perf_event_task_output, 9441 &task_event, 9442 task_ctx); 9443 } 9444 9445 /* 9446 * Allocate data for a new task when profiling system-wide 9447 * events which require PMU specific data 9448 */ 9449 static void 9450 perf_event_alloc_task_data(struct task_struct *child, 9451 struct task_struct *parent) 9452 { 9453 struct kmem_cache *ctx_cache = NULL; 9454 struct perf_ctx_data *cd; 9455 9456 if (!refcount_read(&global_ctx_data_ref)) 9457 return; 9458 9459 scoped_guard (rcu) { 9460 cd = rcu_dereference(parent->perf_ctx_data); 9461 if (cd) 9462 ctx_cache = cd->ctx_cache; 9463 } 9464 9465 if (!ctx_cache) 9466 return; 9467 9468 guard(percpu_read)(&global_ctx_data_rwsem); 9469 scoped_guard (rcu) { 9470 cd = rcu_dereference(child->perf_ctx_data); 9471 if (!cd) { 9472 /* 9473 * A system-wide event may be unaccount, 9474 * when attaching the perf_ctx_data. 9475 */ 9476 if (!refcount_read(&global_ctx_data_ref)) 9477 return; 9478 goto attach; 9479 } 9480 9481 if (!cd->global) { 9482 cd->global = 1; 9483 refcount_inc(&cd->refcount); 9484 } 9485 } 9486 9487 return; 9488 attach: 9489 attach_task_ctx_data(child, ctx_cache, true, GFP_KERNEL); 9490 } 9491 9492 void perf_event_fork(struct task_struct *task) 9493 { 9494 perf_event_task(task, NULL, 1); 9495 perf_event_namespaces(task); 9496 perf_event_alloc_task_data(task, current); 9497 } 9498 9499 /* 9500 * comm tracking 9501 */ 9502 9503 struct perf_comm_event { 9504 struct task_struct *task; 9505 char *comm; 9506 int comm_size; 9507 9508 struct { 9509 struct perf_event_header header; 9510 9511 u32 pid; 9512 u32 tid; 9513 } event_id; 9514 bool exec; 9515 }; 9516 9517 static int perf_event_comm_match(struct perf_event *event) 9518 { 9519 return event->attr.comm; 9520 } 9521 9522 static void perf_event_comm_output(struct perf_event *event, 9523 void *data) 9524 { 9525 struct perf_comm_event *comm_event = data; 9526 struct perf_output_handle handle; 9527 struct perf_sample_data sample; 9528 int ret; 9529 9530 if (!perf_event_comm_match(event)) 9531 return; 9532 9533 perf_event_header__init(&comm_event->event_id.header, &sample, 9534 PERF_RECORD_COMM, 9535 comm_event->exec ? PERF_RECORD_MISC_COMM_EXEC : 0, 9536 sizeof(comm_event->event_id) + comm_event->comm_size, 9537 event); 9538 ret = perf_output_begin(&handle, &sample, event, 9539 comm_event->event_id.header.size); 9540 9541 if (ret) 9542 return; 9543 9544 comm_event->event_id.pid = perf_event_pid(event, comm_event->task); 9545 comm_event->event_id.tid = perf_event_tid(event, comm_event->task); 9546 9547 perf_output_put(&handle, comm_event->event_id); 9548 __output_copy(&handle, comm_event->comm, 9549 comm_event->comm_size); 9550 9551 perf_event__output_id_sample(event, &handle, &sample); 9552 9553 perf_output_end(&handle); 9554 } 9555 9556 static void perf_event_comm_event(struct perf_comm_event *comm_event) 9557 { 9558 char comm[TASK_COMM_LEN]; 9559 unsigned int size; 9560 9561 memset(comm, 0, sizeof(comm)); 9562 strscpy(comm, comm_event->task->comm); 9563 size = ALIGN(strlen(comm)+1, sizeof(u64)); 9564 9565 comm_event->comm = comm; 9566 comm_event->comm_size = size; 9567 9568 perf_iterate_sb(perf_event_comm_output, 9569 comm_event, 9570 NULL); 9571 } 9572 9573 void perf_event_comm(struct task_struct *task, bool exec) 9574 { 9575 struct perf_comm_event comm_event; 9576 9577 if (!atomic_read(&nr_comm_events)) 9578 return; 9579 9580 comm_event = (struct perf_comm_event){ 9581 .task = task, 9582 /* .comm */ 9583 /* .comm_size */ 9584 /* .event_id */ 9585 .exec = exec, 9586 }; 9587 9588 perf_event_comm_event(&comm_event); 9589 } 9590 9591 /* 9592 * namespaces tracking 9593 */ 9594 9595 struct perf_namespaces_event { 9596 struct task_struct *task; 9597 9598 struct { 9599 struct perf_event_header header; 9600 9601 u32 pid; 9602 u32 tid; 9603 u64 nr_namespaces; 9604 struct perf_ns_link_info link_info[NR_NAMESPACES]; 9605 } event_id; 9606 }; 9607 9608 static int perf_event_namespaces_match(struct perf_event *event) 9609 { 9610 return event->attr.namespaces; 9611 } 9612 9613 static void perf_event_namespaces_output(struct perf_event *event, 9614 void *data) 9615 { 9616 struct perf_namespaces_event *namespaces_event = data; 9617 struct perf_output_handle handle; 9618 struct perf_sample_data sample; 9619 int ret; 9620 9621 if (!perf_event_namespaces_match(event)) 9622 return; 9623 9624 perf_event_header__init(&namespaces_event->event_id.header, &sample, 9625 PERF_RECORD_NAMESPACES, 9626 /* misc= */ 0, 9627 sizeof(namespaces_event->event_id), 9628 event); 9629 ret = perf_output_begin(&handle, &sample, event, 9630 namespaces_event->event_id.header.size); 9631 if (ret) 9632 return; 9633 9634 namespaces_event->event_id.pid = perf_event_pid(event, 9635 namespaces_event->task); 9636 namespaces_event->event_id.tid = perf_event_tid(event, 9637 namespaces_event->task); 9638 9639 perf_output_put(&handle, namespaces_event->event_id); 9640 9641 perf_event__output_id_sample(event, &handle, &sample); 9642 9643 perf_output_end(&handle); 9644 } 9645 9646 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info, 9647 struct task_struct *task, 9648 const struct proc_ns_operations *ns_ops) 9649 { 9650 struct path ns_path; 9651 struct inode *ns_inode; 9652 int error; 9653 9654 error = ns_get_path(&ns_path, task, ns_ops); 9655 if (!error) { 9656 ns_inode = ns_path.dentry->d_inode; 9657 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev); 9658 ns_link_info->ino = ns_inode->i_ino; 9659 path_put(&ns_path); 9660 } 9661 } 9662 9663 void perf_event_namespaces(struct task_struct *task) 9664 { 9665 struct perf_namespaces_event namespaces_event; 9666 struct perf_ns_link_info *ns_link_info; 9667 9668 if (!atomic_read(&nr_namespaces_events)) 9669 return; 9670 9671 namespaces_event = (struct perf_namespaces_event){ 9672 .task = task, 9673 .event_id = { 9674 /* .header */ 9675 /* .pid */ 9676 /* .tid */ 9677 .nr_namespaces = NR_NAMESPACES, 9678 /* .link_info[NR_NAMESPACES] */ 9679 }, 9680 }; 9681 9682 ns_link_info = namespaces_event.event_id.link_info; 9683 9684 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX], 9685 task, &mntns_operations); 9686 9687 #ifdef CONFIG_USER_NS 9688 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX], 9689 task, &userns_operations); 9690 #endif 9691 #ifdef CONFIG_NET_NS 9692 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX], 9693 task, &netns_operations); 9694 #endif 9695 #ifdef CONFIG_UTS_NS 9696 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX], 9697 task, &utsns_operations); 9698 #endif 9699 #ifdef CONFIG_IPC_NS 9700 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX], 9701 task, &ipcns_operations); 9702 #endif 9703 #ifdef CONFIG_PID_NS 9704 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX], 9705 task, &pidns_operations); 9706 #endif 9707 #ifdef CONFIG_CGROUPS 9708 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX], 9709 task, &cgroupns_operations); 9710 #endif 9711 9712 perf_iterate_sb(perf_event_namespaces_output, 9713 &namespaces_event, 9714 NULL); 9715 } 9716 9717 /* 9718 * cgroup tracking 9719 */ 9720 #ifdef CONFIG_CGROUP_PERF 9721 9722 struct perf_cgroup_event { 9723 char *path; 9724 int path_size; 9725 struct { 9726 struct perf_event_header header; 9727 u64 id; 9728 char path[]; 9729 } event_id; 9730 }; 9731 9732 static int perf_event_cgroup_match(struct perf_event *event) 9733 { 9734 return event->attr.cgroup; 9735 } 9736 9737 static void perf_event_cgroup_output(struct perf_event *event, void *data) 9738 { 9739 struct perf_cgroup_event *cgroup_event = data; 9740 struct perf_output_handle handle; 9741 struct perf_sample_data sample; 9742 int ret; 9743 u16 size = sizeof(cgroup_event->event_id) + cgroup_event->path_size; 9744 9745 if (!perf_event_cgroup_match(event)) 9746 return; 9747 9748 perf_event_header__init(&cgroup_event->event_id.header, &sample, 9749 PERF_RECORD_CGROUP, /* misc= */ 0, size, 9750 event); 9751 ret = perf_output_begin(&handle, &sample, event, 9752 cgroup_event->event_id.header.size); 9753 if (ret) 9754 return; 9755 9756 perf_output_put(&handle, cgroup_event->event_id); 9757 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size); 9758 9759 perf_event__output_id_sample(event, &handle, &sample); 9760 9761 perf_output_end(&handle); 9762 } 9763 9764 static void perf_event_cgroup(struct cgroup *cgrp) 9765 { 9766 struct perf_cgroup_event cgroup_event; 9767 char path_enomem[16] = "//enomem"; 9768 char *pathname; 9769 size_t size; 9770 9771 if (!atomic_read(&nr_cgroup_events)) 9772 return; 9773 9774 cgroup_event = (struct perf_cgroup_event){ 9775 .event_id = { 9776 .id = cgroup_id(cgrp), 9777 }, 9778 }; 9779 9780 pathname = kmalloc(PATH_MAX, GFP_KERNEL); 9781 if (pathname == NULL) { 9782 cgroup_event.path = path_enomem; 9783 } else { 9784 /* just to be sure to have enough space for alignment */ 9785 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64)); 9786 cgroup_event.path = pathname; 9787 } 9788 9789 /* 9790 * Since our buffer works in 8 byte units we need to align our string 9791 * size to a multiple of 8. However, we must guarantee the tail end is 9792 * zero'd out to avoid leaking random bits to userspace. 9793 */ 9794 size = strlen(cgroup_event.path) + 1; 9795 while (!IS_ALIGNED(size, sizeof(u64))) 9796 cgroup_event.path[size++] = '\0'; 9797 9798 cgroup_event.path_size = size; 9799 9800 perf_iterate_sb(perf_event_cgroup_output, 9801 &cgroup_event, 9802 NULL); 9803 9804 kfree(pathname); 9805 } 9806 9807 #endif 9808 9809 /* 9810 * mmap tracking 9811 */ 9812 9813 struct perf_mmap_event { 9814 struct vm_area_struct *vma; 9815 9816 const char *file_name; 9817 int file_size; 9818 int maj, min; 9819 u64 ino; 9820 u64 ino_generation; 9821 u32 prot, flags; 9822 u8 build_id[BUILD_ID_SIZE_MAX]; 9823 u32 build_id_size; 9824 9825 struct { 9826 struct perf_event_header header; 9827 9828 u32 pid; 9829 u32 tid; 9830 u64 start; 9831 u64 len; 9832 u64 pgoff; 9833 } event_id; 9834 }; 9835 9836 static int perf_event_mmap_match(struct perf_event *event, 9837 void *data) 9838 { 9839 struct perf_mmap_event *mmap_event = data; 9840 struct vm_area_struct *vma = mmap_event->vma; 9841 int executable = vma->vm_flags & VM_EXEC; 9842 9843 return (!executable && event->attr.mmap_data) || 9844 (executable && (event->attr.mmap || event->attr.mmap2)); 9845 } 9846 9847 static void perf_event_mmap_output(struct perf_event *event, 9848 void *data) 9849 { 9850 struct perf_mmap_event *mmap_event = data; 9851 struct perf_output_handle handle; 9852 struct perf_sample_data sample; 9853 int size = sizeof(mmap_event->event_id) + mmap_event->file_size; 9854 u32 type = PERF_RECORD_MMAP; 9855 u16 misc = PERF_RECORD_MISC_USER; 9856 bool use_build_id = false; 9857 int ret; 9858 9859 if (!perf_event_mmap_match(event, data)) 9860 return; 9861 9862 if (event->attr.mmap2) { 9863 type = PERF_RECORD_MMAP2; 9864 size += sizeof(mmap_event->maj); 9865 size += sizeof(mmap_event->min); 9866 size += sizeof(mmap_event->ino); 9867 size += sizeof(mmap_event->ino_generation); 9868 size += sizeof(mmap_event->prot); 9869 size += sizeof(mmap_event->flags); 9870 use_build_id = event->attr.build_id && mmap_event->build_id_size; 9871 if (use_build_id) 9872 misc |= PERF_RECORD_MISC_MMAP_BUILD_ID; 9873 } 9874 if (!(mmap_event->vma->vm_flags & VM_EXEC)) 9875 misc |= PERF_RECORD_MISC_MMAP_DATA; 9876 9877 perf_event_header__init(&mmap_event->event_id.header, &sample, 9878 type, misc, size, event); 9879 ret = perf_output_begin(&handle, &sample, event, 9880 mmap_event->event_id.header.size); 9881 if (ret) 9882 return; 9883 9884 mmap_event->event_id.pid = perf_event_pid(event, current); 9885 mmap_event->event_id.tid = perf_event_tid(event, current); 9886 9887 perf_output_put(&handle, mmap_event->event_id); 9888 9889 if (event->attr.mmap2) { 9890 if (use_build_id) { 9891 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 }; 9892 9893 __output_copy(&handle, size, 4); 9894 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX); 9895 } else { 9896 perf_output_put(&handle, mmap_event->maj); 9897 perf_output_put(&handle, mmap_event->min); 9898 perf_output_put(&handle, mmap_event->ino); 9899 perf_output_put(&handle, mmap_event->ino_generation); 9900 } 9901 perf_output_put(&handle, mmap_event->prot); 9902 perf_output_put(&handle, mmap_event->flags); 9903 } 9904 9905 __output_copy(&handle, mmap_event->file_name, 9906 mmap_event->file_size); 9907 9908 perf_event__output_id_sample(event, &handle, &sample); 9909 9910 perf_output_end(&handle); 9911 } 9912 9913 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event) 9914 { 9915 struct vm_area_struct *vma = mmap_event->vma; 9916 struct file *file = vma->vm_file; 9917 int maj = 0, min = 0; 9918 u64 ino = 0, gen = 0; 9919 u32 prot = 0, flags = 0; 9920 unsigned int size; 9921 char tmp[16]; 9922 char *buf = NULL; 9923 char *name = NULL; 9924 9925 if (vma->vm_flags & VM_READ) 9926 prot |= PROT_READ; 9927 if (vma->vm_flags & VM_WRITE) 9928 prot |= PROT_WRITE; 9929 if (vma->vm_flags & VM_EXEC) 9930 prot |= PROT_EXEC; 9931 9932 if (vma->vm_flags & VM_MAYSHARE) 9933 flags = MAP_SHARED; 9934 else 9935 flags = MAP_PRIVATE; 9936 9937 if (vma->vm_flags & VM_LOCKED) 9938 flags |= MAP_LOCKED; 9939 if (vma_is_hugetlb(vma)) 9940 flags |= MAP_HUGETLB; 9941 9942 if (file) { 9943 const struct inode *inode; 9944 dev_t dev; 9945 9946 buf = kmalloc(PATH_MAX, GFP_KERNEL); 9947 if (!buf) { 9948 name = "//enomem"; 9949 goto cpy_name; 9950 } 9951 /* 9952 * d_path() works from the end of the rb backwards, so we 9953 * need to add enough zero bytes after the string to handle 9954 * the 64bit alignment we do later. 9955 */ 9956 name = d_path(file_user_path(file), buf, PATH_MAX - sizeof(u64)); 9957 if (IS_ERR(name)) { 9958 name = "//toolong"; 9959 goto cpy_name; 9960 } 9961 inode = file_user_inode(vma->vm_file); 9962 dev = inode->i_sb->s_dev; 9963 ino = inode->i_ino; 9964 gen = inode->i_generation; 9965 maj = MAJOR(dev); 9966 min = MINOR(dev); 9967 9968 goto got_name; 9969 } else { 9970 if (vma->vm_ops && vma->vm_ops->name) 9971 name = (char *) vma->vm_ops->name(vma); 9972 if (!name) 9973 name = (char *)arch_vma_name(vma); 9974 if (!name) { 9975 if (vma_is_initial_heap(vma)) 9976 name = "[heap]"; 9977 else if (vma_is_initial_stack(vma)) 9978 name = "[stack]"; 9979 else 9980 name = "//anon"; 9981 } 9982 } 9983 9984 cpy_name: 9985 strscpy(tmp, name); 9986 name = tmp; 9987 got_name: 9988 /* 9989 * Since our buffer works in 8 byte units we need to align our string 9990 * size to a multiple of 8. However, we must guarantee the tail end is 9991 * zero'd out to avoid leaking random bits to userspace. 9992 */ 9993 size = strlen(name)+1; 9994 while (!IS_ALIGNED(size, sizeof(u64))) 9995 name[size++] = '\0'; 9996 9997 mmap_event->file_name = name; 9998 mmap_event->file_size = size; 9999 mmap_event->maj = maj; 10000 mmap_event->min = min; 10001 mmap_event->ino = ino; 10002 mmap_event->ino_generation = gen; 10003 mmap_event->prot = prot; 10004 mmap_event->flags = flags; 10005 10006 if (atomic_read(&nr_build_id_events)) 10007 build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size); 10008 10009 perf_iterate_sb(perf_event_mmap_output, 10010 mmap_event, 10011 NULL); 10012 10013 kfree(buf); 10014 } 10015 10016 /* 10017 * Check whether inode and address range match filter criteria. 10018 */ 10019 static bool perf_addr_filter_match(struct perf_addr_filter *filter, 10020 struct file *file, unsigned long offset, 10021 unsigned long size) 10022 { 10023 /* d_inode(NULL) won't be equal to any mapped user-space file */ 10024 if (!filter->path.dentry) 10025 return false; 10026 10027 if (d_inode(filter->path.dentry) != file_user_inode(file)) 10028 return false; 10029 10030 if (filter->offset > offset + size) 10031 return false; 10032 10033 if (filter->offset + filter->size < offset) 10034 return false; 10035 10036 return true; 10037 } 10038 10039 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter, 10040 struct vm_area_struct *vma, 10041 struct perf_addr_filter_range *fr) 10042 { 10043 unsigned long vma_size = vma->vm_end - vma->vm_start; 10044 unsigned long off = vma_start_pgoff(vma) << PAGE_SHIFT; 10045 struct file *file = vma->vm_file; 10046 10047 if (!perf_addr_filter_match(filter, file, off, vma_size)) 10048 return false; 10049 10050 if (filter->offset < off) { 10051 fr->start = vma->vm_start; 10052 fr->size = min(vma_size, filter->size - (off - filter->offset)); 10053 } else { 10054 fr->start = vma->vm_start + filter->offset - off; 10055 fr->size = min(vma->vm_end - fr->start, filter->size); 10056 } 10057 10058 return true; 10059 } 10060 10061 static void __perf_addr_filters_adjust(struct perf_event *event, void *data) 10062 { 10063 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 10064 struct vm_area_struct *vma = data; 10065 struct perf_addr_filter *filter; 10066 unsigned int restart = 0, count = 0; 10067 unsigned long flags; 10068 10069 if (!has_addr_filter(event)) 10070 return; 10071 10072 if (!vma->vm_file) 10073 return; 10074 10075 raw_spin_lock_irqsave(&ifh->lock, flags); 10076 list_for_each_entry(filter, &ifh->list, entry) { 10077 if (perf_addr_filter_vma_adjust(filter, vma, 10078 &event->addr_filter_ranges[count])) 10079 restart++; 10080 10081 count++; 10082 } 10083 10084 if (restart) 10085 event->addr_filters_gen++; 10086 raw_spin_unlock_irqrestore(&ifh->lock, flags); 10087 10088 if (restart) 10089 perf_event_stop(event, 1); 10090 } 10091 10092 /* 10093 * Adjust all task's events' filters to the new vma 10094 */ 10095 static void perf_addr_filters_adjust(struct vm_area_struct *vma) 10096 { 10097 struct perf_event_context *ctx; 10098 10099 /* 10100 * Data tracing isn't supported yet and as such there is no need 10101 * to keep track of anything that isn't related to executable code: 10102 */ 10103 if (!(vma->vm_flags & VM_EXEC)) 10104 return; 10105 10106 rcu_read_lock(); 10107 ctx = rcu_dereference(current->perf_event_ctxp); 10108 if (ctx) 10109 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true); 10110 rcu_read_unlock(); 10111 } 10112 10113 void perf_event_mmap(struct vm_area_struct *vma) 10114 { 10115 struct perf_mmap_event mmap_event; 10116 10117 if (!atomic_read(&nr_mmap_events)) 10118 return; 10119 10120 mmap_event = (struct perf_mmap_event){ 10121 .vma = vma, 10122 /* .file_name */ 10123 /* .file_size */ 10124 .event_id = { 10125 /* .header */ 10126 /* .pid */ 10127 /* .tid */ 10128 .start = vma->vm_start, 10129 .len = vma->vm_end - vma->vm_start, 10130 .pgoff = (u64)vma_start_pgoff(vma) << PAGE_SHIFT, 10131 }, 10132 /* .maj (attr_mmap2 only) */ 10133 /* .min (attr_mmap2 only) */ 10134 /* .ino (attr_mmap2 only) */ 10135 /* .ino_generation (attr_mmap2 only) */ 10136 /* .prot (attr_mmap2 only) */ 10137 /* .flags (attr_mmap2 only) */ 10138 }; 10139 10140 perf_addr_filters_adjust(vma); 10141 perf_event_mmap_event(&mmap_event); 10142 } 10143 10144 void perf_event_aux_event(struct perf_event *event, unsigned long head, 10145 unsigned long size, u64 flags) 10146 { 10147 struct perf_output_handle handle; 10148 struct perf_sample_data sample; 10149 struct perf_aux_event { 10150 struct perf_event_header header; 10151 u64 offset; 10152 u64 size; 10153 u64 flags; 10154 } rec = { 10155 .offset = head, 10156 .size = size, 10157 .flags = flags, 10158 }; 10159 int ret; 10160 10161 perf_event_header__init(&rec.header, &sample, 10162 PERF_RECORD_AUX, /* misc= */ 0, sizeof(rec), 10163 event); 10164 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10165 10166 if (ret) 10167 return; 10168 10169 perf_output_put(&handle, rec); 10170 perf_event__output_id_sample(event, &handle, &sample); 10171 10172 perf_output_end(&handle); 10173 } 10174 10175 /* 10176 * Lost/dropped samples logging 10177 */ 10178 void perf_log_lost_samples(struct perf_event *event, u64 lost) 10179 { 10180 struct perf_output_handle handle; 10181 struct perf_sample_data sample; 10182 int ret; 10183 10184 struct { 10185 struct perf_event_header header; 10186 u64 lost; 10187 } lost_samples_event = { 10188 .lost = lost, 10189 }; 10190 10191 perf_event_header__init(&lost_samples_event.header, &sample, 10192 PERF_RECORD_LOST_SAMPLES, 10193 /* misc= */ 0, 10194 sizeof(lost_samples_event), 10195 event); 10196 10197 ret = perf_output_begin(&handle, &sample, event, 10198 lost_samples_event.header.size); 10199 if (ret) 10200 return; 10201 10202 perf_output_put(&handle, lost_samples_event); 10203 perf_event__output_id_sample(event, &handle, &sample); 10204 perf_output_end(&handle); 10205 } 10206 10207 /* 10208 * context_switch tracking 10209 */ 10210 10211 struct perf_switch_event { 10212 struct task_struct *task; 10213 struct task_struct *next_prev; 10214 10215 struct { 10216 struct perf_event_header header; 10217 u32 next_prev_pid; 10218 u32 next_prev_tid; 10219 } event_id; 10220 bool sched_in; 10221 bool preempt; 10222 }; 10223 10224 static int perf_event_switch_match(struct perf_event *event) 10225 { 10226 return event->attr.context_switch; 10227 } 10228 10229 static void perf_event_switch_output(struct perf_event *event, void *data) 10230 { 10231 struct perf_switch_event *se = data; 10232 struct perf_output_handle handle; 10233 struct perf_sample_data sample; 10234 u32 type; 10235 u16 misc; 10236 u16 size; 10237 int ret; 10238 10239 if (!perf_event_switch_match(event)) 10240 return; 10241 10242 /* Only CPU-wide events are allowed to see next/prev pid/tid */ 10243 if (event->ctx->task) { 10244 type = PERF_RECORD_SWITCH; 10245 size = sizeof(se->event_id.header); 10246 } else { 10247 type = PERF_RECORD_SWITCH_CPU_WIDE; 10248 size = sizeof(se->event_id); 10249 se->event_id.next_prev_pid = 10250 perf_event_pid(event, se->next_prev); 10251 se->event_id.next_prev_tid = 10252 perf_event_tid(event, se->next_prev); 10253 } 10254 misc = se->sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT; 10255 if (se->preempt) 10256 misc |= PERF_RECORD_MISC_SWITCH_OUT_PREEMPT; 10257 10258 perf_event_header__init(&se->event_id.header, &sample, 10259 type, misc, size, event); 10260 10261 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size); 10262 if (ret) 10263 return; 10264 10265 if (event->ctx->task) 10266 perf_output_put(&handle, se->event_id.header); 10267 else 10268 perf_output_put(&handle, se->event_id); 10269 10270 perf_event__output_id_sample(event, &handle, &sample); 10271 10272 perf_output_end(&handle); 10273 } 10274 10275 static void perf_event_switch(struct task_struct *task, 10276 struct task_struct *next_prev, bool sched_in) 10277 { 10278 struct perf_switch_event switch_event; 10279 10280 /* N.B. caller checks nr_switch_events != 0 */ 10281 10282 switch_event = (struct perf_switch_event){ 10283 .task = task, 10284 .next_prev = next_prev, 10285 /* .event_id */ 10286 .sched_in = sched_in, 10287 .preempt = !sched_in && task_is_runnable(task), 10288 }; 10289 10290 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL); 10291 } 10292 10293 /* 10294 * IRQ throttle logging 10295 */ 10296 10297 static void perf_log_throttle(struct perf_event *event, int enable) 10298 { 10299 struct perf_output_handle handle; 10300 struct perf_sample_data sample; 10301 int ret; 10302 10303 struct { 10304 struct perf_event_header header; 10305 u64 time; 10306 u64 id; 10307 u64 stream_id; 10308 } throttle_event = { 10309 .time = perf_event_clock(event), 10310 .id = primary_event_id(event), 10311 .stream_id = event->id, 10312 }; 10313 10314 perf_event_header__init(&throttle_event.header, &sample, 10315 enable ? PERF_RECORD_UNTHROTTLE 10316 : PERF_RECORD_THROTTLE, 10317 /* misc= */ 0, 10318 sizeof(throttle_event), 10319 event); 10320 10321 ret = perf_output_begin(&handle, &sample, event, 10322 throttle_event.header.size); 10323 if (ret) 10324 return; 10325 10326 perf_output_put(&handle, throttle_event); 10327 perf_event__output_id_sample(event, &handle, &sample); 10328 perf_output_end(&handle); 10329 } 10330 10331 /* 10332 * ksymbol register/unregister tracking 10333 */ 10334 10335 struct perf_ksymbol_event { 10336 const char *name; 10337 int name_len; 10338 struct { 10339 struct perf_event_header header; 10340 u64 addr; 10341 u32 len; 10342 u16 ksym_type; 10343 u16 flags; 10344 } event_id; 10345 }; 10346 10347 static int perf_event_ksymbol_match(struct perf_event *event) 10348 { 10349 return event->attr.ksymbol; 10350 } 10351 10352 static void perf_event_ksymbol_output(struct perf_event *event, void *data) 10353 { 10354 struct perf_ksymbol_event *ksymbol_event = data; 10355 struct perf_output_handle handle; 10356 struct perf_sample_data sample; 10357 int ret; 10358 u16 size = sizeof(ksymbol_event->event_id) + ksymbol_event->name_len; 10359 10360 if (!perf_event_ksymbol_match(event)) 10361 return; 10362 10363 perf_event_header__init(&ksymbol_event->event_id.header, &sample, 10364 PERF_RECORD_KSYMBOL, /* misc= */ 0, size, 10365 event); 10366 ret = perf_output_begin(&handle, &sample, event, 10367 ksymbol_event->event_id.header.size); 10368 if (ret) 10369 return; 10370 10371 perf_output_put(&handle, ksymbol_event->event_id); 10372 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len); 10373 perf_event__output_id_sample(event, &handle, &sample); 10374 10375 perf_output_end(&handle); 10376 } 10377 10378 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister, 10379 const char *sym) 10380 { 10381 struct perf_ksymbol_event ksymbol_event; 10382 char name[KSYM_NAME_LEN]; 10383 u16 flags = 0; 10384 int name_len; 10385 10386 if (!atomic_read(&nr_ksymbol_events)) 10387 return; 10388 10389 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX || 10390 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN) 10391 goto err; 10392 10393 strscpy(name, sym); 10394 name_len = strlen(name) + 1; 10395 while (!IS_ALIGNED(name_len, sizeof(u64))) 10396 name[name_len++] = '\0'; 10397 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64)); 10398 10399 if (unregister) 10400 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER; 10401 10402 ksymbol_event = (struct perf_ksymbol_event){ 10403 .name = name, 10404 .name_len = name_len, 10405 .event_id = { 10406 .addr = addr, 10407 .len = len, 10408 .ksym_type = ksym_type, 10409 .flags = flags, 10410 }, 10411 }; 10412 10413 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL); 10414 return; 10415 err: 10416 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type); 10417 } 10418 10419 /* 10420 * bpf program load/unload tracking 10421 */ 10422 10423 struct perf_bpf_event { 10424 struct bpf_prog *prog; 10425 struct { 10426 struct perf_event_header header; 10427 u16 type; 10428 u16 flags; 10429 u32 id; 10430 u8 tag[BPF_TAG_SIZE]; 10431 } event_id; 10432 }; 10433 10434 static int perf_event_bpf_match(struct perf_event *event) 10435 { 10436 return event->attr.bpf_event; 10437 } 10438 10439 static void perf_event_bpf_output(struct perf_event *event, void *data) 10440 { 10441 struct perf_bpf_event *bpf_event = data; 10442 struct perf_output_handle handle; 10443 struct perf_sample_data sample; 10444 int ret; 10445 10446 if (!perf_event_bpf_match(event)) 10447 return; 10448 10449 perf_event_header__init(&bpf_event->event_id.header, &sample, 10450 PERF_RECORD_BPF_EVENT, 10451 /* misc= */ 0, 10452 sizeof(bpf_event->event_id), 10453 event); 10454 ret = perf_output_begin(&handle, &sample, event, 10455 bpf_event->event_id.header.size); 10456 if (ret) 10457 return; 10458 10459 perf_output_put(&handle, bpf_event->event_id); 10460 perf_event__output_id_sample(event, &handle, &sample); 10461 10462 perf_output_end(&handle); 10463 } 10464 10465 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog, 10466 enum perf_bpf_event_type type) 10467 { 10468 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD; 10469 int i; 10470 10471 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, 10472 (u64)(unsigned long)prog->bpf_func, 10473 prog->jited_len, unregister, 10474 prog->aux->ksym.name); 10475 10476 for (i = 1; i < prog->aux->func_cnt; i++) { 10477 struct bpf_prog *subprog = prog->aux->func[i]; 10478 10479 perf_event_ksymbol( 10480 PERF_RECORD_KSYMBOL_TYPE_BPF, 10481 (u64)(unsigned long)subprog->bpf_func, 10482 subprog->jited_len, unregister, 10483 subprog->aux->ksym.name); 10484 } 10485 } 10486 10487 void perf_event_bpf_event(struct bpf_prog *prog, 10488 enum perf_bpf_event_type type, 10489 u16 flags) 10490 { 10491 struct perf_bpf_event bpf_event; 10492 10493 switch (type) { 10494 case PERF_BPF_EVENT_PROG_LOAD: 10495 case PERF_BPF_EVENT_PROG_UNLOAD: 10496 if (atomic_read(&nr_ksymbol_events)) 10497 perf_event_bpf_emit_ksymbols(prog, type); 10498 break; 10499 default: 10500 return; 10501 } 10502 10503 if (!atomic_read(&nr_bpf_events)) 10504 return; 10505 10506 bpf_event = (struct perf_bpf_event){ 10507 .prog = prog, 10508 .event_id = { 10509 .type = type, 10510 .flags = flags, 10511 .id = prog->aux->id, 10512 }, 10513 }; 10514 10515 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64)); 10516 10517 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE); 10518 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL); 10519 } 10520 10521 struct perf_callchain_deferred_event { 10522 struct unwind_stacktrace *trace; 10523 struct { 10524 struct perf_event_header header; 10525 u64 cookie; 10526 } event; 10527 }; 10528 10529 static void perf_callchain_deferred_output(struct perf_event *event, void *data) 10530 { 10531 struct perf_callchain_deferred_event *deferred_event = data; 10532 struct perf_output_handle handle; 10533 struct perf_sample_data sample; 10534 u64 nr = deferred_event->trace->nr; 10535 u16 size, id_size, max_payload; 10536 int ret; 10537 10538 if (!event->attr.defer_output) 10539 return; 10540 10541 id_size = event->attr.sample_id_all ? event->id_header_size : 0; 10542 max_payload = round_down(U16_MAX - sizeof(deferred_event->event) - 10543 sizeof(u64) - id_size, sizeof(u64)); 10544 nr = min_t(u64, nr, max_payload / sizeof(u64)); 10545 size = sizeof(deferred_event->event) + sizeof(u64) + nr * sizeof(u64); 10546 10547 /* XXX do we really need sample_id_all for this ??? */ 10548 perf_event_header__init(&deferred_event->event.header, &sample, 10549 PERF_RECORD_CALLCHAIN_DEFERRED, 10550 PERF_RECORD_MISC_USER, 10551 size, 10552 event); 10553 10554 ret = perf_output_begin(&handle, &sample, event, 10555 deferred_event->event.header.size); 10556 if (ret) 10557 return; 10558 10559 perf_output_put(&handle, deferred_event->event); 10560 perf_output_put(&handle, nr); 10561 for (u64 i = 0; i < nr; i++) { 10562 u64 entry = deferred_event->trace->entries[i]; 10563 10564 perf_output_put(&handle, entry); 10565 } 10566 perf_event__output_id_sample(event, &handle, &sample); 10567 10568 perf_output_end(&handle); 10569 } 10570 10571 static void perf_unwind_deferred_callback(struct unwind_work *work, 10572 struct unwind_stacktrace *trace, u64 cookie) 10573 { 10574 struct perf_callchain_deferred_event deferred_event = { 10575 .trace = trace, 10576 .event = { 10577 .cookie = cookie, 10578 }, 10579 }; 10580 10581 perf_iterate_sb(perf_callchain_deferred_output, &deferred_event, NULL); 10582 } 10583 10584 struct perf_text_poke_event { 10585 const void *old_bytes; 10586 const void *new_bytes; 10587 u16 tot; 10588 u16 pad; 10589 u16 old_len; 10590 u16 new_len; 10591 10592 struct { 10593 struct perf_event_header header; 10594 10595 u64 addr; 10596 } event_id; 10597 }; 10598 10599 static int perf_event_text_poke_match(struct perf_event *event) 10600 { 10601 return event->attr.text_poke; 10602 } 10603 10604 static void perf_event_text_poke_output(struct perf_event *event, void *data) 10605 { 10606 struct perf_text_poke_event *text_poke_event = data; 10607 struct perf_output_handle handle; 10608 struct perf_sample_data sample; 10609 u16 size = sizeof(text_poke_event->event_id) + text_poke_event->tot + text_poke_event->pad; 10610 u64 padding = 0; 10611 int ret; 10612 10613 if (!perf_event_text_poke_match(event)) 10614 return; 10615 10616 perf_event_header__init(&text_poke_event->event_id.header, &sample, 10617 PERF_RECORD_TEXT_POKE, 10618 PERF_RECORD_MISC_KERNEL, 10619 size, 10620 event); 10621 10622 ret = perf_output_begin(&handle, &sample, event, 10623 text_poke_event->event_id.header.size); 10624 if (ret) 10625 return; 10626 10627 perf_output_put(&handle, text_poke_event->event_id); 10628 perf_output_put(&handle, text_poke_event->old_len); 10629 perf_output_put(&handle, text_poke_event->new_len); 10630 10631 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len); 10632 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len); 10633 10634 if (text_poke_event->pad) 10635 __output_copy(&handle, &padding, text_poke_event->pad); 10636 10637 perf_event__output_id_sample(event, &handle, &sample); 10638 10639 perf_output_end(&handle); 10640 } 10641 10642 void perf_event_text_poke(const void *addr, const void *old_bytes, 10643 size_t old_len, const void *new_bytes, size_t new_len) 10644 { 10645 struct perf_text_poke_event text_poke_event; 10646 size_t tot, pad; 10647 10648 if (!atomic_read(&nr_text_poke_events)) 10649 return; 10650 10651 tot = sizeof(text_poke_event.old_len) + old_len; 10652 tot += sizeof(text_poke_event.new_len) + new_len; 10653 pad = ALIGN(tot, sizeof(u64)) - tot; 10654 10655 text_poke_event = (struct perf_text_poke_event){ 10656 .old_bytes = old_bytes, 10657 .new_bytes = new_bytes, 10658 .tot = tot, 10659 .pad = pad, 10660 .old_len = old_len, 10661 .new_len = new_len, 10662 .event_id = { 10663 .addr = (unsigned long)addr, 10664 }, 10665 }; 10666 10667 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL); 10668 } 10669 10670 void perf_event_itrace_started(struct perf_event *event) 10671 { 10672 WRITE_ONCE(event->attach_state, event->attach_state | PERF_ATTACH_ITRACE); 10673 } 10674 EXPORT_SYMBOL_GPL(perf_event_itrace_started); 10675 10676 static void perf_log_itrace_start(struct perf_event *event) 10677 { 10678 struct perf_output_handle handle; 10679 struct perf_sample_data sample; 10680 struct perf_aux_event { 10681 struct perf_event_header header; 10682 u32 pid; 10683 u32 tid; 10684 } rec; 10685 int ret; 10686 10687 if (event->parent) 10688 event = event->parent; 10689 10690 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) || 10691 event->attach_state & PERF_ATTACH_ITRACE) 10692 return; 10693 10694 rec.pid = perf_event_pid(event, current); 10695 rec.tid = perf_event_tid(event, current); 10696 10697 perf_event_header__init(&rec.header, &sample, 10698 PERF_RECORD_ITRACE_START, /* misc= */ 0, sizeof(rec), 10699 event); 10700 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10701 10702 if (ret) 10703 return; 10704 10705 perf_output_put(&handle, rec); 10706 perf_event__output_id_sample(event, &handle, &sample); 10707 10708 perf_output_end(&handle); 10709 } 10710 10711 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id) 10712 { 10713 struct perf_output_handle handle; 10714 struct perf_sample_data sample; 10715 struct perf_aux_event { 10716 struct perf_event_header header; 10717 u64 hw_id; 10718 } rec; 10719 int ret; 10720 10721 if (event->parent) 10722 event = event->parent; 10723 10724 rec.hw_id = hw_id; 10725 perf_event_header__init(&rec.header, &sample, 10726 PERF_RECORD_AUX_OUTPUT_HW_ID, /* misc= */ 0, 10727 sizeof(rec), event); 10728 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10729 10730 if (ret) 10731 return; 10732 10733 perf_output_put(&handle, rec); 10734 perf_event__output_id_sample(event, &handle, &sample); 10735 10736 perf_output_end(&handle); 10737 } 10738 EXPORT_SYMBOL_GPL(perf_report_aux_output_id); 10739 10740 static int 10741 __perf_event_account_interrupt(struct perf_event *event, int throttle) 10742 { 10743 struct hw_perf_event *hwc = &event->hw; 10744 int ret = 0; 10745 u64 seq; 10746 10747 seq = __this_cpu_read(perf_throttled_seq); 10748 if (seq != hwc->interrupts_seq) { 10749 hwc->interrupts_seq = seq; 10750 hwc->interrupts = 1; 10751 } else { 10752 hwc->interrupts++; 10753 } 10754 10755 if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) { 10756 __this_cpu_inc(perf_throttled_count); 10757 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 10758 perf_event_throttle_group(event); 10759 ret = 1; 10760 } 10761 10762 if (event->attr.freq) { 10763 u64 now = perf_clock(); 10764 s64 delta = now - hwc->freq_time_stamp; 10765 10766 hwc->freq_time_stamp = now; 10767 10768 if (delta > 0 && delta < 2*TICK_NSEC) 10769 perf_adjust_period(event, delta, hwc->last_period, true); 10770 } 10771 10772 return ret; 10773 } 10774 10775 int perf_event_account_interrupt(struct perf_event *event) 10776 { 10777 return __perf_event_account_interrupt(event, 1); 10778 } 10779 10780 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs) 10781 { 10782 /* 10783 * Due to interrupt latency (AKA "skid"), we may enter the 10784 * kernel before taking an overflow, even if the PMU is only 10785 * counting user events. 10786 */ 10787 if (event->attr.exclude_kernel && !user_mode(regs)) 10788 return false; 10789 10790 return true; 10791 } 10792 10793 #ifdef CONFIG_BPF_SYSCALL 10794 static int bpf_overflow_handler(struct perf_event *event, 10795 struct perf_sample_data *data, 10796 struct pt_regs *regs) 10797 { 10798 struct bpf_perf_event_data_kern ctx = { 10799 .data = data, 10800 .event = event, 10801 }; 10802 struct bpf_prog *prog; 10803 int ret = 0; 10804 10805 ctx.regs = perf_arch_bpf_user_pt_regs(regs); 10806 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) 10807 goto out; 10808 rcu_read_lock(); 10809 prog = READ_ONCE(event->prog); 10810 if (prog) { 10811 perf_prepare_sample(data, event, regs); 10812 ret = bpf_prog_run(prog, &ctx); 10813 } 10814 rcu_read_unlock(); 10815 out: 10816 __this_cpu_dec(bpf_prog_active); 10817 10818 return ret; 10819 } 10820 10821 static inline int perf_event_set_bpf_handler(struct perf_event *event, 10822 struct bpf_prog *prog, 10823 u64 bpf_cookie) 10824 { 10825 if (event->overflow_handler_context) 10826 /* hw breakpoint or kernel counter */ 10827 return -EINVAL; 10828 10829 if (event->prog) 10830 return -EEXIST; 10831 10832 if (prog->type != BPF_PROG_TYPE_PERF_EVENT) 10833 return -EINVAL; 10834 10835 if (event->attr.precise_ip && 10836 prog->call_get_stack && 10837 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) || 10838 event->attr.exclude_callchain_kernel || 10839 event->attr.exclude_callchain_user)) { 10840 /* 10841 * On perf_event with precise_ip, calling bpf_get_stack() 10842 * may trigger unwinder warnings and occasional crashes. 10843 * bpf_get_[stack|stackid] works around this issue by using 10844 * callchain attached to perf_sample_data. If the 10845 * perf_event does not full (kernel and user) callchain 10846 * attached to perf_sample_data, do not allow attaching BPF 10847 * program that calls bpf_get_[stack|stackid]. 10848 */ 10849 return -EPROTO; 10850 } 10851 10852 event->prog = prog; 10853 event->bpf_cookie = bpf_cookie; 10854 return 0; 10855 } 10856 10857 static inline void perf_event_free_bpf_handler(struct perf_event *event) 10858 { 10859 struct bpf_prog *prog = event->prog; 10860 10861 if (!prog) 10862 return; 10863 10864 event->prog = NULL; 10865 bpf_prog_put(prog); 10866 } 10867 #else 10868 static inline int bpf_overflow_handler(struct perf_event *event, 10869 struct perf_sample_data *data, 10870 struct pt_regs *regs) 10871 { 10872 return 1; 10873 } 10874 10875 static inline int perf_event_set_bpf_handler(struct perf_event *event, 10876 struct bpf_prog *prog, 10877 u64 bpf_cookie) 10878 { 10879 return -EOPNOTSUPP; 10880 } 10881 10882 static inline void perf_event_free_bpf_handler(struct perf_event *event) 10883 { 10884 } 10885 #endif 10886 10887 /* 10888 * Generic event overflow handling, sampling. 10889 */ 10890 10891 static int __perf_event_overflow(struct perf_event *event, 10892 int throttle, struct perf_sample_data *data, 10893 struct pt_regs *regs) 10894 { 10895 int events = atomic_read(&event->event_limit); 10896 int ret = 0; 10897 10898 /* 10899 * Non-sampling counters might still use the PMI to fold short 10900 * hardware counters, ignore those. 10901 */ 10902 if (unlikely(!is_sampling_event(event))) 10903 return 0; 10904 10905 ret = __perf_event_account_interrupt(event, throttle); 10906 10907 if (event->attr.aux_pause) 10908 perf_event_aux_pause(event->aux_event, true); 10909 10910 if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT && 10911 !bpf_overflow_handler(event, data, regs)) 10912 goto out; 10913 10914 /* 10915 * XXX event_limit might not quite work as expected on inherited 10916 * events 10917 */ 10918 10919 event->pending_kill = POLL_IN; 10920 if (events && atomic_dec_and_test(&event->event_limit)) { 10921 ret = 1; 10922 event->pending_kill = POLL_HUP; 10923 perf_event_disable_inatomic(event); 10924 event->pmu->stop(event, 0); 10925 } 10926 10927 if (event->attr.sigtrap) { 10928 /* 10929 * The desired behaviour of sigtrap vs invalid samples is a bit 10930 * tricky; on the one hand, one should not loose the SIGTRAP if 10931 * it is the first event, on the other hand, we should also not 10932 * trigger the WARN or override the data address. 10933 */ 10934 bool valid_sample = sample_is_allowed(event, regs); 10935 unsigned int pending_id = 1; 10936 enum task_work_notify_mode notify_mode; 10937 10938 if (regs) 10939 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1; 10940 10941 notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME; 10942 10943 if (!event->pending_work && 10944 !task_work_add(current, &event->pending_task, notify_mode)) { 10945 event->pending_work = pending_id; 10946 local_inc(&event->ctx->nr_no_switch_fast); 10947 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount)); 10948 10949 event->pending_addr = 0; 10950 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR)) 10951 event->pending_addr = data->addr; 10952 10953 } else if (event->attr.exclude_kernel && valid_sample) { 10954 /* 10955 * Should not be able to return to user space without 10956 * consuming pending_work; with exceptions: 10957 * 10958 * 1. Where !exclude_kernel, events can overflow again 10959 * in the kernel without returning to user space. 10960 * 10961 * 2. Events that can overflow again before the IRQ- 10962 * work without user space progress (e.g. hrtimer). 10963 * To approximate progress (with false negatives), 10964 * check 32-bit hash of the current IP. 10965 */ 10966 WARN_ON_ONCE(event->pending_work != pending_id); 10967 } 10968 } 10969 10970 READ_ONCE(event->overflow_handler)(event, data, regs); 10971 10972 if (*perf_event_fasync(event) && event->pending_kill) { 10973 event->pending_wakeup = 1; 10974 irq_work_queue(&event->pending_irq); 10975 } 10976 out: 10977 if (event->attr.aux_resume) 10978 perf_event_aux_pause(event->aux_event, false); 10979 10980 return ret; 10981 } 10982 10983 int perf_event_overflow(struct perf_event *event, 10984 struct perf_sample_data *data, 10985 struct pt_regs *regs) 10986 { 10987 /* 10988 * Entry point from hardware PMI, interrupts should be disabled here. 10989 * This serializes us against perf_event_remove_from_context() in 10990 * things like perf_event_release_kernel(). 10991 */ 10992 lockdep_assert_irqs_disabled(); 10993 10994 return __perf_event_overflow(event, 1, data, regs); 10995 } 10996 10997 /* 10998 * Generic software event infrastructure 10999 */ 11000 11001 struct swevent_htable { 11002 struct swevent_hlist *swevent_hlist; 11003 struct mutex hlist_mutex; 11004 int hlist_refcount; 11005 }; 11006 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable); 11007 11008 /* 11009 * We directly increment event->count and keep a second value in 11010 * event->hw.period_left to count intervals. This period event 11011 * is kept in the range [-sample_period, 0] so that we can use the 11012 * sign as trigger. 11013 */ 11014 11015 u64 perf_swevent_set_period(struct perf_event *event) 11016 { 11017 struct hw_perf_event *hwc = &event->hw; 11018 u64 period = hwc->last_period; 11019 u64 nr, offset; 11020 s64 old, val; 11021 11022 hwc->last_period = hwc->sample_period; 11023 11024 old = local64_read(&hwc->period_left); 11025 do { 11026 val = old; 11027 if (val < 0) 11028 return 0; 11029 11030 nr = div64_u64(period + val, period); 11031 offset = nr * period; 11032 val -= offset; 11033 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val)); 11034 11035 return nr; 11036 } 11037 11038 static void perf_swevent_overflow(struct perf_event *event, u64 overflow, 11039 struct perf_sample_data *data, 11040 struct pt_regs *regs) 11041 { 11042 struct hw_perf_event *hwc = &event->hw; 11043 int throttle = 0; 11044 11045 if (!overflow) 11046 overflow = perf_swevent_set_period(event); 11047 11048 if (hwc->interrupts == MAX_INTERRUPTS) 11049 return; 11050 11051 for (; overflow; overflow--) { 11052 if (__perf_event_overflow(event, throttle, 11053 data, regs)) { 11054 /* 11055 * We inhibit the overflow from happening when 11056 * hwc->interrupts == MAX_INTERRUPTS. 11057 */ 11058 break; 11059 } 11060 throttle = 1; 11061 } 11062 } 11063 11064 static void perf_swevent_event(struct perf_event *event, u64 nr, 11065 struct perf_sample_data *data, 11066 struct pt_regs *regs) 11067 { 11068 struct hw_perf_event *hwc = &event->hw; 11069 11070 /* 11071 * This is: 11072 * - software preempt 11073 * - tracepoint preempt 11074 * - tp_target_task irq (ctx->lock) 11075 * - uprobes preempt/irq 11076 * - kprobes preempt/irq 11077 * - hw_breakpoint irq 11078 * 11079 * Any of these are sufficient to hold off RCU and thus ensure @event 11080 * exists. 11081 */ 11082 lockdep_assert_preemption_disabled(); 11083 local64_add(nr, &event->count); 11084 11085 if (!regs) 11086 return; 11087 11088 if (!is_sampling_event(event)) 11089 return; 11090 11091 /* 11092 * Serialize against event_function_call() IPIs like normal overflow 11093 * event handling. Specifically, must not allow 11094 * perf_event_release_kernel() -> perf_remove_from_context() to make 11095 * progress and 'release' the event from under us. 11096 */ 11097 guard(irqsave)(); 11098 if (event->state != PERF_EVENT_STATE_ACTIVE) 11099 return; 11100 11101 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) { 11102 data->period = nr; 11103 return perf_swevent_overflow(event, 1, data, regs); 11104 } else 11105 data->period = event->hw.last_period; 11106 11107 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) 11108 return perf_swevent_overflow(event, 1, data, regs); 11109 11110 if (local64_add_negative(nr, &hwc->period_left)) 11111 return; 11112 11113 perf_swevent_overflow(event, 0, data, regs); 11114 } 11115 11116 int perf_exclude_event(struct perf_event *event, struct pt_regs *regs) 11117 { 11118 if (event->hw.state & PERF_HES_STOPPED) 11119 return 1; 11120 11121 if (regs) { 11122 if (event->attr.exclude_user && user_mode(regs)) 11123 return 1; 11124 11125 if (event->attr.exclude_kernel && !user_mode(regs)) 11126 return 1; 11127 } 11128 11129 return 0; 11130 } 11131 11132 static int perf_swevent_match(struct perf_event *event, 11133 enum perf_type_id type, 11134 u32 event_id, 11135 struct perf_sample_data *data, 11136 struct pt_regs *regs) 11137 { 11138 if (event->attr.type != type) 11139 return 0; 11140 11141 if (event->attr.config != event_id) 11142 return 0; 11143 11144 if (perf_exclude_event(event, regs)) 11145 return 0; 11146 11147 return 1; 11148 } 11149 11150 static inline u64 swevent_hash(u64 type, u32 event_id) 11151 { 11152 u64 val = event_id | (type << 32); 11153 11154 return hash_64(val, SWEVENT_HLIST_BITS); 11155 } 11156 11157 static inline struct hlist_head * 11158 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id) 11159 { 11160 u64 hash = swevent_hash(type, event_id); 11161 11162 return &hlist->heads[hash]; 11163 } 11164 11165 /* For the read side: events when they trigger */ 11166 static inline struct hlist_head * 11167 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id) 11168 { 11169 struct swevent_hlist *hlist; 11170 11171 hlist = rcu_dereference(swhash->swevent_hlist); 11172 if (!hlist) 11173 return NULL; 11174 11175 return __find_swevent_head(hlist, type, event_id); 11176 } 11177 11178 /* For the event head insertion and removal in the hlist */ 11179 static inline struct hlist_head * 11180 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) 11181 { 11182 struct swevent_hlist *hlist; 11183 u32 event_id = event->attr.config; 11184 u64 type = event->attr.type; 11185 11186 /* 11187 * Event scheduling is always serialized against hlist allocation 11188 * and release. Which makes the protected version suitable here. 11189 * The context lock guarantees that. 11190 */ 11191 hlist = rcu_dereference_protected(swhash->swevent_hlist, 11192 lockdep_is_held(&event->ctx->lock)); 11193 if (!hlist) 11194 return NULL; 11195 11196 return __find_swevent_head(hlist, type, event_id); 11197 } 11198 11199 static void do_perf_sw_event(enum perf_type_id type, u32 event_id, 11200 u64 nr, 11201 struct perf_sample_data *data, 11202 struct pt_regs *regs) 11203 { 11204 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 11205 struct perf_event *event; 11206 struct hlist_head *head; 11207 11208 rcu_read_lock(); 11209 head = find_swevent_head_rcu(swhash, type, event_id); 11210 if (!head) 11211 goto end; 11212 11213 hlist_for_each_entry_rcu(event, head, hlist_entry) { 11214 if (perf_swevent_match(event, type, event_id, data, regs)) 11215 perf_swevent_event(event, nr, data, regs); 11216 } 11217 end: 11218 rcu_read_unlock(); 11219 } 11220 11221 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]); 11222 11223 int perf_swevent_get_recursion_context(void) 11224 { 11225 return get_recursion_context(current->perf_recursion); 11226 } 11227 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context); 11228 11229 void perf_swevent_put_recursion_context(int rctx) 11230 { 11231 put_recursion_context(current->perf_recursion, rctx); 11232 } 11233 11234 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 11235 { 11236 struct perf_sample_data data; 11237 11238 if (WARN_ON_ONCE(!regs)) 11239 return; 11240 11241 perf_sample_data_init(&data, addr, 0); 11242 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs); 11243 } 11244 11245 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 11246 { 11247 int rctx; 11248 11249 preempt_disable_notrace(); 11250 rctx = perf_swevent_get_recursion_context(); 11251 if (unlikely(rctx < 0)) 11252 goto fail; 11253 11254 ___perf_sw_event(event_id, nr, regs, addr); 11255 11256 perf_swevent_put_recursion_context(rctx); 11257 fail: 11258 preempt_enable_notrace(); 11259 } 11260 11261 static void perf_swevent_read(struct perf_event *event) 11262 { 11263 } 11264 11265 static int perf_swevent_add(struct perf_event *event, int flags) 11266 { 11267 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 11268 struct hw_perf_event *hwc = &event->hw; 11269 struct hlist_head *head; 11270 11271 if (is_sampling_event(event)) { 11272 hwc->last_period = hwc->sample_period; 11273 perf_swevent_set_period(event); 11274 } 11275 11276 hwc->state = !(flags & PERF_EF_START); 11277 11278 head = find_swevent_head(swhash, event); 11279 if (WARN_ON_ONCE(!head)) 11280 return -EINVAL; 11281 11282 hlist_add_head_rcu(&event->hlist_entry, head); 11283 perf_event_update_userpage(event); 11284 11285 return 0; 11286 } 11287 11288 static void perf_swevent_del(struct perf_event *event, int flags) 11289 { 11290 hlist_del_rcu(&event->hlist_entry); 11291 } 11292 11293 static void perf_swevent_start(struct perf_event *event, int flags) 11294 { 11295 event->hw.state = 0; 11296 } 11297 11298 static void perf_swevent_stop(struct perf_event *event, int flags) 11299 { 11300 event->hw.state = PERF_HES_STOPPED; 11301 } 11302 11303 /* Deref the hlist from the update side */ 11304 static inline struct swevent_hlist * 11305 swevent_hlist_deref(struct swevent_htable *swhash) 11306 { 11307 return rcu_dereference_protected(swhash->swevent_hlist, 11308 lockdep_is_held(&swhash->hlist_mutex)); 11309 } 11310 11311 static void swevent_hlist_release(struct swevent_htable *swhash) 11312 { 11313 struct swevent_hlist *hlist = swevent_hlist_deref(swhash); 11314 11315 if (!hlist) 11316 return; 11317 11318 RCU_INIT_POINTER(swhash->swevent_hlist, NULL); 11319 kfree_rcu(hlist, rcu_head); 11320 } 11321 11322 static void swevent_hlist_put_cpu(int cpu) 11323 { 11324 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 11325 11326 mutex_lock(&swhash->hlist_mutex); 11327 11328 if (!--swhash->hlist_refcount) 11329 swevent_hlist_release(swhash); 11330 11331 mutex_unlock(&swhash->hlist_mutex); 11332 } 11333 11334 static void swevent_hlist_put(void) 11335 { 11336 int cpu; 11337 11338 for_each_possible_cpu(cpu) 11339 swevent_hlist_put_cpu(cpu); 11340 } 11341 11342 static int swevent_hlist_get_cpu(int cpu) 11343 { 11344 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 11345 int err = 0; 11346 11347 mutex_lock(&swhash->hlist_mutex); 11348 if (!swevent_hlist_deref(swhash) && 11349 cpumask_test_cpu(cpu, perf_online_mask)) { 11350 struct swevent_hlist *hlist; 11351 11352 hlist = kzalloc_obj(*hlist); 11353 if (!hlist) { 11354 err = -ENOMEM; 11355 goto exit; 11356 } 11357 rcu_assign_pointer(swhash->swevent_hlist, hlist); 11358 } 11359 swhash->hlist_refcount++; 11360 exit: 11361 mutex_unlock(&swhash->hlist_mutex); 11362 11363 return err; 11364 } 11365 11366 static int swevent_hlist_get(void) 11367 { 11368 int err, cpu, failed_cpu; 11369 11370 mutex_lock(&pmus_lock); 11371 for_each_possible_cpu(cpu) { 11372 err = swevent_hlist_get_cpu(cpu); 11373 if (err) { 11374 failed_cpu = cpu; 11375 goto fail; 11376 } 11377 } 11378 mutex_unlock(&pmus_lock); 11379 return 0; 11380 fail: 11381 for_each_possible_cpu(cpu) { 11382 if (cpu == failed_cpu) 11383 break; 11384 swevent_hlist_put_cpu(cpu); 11385 } 11386 mutex_unlock(&pmus_lock); 11387 return err; 11388 } 11389 11390 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX]; 11391 11392 static void sw_perf_event_destroy(struct perf_event *event) 11393 { 11394 u64 event_id = event->attr.config; 11395 11396 WARN_ON(event->parent); 11397 11398 static_key_slow_dec(&perf_swevent_enabled[event_id]); 11399 swevent_hlist_put(); 11400 } 11401 11402 static struct pmu perf_cpu_clock; /* fwd declaration */ 11403 static struct pmu perf_task_clock; 11404 11405 static int perf_swevent_init(struct perf_event *event) 11406 { 11407 u64 event_id = event->attr.config; 11408 11409 if (event->attr.type != PERF_TYPE_SOFTWARE) 11410 return -ENOENT; 11411 11412 /* 11413 * no branch sampling for software events 11414 */ 11415 if (has_branch_stack(event)) 11416 return -EOPNOTSUPP; 11417 11418 switch (event_id) { 11419 case PERF_COUNT_SW_CPU_CLOCK: 11420 event->attr.type = perf_cpu_clock.type; 11421 return -ENOENT; 11422 case PERF_COUNT_SW_TASK_CLOCK: 11423 event->attr.type = perf_task_clock.type; 11424 return -ENOENT; 11425 11426 default: 11427 break; 11428 } 11429 11430 if (event_id >= PERF_COUNT_SW_MAX) 11431 return -ENOENT; 11432 11433 if (!event->parent) { 11434 int err; 11435 11436 err = swevent_hlist_get(); 11437 if (err) 11438 return err; 11439 11440 static_key_slow_inc(&perf_swevent_enabled[event_id]); 11441 event->destroy = sw_perf_event_destroy; 11442 } 11443 11444 return 0; 11445 } 11446 11447 static struct pmu perf_swevent = { 11448 .task_ctx_nr = perf_sw_context, 11449 11450 .capabilities = PERF_PMU_CAP_NO_NMI, 11451 11452 .event_init = perf_swevent_init, 11453 .add = perf_swevent_add, 11454 .del = perf_swevent_del, 11455 .start = perf_swevent_start, 11456 .stop = perf_swevent_stop, 11457 .read = perf_swevent_read, 11458 }; 11459 11460 #ifdef CONFIG_EVENT_TRACING 11461 11462 static void tp_perf_event_destroy(struct perf_event *event) 11463 { 11464 perf_trace_destroy(event); 11465 } 11466 11467 static int perf_tp_event_init(struct perf_event *event) 11468 { 11469 int err; 11470 11471 if (event->attr.type != PERF_TYPE_TRACEPOINT) 11472 return -ENOENT; 11473 11474 /* 11475 * no branch sampling for tracepoint events 11476 */ 11477 if (has_branch_stack(event)) 11478 return -EOPNOTSUPP; 11479 11480 err = perf_trace_init(event); 11481 if (err) 11482 return err; 11483 11484 event->destroy = tp_perf_event_destroy; 11485 11486 return 0; 11487 } 11488 11489 static struct pmu perf_tracepoint = { 11490 .task_ctx_nr = perf_sw_context, 11491 11492 .event_init = perf_tp_event_init, 11493 .add = perf_trace_add, 11494 .del = perf_trace_del, 11495 .start = perf_swevent_start, 11496 .stop = perf_swevent_stop, 11497 .read = perf_swevent_read, 11498 }; 11499 11500 static int perf_tp_filter_match(struct perf_event *event, 11501 struct perf_raw_record *raw) 11502 { 11503 void *record = raw->frag.data; 11504 11505 /* only top level events have filters set */ 11506 if (event->parent) 11507 event = event->parent; 11508 11509 if (likely(!event->filter) || filter_match_preds(event->filter, record)) 11510 return 1; 11511 return 0; 11512 } 11513 11514 static int perf_tp_event_match(struct perf_event *event, 11515 struct perf_raw_record *raw, 11516 struct pt_regs *regs) 11517 { 11518 if (event->hw.state & PERF_HES_STOPPED) 11519 return 0; 11520 /* 11521 * If exclude_kernel, only trace user-space tracepoints (uprobes) 11522 */ 11523 if (event->attr.exclude_kernel && !user_mode(regs)) 11524 return 0; 11525 11526 if (!perf_tp_filter_match(event, raw)) 11527 return 0; 11528 11529 return 1; 11530 } 11531 11532 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx, 11533 struct trace_event_call *call, u64 count, 11534 struct pt_regs *regs, struct hlist_head *head, 11535 struct task_struct *task) 11536 { 11537 if (bpf_prog_array_valid(call)) { 11538 *(struct pt_regs **)raw_data = regs; 11539 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) { 11540 perf_swevent_put_recursion_context(rctx); 11541 return; 11542 } 11543 } 11544 perf_tp_event(call->event.type, count, raw_data, size, regs, head, 11545 rctx, task); 11546 } 11547 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit); 11548 11549 static void __perf_tp_event_target_task(u64 count, void *record, 11550 struct pt_regs *regs, 11551 struct perf_sample_data *data, 11552 struct perf_raw_record *raw, 11553 struct perf_event *event) 11554 { 11555 struct trace_entry *entry = record; 11556 11557 if (event->attr.config != entry->type) 11558 return; 11559 /* Cannot deliver synchronous signal to other task. */ 11560 if (event->attr.sigtrap) 11561 return; 11562 if (perf_tp_event_match(event, raw, regs)) { 11563 perf_sample_data_init(data, 0, 0); 11564 perf_sample_save_raw_data(data, event, raw); 11565 perf_swevent_event(event, count, data, regs); 11566 } 11567 } 11568 11569 static void perf_tp_event_target_task(u64 count, void *record, 11570 struct pt_regs *regs, 11571 struct perf_sample_data *data, 11572 struct perf_raw_record *raw, 11573 struct perf_event_context *ctx) 11574 { 11575 unsigned int cpu = smp_processor_id(); 11576 struct pmu *pmu = &perf_tracepoint; 11577 struct perf_event *event, *sibling; 11578 11579 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) { 11580 __perf_tp_event_target_task(count, record, regs, data, raw, event); 11581 for_each_sibling_event(sibling, event) 11582 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 11583 } 11584 11585 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) { 11586 __perf_tp_event_target_task(count, record, regs, data, raw, event); 11587 for_each_sibling_event(sibling, event) 11588 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 11589 } 11590 } 11591 11592 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size, 11593 struct pt_regs *regs, struct hlist_head *head, int rctx, 11594 struct task_struct *task) 11595 { 11596 struct perf_sample_data data; 11597 struct perf_event *event; 11598 11599 /* 11600 * Per being a tracepoint, this runs with preemption disabled. 11601 */ 11602 lockdep_assert_preemption_disabled(); 11603 11604 struct perf_raw_record raw = { 11605 .frag = { 11606 .size = entry_size, 11607 .data = record, 11608 }, 11609 }; 11610 11611 perf_trace_buf_update(record, event_type); 11612 11613 hlist_for_each_entry_rcu(event, head, hlist_entry) { 11614 if (perf_tp_event_match(event, &raw, regs)) { 11615 /* 11616 * Here use the same on-stack perf_sample_data, 11617 * some members in data are event-specific and 11618 * need to be re-computed for different sweveents. 11619 * Re-initialize data->sample_flags safely to avoid 11620 * the problem that next event skips preparing data 11621 * because data->sample_flags is set. 11622 */ 11623 perf_sample_data_init(&data, 0, 0); 11624 perf_sample_save_raw_data(&data, event, &raw); 11625 perf_swevent_event(event, count, &data, regs); 11626 } 11627 } 11628 11629 /* 11630 * If we got specified a target task, also iterate its context and 11631 * deliver this event there too. 11632 */ 11633 if (task && task != current) { 11634 struct perf_event_context *ctx; 11635 11636 rcu_read_lock(); 11637 ctx = rcu_dereference(task->perf_event_ctxp); 11638 if (!ctx) 11639 goto unlock; 11640 11641 raw_spin_lock(&ctx->lock); 11642 perf_tp_event_target_task(count, record, regs, &data, &raw, ctx); 11643 raw_spin_unlock(&ctx->lock); 11644 unlock: 11645 rcu_read_unlock(); 11646 } 11647 11648 perf_swevent_put_recursion_context(rctx); 11649 } 11650 EXPORT_SYMBOL_GPL(perf_tp_event); 11651 11652 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS) 11653 /* 11654 * Flags in config, used by dynamic PMU kprobe and uprobe 11655 * The flags should match following PMU_FORMAT_ATTR(). 11656 * 11657 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe 11658 * if not set, create kprobe/uprobe 11659 * 11660 * The following values specify a reference counter (or semaphore in the 11661 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically 11662 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset. 11663 * 11664 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset 11665 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left 11666 */ 11667 enum perf_probe_config { 11668 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */ 11669 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32, 11670 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS, 11671 }; 11672 11673 PMU_FORMAT_ATTR(retprobe, "config:0"); 11674 #endif 11675 11676 #ifdef CONFIG_KPROBE_EVENTS 11677 static struct attribute *kprobe_attrs[] = { 11678 &format_attr_retprobe.attr, 11679 NULL, 11680 }; 11681 11682 static struct attribute_group kprobe_format_group = { 11683 .name = "format", 11684 .attrs = kprobe_attrs, 11685 }; 11686 11687 static const struct attribute_group *kprobe_attr_groups[] = { 11688 &kprobe_format_group, 11689 NULL, 11690 }; 11691 11692 static int perf_kprobe_event_init(struct perf_event *event); 11693 static struct pmu perf_kprobe = { 11694 .task_ctx_nr = perf_sw_context, 11695 .event_init = perf_kprobe_event_init, 11696 .add = perf_trace_add, 11697 .del = perf_trace_del, 11698 .start = perf_swevent_start, 11699 .stop = perf_swevent_stop, 11700 .read = perf_swevent_read, 11701 .attr_groups = kprobe_attr_groups, 11702 }; 11703 11704 static int perf_kprobe_event_init(struct perf_event *event) 11705 { 11706 int err; 11707 bool is_retprobe; 11708 11709 if (event->attr.type != perf_kprobe.type) 11710 return -ENOENT; 11711 11712 if (!perfmon_capable()) 11713 return -EACCES; 11714 11715 /* 11716 * no branch sampling for probe events 11717 */ 11718 if (has_branch_stack(event)) 11719 return -EOPNOTSUPP; 11720 11721 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 11722 err = perf_kprobe_init(event, is_retprobe); 11723 if (err) 11724 return err; 11725 11726 event->destroy = perf_kprobe_destroy; 11727 11728 return 0; 11729 } 11730 #endif /* CONFIG_KPROBE_EVENTS */ 11731 11732 #ifdef CONFIG_UPROBE_EVENTS 11733 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63"); 11734 11735 static struct attribute *uprobe_attrs[] = { 11736 &format_attr_retprobe.attr, 11737 &format_attr_ref_ctr_offset.attr, 11738 NULL, 11739 }; 11740 11741 static struct attribute_group uprobe_format_group = { 11742 .name = "format", 11743 .attrs = uprobe_attrs, 11744 }; 11745 11746 static const struct attribute_group *uprobe_attr_groups[] = { 11747 &uprobe_format_group, 11748 NULL, 11749 }; 11750 11751 static int perf_uprobe_event_init(struct perf_event *event); 11752 static struct pmu perf_uprobe = { 11753 .task_ctx_nr = perf_sw_context, 11754 .event_init = perf_uprobe_event_init, 11755 .add = perf_trace_add, 11756 .del = perf_trace_del, 11757 .start = perf_swevent_start, 11758 .stop = perf_swevent_stop, 11759 .read = perf_swevent_read, 11760 .attr_groups = uprobe_attr_groups, 11761 }; 11762 11763 static int perf_uprobe_event_init(struct perf_event *event) 11764 { 11765 int err; 11766 unsigned long ref_ctr_offset; 11767 bool is_retprobe; 11768 11769 if (event->attr.type != perf_uprobe.type) 11770 return -ENOENT; 11771 11772 if (!capable(CAP_SYS_ADMIN)) 11773 return -EACCES; 11774 11775 /* 11776 * no branch sampling for probe events 11777 */ 11778 if (has_branch_stack(event)) 11779 return -EOPNOTSUPP; 11780 11781 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 11782 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT; 11783 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe); 11784 if (err) 11785 return err; 11786 11787 event->destroy = perf_uprobe_destroy; 11788 11789 return 0; 11790 } 11791 #endif /* CONFIG_UPROBE_EVENTS */ 11792 11793 static inline void perf_tp_register(void) 11794 { 11795 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT); 11796 #ifdef CONFIG_KPROBE_EVENTS 11797 perf_pmu_register(&perf_kprobe, "kprobe", -1); 11798 #endif 11799 #ifdef CONFIG_UPROBE_EVENTS 11800 perf_pmu_register(&perf_uprobe, "uprobe", -1); 11801 #endif 11802 } 11803 11804 static void perf_event_free_filter(struct perf_event *event) 11805 { 11806 ftrace_profile_free_filter(event); 11807 } 11808 11809 /* 11810 * returns true if the event is a tracepoint, or a kprobe/upprobe created 11811 * with perf_event_open() 11812 */ 11813 static inline bool perf_event_is_tracing(struct perf_event *event) 11814 { 11815 if (event->pmu == &perf_tracepoint) 11816 return true; 11817 #ifdef CONFIG_KPROBE_EVENTS 11818 if (event->pmu == &perf_kprobe) 11819 return true; 11820 #endif 11821 #ifdef CONFIG_UPROBE_EVENTS 11822 if (event->pmu == &perf_uprobe) 11823 return true; 11824 #endif 11825 return false; 11826 } 11827 11828 static int __perf_event_set_bpf_prog(struct perf_event *event, 11829 struct bpf_prog *prog, 11830 u64 bpf_cookie) 11831 { 11832 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp; 11833 11834 if (event->state <= PERF_EVENT_STATE_REVOKED) 11835 return -ENODEV; 11836 11837 if (!perf_event_is_tracing(event)) 11838 return perf_event_set_bpf_handler(event, prog, bpf_cookie); 11839 11840 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE; 11841 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE; 11842 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT; 11843 is_syscall_tp = is_syscall_trace_event(event->tp_event); 11844 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp) 11845 /* bpf programs can only be attached to u/kprobe or tracepoint */ 11846 return -EINVAL; 11847 11848 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) || 11849 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) || 11850 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) 11851 return -EINVAL; 11852 11853 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe) 11854 /* only uprobe programs are allowed to be sleepable */ 11855 return -EINVAL; 11856 11857 if (prog->type == BPF_PROG_TYPE_TRACEPOINT && prog->sleepable) { 11858 /* 11859 * Sleepable tracepoint programs can only attach to faultable 11860 * tracepoints. Currently only syscall tracepoints are faultable. 11861 */ 11862 if (!is_syscall_tp) 11863 return -EINVAL; 11864 } 11865 11866 /* Kprobe override only works for kprobes, not uprobes. */ 11867 if (prog->kprobe_override && !is_kprobe) 11868 return -EINVAL; 11869 11870 /* Writing to context allowed only for uprobes. */ 11871 if (prog->aux->kprobe_write_ctx && !is_uprobe) 11872 return -EINVAL; 11873 11874 if (is_tracepoint || is_syscall_tp) { 11875 int off = trace_event_get_offsets(event->tp_event); 11876 11877 if (prog->aux->max_ctx_offset > off) 11878 return -EACCES; 11879 } 11880 11881 return perf_event_attach_bpf_prog(event, prog, bpf_cookie); 11882 } 11883 11884 int perf_event_set_bpf_prog(struct perf_event *event, 11885 struct bpf_prog *prog, 11886 u64 bpf_cookie) 11887 { 11888 struct perf_event_context *ctx; 11889 int ret; 11890 11891 ctx = perf_event_ctx_lock(event); 11892 ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie); 11893 perf_event_ctx_unlock(event, ctx); 11894 11895 return ret; 11896 } 11897 11898 void perf_event_free_bpf_prog(struct perf_event *event) 11899 { 11900 if (!event->prog) 11901 return; 11902 11903 if (!perf_event_is_tracing(event)) { 11904 perf_event_free_bpf_handler(event); 11905 return; 11906 } 11907 perf_event_detach_bpf_prog(event); 11908 } 11909 11910 #else 11911 11912 static inline void perf_tp_register(void) 11913 { 11914 } 11915 11916 static void perf_event_free_filter(struct perf_event *event) 11917 { 11918 } 11919 11920 static int __perf_event_set_bpf_prog(struct perf_event *event, 11921 struct bpf_prog *prog, 11922 u64 bpf_cookie) 11923 { 11924 return -ENOENT; 11925 } 11926 11927 int perf_event_set_bpf_prog(struct perf_event *event, 11928 struct bpf_prog *prog, 11929 u64 bpf_cookie) 11930 { 11931 return -ENOENT; 11932 } 11933 11934 void perf_event_free_bpf_prog(struct perf_event *event) 11935 { 11936 } 11937 #endif /* CONFIG_EVENT_TRACING */ 11938 11939 #ifdef CONFIG_HAVE_HW_BREAKPOINT 11940 void perf_bp_event(struct perf_event *bp, void *data) 11941 { 11942 struct perf_sample_data sample; 11943 struct pt_regs *regs = data; 11944 11945 /* 11946 * Exception context, will have interrupts disabled. 11947 */ 11948 lockdep_assert_irqs_disabled(); 11949 11950 perf_sample_data_init(&sample, bp->attr.bp_addr, 0); 11951 11952 if (!bp->hw.state && !perf_exclude_event(bp, regs)) 11953 perf_swevent_event(bp, 1, &sample, regs); 11954 } 11955 #endif 11956 11957 /* 11958 * Allocate a new address filter 11959 */ 11960 static struct perf_addr_filter * 11961 perf_addr_filter_new(struct perf_event *event, struct list_head *filters) 11962 { 11963 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu); 11964 struct perf_addr_filter *filter; 11965 11966 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node); 11967 if (!filter) 11968 return NULL; 11969 11970 INIT_LIST_HEAD(&filter->entry); 11971 list_add_tail(&filter->entry, filters); 11972 11973 return filter; 11974 } 11975 11976 static void free_filters_list(struct list_head *filters) 11977 { 11978 struct perf_addr_filter *filter, *iter; 11979 11980 list_for_each_entry_safe(filter, iter, filters, entry) { 11981 path_put(&filter->path); 11982 list_del(&filter->entry); 11983 kfree(filter); 11984 } 11985 } 11986 11987 /* 11988 * Free existing address filters and optionally install new ones 11989 */ 11990 static void perf_addr_filters_splice(struct perf_event *event, 11991 struct list_head *head) 11992 { 11993 unsigned long flags; 11994 LIST_HEAD(list); 11995 11996 if (!has_addr_filter(event)) 11997 return; 11998 11999 /* don't bother with children, they don't have their own filters */ 12000 if (event->parent) 12001 return; 12002 12003 raw_spin_lock_irqsave(&event->addr_filters.lock, flags); 12004 12005 list_splice_init(&event->addr_filters.list, &list); 12006 if (head) 12007 list_splice(head, &event->addr_filters.list); 12008 12009 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags); 12010 12011 free_filters_list(&list); 12012 } 12013 12014 static void perf_free_addr_filters(struct perf_event *event) 12015 { 12016 /* 12017 * Used during free paths, there is no concurrency. 12018 */ 12019 if (list_empty(&event->addr_filters.list)) 12020 return; 12021 12022 perf_addr_filters_splice(event, NULL); 12023 } 12024 12025 /* 12026 * Scan through mm's vmas and see if one of them matches the 12027 * @filter; if so, adjust filter's address range. 12028 * Called with mm::mmap_lock down for reading. 12029 */ 12030 static void perf_addr_filter_apply(struct perf_addr_filter *filter, 12031 struct mm_struct *mm, 12032 struct perf_addr_filter_range *fr) 12033 { 12034 struct vm_area_struct *vma; 12035 VMA_ITERATOR(vmi, mm, 0); 12036 12037 for_each_vma(vmi, vma) { 12038 if (!vma->vm_file) 12039 continue; 12040 12041 if (perf_addr_filter_vma_adjust(filter, vma, fr)) 12042 return; 12043 } 12044 } 12045 12046 /* 12047 * Update event's address range filters based on the 12048 * task's existing mappings, if any. 12049 */ 12050 static void perf_event_addr_filters_apply(struct perf_event *event) 12051 { 12052 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 12053 struct task_struct *task = READ_ONCE(event->ctx->task); 12054 struct perf_addr_filter *filter; 12055 struct mm_struct *mm = NULL; 12056 unsigned int count = 0; 12057 unsigned long flags; 12058 12059 /* 12060 * We may observe TASK_TOMBSTONE, which means that the event tear-down 12061 * will stop on the parent's child_mutex that our caller is also holding 12062 */ 12063 if (task == TASK_TOMBSTONE) 12064 return; 12065 12066 if (ifh->nr_file_filters) { 12067 mm = get_task_mm(task); 12068 if (!mm) 12069 goto restart; 12070 12071 mmap_read_lock(mm); 12072 } 12073 12074 raw_spin_lock_irqsave(&ifh->lock, flags); 12075 list_for_each_entry(filter, &ifh->list, entry) { 12076 if (filter->path.dentry) { 12077 /* 12078 * Adjust base offset if the filter is associated to a 12079 * binary that needs to be mapped: 12080 */ 12081 event->addr_filter_ranges[count].start = 0; 12082 event->addr_filter_ranges[count].size = 0; 12083 12084 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]); 12085 } else { 12086 event->addr_filter_ranges[count].start = filter->offset; 12087 event->addr_filter_ranges[count].size = filter->size; 12088 } 12089 12090 count++; 12091 } 12092 12093 event->addr_filters_gen++; 12094 raw_spin_unlock_irqrestore(&ifh->lock, flags); 12095 12096 if (ifh->nr_file_filters) { 12097 mmap_read_unlock(mm); 12098 12099 mmput(mm); 12100 } 12101 12102 restart: 12103 perf_event_stop(event, 1); 12104 } 12105 12106 /* 12107 * Address range filtering: limiting the data to certain 12108 * instruction address ranges. Filters are ioctl()ed to us from 12109 * userspace as ascii strings. 12110 * 12111 * Filter string format: 12112 * 12113 * ACTION RANGE_SPEC 12114 * where ACTION is one of the 12115 * * "filter": limit the trace to this region 12116 * * "start": start tracing from this address 12117 * * "stop": stop tracing at this address/region; 12118 * RANGE_SPEC is 12119 * * for kernel addresses: <start address>[/<size>] 12120 * * for object files: <start address>[/<size>]@</path/to/object/file> 12121 * 12122 * if <size> is not specified or is zero, the range is treated as a single 12123 * address; not valid for ACTION=="filter". 12124 */ 12125 enum { 12126 IF_ACT_NONE = -1, 12127 IF_ACT_FILTER, 12128 IF_ACT_START, 12129 IF_ACT_STOP, 12130 IF_SRC_FILE, 12131 IF_SRC_KERNEL, 12132 IF_SRC_FILEADDR, 12133 IF_SRC_KERNELADDR, 12134 }; 12135 12136 enum { 12137 IF_STATE_ACTION = 0, 12138 IF_STATE_SOURCE, 12139 IF_STATE_END, 12140 }; 12141 12142 static const match_table_t if_tokens = { 12143 { IF_ACT_FILTER, "filter" }, 12144 { IF_ACT_START, "start" }, 12145 { IF_ACT_STOP, "stop" }, 12146 { IF_SRC_FILE, "%u/%u@%s" }, 12147 { IF_SRC_KERNEL, "%u/%u" }, 12148 { IF_SRC_FILEADDR, "%u@%s" }, 12149 { IF_SRC_KERNELADDR, "%u" }, 12150 { IF_ACT_NONE, NULL }, 12151 }; 12152 12153 /* 12154 * Address filter string parser 12155 */ 12156 static int 12157 perf_event_parse_addr_filter(struct perf_event *event, char *fstr, 12158 struct list_head *filters) 12159 { 12160 struct perf_addr_filter *filter = NULL; 12161 char *start, *orig, *filename = NULL; 12162 substring_t args[MAX_OPT_ARGS]; 12163 int state = IF_STATE_ACTION, token; 12164 unsigned int kernel = 0; 12165 int ret = -EINVAL; 12166 12167 orig = fstr = kstrdup(fstr, GFP_KERNEL); 12168 if (!fstr) 12169 return -ENOMEM; 12170 12171 while ((start = strsep(&fstr, " ,\n")) != NULL) { 12172 static const enum perf_addr_filter_action_t actions[] = { 12173 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER, 12174 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START, 12175 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP, 12176 }; 12177 ret = -EINVAL; 12178 12179 if (!*start) 12180 continue; 12181 12182 /* filter definition begins */ 12183 if (state == IF_STATE_ACTION) { 12184 filter = perf_addr_filter_new(event, filters); 12185 if (!filter) 12186 goto fail; 12187 } 12188 12189 token = match_token(start, if_tokens, args); 12190 switch (token) { 12191 case IF_ACT_FILTER: 12192 case IF_ACT_START: 12193 case IF_ACT_STOP: 12194 if (state != IF_STATE_ACTION) 12195 goto fail; 12196 12197 filter->action = actions[token]; 12198 state = IF_STATE_SOURCE; 12199 break; 12200 12201 case IF_SRC_KERNELADDR: 12202 case IF_SRC_KERNEL: 12203 kernel = 1; 12204 fallthrough; 12205 12206 case IF_SRC_FILEADDR: 12207 case IF_SRC_FILE: 12208 if (state != IF_STATE_SOURCE) 12209 goto fail; 12210 12211 *args[0].to = 0; 12212 ret = kstrtoul(args[0].from, 0, &filter->offset); 12213 if (ret) 12214 goto fail; 12215 12216 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) { 12217 *args[1].to = 0; 12218 ret = kstrtoul(args[1].from, 0, &filter->size); 12219 if (ret) 12220 goto fail; 12221 } 12222 12223 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) { 12224 int fpos = token == IF_SRC_FILE ? 2 : 1; 12225 12226 kfree(filename); 12227 filename = match_strdup(&args[fpos]); 12228 if (!filename) { 12229 ret = -ENOMEM; 12230 goto fail; 12231 } 12232 } 12233 12234 state = IF_STATE_END; 12235 break; 12236 12237 default: 12238 goto fail; 12239 } 12240 12241 /* 12242 * Filter definition is fully parsed, validate and install it. 12243 * Make sure that it doesn't contradict itself or the event's 12244 * attribute. 12245 */ 12246 if (state == IF_STATE_END) { 12247 ret = -EINVAL; 12248 12249 /* 12250 * ACTION "filter" must have a non-zero length region 12251 * specified. 12252 */ 12253 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER && 12254 !filter->size) 12255 goto fail; 12256 12257 if (!kernel) { 12258 if (!filename) 12259 goto fail; 12260 12261 /* 12262 * For now, we only support file-based filters 12263 * in per-task events; doing so for CPU-wide 12264 * events requires additional context switching 12265 * trickery, since same object code will be 12266 * mapped at different virtual addresses in 12267 * different processes. 12268 */ 12269 ret = -EOPNOTSUPP; 12270 if (!event->ctx->task) 12271 goto fail; 12272 12273 /* look up the path and grab its inode */ 12274 ret = kern_path(filename, LOOKUP_FOLLOW, 12275 &filter->path); 12276 if (ret) 12277 goto fail; 12278 12279 ret = -EINVAL; 12280 if (!filter->path.dentry || 12281 !S_ISREG(d_inode(filter->path.dentry) 12282 ->i_mode)) 12283 goto fail; 12284 12285 event->addr_filters.nr_file_filters++; 12286 } 12287 12288 /* ready to consume more filters */ 12289 kfree(filename); 12290 filename = NULL; 12291 state = IF_STATE_ACTION; 12292 filter = NULL; 12293 kernel = 0; 12294 } 12295 } 12296 12297 if (state != IF_STATE_ACTION) 12298 goto fail; 12299 12300 kfree(filename); 12301 kfree(orig); 12302 12303 return 0; 12304 12305 fail: 12306 kfree(filename); 12307 free_filters_list(filters); 12308 kfree(orig); 12309 12310 return ret; 12311 } 12312 12313 static int 12314 perf_event_set_addr_filter(struct perf_event *event, char *filter_str) 12315 { 12316 LIST_HEAD(filters); 12317 int ret; 12318 12319 /* 12320 * Since this is called in perf_ioctl() path, we're already holding 12321 * ctx::mutex. 12322 */ 12323 lockdep_assert_held(&event->ctx->mutex); 12324 12325 if (WARN_ON_ONCE(event->parent)) 12326 return -EINVAL; 12327 12328 ret = perf_event_parse_addr_filter(event, filter_str, &filters); 12329 if (ret) 12330 goto fail_clear_files; 12331 12332 ret = event->pmu->addr_filters_validate(&filters); 12333 if (ret) 12334 goto fail_free_filters; 12335 12336 /* remove existing filters, if any */ 12337 perf_addr_filters_splice(event, &filters); 12338 12339 /* install new filters */ 12340 perf_event_for_each_child(event, perf_event_addr_filters_apply); 12341 12342 return ret; 12343 12344 fail_free_filters: 12345 free_filters_list(&filters); 12346 12347 fail_clear_files: 12348 event->addr_filters.nr_file_filters = 0; 12349 12350 return ret; 12351 } 12352 12353 static int perf_event_set_filter(struct perf_event *event, void __user *arg) 12354 { 12355 int ret = -EINVAL; 12356 char *filter_str; 12357 12358 filter_str = strndup_user(arg, PAGE_SIZE); 12359 if (IS_ERR(filter_str)) 12360 return PTR_ERR(filter_str); 12361 12362 #ifdef CONFIG_EVENT_TRACING 12363 if (perf_event_is_tracing(event)) { 12364 struct perf_event_context *ctx = event->ctx; 12365 12366 /* 12367 * Beware, here be dragons!! 12368 * 12369 * the tracepoint muck will deadlock against ctx->mutex, but 12370 * the tracepoint stuff does not actually need it. So 12371 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we 12372 * already have a reference on ctx. 12373 * 12374 * This can result in event getting moved to a different ctx, 12375 * but that does not affect the tracepoint state. 12376 */ 12377 mutex_unlock(&ctx->mutex); 12378 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str); 12379 mutex_lock(&ctx->mutex); 12380 } else 12381 #endif 12382 if (has_addr_filter(event)) 12383 ret = perf_event_set_addr_filter(event, filter_str); 12384 12385 kfree(filter_str); 12386 return ret; 12387 } 12388 12389 /* 12390 * hrtimer based swevent callback 12391 */ 12392 12393 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer) 12394 { 12395 enum hrtimer_restart ret = HRTIMER_RESTART; 12396 struct perf_sample_data data; 12397 struct pt_regs *regs; 12398 struct perf_event *event; 12399 u64 period; 12400 12401 event = container_of(hrtimer, struct perf_event, hw.hrtimer); 12402 12403 if (event->state != PERF_EVENT_STATE_ACTIVE || 12404 event->hw.state & PERF_HES_STOPPED) 12405 return HRTIMER_NORESTART; 12406 12407 event->pmu->read(event); 12408 12409 perf_sample_data_init(&data, 0, event->hw.last_period); 12410 regs = get_irq_regs(); 12411 12412 if (regs && !perf_exclude_event(event, regs)) { 12413 if (!(event->attr.exclude_idle && is_idle_task(current))) 12414 if (perf_event_overflow(event, &data, regs)) 12415 ret = HRTIMER_NORESTART; 12416 } 12417 12418 period = max_t(u64, 10000, event->hw.sample_period); 12419 hrtimer_forward_now(hrtimer, ns_to_ktime(period)); 12420 12421 return ret; 12422 } 12423 12424 static void perf_swevent_start_hrtimer(struct perf_event *event) 12425 { 12426 struct hw_perf_event *hwc = &event->hw; 12427 s64 period; 12428 12429 if (!is_sampling_event(event)) 12430 return; 12431 12432 period = local64_read(&hwc->period_left); 12433 if (period) { 12434 if (period < 0) 12435 period = 10000; 12436 12437 local64_set(&hwc->period_left, 0); 12438 } else { 12439 period = max_t(u64, 10000, hwc->sample_period); 12440 } 12441 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period), 12442 HRTIMER_MODE_REL_PINNED_HARD); 12443 } 12444 12445 static void perf_swevent_cancel_hrtimer(struct perf_event *event) 12446 { 12447 struct hw_perf_event *hwc = &event->hw; 12448 12449 /* 12450 * Careful: this function can be triggered in the hrtimer handler, 12451 * for cpu-clock events, so hrtimer_cancel() would cause a 12452 * deadlock. 12453 * 12454 * So use hrtimer_try_to_cancel() to try to stop the hrtimer, 12455 * and the cpu-clock handler also sets the PERF_HES_STOPPED flag, 12456 * which guarantees that perf_swevent_hrtimer() will stop the 12457 * hrtimer once it sees the PERF_HES_STOPPED flag. 12458 */ 12459 if (is_sampling_event(event) && (hwc->interrupts != MAX_INTERRUPTS)) { 12460 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer); 12461 local64_set(&hwc->period_left, ktime_to_ns(remaining)); 12462 12463 hrtimer_try_to_cancel(&hwc->hrtimer); 12464 } 12465 } 12466 12467 static void perf_swevent_destroy_hrtimer(struct perf_event *event) 12468 { 12469 hrtimer_cancel(&event->hw.hrtimer); 12470 } 12471 12472 static void perf_swevent_init_hrtimer(struct perf_event *event) 12473 { 12474 struct hw_perf_event *hwc = &event->hw; 12475 12476 if (!is_sampling_event(event)) 12477 return; 12478 12479 hrtimer_setup(&hwc->hrtimer, perf_swevent_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD); 12480 event->destroy = perf_swevent_destroy_hrtimer; 12481 12482 /* 12483 * Since hrtimers have a fixed rate, we can do a static freq->period 12484 * mapping and avoid the whole period adjust feedback stuff. 12485 */ 12486 if (event->attr.freq) { 12487 long freq = event->attr.sample_freq; 12488 12489 event->attr.sample_period = NSEC_PER_SEC / freq; 12490 hwc->sample_period = event->attr.sample_period; 12491 local64_set(&hwc->period_left, hwc->sample_period); 12492 hwc->last_period = hwc->sample_period; 12493 event->attr.freq = 0; 12494 } 12495 } 12496 12497 /* 12498 * Software event: cpu wall time clock 12499 */ 12500 12501 static void cpu_clock_event_update(struct perf_event *event) 12502 { 12503 s64 prev; 12504 u64 now; 12505 12506 now = local_clock(); 12507 prev = local64_xchg(&event->hw.prev_count, now); 12508 local64_add(now - prev, &event->count); 12509 } 12510 12511 static void cpu_clock_event_start(struct perf_event *event, int flags) 12512 { 12513 event->hw.state = 0; 12514 local64_set(&event->hw.prev_count, local_clock()); 12515 perf_swevent_start_hrtimer(event); 12516 } 12517 12518 static void cpu_clock_event_stop(struct perf_event *event, int flags) 12519 { 12520 event->hw.state = PERF_HES_STOPPED; 12521 perf_swevent_cancel_hrtimer(event); 12522 if (flags & PERF_EF_UPDATE) 12523 cpu_clock_event_update(event); 12524 } 12525 12526 static int cpu_clock_event_add(struct perf_event *event, int flags) 12527 { 12528 if (flags & PERF_EF_START) 12529 cpu_clock_event_start(event, flags); 12530 perf_event_update_userpage(event); 12531 12532 return 0; 12533 } 12534 12535 static void cpu_clock_event_del(struct perf_event *event, int flags) 12536 { 12537 cpu_clock_event_stop(event, PERF_EF_UPDATE); 12538 } 12539 12540 static void cpu_clock_event_read(struct perf_event *event) 12541 { 12542 cpu_clock_event_update(event); 12543 } 12544 12545 static int cpu_clock_event_init(struct perf_event *event) 12546 { 12547 if (event->attr.type != perf_cpu_clock.type) 12548 return -ENOENT; 12549 12550 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK) 12551 return -ENOENT; 12552 12553 /* 12554 * no branch sampling for software events 12555 */ 12556 if (has_branch_stack(event)) 12557 return -EOPNOTSUPP; 12558 12559 perf_swevent_init_hrtimer(event); 12560 12561 return 0; 12562 } 12563 12564 static struct pmu perf_cpu_clock = { 12565 .task_ctx_nr = perf_sw_context, 12566 12567 .capabilities = PERF_PMU_CAP_NO_NMI, 12568 .dev = PMU_NULL_DEV, 12569 12570 .event_init = cpu_clock_event_init, 12571 .add = cpu_clock_event_add, 12572 .del = cpu_clock_event_del, 12573 .start = cpu_clock_event_start, 12574 .stop = cpu_clock_event_stop, 12575 .read = cpu_clock_event_read, 12576 }; 12577 12578 /* 12579 * Software event: task time clock 12580 */ 12581 12582 static void task_clock_event_update(struct perf_event *event, u64 now) 12583 { 12584 u64 prev; 12585 s64 delta; 12586 12587 prev = local64_xchg(&event->hw.prev_count, now); 12588 delta = now - prev; 12589 local64_add(delta, &event->count); 12590 } 12591 12592 static void task_clock_event_start(struct perf_event *event, int flags) 12593 { 12594 event->hw.state = 0; 12595 local64_set(&event->hw.prev_count, event->ctx->time.time); 12596 perf_swevent_start_hrtimer(event); 12597 } 12598 12599 static void task_clock_event_stop(struct perf_event *event, int flags) 12600 { 12601 event->hw.state = PERF_HES_STOPPED; 12602 perf_swevent_cancel_hrtimer(event); 12603 if (flags & PERF_EF_UPDATE) 12604 task_clock_event_update(event, event->ctx->time.time); 12605 } 12606 12607 static int task_clock_event_add(struct perf_event *event, int flags) 12608 { 12609 if (flags & PERF_EF_START) 12610 task_clock_event_start(event, flags); 12611 perf_event_update_userpage(event); 12612 12613 return 0; 12614 } 12615 12616 static void task_clock_event_del(struct perf_event *event, int flags) 12617 { 12618 task_clock_event_stop(event, PERF_EF_UPDATE); 12619 } 12620 12621 static void task_clock_event_read(struct perf_event *event) 12622 { 12623 u64 now = perf_clock(); 12624 u64 delta = now - event->ctx->time.stamp; 12625 u64 time = event->ctx->time.time + delta; 12626 12627 task_clock_event_update(event, time); 12628 } 12629 12630 static int task_clock_event_init(struct perf_event *event) 12631 { 12632 if (event->attr.type != perf_task_clock.type) 12633 return -ENOENT; 12634 12635 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK) 12636 return -ENOENT; 12637 12638 /* 12639 * no branch sampling for software events 12640 */ 12641 if (has_branch_stack(event)) 12642 return -EOPNOTSUPP; 12643 12644 perf_swevent_init_hrtimer(event); 12645 12646 return 0; 12647 } 12648 12649 static struct pmu perf_task_clock = { 12650 .task_ctx_nr = perf_sw_context, 12651 12652 .capabilities = PERF_PMU_CAP_NO_NMI, 12653 .dev = PMU_NULL_DEV, 12654 12655 .event_init = task_clock_event_init, 12656 .add = task_clock_event_add, 12657 .del = task_clock_event_del, 12658 .start = task_clock_event_start, 12659 .stop = task_clock_event_stop, 12660 .read = task_clock_event_read, 12661 }; 12662 12663 static void perf_pmu_nop_void(struct pmu *pmu) 12664 { 12665 } 12666 12667 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags) 12668 { 12669 } 12670 12671 static int perf_pmu_nop_int(struct pmu *pmu) 12672 { 12673 return 0; 12674 } 12675 12676 static int perf_event_nop_int(struct perf_event *event, u64 value) 12677 { 12678 return 0; 12679 } 12680 12681 static DEFINE_PER_CPU(unsigned int, nop_txn_flags); 12682 12683 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags) 12684 { 12685 __this_cpu_write(nop_txn_flags, flags); 12686 12687 if (flags & ~PERF_PMU_TXN_ADD) 12688 return; 12689 12690 perf_pmu_disable(pmu); 12691 } 12692 12693 static int perf_pmu_commit_txn(struct pmu *pmu) 12694 { 12695 unsigned int flags = __this_cpu_read(nop_txn_flags); 12696 12697 __this_cpu_write(nop_txn_flags, 0); 12698 12699 if (flags & ~PERF_PMU_TXN_ADD) 12700 return 0; 12701 12702 perf_pmu_enable(pmu); 12703 return 0; 12704 } 12705 12706 static void perf_pmu_cancel_txn(struct pmu *pmu) 12707 { 12708 unsigned int flags = __this_cpu_read(nop_txn_flags); 12709 12710 __this_cpu_write(nop_txn_flags, 0); 12711 12712 if (flags & ~PERF_PMU_TXN_ADD) 12713 return; 12714 12715 perf_pmu_enable(pmu); 12716 } 12717 12718 static int perf_event_idx_default(struct perf_event *event) 12719 { 12720 return 0; 12721 } 12722 12723 /* 12724 * Let userspace know that this PMU supports address range filtering: 12725 */ 12726 static ssize_t nr_addr_filters_show(struct device *dev, 12727 struct device_attribute *attr, 12728 char *page) 12729 { 12730 struct pmu *pmu = dev_get_drvdata(dev); 12731 12732 return sysfs_emit(page, "%d\n", pmu->nr_addr_filters); 12733 } 12734 DEVICE_ATTR_RO(nr_addr_filters); 12735 12736 static struct idr pmu_idr; 12737 12738 static ssize_t 12739 type_show(struct device *dev, struct device_attribute *attr, char *page) 12740 { 12741 struct pmu *pmu = dev_get_drvdata(dev); 12742 12743 return sysfs_emit(page, "%d\n", pmu->type); 12744 } 12745 static DEVICE_ATTR_RO(type); 12746 12747 static ssize_t 12748 perf_event_mux_interval_ms_show(struct device *dev, 12749 struct device_attribute *attr, 12750 char *page) 12751 { 12752 struct pmu *pmu = dev_get_drvdata(dev); 12753 12754 return sysfs_emit(page, "%d\n", pmu->hrtimer_interval_ms); 12755 } 12756 12757 static DEFINE_MUTEX(mux_interval_mutex); 12758 12759 static ssize_t 12760 perf_event_mux_interval_ms_store(struct device *dev, 12761 struct device_attribute *attr, 12762 const char *buf, size_t count) 12763 { 12764 struct pmu *pmu = dev_get_drvdata(dev); 12765 int timer, cpu, ret; 12766 12767 ret = kstrtoint(buf, 0, &timer); 12768 if (ret) 12769 return ret; 12770 12771 if (timer < 1) 12772 return -EINVAL; 12773 12774 /* same value, noting to do */ 12775 if (timer == pmu->hrtimer_interval_ms) 12776 return count; 12777 12778 mutex_lock(&mux_interval_mutex); 12779 pmu->hrtimer_interval_ms = timer; 12780 12781 /* update all cpuctx for this PMU */ 12782 cpus_read_lock(); 12783 for_each_online_cpu(cpu) { 12784 struct perf_cpu_pmu_context *cpc; 12785 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); 12786 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); 12787 12788 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc); 12789 } 12790 cpus_read_unlock(); 12791 mutex_unlock(&mux_interval_mutex); 12792 12793 return count; 12794 } 12795 static DEVICE_ATTR_RW(perf_event_mux_interval_ms); 12796 12797 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu) 12798 { 12799 switch (scope) { 12800 case PERF_PMU_SCOPE_CORE: 12801 return topology_sibling_cpumask(cpu); 12802 case PERF_PMU_SCOPE_DIE: 12803 return topology_die_cpumask(cpu); 12804 case PERF_PMU_SCOPE_CLUSTER: 12805 return topology_cluster_cpumask(cpu); 12806 case PERF_PMU_SCOPE_PKG: 12807 return topology_core_cpumask(cpu); 12808 case PERF_PMU_SCOPE_SYS_WIDE: 12809 return cpu_online_mask; 12810 } 12811 12812 return NULL; 12813 } 12814 12815 static inline struct cpumask *perf_scope_cpumask(unsigned int scope) 12816 { 12817 switch (scope) { 12818 case PERF_PMU_SCOPE_CORE: 12819 return perf_online_core_mask; 12820 case PERF_PMU_SCOPE_DIE: 12821 return perf_online_die_mask; 12822 case PERF_PMU_SCOPE_CLUSTER: 12823 return perf_online_cluster_mask; 12824 case PERF_PMU_SCOPE_PKG: 12825 return perf_online_pkg_mask; 12826 case PERF_PMU_SCOPE_SYS_WIDE: 12827 return perf_online_sys_mask; 12828 } 12829 12830 return NULL; 12831 } 12832 12833 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr, 12834 char *buf) 12835 { 12836 struct pmu *pmu = dev_get_drvdata(dev); 12837 struct cpumask *mask = perf_scope_cpumask(pmu->scope); 12838 12839 if (mask) 12840 return sysfs_emit(buf, "%*pbl\n", cpumask_pr_args(mask)); 12841 return 0; 12842 } 12843 12844 static DEVICE_ATTR_RO(cpumask); 12845 12846 static struct attribute *pmu_dev_attrs[] = { 12847 &dev_attr_type.attr, 12848 &dev_attr_perf_event_mux_interval_ms.attr, 12849 &dev_attr_nr_addr_filters.attr, 12850 &dev_attr_cpumask.attr, 12851 NULL, 12852 }; 12853 12854 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n) 12855 { 12856 struct device *dev = kobj_to_dev(kobj); 12857 struct pmu *pmu = dev_get_drvdata(dev); 12858 12859 if (n == 2 && !pmu->nr_addr_filters) 12860 return 0; 12861 12862 /* cpumask */ 12863 if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE) 12864 return 0; 12865 12866 return a->mode; 12867 } 12868 12869 static struct attribute_group pmu_dev_attr_group = { 12870 .is_visible = pmu_dev_is_visible, 12871 .attrs = pmu_dev_attrs, 12872 }; 12873 12874 static const struct attribute_group *pmu_dev_groups[] = { 12875 &pmu_dev_attr_group, 12876 NULL, 12877 }; 12878 12879 static int pmu_bus_running; 12880 static const struct bus_type pmu_bus = { 12881 .name = "event_source", 12882 .dev_groups = pmu_dev_groups, 12883 }; 12884 12885 static void pmu_dev_release(struct device *dev) 12886 { 12887 kfree(dev); 12888 } 12889 12890 static int pmu_dev_alloc(struct pmu *pmu) 12891 { 12892 int ret = -ENOMEM; 12893 12894 pmu->dev = kzalloc_obj(struct device); 12895 if (!pmu->dev) 12896 goto out; 12897 12898 pmu->dev->groups = pmu->attr_groups; 12899 device_initialize(pmu->dev); 12900 12901 dev_set_drvdata(pmu->dev, pmu); 12902 pmu->dev->bus = &pmu_bus; 12903 pmu->dev->parent = pmu->parent; 12904 pmu->dev->release = pmu_dev_release; 12905 12906 ret = dev_set_name(pmu->dev, "%s", pmu->name); 12907 if (ret) 12908 goto free_dev; 12909 12910 ret = device_add(pmu->dev); 12911 if (ret) 12912 goto free_dev; 12913 12914 if (pmu->attr_update) { 12915 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update); 12916 if (ret) 12917 goto del_dev; 12918 } 12919 12920 out: 12921 return ret; 12922 12923 del_dev: 12924 device_del(pmu->dev); 12925 12926 free_dev: 12927 put_device(pmu->dev); 12928 pmu->dev = NULL; 12929 goto out; 12930 } 12931 12932 static struct lock_class_key cpuctx_mutex; 12933 static struct lock_class_key cpuctx_lock; 12934 12935 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new) 12936 { 12937 void *tmp, *val = idr_find(idr, id); 12938 12939 if (val != old) 12940 return false; 12941 12942 tmp = idr_replace(idr, new, id); 12943 if (IS_ERR(tmp)) 12944 return false; 12945 12946 WARN_ON_ONCE(tmp != val); 12947 return true; 12948 } 12949 12950 static void perf_pmu_free(struct pmu *pmu) 12951 { 12952 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) { 12953 if (pmu->nr_addr_filters) 12954 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters); 12955 device_del(pmu->dev); 12956 put_device(pmu->dev); 12957 } 12958 12959 if (pmu->cpu_pmu_context) { 12960 int cpu; 12961 12962 for_each_possible_cpu(cpu) { 12963 struct perf_cpu_pmu_context *cpc; 12964 12965 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); 12966 if (!cpc) 12967 continue; 12968 if (cpc->epc.embedded) { 12969 /* refcount managed */ 12970 put_pmu_ctx(&cpc->epc); 12971 continue; 12972 } 12973 kfree(cpc); 12974 } 12975 free_percpu(pmu->cpu_pmu_context); 12976 } 12977 } 12978 12979 DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T)) 12980 12981 int perf_pmu_register(struct pmu *_pmu, const char *name, int type) 12982 { 12983 int cpu, max = PERF_TYPE_MAX; 12984 12985 struct pmu *pmu __free(pmu_unregister) = _pmu; 12986 guard(mutex)(&pmus_lock); 12987 12988 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n")) 12989 return -EINVAL; 12990 12991 if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE, 12992 "Can not register a pmu with an invalid scope.\n")) 12993 return -EINVAL; 12994 12995 pmu->name = name; 12996 12997 if (type >= 0) 12998 max = type; 12999 13000 CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL); 13001 if (pmu_type.id < 0) 13002 return pmu_type.id; 13003 13004 WARN_ON(type >= 0 && pmu_type.id != type); 13005 13006 pmu->type = pmu_type.id; 13007 atomic_set(&pmu->exclusive_cnt, 0); 13008 13009 if (pmu_bus_running && !pmu->dev) { 13010 int ret = pmu_dev_alloc(pmu); 13011 if (ret) 13012 return ret; 13013 } 13014 13015 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *); 13016 if (!pmu->cpu_pmu_context) 13017 return -ENOMEM; 13018 13019 for_each_possible_cpu(cpu) { 13020 struct perf_cpu_pmu_context *cpc = 13021 kmalloc_node(sizeof(struct perf_cpu_pmu_context), 13022 GFP_KERNEL | __GFP_ZERO, 13023 cpu_to_node(cpu)); 13024 13025 if (!cpc) 13026 return -ENOMEM; 13027 13028 *per_cpu_ptr(pmu->cpu_pmu_context, cpu) = cpc; 13029 __perf_init_event_pmu_context(&cpc->epc, pmu); 13030 __perf_mux_hrtimer_init(cpc, cpu); 13031 } 13032 13033 if (!pmu->start_txn) { 13034 if (pmu->pmu_enable) { 13035 /* 13036 * If we have pmu_enable/pmu_disable calls, install 13037 * transaction stubs that use that to try and batch 13038 * hardware accesses. 13039 */ 13040 pmu->start_txn = perf_pmu_start_txn; 13041 pmu->commit_txn = perf_pmu_commit_txn; 13042 pmu->cancel_txn = perf_pmu_cancel_txn; 13043 } else { 13044 pmu->start_txn = perf_pmu_nop_txn; 13045 pmu->commit_txn = perf_pmu_nop_int; 13046 pmu->cancel_txn = perf_pmu_nop_void; 13047 } 13048 } 13049 13050 if (!pmu->pmu_enable) { 13051 pmu->pmu_enable = perf_pmu_nop_void; 13052 pmu->pmu_disable = perf_pmu_nop_void; 13053 } 13054 13055 if (!pmu->check_period) 13056 pmu->check_period = perf_event_nop_int; 13057 13058 if (!pmu->event_idx) 13059 pmu->event_idx = perf_event_idx_default; 13060 13061 INIT_LIST_HEAD(&pmu->events); 13062 spin_lock_init(&pmu->events_lock); 13063 13064 /* 13065 * Now that the PMU is complete, make it visible to perf_try_init_event(). 13066 */ 13067 if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu)) 13068 return -EINVAL; 13069 list_add_rcu(&pmu->entry, &pmus); 13070 13071 take_idr_id(pmu_type); 13072 _pmu = no_free_ptr(pmu); // let it rip 13073 return 0; 13074 } 13075 EXPORT_SYMBOL_GPL(perf_pmu_register); 13076 13077 static void __pmu_detach_event(struct pmu *pmu, struct perf_event *event, 13078 struct perf_event_context *ctx) 13079 { 13080 /* 13081 * De-schedule the event and mark it REVOKED. 13082 */ 13083 perf_event_exit_event(event, ctx, ctx->task, DETACH_REVOKE); 13084 13085 /* 13086 * All _free_event() bits that rely on event->pmu: 13087 * 13088 * Notably, perf_mmap() relies on the ordering here. 13089 */ 13090 scoped_guard (mutex, &event->mmap_mutex) { 13091 WARN_ON_ONCE(pmu->event_unmapped); 13092 /* 13093 * Mostly an empty lock sequence, such that perf_mmap(), which 13094 * relies on mmap_mutex, is sure to observe the state change. 13095 */ 13096 } 13097 13098 perf_event_free_bpf_prog(event); 13099 perf_free_addr_filters(event); 13100 13101 if (event->destroy) { 13102 event->destroy(event); 13103 event->destroy = NULL; 13104 } 13105 13106 if (event->pmu_ctx) { 13107 put_pmu_ctx(event->pmu_ctx); 13108 event->pmu_ctx = NULL; 13109 } 13110 13111 exclusive_event_destroy(event); 13112 module_put(pmu->module); 13113 13114 mediated_pmu_unaccount_event(event); 13115 event->pmu = NULL; /* force fault instead of UAF */ 13116 } 13117 13118 static void pmu_detach_event(struct pmu *pmu, struct perf_event *event) 13119 { 13120 struct perf_event_context *ctx; 13121 13122 ctx = perf_event_ctx_lock(event); 13123 __pmu_detach_event(pmu, event, ctx); 13124 perf_event_ctx_unlock(event, ctx); 13125 13126 scoped_guard (spinlock, &pmu->events_lock) 13127 list_del(&event->pmu_list); 13128 } 13129 13130 static struct perf_event *pmu_get_event(struct pmu *pmu) 13131 { 13132 struct perf_event *event; 13133 13134 guard(spinlock)(&pmu->events_lock); 13135 list_for_each_entry(event, &pmu->events, pmu_list) { 13136 if (atomic_long_inc_not_zero(&event->refcount)) 13137 return event; 13138 } 13139 13140 return NULL; 13141 } 13142 13143 static bool pmu_empty(struct pmu *pmu) 13144 { 13145 guard(spinlock)(&pmu->events_lock); 13146 return list_empty(&pmu->events); 13147 } 13148 13149 static void pmu_detach_events(struct pmu *pmu) 13150 { 13151 struct perf_event *event; 13152 13153 for (;;) { 13154 event = pmu_get_event(pmu); 13155 if (!event) 13156 break; 13157 13158 pmu_detach_event(pmu, event); 13159 put_event(event); 13160 } 13161 13162 /* 13163 * wait for pending _free_event()s 13164 */ 13165 wait_var_event(pmu, pmu_empty(pmu)); 13166 } 13167 13168 int perf_pmu_unregister(struct pmu *pmu) 13169 { 13170 scoped_guard (mutex, &pmus_lock) { 13171 if (!idr_cmpxchg(&pmu_idr, pmu->type, pmu, NULL)) 13172 return -EINVAL; 13173 13174 list_del_rcu(&pmu->entry); 13175 } 13176 13177 /* 13178 * We dereference the pmu list under both SRCU and regular RCU, so 13179 * synchronize against both of those. 13180 * 13181 * Notably, the entirety of event creation, from perf_init_event() 13182 * (which will now fail, because of the above) until 13183 * perf_install_in_context() should be under SRCU such that 13184 * this synchronizes against event creation. This avoids trying to 13185 * detach events that are not fully formed. 13186 */ 13187 synchronize_srcu(&pmus_srcu); 13188 synchronize_rcu(); 13189 13190 if (pmu->event_unmapped && !pmu_empty(pmu)) { 13191 /* 13192 * Can't force remove events when pmu::event_unmapped() 13193 * is used in perf_mmap_close(). 13194 */ 13195 guard(mutex)(&pmus_lock); 13196 idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu); 13197 list_add_rcu(&pmu->entry, &pmus); 13198 return -EBUSY; 13199 } 13200 13201 scoped_guard (mutex, &pmus_lock) 13202 idr_remove(&pmu_idr, pmu->type); 13203 13204 /* 13205 * PMU is removed from the pmus list, so no new events will 13206 * be created, now take care of the existing ones. 13207 */ 13208 pmu_detach_events(pmu); 13209 13210 /* 13211 * PMU is unused, make it go away. 13212 */ 13213 perf_pmu_free(pmu); 13214 return 0; 13215 } 13216 EXPORT_SYMBOL_GPL(perf_pmu_unregister); 13217 13218 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) 13219 { 13220 struct perf_event_context *ctx = NULL; 13221 int ret; 13222 13223 if (!try_module_get(pmu->module)) 13224 return -ENODEV; 13225 13226 /* 13227 * A number of pmu->event_init() methods iterate the sibling_list to, 13228 * for example, validate if the group fits on the PMU. Therefore, 13229 * if this is a sibling event, acquire the ctx->mutex to protect 13230 * the sibling_list. 13231 */ 13232 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) { 13233 /* 13234 * This ctx->mutex can nest when we're called through 13235 * inheritance. See the perf_event_ctx_lock_nested() comment. 13236 */ 13237 ctx = perf_event_ctx_lock_nested(event->group_leader, 13238 SINGLE_DEPTH_NESTING); 13239 BUG_ON(!ctx); 13240 } 13241 13242 event->pmu = pmu; 13243 ret = pmu->event_init(event); 13244 13245 if (ctx) 13246 perf_event_ctx_unlock(event->group_leader, ctx); 13247 13248 if (ret) 13249 goto err_pmu; 13250 13251 if (!(pmu->capabilities & PERF_PMU_CAP_SIMD_REGS) && 13252 event_has_simd_regs(event)) { 13253 ret = -EOPNOTSUPP; 13254 goto err_destroy; 13255 } 13256 13257 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) && 13258 event_has_extended_regs(event)) { 13259 ret = -EOPNOTSUPP; 13260 goto err_destroy; 13261 } 13262 13263 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE && 13264 event_has_any_exclude_flag(event)) { 13265 ret = -EINVAL; 13266 goto err_destroy; 13267 } 13268 13269 if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) { 13270 const struct cpumask *cpumask; 13271 struct cpumask *pmu_cpumask; 13272 int cpu; 13273 13274 cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu); 13275 pmu_cpumask = perf_scope_cpumask(pmu->scope); 13276 13277 ret = -ENODEV; 13278 if (!pmu_cpumask || !cpumask) 13279 goto err_destroy; 13280 13281 cpu = cpumask_any_and(pmu_cpumask, cpumask); 13282 if (cpu >= nr_cpu_ids) 13283 goto err_destroy; 13284 13285 event->event_caps |= PERF_EV_CAP_READ_SCOPE; 13286 } 13287 13288 return 0; 13289 13290 err_destroy: 13291 if (event->destroy) { 13292 event->destroy(event); 13293 event->destroy = NULL; 13294 } 13295 13296 err_pmu: 13297 event->pmu = NULL; 13298 module_put(pmu->module); 13299 return ret; 13300 } 13301 13302 static struct pmu *perf_init_event(struct perf_event *event) 13303 { 13304 bool extended_type = false; 13305 struct pmu *pmu; 13306 int type, ret; 13307 13308 guard(srcu)(&pmus_srcu); /* pmu idr/list access */ 13309 13310 /* 13311 * Save original type before calling pmu->event_init() since certain 13312 * pmus overwrites event->attr.type to forward event to another pmu. 13313 */ 13314 event->orig_type = event->attr.type; 13315 13316 /* Try parent's PMU first: */ 13317 if (event->parent && event->parent->pmu) { 13318 pmu = event->parent->pmu; 13319 ret = perf_try_init_event(pmu, event); 13320 if (!ret) 13321 return pmu; 13322 } 13323 13324 /* 13325 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE 13326 * are often aliases for PERF_TYPE_RAW. 13327 */ 13328 type = event->attr.type; 13329 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) { 13330 type = event->attr.config >> PERF_PMU_TYPE_SHIFT; 13331 if (!type) { 13332 type = PERF_TYPE_RAW; 13333 } else { 13334 extended_type = true; 13335 event->attr.config &= PERF_HW_EVENT_MASK; 13336 } 13337 } 13338 13339 again: 13340 scoped_guard (rcu) 13341 pmu = idr_find(&pmu_idr, type); 13342 if (pmu) { 13343 if (event->attr.type != type && type != PERF_TYPE_RAW && 13344 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE)) 13345 return ERR_PTR(-ENOENT); 13346 13347 ret = perf_try_init_event(pmu, event); 13348 if (ret == -ENOENT && event->attr.type != type && !extended_type) { 13349 type = event->attr.type; 13350 goto again; 13351 } 13352 13353 if (ret) 13354 return ERR_PTR(ret); 13355 13356 return pmu; 13357 } 13358 13359 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) { 13360 ret = perf_try_init_event(pmu, event); 13361 if (!ret) 13362 return pmu; 13363 13364 if (ret != -ENOENT) 13365 return ERR_PTR(ret); 13366 } 13367 13368 return ERR_PTR(-ENOENT); 13369 } 13370 13371 static void attach_sb_event(struct perf_event *event) 13372 { 13373 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 13374 13375 raw_spin_lock(&pel->lock); 13376 list_add_rcu(&event->sb_list, &pel->list); 13377 raw_spin_unlock(&pel->lock); 13378 } 13379 13380 /* 13381 * We keep a list of all !task (and therefore per-cpu) events 13382 * that need to receive side-band records. 13383 * 13384 * This avoids having to scan all the various PMU per-cpu contexts 13385 * looking for them. 13386 */ 13387 static void account_pmu_sb_event(struct perf_event *event) 13388 { 13389 if (is_sb_event(event)) 13390 attach_sb_event(event); 13391 } 13392 13393 /* Freq events need the tick to stay alive (see perf_event_task_tick). */ 13394 static void account_freq_event_nohz(void) 13395 { 13396 #ifdef CONFIG_NO_HZ_FULL 13397 /* Lock so we don't race with concurrent unaccount */ 13398 spin_lock(&nr_freq_lock); 13399 if (atomic_inc_return(&nr_freq_events) == 1) 13400 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS); 13401 spin_unlock(&nr_freq_lock); 13402 #endif 13403 } 13404 13405 static void account_freq_event(void) 13406 { 13407 if (tick_nohz_full_enabled()) 13408 account_freq_event_nohz(); 13409 else 13410 atomic_inc(&nr_freq_events); 13411 } 13412 13413 13414 static void account_event(struct perf_event *event) 13415 { 13416 bool inc = false; 13417 13418 if (event->parent) 13419 return; 13420 13421 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB)) 13422 inc = true; 13423 if (event->attr.mmap || event->attr.mmap_data) 13424 atomic_inc(&nr_mmap_events); 13425 if (event->attr.build_id) 13426 atomic_inc(&nr_build_id_events); 13427 if (event->attr.comm) 13428 atomic_inc(&nr_comm_events); 13429 if (event->attr.namespaces) 13430 atomic_inc(&nr_namespaces_events); 13431 if (event->attr.cgroup) 13432 atomic_inc(&nr_cgroup_events); 13433 if (event->attr.task) 13434 atomic_inc(&nr_task_events); 13435 if (event->attr.freq) 13436 account_freq_event(); 13437 if (event->attr.context_switch) { 13438 atomic_inc(&nr_switch_events); 13439 inc = true; 13440 } 13441 if (has_branch_stack(event)) 13442 inc = true; 13443 if (is_cgroup_event(event)) 13444 inc = true; 13445 if (event->attr.ksymbol) 13446 atomic_inc(&nr_ksymbol_events); 13447 if (event->attr.bpf_event) 13448 atomic_inc(&nr_bpf_events); 13449 if (event->attr.text_poke) 13450 atomic_inc(&nr_text_poke_events); 13451 13452 if (inc) { 13453 /* 13454 * We need the mutex here because static_branch_enable() 13455 * must complete *before* the perf_sched_count increment 13456 * becomes visible. 13457 */ 13458 if (atomic_inc_not_zero(&perf_sched_count)) 13459 goto enabled; 13460 13461 mutex_lock(&perf_sched_mutex); 13462 if (!atomic_read(&perf_sched_count)) { 13463 static_branch_enable(&perf_sched_events); 13464 /* 13465 * Guarantee that all CPUs observe they key change and 13466 * call the perf scheduling hooks before proceeding to 13467 * install events that need them. 13468 */ 13469 synchronize_rcu(); 13470 } 13471 /* 13472 * Now that we have waited for the sync_sched(), allow further 13473 * increments to by-pass the mutex. 13474 */ 13475 atomic_inc(&perf_sched_count); 13476 mutex_unlock(&perf_sched_mutex); 13477 } 13478 enabled: 13479 13480 account_pmu_sb_event(event); 13481 } 13482 13483 /* 13484 * Allocate and initialize an event structure 13485 */ 13486 static struct perf_event * 13487 perf_event_alloc(struct perf_event_attr *attr, int cpu, 13488 struct task_struct *task, 13489 struct perf_event *group_leader, 13490 struct perf_event *parent_event, 13491 perf_overflow_handler_t overflow_handler, 13492 void *context, int cgroup_fd) 13493 { 13494 struct pmu *pmu; 13495 struct hw_perf_event *hwc; 13496 long err = -EINVAL; 13497 int node; 13498 13499 if ((unsigned)cpu >= nr_cpu_ids) { 13500 if (!task || cpu != -1) 13501 return ERR_PTR(-EINVAL); 13502 } 13503 if (attr->sigtrap && !task) { 13504 /* Requires a task: avoid signalling random tasks. */ 13505 return ERR_PTR(-EINVAL); 13506 } 13507 13508 node = (cpu >= 0) ? cpu_to_node(cpu) : -1; 13509 struct perf_event *event __free(__free_event) = 13510 kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node); 13511 if (!event) 13512 return ERR_PTR(-ENOMEM); 13513 13514 /* 13515 * Single events are their own group leaders, with an 13516 * empty sibling list: 13517 */ 13518 if (!group_leader) 13519 group_leader = event; 13520 13521 mutex_init(&event->child_mutex); 13522 INIT_LIST_HEAD(&event->child_list); 13523 13524 INIT_LIST_HEAD(&event->event_entry); 13525 INIT_LIST_HEAD(&event->sibling_list); 13526 INIT_LIST_HEAD(&event->active_list); 13527 init_event_group(event); 13528 INIT_LIST_HEAD(&event->rb_entry); 13529 INIT_LIST_HEAD(&event->active_entry); 13530 INIT_LIST_HEAD(&event->addr_filters.list); 13531 INIT_HLIST_NODE(&event->hlist_entry); 13532 INIT_LIST_HEAD(&event->pmu_list); 13533 13534 13535 init_waitqueue_head(&event->waitq); 13536 init_irq_work(&event->pending_irq, perf_pending_irq); 13537 event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable); 13538 init_task_work(&event->pending_task, perf_pending_task); 13539 13540 mutex_init(&event->mmap_mutex); 13541 raw_spin_lock_init(&event->addr_filters.lock); 13542 13543 atomic_long_set(&event->refcount, 1); 13544 event->cpu = cpu; 13545 event->attr = *attr; 13546 event->group_leader = group_leader; 13547 event->pmu = NULL; 13548 event->oncpu = -1; 13549 13550 event->parent = parent_event; 13551 13552 event->ns = get_pid_ns(task_active_pid_ns(current)); 13553 event->id = atomic64_inc_return(&perf_event_id); 13554 13555 event->state = PERF_EVENT_STATE_INACTIVE; 13556 13557 if (parent_event) 13558 event->event_caps = parent_event->event_caps; 13559 13560 if (task) { 13561 event->attach_state = PERF_ATTACH_TASK; 13562 /* 13563 * XXX pmu::event_init needs to know what task to account to 13564 * and we cannot use the ctx information because we need the 13565 * pmu before we get a ctx. 13566 */ 13567 event->hw.target = get_task_struct(task); 13568 } 13569 13570 event->clock = &local_clock; 13571 if (parent_event) 13572 event->clock = parent_event->clock; 13573 13574 if (!overflow_handler && parent_event) { 13575 overflow_handler = parent_event->overflow_handler; 13576 context = parent_event->overflow_handler_context; 13577 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING) 13578 if (parent_event->prog) { 13579 struct bpf_prog *prog = parent_event->prog; 13580 13581 bpf_prog_inc(prog); 13582 event->prog = prog; 13583 } 13584 #endif 13585 } 13586 13587 if (overflow_handler) { 13588 event->overflow_handler = overflow_handler; 13589 event->overflow_handler_context = context; 13590 } else if (is_write_backward(event)){ 13591 event->overflow_handler = perf_event_output_backward; 13592 event->overflow_handler_context = NULL; 13593 } else { 13594 event->overflow_handler = perf_event_output_forward; 13595 event->overflow_handler_context = NULL; 13596 } 13597 13598 perf_event__state_init(event); 13599 13600 pmu = NULL; 13601 13602 hwc = &event->hw; 13603 hwc->sample_period = attr->sample_period; 13604 if (is_event_in_freq_mode(event)) 13605 hwc->sample_period = 1; 13606 hwc->last_period = hwc->sample_period; 13607 13608 local64_set(&hwc->period_left, hwc->sample_period); 13609 13610 /* 13611 * We do not support PERF_SAMPLE_READ on inherited events unless 13612 * PERF_SAMPLE_TID is also selected, which allows inherited events to 13613 * collect per-thread samples. 13614 * See perf_output_read(). 13615 */ 13616 if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID)) 13617 return ERR_PTR(-EINVAL); 13618 13619 if (!has_branch_stack(event)) 13620 event->attr.branch_sample_type = 0; 13621 13622 pmu = perf_init_event(event); 13623 if (IS_ERR(pmu)) 13624 return (void*)pmu; 13625 13626 /* 13627 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config(). 13628 * The attach should be right after the perf_init_event(). 13629 * Otherwise, the __free_event() would mistakenly detach the non-exist 13630 * perf_ctx_data because of the other errors between them. 13631 */ 13632 if (event->attach_state & PERF_ATTACH_TASK_DATA) { 13633 err = attach_perf_ctx_data(event); 13634 if (err) 13635 return ERR_PTR(err); 13636 } 13637 13638 /* 13639 * Disallow uncore-task events. Similarly, disallow uncore-cgroup 13640 * events (they don't make sense as the cgroup will be different 13641 * on other CPUs in the uncore mask). 13642 */ 13643 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) 13644 return ERR_PTR(-EINVAL); 13645 13646 if (event->attr.aux_output && 13647 (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) || 13648 event->attr.aux_pause || event->attr.aux_resume)) 13649 return ERR_PTR(-EOPNOTSUPP); 13650 13651 if (event->attr.aux_pause && event->attr.aux_resume) 13652 return ERR_PTR(-EINVAL); 13653 13654 if (event->attr.aux_start_paused) { 13655 if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) 13656 return ERR_PTR(-EOPNOTSUPP); 13657 event->hw.aux_paused = 1; 13658 } 13659 13660 if (cgroup_fd != -1) { 13661 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader); 13662 if (err) 13663 return ERR_PTR(err); 13664 } 13665 13666 err = exclusive_event_init(event); 13667 if (err) 13668 return ERR_PTR(err); 13669 13670 if (has_addr_filter(event)) { 13671 event->addr_filter_ranges = kzalloc_objs(struct perf_addr_filter_range, 13672 pmu->nr_addr_filters); 13673 if (!event->addr_filter_ranges) 13674 return ERR_PTR(-ENOMEM); 13675 13676 /* 13677 * Clone the parent's vma offsets: they are valid until exec() 13678 * even if the mm is not shared with the parent. 13679 */ 13680 if (event->parent) { 13681 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 13682 13683 raw_spin_lock_irq(&ifh->lock); 13684 memcpy(event->addr_filter_ranges, 13685 event->parent->addr_filter_ranges, 13686 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range)); 13687 raw_spin_unlock_irq(&ifh->lock); 13688 } 13689 13690 /* force hw sync on the address filters */ 13691 event->addr_filters_gen = 1; 13692 } 13693 13694 if (!event->parent) { 13695 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) { 13696 err = get_callchain_buffers(attr->sample_max_stack); 13697 if (err) 13698 return ERR_PTR(err); 13699 event->attach_state |= PERF_ATTACH_CALLCHAIN; 13700 } 13701 } 13702 13703 err = security_perf_event_alloc(event); 13704 if (err) 13705 return ERR_PTR(err); 13706 13707 err = mediated_pmu_account_event(event); 13708 if (err) 13709 return ERR_PTR(err); 13710 13711 /* symmetric to unaccount_event() in _free_event() */ 13712 account_event(event); 13713 13714 /* 13715 * Event creation should be under SRCU, see perf_pmu_unregister(). 13716 */ 13717 lockdep_assert_held(&pmus_srcu); 13718 scoped_guard (spinlock, &pmu->events_lock) 13719 list_add(&event->pmu_list, &pmu->events); 13720 13721 return_ptr(event); 13722 } 13723 13724 static int perf_copy_attr(struct perf_event_attr __user *uattr, 13725 struct perf_event_attr *attr) 13726 { 13727 u32 size; 13728 int ret; 13729 13730 /* Zero the full structure, so that a short copy will be nice. */ 13731 memset(attr, 0, sizeof(*attr)); 13732 13733 ret = get_user(size, &uattr->size); 13734 if (ret) 13735 return ret; 13736 13737 /* ABI compatibility quirk: */ 13738 if (!size) 13739 size = PERF_ATTR_SIZE_VER0; 13740 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE) 13741 goto err_size; 13742 13743 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size); 13744 if (ret) { 13745 if (ret == -E2BIG) 13746 goto err_size; 13747 return ret; 13748 } 13749 13750 attr->size = size; 13751 13752 if (attr->__reserved_1 || attr->__reserved_2 || 13753 attr->__reserved_3 || attr->__reserved_4) 13754 return -EINVAL; 13755 13756 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) 13757 return -EINVAL; 13758 13759 if (attr->read_format & ~(PERF_FORMAT_MAX-1)) 13760 return -EINVAL; 13761 13762 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) { 13763 u64 mask = attr->branch_sample_type; 13764 13765 /* only using defined bits */ 13766 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1)) 13767 return -EINVAL; 13768 13769 /* at least one branch bit must be set */ 13770 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL)) 13771 return -EINVAL; 13772 13773 /* propagate priv level, when not set for branch */ 13774 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) { 13775 13776 /* exclude_kernel checked on syscall entry */ 13777 if (!attr->exclude_kernel) 13778 mask |= PERF_SAMPLE_BRANCH_KERNEL; 13779 13780 if (!attr->exclude_user) 13781 mask |= PERF_SAMPLE_BRANCH_USER; 13782 13783 if (!attr->exclude_hv) 13784 mask |= PERF_SAMPLE_BRANCH_HV; 13785 /* 13786 * adjust user setting (for HW filter setup) 13787 */ 13788 attr->branch_sample_type = mask; 13789 } 13790 /* privileged levels capture (kernel, hv): check permissions */ 13791 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) { 13792 ret = perf_allow_kernel(); 13793 if (ret) 13794 return ret; 13795 } 13796 } 13797 13798 if (attr->sample_type & PERF_SAMPLE_REGS_USER) { 13799 ret = perf_reg_validate(attr->sample_regs_user, 13800 attr->sample_simd_regs_enabled); 13801 if (ret) 13802 return ret; 13803 if (attr->sample_simd_regs_enabled) { 13804 ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, 13805 attr->sample_simd_vec_reg_user, 13806 attr->sample_simd_pred_reg_qwords, 13807 attr->sample_simd_pred_reg_user); 13808 if (ret) 13809 return ret; 13810 } 13811 } 13812 13813 if (attr->sample_type & PERF_SAMPLE_STACK_USER) { 13814 if (!arch_perf_have_user_stack_dump()) 13815 return -ENOSYS; 13816 13817 /* 13818 * We have __u32 type for the size, but so far 13819 * we can only use __u16 as maximum due to the 13820 * __u16 sample size limit. 13821 */ 13822 if (attr->sample_stack_user >= USHRT_MAX) 13823 return -EINVAL; 13824 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64))) 13825 return -EINVAL; 13826 } 13827 13828 if (!attr->sample_max_stack) 13829 attr->sample_max_stack = sysctl_perf_event_max_stack; 13830 13831 if (attr->sample_type & PERF_SAMPLE_REGS_INTR) { 13832 ret = perf_reg_validate(attr->sample_regs_intr, 13833 attr->sample_simd_regs_enabled); 13834 if (ret) 13835 return ret; 13836 if (attr->sample_simd_regs_enabled) { 13837 ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, 13838 attr->sample_simd_vec_reg_intr, 13839 attr->sample_simd_pred_reg_qwords, 13840 attr->sample_simd_pred_reg_intr); 13841 if (ret) 13842 return ret; 13843 } 13844 } 13845 13846 #ifndef CONFIG_CGROUP_PERF 13847 if (attr->sample_type & PERF_SAMPLE_CGROUP) 13848 return -EINVAL; 13849 #endif 13850 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) && 13851 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT)) 13852 return -EINVAL; 13853 13854 if (!attr->inherit && attr->inherit_thread) 13855 return -EINVAL; 13856 13857 if (attr->remove_on_exec && attr->enable_on_exec) 13858 return -EINVAL; 13859 13860 if (attr->sigtrap && !attr->remove_on_exec) 13861 return -EINVAL; 13862 13863 out: 13864 return ret; 13865 13866 err_size: 13867 put_user(sizeof(*attr), &uattr->size); 13868 ret = -E2BIG; 13869 goto out; 13870 } 13871 13872 static void mutex_lock_double(struct mutex *a, struct mutex *b) 13873 { 13874 if (b < a) 13875 swap(a, b); 13876 13877 mutex_lock(a); 13878 mutex_lock_nested(b, SINGLE_DEPTH_NESTING); 13879 } 13880 13881 static int 13882 perf_event_set_output(struct perf_event *event, struct perf_event *output_event) 13883 { 13884 struct perf_buffer *rb = NULL; 13885 int ret = -EINVAL; 13886 13887 if (!output_event) { 13888 mutex_lock(&event->mmap_mutex); 13889 goto set; 13890 } 13891 13892 /* don't allow circular references */ 13893 if (event == output_event) 13894 goto out; 13895 13896 /* 13897 * Don't allow cross-cpu buffers 13898 */ 13899 if (output_event->cpu != event->cpu) 13900 goto out; 13901 13902 /* 13903 * If its not a per-cpu rb, it must be the same task. 13904 */ 13905 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target) 13906 goto out; 13907 13908 /* 13909 * Mixing clocks in the same buffer is trouble you don't need. 13910 */ 13911 if (output_event->clock != event->clock) 13912 goto out; 13913 13914 /* 13915 * Either writing ring buffer from beginning or from end. 13916 * Mixing is not allowed. 13917 */ 13918 if (is_write_backward(output_event) != is_write_backward(event)) 13919 goto out; 13920 13921 /* 13922 * If both events generate aux data, they must be on the same PMU 13923 */ 13924 if (has_aux(event) && has_aux(output_event) && 13925 event->pmu != output_event->pmu) 13926 goto out; 13927 13928 /* 13929 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since 13930 * output_event is already on rb->event_list, and the list iteration 13931 * restarts after every removal, it is guaranteed this new event is 13932 * observed *OR* if output_event is already removed, it's guaranteed we 13933 * observe !rb->mmap_count. 13934 */ 13935 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex); 13936 set: 13937 /* Can't redirect output if we've got an active mmap() */ 13938 if (refcount_read(&event->mmap_count)) 13939 goto unlock; 13940 13941 if (output_event) { 13942 if (output_event->state <= PERF_EVENT_STATE_REVOKED) 13943 goto unlock; 13944 13945 /* get the rb we want to redirect to */ 13946 rb = ring_buffer_get(output_event); 13947 if (!rb) 13948 goto unlock; 13949 13950 /* did we race against perf_mmap_close() */ 13951 if (!refcount_read(&rb->mmap_count)) { 13952 ring_buffer_put(rb); 13953 goto unlock; 13954 } 13955 } 13956 13957 ring_buffer_attach(event, rb); 13958 13959 ret = 0; 13960 unlock: 13961 mutex_unlock(&event->mmap_mutex); 13962 if (output_event) 13963 mutex_unlock(&output_event->mmap_mutex); 13964 13965 out: 13966 return ret; 13967 } 13968 13969 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id) 13970 { 13971 bool nmi_safe = false; 13972 13973 switch (clk_id) { 13974 case CLOCK_MONOTONIC: 13975 event->clock = &ktime_get_mono_fast_ns; 13976 nmi_safe = true; 13977 break; 13978 13979 case CLOCK_MONOTONIC_RAW: 13980 event->clock = &ktime_get_raw_fast_ns; 13981 nmi_safe = true; 13982 break; 13983 13984 case CLOCK_REALTIME: 13985 event->clock = &ktime_get_real_ns; 13986 break; 13987 13988 case CLOCK_BOOTTIME: 13989 event->clock = &ktime_get_boottime_ns; 13990 break; 13991 13992 case CLOCK_TAI: 13993 event->clock = &ktime_get_clocktai_ns; 13994 break; 13995 13996 default: 13997 return -EINVAL; 13998 } 13999 14000 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI)) 14001 return -EINVAL; 14002 14003 return 0; 14004 } 14005 14006 static bool 14007 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task) 14008 { 14009 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS; 14010 bool is_capable = perfmon_capable(); 14011 14012 if (attr->sigtrap) { 14013 /* 14014 * perf_event_attr::sigtrap sends signals to the other task. 14015 * Require the current task to also have CAP_KILL. 14016 */ 14017 rcu_read_lock(); 14018 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL); 14019 rcu_read_unlock(); 14020 14021 /* 14022 * If the required capabilities aren't available, checks for 14023 * ptrace permissions: upgrade to ATTACH, since sending signals 14024 * can effectively change the target task. 14025 */ 14026 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS; 14027 } 14028 14029 /* 14030 * Preserve ptrace permission check for backwards compatibility. The 14031 * ptrace check also includes checks that the current task and other 14032 * task have matching uids, and is therefore not done here explicitly. 14033 */ 14034 return is_capable || ptrace_may_access(task, ptrace_mode); 14035 } 14036 14037 /** 14038 * sys_perf_event_open - open a performance event, associate it to a task/cpu 14039 * 14040 * @attr_uptr: event_id type attributes for monitoring/sampling 14041 * @pid: target pid 14042 * @cpu: target cpu 14043 * @group_fd: group leader event fd 14044 * @flags: perf event open flags 14045 */ 14046 SYSCALL_DEFINE5(perf_event_open, 14047 struct perf_event_attr __user *, attr_uptr, 14048 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) 14049 { 14050 struct perf_event *group_leader = NULL, *output_event = NULL; 14051 struct perf_event_pmu_context *pmu_ctx; 14052 struct perf_event *event, *sibling; 14053 struct perf_event_attr attr; 14054 struct perf_event_context *ctx; 14055 struct file *event_file = NULL; 14056 struct task_struct *task = NULL; 14057 struct pmu *pmu; 14058 int event_fd; 14059 int move_group = 0; 14060 int err; 14061 int f_flags = O_RDWR; 14062 int cgroup_fd = -1; 14063 14064 /* for future expandability... */ 14065 if (flags & ~PERF_FLAG_ALL) 14066 return -EINVAL; 14067 14068 err = perf_copy_attr(attr_uptr, &attr); 14069 if (err) 14070 return err; 14071 14072 /* Do we allow access to perf_event_open(2) ? */ 14073 err = security_perf_event_open(PERF_SECURITY_OPEN); 14074 if (err) 14075 return err; 14076 14077 if (!attr.exclude_kernel || attr.text_poke || 14078 ((attr.sample_type & PERF_SAMPLE_CALLCHAIN) && 14079 !attr.exclude_callchain_kernel)) { 14080 err = perf_allow_kernel(); 14081 if (err) 14082 return err; 14083 } 14084 14085 if (attr.namespaces) { 14086 if (!perfmon_capable()) 14087 return -EACCES; 14088 } 14089 14090 if (attr.freq) { 14091 if (attr.sample_freq > sysctl_perf_event_sample_rate) 14092 return -EINVAL; 14093 } else { 14094 if (attr.sample_period & (1ULL << 63)) 14095 return -EINVAL; 14096 } 14097 14098 /* Only privileged users can get physical addresses */ 14099 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) { 14100 err = perf_allow_kernel(); 14101 if (err) 14102 return err; 14103 } 14104 14105 /* REGS_INTR can leak data, lockdown must prevent this */ 14106 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) { 14107 err = security_locked_down(LOCKDOWN_PERF); 14108 if (err) 14109 return err; 14110 } 14111 14112 /* 14113 * In cgroup mode, the pid argument is used to pass the fd 14114 * opened to the cgroup directory in cgroupfs. The cpu argument 14115 * designates the cpu on which to monitor threads from that 14116 * cgroup. 14117 */ 14118 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) 14119 return -EINVAL; 14120 14121 if (flags & PERF_FLAG_FD_CLOEXEC) 14122 f_flags |= O_CLOEXEC; 14123 14124 event_fd = get_unused_fd_flags(f_flags); 14125 if (event_fd < 0) 14126 return event_fd; 14127 14128 /* 14129 * Event creation should be under SRCU, see perf_pmu_unregister(). 14130 */ 14131 guard(srcu)(&pmus_srcu); 14132 14133 CLASS(fd, group)(group_fd); // group_fd == -1 => empty 14134 if (group_fd != -1) { 14135 if (!is_perf_file(group)) { 14136 err = -EBADF; 14137 goto err_fd; 14138 } 14139 group_leader = fd_file(group)->private_data; 14140 if (group_leader->state <= PERF_EVENT_STATE_EXIT) { 14141 err = -ENODEV; 14142 goto err_fd; 14143 } 14144 if (flags & PERF_FLAG_FD_OUTPUT) 14145 output_event = group_leader; 14146 if (flags & PERF_FLAG_FD_NO_GROUP) 14147 group_leader = NULL; 14148 } 14149 14150 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { 14151 task = find_lively_task_by_vpid(pid); 14152 if (IS_ERR(task)) { 14153 err = PTR_ERR(task); 14154 goto err_fd; 14155 } 14156 } 14157 14158 if (task && group_leader && 14159 group_leader->attr.inherit != attr.inherit) { 14160 err = -EINVAL; 14161 goto err_task; 14162 } 14163 14164 if (flags & PERF_FLAG_PID_CGROUP) 14165 cgroup_fd = pid; 14166 14167 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, 14168 NULL, NULL, cgroup_fd); 14169 if (IS_ERR(event)) { 14170 err = PTR_ERR(event); 14171 goto err_task; 14172 } 14173 14174 if (is_sampling_event(event)) { 14175 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { 14176 err = -EOPNOTSUPP; 14177 goto err_alloc; 14178 } 14179 } 14180 14181 /* 14182 * Special case software events and allow them to be part of 14183 * any hardware group. 14184 */ 14185 pmu = event->pmu; 14186 14187 if (attr.use_clockid) { 14188 err = perf_event_set_clock(event, attr.clockid); 14189 if (err) 14190 goto err_alloc; 14191 } 14192 14193 if (pmu->task_ctx_nr == perf_sw_context) 14194 event->event_caps |= PERF_EV_CAP_SOFTWARE; 14195 14196 if (task) { 14197 err = down_read_interruptible(&task->signal->exec_update_lock); 14198 if (err) 14199 goto err_alloc; 14200 14201 /* 14202 * We must hold exec_update_lock across this and any potential 14203 * perf_install_in_context() call for this new event to 14204 * serialize against exec() altering our credentials (and the 14205 * perf_event_exit_task() that could imply). 14206 */ 14207 err = -EACCES; 14208 if (!perf_check_permission(&attr, task)) 14209 goto err_cred; 14210 } 14211 14212 /* 14213 * Get the target context (task or percpu): 14214 */ 14215 ctx = find_get_context(task, event); 14216 if (IS_ERR(ctx)) { 14217 err = PTR_ERR(ctx); 14218 goto err_cred; 14219 } 14220 14221 mutex_lock(&ctx->mutex); 14222 14223 if (ctx->task == TASK_TOMBSTONE) { 14224 err = -ESRCH; 14225 goto err_locked; 14226 } 14227 14228 if (!task) { 14229 /* 14230 * Check if the @cpu we're creating an event for is online. 14231 * 14232 * We use the perf_cpu_context::ctx::mutex to serialize against 14233 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 14234 */ 14235 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu); 14236 14237 if (!cpuctx->online) { 14238 err = -ENODEV; 14239 goto err_locked; 14240 } 14241 } 14242 14243 if (group_leader) { 14244 err = -EINVAL; 14245 14246 /* 14247 * Do not allow a recursive hierarchy (this new sibling 14248 * becoming part of another group-sibling): 14249 */ 14250 if (group_leader->group_leader != group_leader) 14251 goto err_locked; 14252 14253 /* All events in a group should have the same clock */ 14254 if (group_leader->clock != event->clock) 14255 goto err_locked; 14256 14257 /* 14258 * Make sure we're both events for the same CPU; 14259 * grouping events for different CPUs is broken; since 14260 * you can never concurrently schedule them anyhow. 14261 */ 14262 if (group_leader->cpu != event->cpu) 14263 goto err_locked; 14264 14265 /* 14266 * Make sure we're both on the same context; either task or cpu. 14267 */ 14268 if (group_leader->ctx != ctx) 14269 goto err_locked; 14270 14271 /* Recheck under ctx::mutex to serialize against remove-on-exec. */ 14272 if (group_leader->state <= PERF_EVENT_STATE_EXIT) { 14273 err = -ENODEV; 14274 goto err_locked; 14275 } 14276 14277 /* 14278 * Only a group leader can be exclusive or pinned 14279 */ 14280 if (attr.exclusive || attr.pinned) 14281 goto err_locked; 14282 14283 if (is_software_event(event) && 14284 !in_software_context(group_leader)) { 14285 /* 14286 * If the event is a sw event, but the group_leader 14287 * is on hw context. 14288 * 14289 * Allow the addition of software events to hw 14290 * groups, this is safe because software events 14291 * never fail to schedule. 14292 * 14293 * Note the comment that goes with struct 14294 * perf_event_pmu_context. 14295 */ 14296 pmu = group_leader->pmu_ctx->pmu; 14297 } else if (!is_software_event(event)) { 14298 if (is_software_event(group_leader) && 14299 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { 14300 /* 14301 * In case the group is a pure software group, and we 14302 * try to add a hardware event, move the whole group to 14303 * the hardware context. 14304 */ 14305 move_group = 1; 14306 } 14307 14308 /* Don't allow group of multiple hw events from different pmus */ 14309 if (!in_software_context(group_leader) && 14310 group_leader->pmu_ctx->pmu != pmu) 14311 goto err_locked; 14312 } 14313 } 14314 14315 /* 14316 * Now that we're certain of the pmu; find the pmu_ctx. 14317 */ 14318 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 14319 if (IS_ERR(pmu_ctx)) { 14320 err = PTR_ERR(pmu_ctx); 14321 goto err_locked; 14322 } 14323 event->pmu_ctx = pmu_ctx; 14324 14325 if (output_event) { 14326 err = perf_event_set_output(event, output_event); 14327 if (err) 14328 goto err_context; 14329 } 14330 14331 if (!perf_event_validate_size(event)) { 14332 err = -E2BIG; 14333 goto err_context; 14334 } 14335 14336 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) { 14337 err = -EINVAL; 14338 goto err_context; 14339 } 14340 14341 /* 14342 * Must be under the same ctx::mutex as perf_install_in_context(), 14343 * because we need to serialize with concurrent event creation. 14344 */ 14345 if (!exclusive_event_installable(event, ctx)) { 14346 err = -EBUSY; 14347 goto err_context; 14348 } 14349 14350 WARN_ON_ONCE(ctx->parent_ctx); 14351 14352 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); 14353 if (IS_ERR(event_file)) { 14354 err = PTR_ERR(event_file); 14355 event_file = NULL; 14356 goto err_context; 14357 } 14358 14359 /* 14360 * This is the point on no return; we cannot fail hereafter. This is 14361 * where we start modifying current state. 14362 */ 14363 14364 if (move_group) { 14365 perf_remove_from_context(group_leader, 0); 14366 put_pmu_ctx(group_leader->pmu_ctx); 14367 14368 for_each_sibling_event(sibling, group_leader) { 14369 perf_remove_from_context(sibling, 0); 14370 put_pmu_ctx(sibling->pmu_ctx); 14371 } 14372 14373 /* 14374 * Install the group siblings before the group leader. 14375 * 14376 * Because a group leader will try and install the entire group 14377 * (through the sibling list, which is still in-tact), we can 14378 * end up with siblings installed in the wrong context. 14379 * 14380 * By installing siblings first we NO-OP because they're not 14381 * reachable through the group lists. 14382 */ 14383 for_each_sibling_event(sibling, group_leader) { 14384 sibling->pmu_ctx = pmu_ctx; 14385 get_pmu_ctx(pmu_ctx); 14386 perf_event__state_init(sibling); 14387 perf_install_in_context(ctx, sibling, sibling->cpu); 14388 } 14389 14390 /* 14391 * Removing from the context ends up with disabled 14392 * event. What we want here is event in the initial 14393 * startup state, ready to be add into new context. 14394 */ 14395 group_leader->pmu_ctx = pmu_ctx; 14396 get_pmu_ctx(pmu_ctx); 14397 perf_event__state_init(group_leader); 14398 perf_install_in_context(ctx, group_leader, group_leader->cpu); 14399 } 14400 14401 /* 14402 * Precalculate sample_data sizes; do while holding ctx::mutex such 14403 * that we're serialized against further additions and before 14404 * perf_install_in_context() which is the point the event is active and 14405 * can use these values. 14406 */ 14407 perf_event__header_size(event); 14408 perf_event__id_header_size(event); 14409 14410 event->owner = current; 14411 14412 perf_install_in_context(ctx, event, event->cpu); 14413 perf_unpin_context(ctx); 14414 14415 mutex_unlock(&ctx->mutex); 14416 14417 if (task) { 14418 up_read(&task->signal->exec_update_lock); 14419 put_task_struct(task); 14420 } 14421 14422 mutex_lock(¤t->perf_event_mutex); 14423 list_add_tail(&event->owner_entry, ¤t->perf_event_list); 14424 mutex_unlock(¤t->perf_event_mutex); 14425 14426 /* 14427 * File reference in group guarantees that group_leader has been 14428 * kept alive until we place the new event on the sibling_list. 14429 * This ensures destruction of the group leader will find 14430 * the pointer to itself in perf_group_detach(). 14431 */ 14432 fd_install(event_fd, event_file); 14433 return event_fd; 14434 14435 err_context: 14436 put_pmu_ctx(event->pmu_ctx); 14437 event->pmu_ctx = NULL; /* _free_event() */ 14438 err_locked: 14439 mutex_unlock(&ctx->mutex); 14440 perf_unpin_context(ctx); 14441 put_ctx(ctx); 14442 err_cred: 14443 if (task) 14444 up_read(&task->signal->exec_update_lock); 14445 err_alloc: 14446 put_event(event); 14447 err_task: 14448 if (task) 14449 put_task_struct(task); 14450 err_fd: 14451 put_unused_fd(event_fd); 14452 return err; 14453 } 14454 14455 /** 14456 * perf_event_create_kernel_counter 14457 * 14458 * @attr: attributes of the counter to create 14459 * @cpu: cpu in which the counter is bound 14460 * @task: task to profile (NULL for percpu) 14461 * @overflow_handler: callback to trigger when we hit the event 14462 * @context: context data could be used in overflow_handler callback 14463 */ 14464 struct perf_event * 14465 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu, 14466 struct task_struct *task, 14467 perf_overflow_handler_t overflow_handler, 14468 void *context) 14469 { 14470 struct perf_event_pmu_context *pmu_ctx; 14471 struct perf_event_context *ctx; 14472 struct perf_event *event; 14473 struct pmu *pmu; 14474 int err; 14475 14476 /* 14477 * Grouping is not supported for kernel events, neither is 'AUX', 14478 * make sure the caller's intentions are adjusted. 14479 */ 14480 if (attr->aux_output || attr->aux_action) 14481 return ERR_PTR(-EINVAL); 14482 14483 /* 14484 * Event creation should be under SRCU, see perf_pmu_unregister(). 14485 */ 14486 guard(srcu)(&pmus_srcu); 14487 14488 event = perf_event_alloc(attr, cpu, task, NULL, NULL, 14489 overflow_handler, context, -1); 14490 if (IS_ERR(event)) { 14491 err = PTR_ERR(event); 14492 goto err; 14493 } 14494 14495 /* Mark owner so we could distinguish it from user events. */ 14496 event->owner = TASK_TOMBSTONE; 14497 pmu = event->pmu; 14498 14499 if (pmu->task_ctx_nr == perf_sw_context) 14500 event->event_caps |= PERF_EV_CAP_SOFTWARE; 14501 14502 /* 14503 * Get the target context (task or percpu): 14504 */ 14505 ctx = find_get_context(task, event); 14506 if (IS_ERR(ctx)) { 14507 err = PTR_ERR(ctx); 14508 goto err_alloc; 14509 } 14510 14511 WARN_ON_ONCE(ctx->parent_ctx); 14512 mutex_lock(&ctx->mutex); 14513 if (ctx->task == TASK_TOMBSTONE) { 14514 err = -ESRCH; 14515 goto err_unlock; 14516 } 14517 14518 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 14519 if (IS_ERR(pmu_ctx)) { 14520 err = PTR_ERR(pmu_ctx); 14521 goto err_unlock; 14522 } 14523 event->pmu_ctx = pmu_ctx; 14524 14525 if (!task) { 14526 /* 14527 * Check if the @cpu we're creating an event for is online. 14528 * 14529 * We use the perf_cpu_context::ctx::mutex to serialize against 14530 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 14531 */ 14532 struct perf_cpu_context *cpuctx = 14533 container_of(ctx, struct perf_cpu_context, ctx); 14534 if (!cpuctx->online) { 14535 err = -ENODEV; 14536 goto err_pmu_ctx; 14537 } 14538 } 14539 14540 if (!exclusive_event_installable(event, ctx)) { 14541 err = -EBUSY; 14542 goto err_pmu_ctx; 14543 } 14544 14545 perf_install_in_context(ctx, event, event->cpu); 14546 perf_unpin_context(ctx); 14547 mutex_unlock(&ctx->mutex); 14548 14549 return event; 14550 14551 err_pmu_ctx: 14552 put_pmu_ctx(pmu_ctx); 14553 event->pmu_ctx = NULL; /* _free_event() */ 14554 err_unlock: 14555 mutex_unlock(&ctx->mutex); 14556 perf_unpin_context(ctx); 14557 put_ctx(ctx); 14558 err_alloc: 14559 put_event(event); 14560 err: 14561 return ERR_PTR(err); 14562 } 14563 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter); 14564 14565 static void __perf_pmu_remove(struct perf_event_context *ctx, struct pmu *pmu, 14566 struct list_head *events) 14567 { 14568 struct perf_event *event, *tmp; 14569 14570 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) { 14571 if (event->pmu_ctx->pmu != pmu) 14572 continue; 14573 14574 perf_remove_from_context(event, 0); 14575 put_pmu_ctx(event->pmu_ctx); 14576 list_add(&event->migrate_entry, events); 14577 } 14578 } 14579 14580 static void __perf_pmu_install_event(struct pmu *pmu, 14581 struct perf_event_context *ctx, 14582 int cpu, struct perf_event *event) 14583 { 14584 struct perf_event_pmu_context *epc; 14585 struct perf_event_context *old_ctx = event->ctx; 14586 14587 get_ctx(ctx); /* normally find_get_context() */ 14588 14589 event->cpu = cpu; 14590 epc = find_get_pmu_context(pmu, ctx, event); 14591 event->pmu_ctx = epc; 14592 14593 if (event->state >= PERF_EVENT_STATE_OFF) 14594 event->state = PERF_EVENT_STATE_INACTIVE; 14595 perf_install_in_context(ctx, event, cpu); 14596 14597 /* 14598 * Now that event->ctx is updated and visible, put the old ctx. 14599 */ 14600 put_ctx(old_ctx); 14601 } 14602 14603 static void __perf_pmu_install(struct perf_event_context *ctx, 14604 int cpu, struct pmu *pmu, struct list_head *events) 14605 { 14606 struct perf_event *event, *tmp; 14607 14608 /* 14609 * Re-instate events in 2 passes. 14610 * 14611 * Skip over group leaders and only install siblings on this first 14612 * pass, siblings will not get enabled without a leader, however a 14613 * leader will enable its siblings, even if those are still on the old 14614 * context. 14615 */ 14616 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 14617 if (event->group_leader == event) 14618 continue; 14619 14620 list_del(&event->migrate_entry); 14621 __perf_pmu_install_event(pmu, ctx, cpu, event); 14622 } 14623 14624 /* 14625 * Once all the siblings are setup properly, install the group leaders 14626 * to make it go. 14627 */ 14628 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 14629 list_del(&event->migrate_entry); 14630 __perf_pmu_install_event(pmu, ctx, cpu, event); 14631 } 14632 } 14633 14634 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu) 14635 { 14636 struct perf_event_context *src_ctx, *dst_ctx; 14637 LIST_HEAD(events); 14638 14639 /* 14640 * Since per-cpu context is persistent, no need to grab an extra 14641 * reference. 14642 */ 14643 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx; 14644 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx; 14645 14646 /* 14647 * See perf_event_ctx_lock() for comments on the details 14648 * of swizzling perf_event::ctx. 14649 */ 14650 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex); 14651 14652 __perf_pmu_remove(src_ctx, pmu, &events); 14653 14654 if (!list_empty(&events)) { 14655 /* 14656 * Wait for the events to quiesce before re-instating them. 14657 */ 14658 synchronize_rcu(); 14659 14660 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events); 14661 } 14662 14663 mutex_unlock(&dst_ctx->mutex); 14664 mutex_unlock(&src_ctx->mutex); 14665 } 14666 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context); 14667 14668 static void sync_child_event(struct perf_event *child_event, 14669 struct task_struct *task) 14670 { 14671 struct perf_event *parent_event = child_event->parent; 14672 u64 child_val; 14673 14674 if (child_event->attr.inherit_stat) { 14675 if (task && task != TASK_TOMBSTONE) 14676 perf_event_read_event(child_event, task); 14677 } 14678 14679 child_val = perf_event_count(child_event, false); 14680 14681 /* 14682 * Add back the child's count to the parent's count: 14683 */ 14684 atomic64_add(child_val, &parent_event->child_count); 14685 atomic64_add(child_event->total_time_enabled, 14686 &parent_event->child_total_time_enabled); 14687 atomic64_add(child_event->total_time_running, 14688 &parent_event->child_total_time_running); 14689 } 14690 14691 static void 14692 perf_event_exit_event(struct perf_event *event, 14693 struct perf_event_context *ctx, 14694 struct task_struct *task, 14695 unsigned long detach_flags) 14696 { 14697 struct perf_event *parent_event = event->parent; 14698 unsigned int attach_state; 14699 14700 detach_flags |= DETACH_EXIT; 14701 14702 if (parent_event) { 14703 /* 14704 * Do not destroy the 'original' grouping; because of the 14705 * context switch optimization the original events could've 14706 * ended up in a random child task. 14707 * 14708 * If we were to destroy the original group, all group related 14709 * operations would cease to function properly after this 14710 * random child dies. 14711 * 14712 * Do destroy all inherited groups, we don't care about those 14713 * and being thorough is better. 14714 */ 14715 detach_flags |= DETACH_GROUP | DETACH_CHILD; 14716 mutex_lock(&parent_event->child_mutex); 14717 /* PERF_ATTACH_ITRACE might be set concurrently */ 14718 attach_state = READ_ONCE(event->attach_state); 14719 14720 if (attach_state & PERF_ATTACH_CHILD) 14721 sync_child_event(event, task); 14722 } 14723 14724 if (detach_flags & DETACH_REVOKE) 14725 detach_flags |= DETACH_GROUP; 14726 14727 perf_remove_from_context(event, detach_flags); 14728 /* 14729 * Child events can be freed. 14730 */ 14731 if (parent_event) { 14732 mutex_unlock(&parent_event->child_mutex); 14733 14734 /* 14735 * Match the refcount initialization. Make sure it doesn't happen 14736 * twice if pmu_detach_event() calls it on an already exited task. 14737 */ 14738 if (attach_state & PERF_ATTACH_CHILD) { 14739 /* 14740 * Kick perf_poll() for is_event_hup(); 14741 */ 14742 perf_event_wakeup(parent_event); 14743 /* 14744 * pmu_detach_event() will have an extra refcount. 14745 * perf_pending_task() might have one too. 14746 */ 14747 put_event(event); 14748 } 14749 14750 return; 14751 } 14752 14753 /* 14754 * Parent events are governed by their filedesc, retain them. 14755 */ 14756 perf_event_wakeup(event); 14757 } 14758 14759 static void perf_event_exit_task_context(struct task_struct *task, bool exit) 14760 { 14761 struct perf_event_context *ctx, *clone_ctx = NULL; 14762 struct perf_event *child_event, *next; 14763 14764 ctx = perf_pin_task_context(task); 14765 if (!ctx) 14766 return; 14767 14768 /* 14769 * In order to reduce the amount of tricky in ctx tear-down, we hold 14770 * ctx::mutex over the entire thing. This serializes against almost 14771 * everything that wants to access the ctx. 14772 * 14773 * The exception is sys_perf_event_open() / 14774 * perf_event_create_kernel_count() which does find_get_context() 14775 * without ctx::mutex (it cannot because of the move_group double mutex 14776 * lock thing). See the comments in perf_install_in_context(). 14777 */ 14778 mutex_lock(&ctx->mutex); 14779 14780 /* 14781 * In a single ctx::lock section, de-schedule the events and detach the 14782 * context from the task such that we cannot ever get it scheduled back 14783 * in. 14784 */ 14785 raw_spin_lock_irq(&ctx->lock); 14786 if (exit) 14787 task_ctx_sched_out(ctx, NULL, EVENT_ALL); 14788 14789 /* 14790 * Now that the context is inactive, destroy the task <-> ctx relation 14791 * and mark the context dead. 14792 */ 14793 RCU_INIT_POINTER(task->perf_event_ctxp, NULL); 14794 put_ctx(ctx); /* cannot be last */ 14795 WRITE_ONCE(ctx->task, TASK_TOMBSTONE); 14796 put_task_struct(task); /* cannot be last */ 14797 14798 clone_ctx = unclone_ctx(ctx); 14799 raw_spin_unlock_irq(&ctx->lock); 14800 14801 if (clone_ctx) 14802 put_ctx(clone_ctx); 14803 14804 /* 14805 * Report the task dead after unscheduling the events so that we 14806 * won't get any samples after PERF_RECORD_EXIT. We can however still 14807 * get a few PERF_RECORD_READ events. 14808 */ 14809 if (exit) 14810 perf_event_task(task, ctx, 0); 14811 14812 list_for_each_entry_safe(child_event, next, &ctx->event_list, event_entry) 14813 perf_event_exit_event(child_event, ctx, exit ? task : NULL, 0); 14814 14815 mutex_unlock(&ctx->mutex); 14816 14817 if (!exit) { 14818 /* 14819 * perf_event_release_kernel() could still have a reference on 14820 * this context. In that case we must wait for these events to 14821 * have been freed (in particular all their references to this 14822 * task must've been dropped). 14823 * 14824 * Without this copy_process() will unconditionally free this 14825 * task (irrespective of its reference count) and 14826 * _free_event()'s put_task_struct(event->hw.target) will be a 14827 * use-after-free. 14828 * 14829 * Wait for all events to drop their context reference. 14830 */ 14831 wait_var_event(&ctx->refcount, 14832 refcount_read(&ctx->refcount) == 1); 14833 } 14834 put_ctx(ctx); 14835 } 14836 14837 /* 14838 * When a task exits, feed back event values to parent events. 14839 * 14840 * Can be called with exec_update_lock held when called from 14841 * setup_new_exec(). 14842 */ 14843 void perf_event_exit_task(struct task_struct *task) 14844 { 14845 struct perf_event *event, *tmp; 14846 14847 WARN_ON_ONCE(task != current); 14848 14849 mutex_lock(&task->perf_event_mutex); 14850 list_for_each_entry_safe(event, tmp, &task->perf_event_list, 14851 owner_entry) { 14852 list_del_init(&event->owner_entry); 14853 14854 /* 14855 * Ensure the list deletion is visible before we clear 14856 * the owner, closes a race against perf_release() where 14857 * we need to serialize on the owner->perf_event_mutex. 14858 */ 14859 smp_store_release(&event->owner, NULL); 14860 } 14861 mutex_unlock(&task->perf_event_mutex); 14862 14863 perf_event_exit_task_context(task, true); 14864 14865 /* 14866 * The perf_event_exit_task_context calls perf_event_task 14867 * with task's task_ctx, which generates EXIT events for 14868 * task contexts and sets task->perf_event_ctxp[] to NULL. 14869 * At this point we need to send EXIT events to cpu contexts. 14870 */ 14871 perf_event_task(task, NULL, 0); 14872 14873 /* 14874 * Detach the perf_ctx_data for the system-wide event. 14875 * 14876 * Done without holding global_ctx_data_rwsem; typically 14877 * attach_global_ctx_data() will skip over this task, but otherwise 14878 * attach_task_ctx_data() will observe PF_EXITING. 14879 */ 14880 detach_task_ctx_data(task); 14881 } 14882 14883 /* 14884 * Free a context as created by inheritance by perf_event_init_task() below, 14885 * used by fork() in case of fail. 14886 * 14887 * Even though the task has never lived, the context and events have been 14888 * exposed through the child_list, so we must take care tearing it all down. 14889 */ 14890 void perf_event_free_task(struct task_struct *task) 14891 { 14892 perf_event_exit_task_context(task, false); 14893 } 14894 14895 void perf_event_delayed_put(struct task_struct *task) 14896 { 14897 WARN_ON_ONCE(task->perf_event_ctxp); 14898 } 14899 14900 struct file *perf_event_get(unsigned int fd) 14901 { 14902 struct file *file = fget(fd); 14903 if (!file) 14904 return ERR_PTR(-EBADF); 14905 14906 if (file->f_op != &perf_fops) { 14907 fput(file); 14908 return ERR_PTR(-EBADF); 14909 } 14910 14911 return file; 14912 } 14913 14914 const struct perf_event *perf_get_event(struct file *file) 14915 { 14916 if (file->f_op != &perf_fops) 14917 return ERR_PTR(-EINVAL); 14918 14919 return file->private_data; 14920 } 14921 14922 const struct perf_event_attr *perf_event_attrs(struct perf_event *event) 14923 { 14924 if (!event) 14925 return ERR_PTR(-EINVAL); 14926 14927 return &event->attr; 14928 } 14929 14930 int perf_allow_kernel(void) 14931 { 14932 if (sysctl_perf_event_paranoid > 1 && !perfmon_capable()) 14933 return -EACCES; 14934 14935 return security_perf_event_open(PERF_SECURITY_KERNEL); 14936 } 14937 EXPORT_SYMBOL_GPL(perf_allow_kernel); 14938 14939 int perf_allow_cpu(void) 14940 { 14941 if (sysctl_perf_event_paranoid > 0 && !perfmon_capable()) 14942 return -EACCES; 14943 14944 return security_perf_event_open(PERF_SECURITY_CPU); 14945 } 14946 EXPORT_SYMBOL_GPL(perf_allow_cpu); 14947 14948 int perf_allow_tracepoint(void) 14949 { 14950 if (sysctl_perf_event_paranoid > -1 && !perfmon_capable()) 14951 return -EPERM; 14952 14953 return security_perf_event_open(PERF_SECURITY_TRACEPOINT); 14954 } 14955 EXPORT_SYMBOL_GPL(perf_allow_tracepoint); 14956 14957 /* 14958 * Inherit an event from parent task to child task. 14959 * 14960 * Returns: 14961 * - valid pointer on success 14962 * - NULL for orphaned events 14963 * - IS_ERR() on error 14964 */ 14965 static struct perf_event * 14966 inherit_event(struct perf_event *parent_event, 14967 struct task_struct *parent, 14968 struct perf_event_context *parent_ctx, 14969 struct task_struct *child, 14970 struct perf_event *group_leader, 14971 struct perf_event_context *child_ctx) 14972 { 14973 enum perf_event_state parent_state = parent_event->state; 14974 struct perf_event_pmu_context *pmu_ctx; 14975 struct perf_event *child_event; 14976 unsigned long flags; 14977 14978 /* 14979 * Instead of creating recursive hierarchies of events, 14980 * we link inherited events back to the original parent, 14981 * which has a filp for sure, which we use as the reference 14982 * count: 14983 */ 14984 if (parent_event->parent) 14985 parent_event = parent_event->parent; 14986 14987 if (parent_event->state <= PERF_EVENT_STATE_REVOKED) 14988 return NULL; 14989 14990 /* 14991 * Event creation should be under SRCU, see perf_pmu_unregister(). 14992 */ 14993 guard(srcu)(&pmus_srcu); 14994 14995 child_event = perf_event_alloc(&parent_event->attr, 14996 parent_event->cpu, 14997 child, 14998 group_leader, parent_event, 14999 NULL, NULL, -1); 15000 if (IS_ERR(child_event)) 15001 return child_event; 15002 15003 get_ctx(child_ctx); 15004 child_event->ctx = child_ctx; 15005 15006 pmu_ctx = find_get_pmu_context(parent_event->pmu_ctx->pmu, child_ctx, child_event); 15007 if (IS_ERR(pmu_ctx)) { 15008 free_event(child_event); 15009 return ERR_CAST(pmu_ctx); 15010 } 15011 child_event->pmu_ctx = pmu_ctx; 15012 15013 /* 15014 * is_orphaned_event() and list_add_tail(&parent_event->child_list) 15015 * must be under the same lock in order to serialize against 15016 * perf_event_release_kernel(), such that either we must observe 15017 * is_orphaned_event() or they will observe us on the child_list. 15018 */ 15019 mutex_lock(&parent_event->child_mutex); 15020 if (is_orphaned_event(parent_event) || 15021 !atomic_long_inc_not_zero(&parent_event->refcount)) { 15022 mutex_unlock(&parent_event->child_mutex); 15023 free_event(child_event); 15024 return NULL; 15025 } 15026 15027 /* 15028 * Make the child state follow the state of the parent event, 15029 * not its attr.disabled bit. We hold the parent's mutex, 15030 * so we won't race with perf_event_{en, dis}able_family. 15031 */ 15032 if (parent_state >= PERF_EVENT_STATE_INACTIVE) 15033 child_event->state = PERF_EVENT_STATE_INACTIVE; 15034 else 15035 child_event->state = PERF_EVENT_STATE_OFF; 15036 15037 if (parent_event->attr.freq) { 15038 u64 sample_period = parent_event->hw.sample_period; 15039 struct hw_perf_event *hwc = &child_event->hw; 15040 15041 hwc->sample_period = sample_period; 15042 hwc->last_period = sample_period; 15043 15044 local64_set(&hwc->period_left, sample_period); 15045 } 15046 15047 child_event->overflow_handler = parent_event->overflow_handler; 15048 child_event->overflow_handler_context 15049 = parent_event->overflow_handler_context; 15050 15051 /* 15052 * Precalculate sample_data sizes 15053 */ 15054 perf_event__header_size(child_event); 15055 perf_event__id_header_size(child_event); 15056 15057 /* 15058 * Link it up in the child's context: 15059 */ 15060 raw_spin_lock_irqsave(&child_ctx->lock, flags); 15061 add_event_to_ctx(child_event, child_ctx); 15062 child_event->attach_state |= PERF_ATTACH_CHILD; 15063 raw_spin_unlock_irqrestore(&child_ctx->lock, flags); 15064 15065 /* 15066 * Link this into the parent event's child list 15067 */ 15068 list_add_tail(&child_event->child_list, &parent_event->child_list); 15069 mutex_unlock(&parent_event->child_mutex); 15070 15071 return child_event; 15072 } 15073 15074 /* 15075 * Inherits an event group. 15076 * 15077 * This will quietly suppress orphaned events; !inherit_event() is not an error. 15078 * This matches with perf_event_release_kernel() removing all child events. 15079 * 15080 * Returns: 15081 * - 0 on success 15082 * - <0 on error 15083 */ 15084 static int inherit_group(struct perf_event *parent_event, 15085 struct task_struct *parent, 15086 struct perf_event_context *parent_ctx, 15087 struct task_struct *child, 15088 struct perf_event_context *child_ctx) 15089 { 15090 struct perf_event *leader; 15091 struct perf_event *sub; 15092 struct perf_event *child_ctr; 15093 15094 leader = inherit_event(parent_event, parent, parent_ctx, 15095 child, NULL, child_ctx); 15096 if (IS_ERR(leader)) 15097 return PTR_ERR(leader); 15098 /* 15099 * @leader can be NULL here because of is_orphaned_event(). In this 15100 * case inherit_event() will create individual events, similar to what 15101 * perf_group_detach() would do anyway. 15102 */ 15103 for_each_sibling_event(sub, parent_event) { 15104 child_ctr = inherit_event(sub, parent, parent_ctx, 15105 child, leader, child_ctx); 15106 if (IS_ERR(child_ctr)) 15107 return PTR_ERR(child_ctr); 15108 15109 if (sub->aux_event == parent_event && child_ctr && 15110 !perf_get_aux_event(child_ctr, leader)) 15111 return -EINVAL; 15112 } 15113 if (leader) 15114 leader->group_generation = parent_event->group_generation; 15115 return 0; 15116 } 15117 15118 /* 15119 * Creates the child task context and tries to inherit the event-group. 15120 * 15121 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave 15122 * inherited_all set when we 'fail' to inherit an orphaned event; this is 15123 * consistent with perf_event_release_kernel() removing all child events. 15124 * 15125 * Returns: 15126 * - 0 on success 15127 * - <0 on error 15128 */ 15129 static int 15130 inherit_task_group(struct perf_event *event, struct task_struct *parent, 15131 struct perf_event_context *parent_ctx, 15132 struct task_struct *child, 15133 u64 clone_flags, int *inherited_all) 15134 { 15135 struct perf_event_context *child_ctx; 15136 int ret; 15137 15138 if (!event->attr.inherit || 15139 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) || 15140 /* Do not inherit if sigtrap and signal handlers were cleared. */ 15141 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) { 15142 *inherited_all = 0; 15143 return 0; 15144 } 15145 15146 child_ctx = child->perf_event_ctxp; 15147 if (!child_ctx) { 15148 /* 15149 * This is executed from the parent task context, so 15150 * inherit events that have been marked for cloning. 15151 * First allocate and initialize a context for the 15152 * child. 15153 */ 15154 child_ctx = alloc_perf_context(child); 15155 if (!child_ctx) 15156 return -ENOMEM; 15157 15158 child->perf_event_ctxp = child_ctx; 15159 } 15160 15161 ret = inherit_group(event, parent, parent_ctx, child, child_ctx); 15162 if (ret) 15163 *inherited_all = 0; 15164 15165 return ret; 15166 } 15167 15168 /* 15169 * Initialize the perf_event context in task_struct 15170 */ 15171 static int perf_event_init_context(struct task_struct *child, u64 clone_flags) 15172 { 15173 struct perf_event_context *child_ctx, *parent_ctx; 15174 struct perf_event_context *cloned_ctx; 15175 struct perf_event *event; 15176 struct task_struct *parent = current; 15177 int inherited_all = 1; 15178 unsigned long flags; 15179 int ret = 0; 15180 15181 if (likely(!parent->perf_event_ctxp)) 15182 return 0; 15183 15184 /* 15185 * If the parent's context is a clone, pin it so it won't get 15186 * swapped under us. 15187 */ 15188 parent_ctx = perf_pin_task_context(parent); 15189 if (!parent_ctx) 15190 return 0; 15191 15192 /* 15193 * No need to check if parent_ctx != NULL here; since we saw 15194 * it non-NULL earlier, the only reason for it to become NULL 15195 * is if we exit, and since we're currently in the middle of 15196 * a fork we can't be exiting at the same time. 15197 */ 15198 15199 /* 15200 * Lock the parent list. No need to lock the child - not PID 15201 * hashed yet and not running, so nobody can access it. 15202 */ 15203 mutex_lock(&parent_ctx->mutex); 15204 15205 /* 15206 * We dont have to disable NMIs - we are only looking at 15207 * the list, not manipulating it: 15208 */ 15209 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) { 15210 ret = inherit_task_group(event, parent, parent_ctx, 15211 child, clone_flags, &inherited_all); 15212 if (ret) 15213 goto out_unlock; 15214 } 15215 15216 /* 15217 * We can't hold ctx->lock when iterating the ->flexible_group list due 15218 * to allocations, but we need to prevent rotation because 15219 * rotate_ctx() will change the list from interrupt context. 15220 */ 15221 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 15222 parent_ctx->rotate_disable = 1; 15223 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 15224 15225 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) { 15226 ret = inherit_task_group(event, parent, parent_ctx, 15227 child, clone_flags, &inherited_all); 15228 if (ret) 15229 goto out_unlock; 15230 } 15231 15232 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 15233 parent_ctx->rotate_disable = 0; 15234 15235 child_ctx = child->perf_event_ctxp; 15236 15237 if (child_ctx && inherited_all) { 15238 /* 15239 * Mark the child context as a clone of the parent 15240 * context, or of whatever the parent is a clone of. 15241 * 15242 * Note that if the parent is a clone, the holding of 15243 * parent_ctx->lock avoids it from being uncloned. 15244 */ 15245 cloned_ctx = parent_ctx->parent_ctx; 15246 if (cloned_ctx) { 15247 child_ctx->parent_ctx = cloned_ctx; 15248 child_ctx->parent_gen = parent_ctx->parent_gen; 15249 } else { 15250 child_ctx->parent_ctx = parent_ctx; 15251 child_ctx->parent_gen = parent_ctx->generation; 15252 } 15253 get_ctx(child_ctx->parent_ctx); 15254 } 15255 15256 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 15257 out_unlock: 15258 mutex_unlock(&parent_ctx->mutex); 15259 15260 perf_unpin_context(parent_ctx); 15261 put_ctx(parent_ctx); 15262 15263 return ret; 15264 } 15265 15266 /* 15267 * Initialize the perf_event context in task_struct 15268 */ 15269 int perf_event_init_task(struct task_struct *child, u64 clone_flags) 15270 { 15271 int ret; 15272 15273 memset(child->perf_recursion, 0, sizeof(child->perf_recursion)); 15274 child->perf_event_ctxp = NULL; 15275 mutex_init(&child->perf_event_mutex); 15276 INIT_LIST_HEAD(&child->perf_event_list); 15277 child->perf_ctx_data = NULL; 15278 15279 ret = perf_event_init_context(child, clone_flags); 15280 if (ret) { 15281 perf_event_free_task(child); 15282 return ret; 15283 } 15284 15285 return 0; 15286 } 15287 15288 static void __init perf_event_init_all_cpus(void) 15289 { 15290 struct swevent_htable *swhash; 15291 struct perf_cpu_context *cpuctx; 15292 int cpu; 15293 15294 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL); 15295 zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL); 15296 zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL); 15297 zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL); 15298 zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL); 15299 zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL); 15300 15301 15302 for_each_possible_cpu(cpu) { 15303 swhash = &per_cpu(swevent_htable, cpu); 15304 mutex_init(&swhash->hlist_mutex); 15305 15306 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu)); 15307 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu)); 15308 15309 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu)); 15310 15311 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15312 __perf_event_init_context(&cpuctx->ctx); 15313 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); 15314 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); 15315 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask); 15316 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default); 15317 cpuctx->heap = cpuctx->heap_default; 15318 } 15319 } 15320 15321 static void perf_swevent_init_cpu(unsigned int cpu) 15322 { 15323 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 15324 15325 mutex_lock(&swhash->hlist_mutex); 15326 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) { 15327 struct swevent_hlist *hlist; 15328 15329 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); 15330 WARN_ON(!hlist); 15331 rcu_assign_pointer(swhash->swevent_hlist, hlist); 15332 } 15333 mutex_unlock(&swhash->hlist_mutex); 15334 } 15335 15336 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE 15337 static void __perf_event_exit_context(void *__info) 15338 { 15339 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 15340 struct perf_event_context *ctx = __info; 15341 struct perf_event *event; 15342 15343 raw_spin_lock(&ctx->lock); 15344 ctx_sched_out(ctx, NULL, EVENT_TIME); 15345 list_for_each_entry(event, &ctx->event_list, event_entry) 15346 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP); 15347 raw_spin_unlock(&ctx->lock); 15348 } 15349 15350 static void perf_event_clear_cpumask(unsigned int cpu) 15351 { 15352 int target[PERF_PMU_MAX_SCOPE]; 15353 unsigned int scope; 15354 struct pmu *pmu; 15355 15356 cpumask_clear_cpu(cpu, perf_online_mask); 15357 15358 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15359 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 15360 struct cpumask *pmu_cpumask = perf_scope_cpumask(scope); 15361 15362 target[scope] = -1; 15363 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 15364 continue; 15365 15366 if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask)) 15367 continue; 15368 target[scope] = cpumask_any_but(cpumask, cpu); 15369 if (target[scope] < nr_cpu_ids) 15370 cpumask_set_cpu(target[scope], pmu_cpumask); 15371 } 15372 15373 /* migrate */ 15374 list_for_each_entry(pmu, &pmus, entry) { 15375 if (pmu->scope == PERF_PMU_SCOPE_NONE || 15376 WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE)) 15377 continue; 15378 15379 if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids) 15380 perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]); 15381 } 15382 } 15383 15384 static void perf_event_exit_cpu_context(int cpu) 15385 { 15386 struct perf_cpu_context *cpuctx; 15387 struct perf_event_context *ctx; 15388 15389 // XXX simplify cpuctx->online 15390 mutex_lock(&pmus_lock); 15391 /* 15392 * Clear the cpumasks, and migrate to other CPUs if possible. 15393 * Must be invoked before the __perf_event_exit_context. 15394 */ 15395 perf_event_clear_cpumask(cpu); 15396 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15397 ctx = &cpuctx->ctx; 15398 15399 mutex_lock(&ctx->mutex); 15400 if (ctx->nr_events) 15401 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1); 15402 cpuctx->online = 0; 15403 mutex_unlock(&ctx->mutex); 15404 mutex_unlock(&pmus_lock); 15405 } 15406 #else 15407 15408 static void perf_event_exit_cpu_context(int cpu) { } 15409 15410 #endif 15411 15412 static void perf_event_setup_cpumask(unsigned int cpu) 15413 { 15414 struct cpumask *pmu_cpumask; 15415 unsigned int scope; 15416 15417 /* 15418 * Early boot stage, the cpumask hasn't been set yet. 15419 * The perf_online_<domain>_masks includes the first CPU of each domain. 15420 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks. 15421 */ 15422 if (cpumask_empty(perf_online_mask)) { 15423 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15424 pmu_cpumask = perf_scope_cpumask(scope); 15425 if (WARN_ON_ONCE(!pmu_cpumask)) 15426 continue; 15427 cpumask_set_cpu(cpu, pmu_cpumask); 15428 } 15429 goto end; 15430 } 15431 15432 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15433 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 15434 15435 pmu_cpumask = perf_scope_cpumask(scope); 15436 15437 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 15438 continue; 15439 15440 if (!cpumask_empty(cpumask) && 15441 cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids) 15442 cpumask_set_cpu(cpu, pmu_cpumask); 15443 } 15444 end: 15445 cpumask_set_cpu(cpu, perf_online_mask); 15446 } 15447 15448 int perf_event_init_cpu(unsigned int cpu) 15449 { 15450 struct perf_cpu_context *cpuctx; 15451 struct perf_event_context *ctx; 15452 15453 perf_swevent_init_cpu(cpu); 15454 15455 mutex_lock(&pmus_lock); 15456 perf_event_setup_cpumask(cpu); 15457 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15458 ctx = &cpuctx->ctx; 15459 15460 mutex_lock(&ctx->mutex); 15461 cpuctx->online = 1; 15462 mutex_unlock(&ctx->mutex); 15463 mutex_unlock(&pmus_lock); 15464 15465 return 0; 15466 } 15467 15468 int perf_event_exit_cpu(unsigned int cpu) 15469 { 15470 perf_event_exit_cpu_context(cpu); 15471 return 0; 15472 } 15473 15474 static int 15475 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v) 15476 { 15477 int cpu; 15478 15479 for_each_online_cpu(cpu) 15480 perf_event_exit_cpu(cpu); 15481 15482 return NOTIFY_OK; 15483 } 15484 15485 /* 15486 * Run the perf reboot notifier at the very last possible moment so that 15487 * the generic watchdog code runs as long as possible. 15488 */ 15489 static struct notifier_block perf_reboot_notifier = { 15490 .notifier_call = perf_reboot, 15491 .priority = INT_MIN, 15492 }; 15493 15494 void __init perf_event_init(void) 15495 { 15496 int ret; 15497 15498 idr_init(&pmu_idr); 15499 15500 unwind_deferred_init(&perf_unwind_work, 15501 perf_unwind_deferred_callback); 15502 15503 perf_event_init_all_cpus(); 15504 init_srcu_struct(&pmus_srcu); 15505 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE); 15506 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1); 15507 perf_pmu_register(&perf_task_clock, "task_clock", -1); 15508 perf_tp_register(); 15509 perf_event_init_cpu(smp_processor_id()); 15510 register_reboot_notifier(&perf_reboot_notifier); 15511 15512 ret = init_hw_breakpoint(); 15513 WARN(ret, "hw_breakpoint initialization failed with: %d", ret); 15514 15515 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC); 15516 15517 /* 15518 * Build time assertion that we keep the data_head at the intended 15519 * location. IOW, validation we got the __reserved[] size right. 15520 */ 15521 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head)) 15522 != 1024); 15523 } 15524 15525 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr, 15526 char *page) 15527 { 15528 struct perf_pmu_events_attr *pmu_attr = 15529 container_of(attr, struct perf_pmu_events_attr, attr); 15530 15531 if (pmu_attr->event_str) 15532 return sprintf(page, "%s\n", pmu_attr->event_str); 15533 15534 return 0; 15535 } 15536 EXPORT_SYMBOL_GPL(perf_event_sysfs_show); 15537 15538 static int __init perf_event_sysfs_init(void) 15539 { 15540 struct pmu *pmu; 15541 int ret; 15542 15543 mutex_lock(&pmus_lock); 15544 15545 ret = bus_register(&pmu_bus); 15546 if (ret) 15547 goto unlock; 15548 15549 list_for_each_entry(pmu, &pmus, entry) { 15550 if (pmu->dev) 15551 continue; 15552 15553 ret = pmu_dev_alloc(pmu); 15554 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret); 15555 } 15556 pmu_bus_running = 1; 15557 ret = 0; 15558 15559 unlock: 15560 mutex_unlock(&pmus_lock); 15561 15562 return ret; 15563 } 15564 device_initcall(perf_event_sysfs_init); 15565 15566 #ifdef CONFIG_CGROUP_PERF 15567 static struct cgroup_subsys_state * 15568 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 15569 { 15570 struct perf_cgroup *jc; 15571 15572 jc = kzalloc_obj(*jc); 15573 if (!jc) 15574 return ERR_PTR(-ENOMEM); 15575 15576 jc->info = alloc_percpu(struct perf_cgroup_info); 15577 if (!jc->info) { 15578 kfree(jc); 15579 return ERR_PTR(-ENOMEM); 15580 } 15581 15582 return &jc->css; 15583 } 15584 15585 static void perf_cgroup_css_free(struct cgroup_subsys_state *css) 15586 { 15587 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css); 15588 15589 free_percpu(jc->info); 15590 kfree(jc); 15591 } 15592 15593 static int perf_cgroup_css_online(struct cgroup_subsys_state *css) 15594 { 15595 perf_event_cgroup(css->cgroup); 15596 return 0; 15597 } 15598 15599 static int __perf_cgroup_move(void *info) 15600 { 15601 struct task_struct *task = info; 15602 15603 preempt_disable(); 15604 perf_cgroup_switch(task); 15605 preempt_enable(); 15606 15607 return 0; 15608 } 15609 15610 static void perf_cgroup_attach(struct cgroup_taskset *tset) 15611 { 15612 struct task_struct *task; 15613 struct cgroup_subsys_state *css; 15614 15615 cgroup_taskset_for_each(task, css, tset) 15616 task_function_call(task, __perf_cgroup_move, task); 15617 } 15618 15619 struct cgroup_subsys perf_event_cgrp_subsys = { 15620 .css_alloc = perf_cgroup_css_alloc, 15621 .css_free = perf_cgroup_css_free, 15622 .css_online = perf_cgroup_css_online, 15623 .attach = perf_cgroup_attach, 15624 /* 15625 * Implicitly enable on dfl hierarchy so that perf events can 15626 * always be filtered by cgroup2 path as long as perf_event 15627 * controller is not mounted on a legacy hierarchy. 15628 */ 15629 .implicit_on_dfl = true, 15630 .threaded = true, 15631 }; 15632 #endif /* CONFIG_CGROUP_PERF */ 15633 15634 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t); 15635