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) 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 * We'd expect this to only occur if the irq_work is delayed and either 7651 * ctx->task or current has changed in the meantime. This can be the 7652 * case on architectures that do not implement arch_irq_work_raise(). 7653 */ 7654 if (WARN_ON_ONCE(event->ctx->task != current)) 7655 return; 7656 7657 send_sig_perf((void __user *)event->pending_addr, 7658 event->orig_type, event->attr.sig_data); 7659 } 7660 7661 /* 7662 * Deliver the pending work in-event-context or follow the context. 7663 */ 7664 static void __perf_pending_disable(struct perf_event *event) 7665 { 7666 int cpu = READ_ONCE(event->oncpu); 7667 7668 /* 7669 * If the event isn't running; we done. event_sched_out() will have 7670 * taken care of things. 7671 */ 7672 if (cpu < 0) 7673 return; 7674 7675 /* 7676 * Yay, we hit home and are in the context of the event. 7677 */ 7678 if (cpu == smp_processor_id()) { 7679 if (event->pending_disable) { 7680 event->pending_disable = 0; 7681 perf_event_disable_local(event); 7682 } 7683 return; 7684 } 7685 7686 /* 7687 * CPU-A CPU-B 7688 * 7689 * perf_event_disable_inatomic() 7690 * @pending_disable = 1; 7691 * irq_work_queue(); 7692 * 7693 * sched-out 7694 * @pending_disable = 0; 7695 * 7696 * sched-in 7697 * perf_event_disable_inatomic() 7698 * @pending_disable = 1; 7699 * irq_work_queue(); // FAILS 7700 * 7701 * irq_work_run() 7702 * perf_pending_disable() 7703 * 7704 * But the event runs on CPU-B and wants disabling there. 7705 */ 7706 irq_work_queue_on(&event->pending_disable_irq, cpu); 7707 } 7708 7709 static void perf_pending_disable(struct irq_work *entry) 7710 { 7711 struct perf_event *event = container_of(entry, struct perf_event, pending_disable_irq); 7712 int rctx; 7713 7714 /* 7715 * If we 'fail' here, that's OK, it means recursion is already disabled 7716 * and we won't recurse 'further'. 7717 */ 7718 rctx = perf_swevent_get_recursion_context(); 7719 __perf_pending_disable(event); 7720 if (rctx >= 0) 7721 perf_swevent_put_recursion_context(rctx); 7722 } 7723 7724 static void perf_pending_irq(struct irq_work *entry) 7725 { 7726 struct perf_event *event = container_of(entry, struct perf_event, pending_irq); 7727 int rctx; 7728 7729 /* 7730 * If we 'fail' here, that's OK, it means recursion is already disabled 7731 * and we won't recurse 'further'. 7732 */ 7733 rctx = perf_swevent_get_recursion_context(); 7734 7735 /* 7736 * The wakeup isn't bound to the context of the event -- it can happen 7737 * irrespective of where the event is. 7738 */ 7739 if (event->pending_wakeup) { 7740 event->pending_wakeup = 0; 7741 perf_event_wakeup(event); 7742 } 7743 7744 if (rctx >= 0) 7745 perf_swevent_put_recursion_context(rctx); 7746 } 7747 7748 static void perf_pending_task(struct callback_head *head) 7749 { 7750 struct perf_event *event = container_of(head, struct perf_event, pending_task); 7751 int rctx; 7752 7753 /* 7754 * If we 'fail' here, that's OK, it means recursion is already disabled 7755 * and we won't recurse 'further'. 7756 */ 7757 rctx = perf_swevent_get_recursion_context(); 7758 7759 if (event->pending_work) { 7760 event->pending_work = 0; 7761 perf_sigtrap(event); 7762 local_dec(&event->ctx->nr_no_switch_fast); 7763 } 7764 put_event(event); 7765 7766 if (rctx >= 0) 7767 perf_swevent_put_recursion_context(rctx); 7768 } 7769 7770 #ifdef CONFIG_GUEST_PERF_EVENTS 7771 struct perf_guest_info_callbacks __rcu *perf_guest_cbs; 7772 7773 DEFINE_STATIC_CALL_RET0(__perf_guest_state, *perf_guest_cbs->state); 7774 DEFINE_STATIC_CALL_RET0(__perf_guest_get_ip, *perf_guest_cbs->get_ip); 7775 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_intel_pt_intr, *perf_guest_cbs->handle_intel_pt_intr); 7776 DEFINE_STATIC_CALL_RET0(__perf_guest_handle_mediated_pmi, *perf_guest_cbs->handle_mediated_pmi); 7777 7778 void perf_register_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7779 { 7780 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs))) 7781 return; 7782 7783 rcu_assign_pointer(perf_guest_cbs, cbs); 7784 static_call_update(__perf_guest_state, cbs->state); 7785 static_call_update(__perf_guest_get_ip, cbs->get_ip); 7786 7787 /* Implementing ->handle_intel_pt_intr is optional. */ 7788 if (cbs->handle_intel_pt_intr) 7789 static_call_update(__perf_guest_handle_intel_pt_intr, 7790 cbs->handle_intel_pt_intr); 7791 7792 if (cbs->handle_mediated_pmi) 7793 static_call_update(__perf_guest_handle_mediated_pmi, 7794 cbs->handle_mediated_pmi); 7795 } 7796 EXPORT_SYMBOL_GPL(perf_register_guest_info_callbacks); 7797 7798 void perf_unregister_guest_info_callbacks(struct perf_guest_info_callbacks *cbs) 7799 { 7800 if (WARN_ON_ONCE(rcu_access_pointer(perf_guest_cbs) != cbs)) 7801 return; 7802 7803 rcu_assign_pointer(perf_guest_cbs, NULL); 7804 static_call_update(__perf_guest_state, (void *)&__static_call_return0); 7805 static_call_update(__perf_guest_get_ip, (void *)&__static_call_return0); 7806 static_call_update(__perf_guest_handle_intel_pt_intr, (void *)&__static_call_return0); 7807 static_call_update(__perf_guest_handle_mediated_pmi, (void *)&__static_call_return0); 7808 synchronize_rcu(); 7809 } 7810 EXPORT_SYMBOL_GPL(perf_unregister_guest_info_callbacks); 7811 #endif 7812 7813 static bool should_sample_guest(struct perf_event *event) 7814 { 7815 return !event->attr.exclude_guest && perf_guest_state(); 7816 } 7817 7818 unsigned long perf_misc_flags(struct perf_event *event, 7819 struct pt_regs *regs) 7820 { 7821 if (should_sample_guest(event)) 7822 return perf_arch_guest_misc_flags(regs); 7823 7824 return perf_arch_misc_flags(regs); 7825 } 7826 7827 unsigned long perf_instruction_pointer(struct perf_event *event, 7828 struct pt_regs *regs) 7829 { 7830 /* 7831 * Hardware skid can lead to a scenario where a PMI is 7832 * delivered after the CPU has already entered kernel mode. 7833 * In that case, user-space sampling must not expose kernel 7834 * register state. 7835 */ 7836 if (should_sample_guest(event)) { 7837 return event->attr.exclude_kernel && 7838 !(perf_guest_state() & PERF_GUEST_USER) ? 7839 0 : perf_guest_get_ip(); 7840 } 7841 7842 return event->attr.exclude_kernel && !user_mode(regs) ? 7843 0 : perf_arch_instruction_pointer(regs); 7844 } 7845 7846 u64 __weak perf_reg_value(struct pt_regs *regs, int idx) 7847 { 7848 return 0; 7849 } 7850 7851 int __weak perf_reg_validate(u64 mask, bool simd_enabled) 7852 { 7853 return mask ? -ENOSYS : 0; 7854 } 7855 7856 u64 __weak perf_reg_abi(struct task_struct *task) 7857 { 7858 return PERF_SAMPLE_REGS_ABI_NONE; 7859 } 7860 7861 void __weak perf_get_regs_user(struct perf_regs *regs_user, 7862 struct pt_regs *regs) 7863 { 7864 regs_user->regs = task_pt_regs(current); 7865 regs_user->abi = perf_reg_abi(current); 7866 } 7867 7868 #define word_for_each_set_bit(bit, val) \ 7869 for (unsigned long long __v = (val); \ 7870 __v && ((bit = __builtin_ctzll(__v)), 1); \ 7871 __v &= __v - 1) 7872 7873 static void 7874 perf_output_sample_regs(struct perf_output_handle *handle, 7875 struct pt_regs *regs, u64 mask) 7876 { 7877 int bit; 7878 7879 word_for_each_set_bit(bit, mask) { 7880 u64 val = perf_reg_value(regs, bit); 7881 perf_output_put(handle, val); 7882 } 7883 } 7884 7885 static void 7886 perf_output_sample_simd_regs(struct perf_output_handle *handle, 7887 struct perf_event *event, 7888 struct pt_regs *regs, 7889 u64 mask, u32 pred_mask) 7890 { 7891 u64 pred_qwords = event->attr.sample_simd_pred_reg_qwords; 7892 u64 vec_qwords = event->attr.sample_simd_vec_reg_qwords; 7893 u64 nr_vectors = hweight64(mask); 7894 u64 nr_pred = hweight32(pred_mask); 7895 int bit; 7896 7897 perf_output_put(handle, nr_vectors); 7898 perf_output_put(handle, vec_qwords); 7899 perf_output_put(handle, nr_pred); 7900 perf_output_put(handle, pred_qwords); 7901 7902 if (nr_vectors) { 7903 word_for_each_set_bit(bit, mask) { 7904 for (int i = 0; i < vec_qwords; i++) { 7905 u64 val = perf_simd_reg_value(regs, bit, 7906 i, false); 7907 perf_output_put(handle, val); 7908 } 7909 } 7910 } 7911 if (nr_pred) { 7912 word_for_each_set_bit(bit, pred_mask) { 7913 for (int i = 0; i < pred_qwords; i++) { 7914 u64 val = perf_simd_reg_value(regs, bit, 7915 i, true); 7916 perf_output_put(handle, val); 7917 } 7918 } 7919 } 7920 } 7921 7922 static void perf_sample_regs_user(struct perf_regs *regs_user, 7923 struct pt_regs *regs) 7924 { 7925 if (user_mode(regs)) { 7926 regs_user->abi = perf_reg_abi(current); 7927 regs_user->regs = regs; 7928 } else if (is_user_task(current)) { 7929 perf_get_regs_user(regs_user, regs); 7930 } else { 7931 regs_user->abi = PERF_SAMPLE_REGS_ABI_NONE; 7932 regs_user->regs = NULL; 7933 } 7934 } 7935 7936 static void perf_sample_regs_intr(struct perf_regs *regs_intr, 7937 struct pt_regs *regs, 7938 bool exclude_kernel) 7939 { 7940 /* 7941 * Hardware skid can lead to a scenario where a PMI is 7942 * delivered after the CPU has already entered kernel mode. 7943 * In that case, user-space sampling must not expose kernel 7944 * register state. 7945 */ 7946 if (exclude_kernel && !user_mode(regs)) { 7947 regs_intr->abi = PERF_SAMPLE_REGS_ABI_NONE; 7948 regs_intr->regs = NULL; 7949 } else { 7950 regs_intr->regs = regs; 7951 regs_intr->abi = perf_reg_abi(current); 7952 } 7953 } 7954 7955 int __weak perf_simd_reg_validate(u16 vec_qwords, u64 vec_mask, 7956 u16 pred_qwords, u32 pred_mask) 7957 { 7958 return -EINVAL; 7959 } 7960 7961 u64 __weak perf_simd_reg_value(struct pt_regs *regs, int idx, 7962 u16 qwords_idx, bool pred) 7963 { 7964 return 0; 7965 } 7966 7967 /* 7968 * Get remaining task size from user stack pointer. 7969 * 7970 * It'd be better to take stack vma map and limit this more 7971 * precisely, but there's no way to get it safely under interrupt, 7972 * so using TASK_SIZE as limit. 7973 */ 7974 static u64 perf_ustack_task_size(struct pt_regs *regs) 7975 { 7976 unsigned long addr = perf_user_stack_pointer(regs); 7977 7978 if (!addr || addr >= TASK_SIZE) 7979 return 0; 7980 7981 return TASK_SIZE - addr; 7982 } 7983 7984 static u16 7985 perf_sample_ustack_size(u16 stack_size, u16 header_size, 7986 struct pt_regs *regs) 7987 { 7988 u64 task_size; 7989 7990 /* No regs, no stack pointer, no dump. */ 7991 if (!regs) 7992 return 0; 7993 7994 /* No mm, no stack, no dump. */ 7995 if (!current->mm) 7996 return 0; 7997 7998 /* 7999 * Check if we fit in with the requested stack size into the: 8000 * - TASK_SIZE 8001 * If we don't, we limit the size to the TASK_SIZE. 8002 * 8003 * - remaining sample size 8004 * If we don't, we customize the stack size to 8005 * fit in to the remaining sample size. 8006 */ 8007 8008 task_size = min((u64) USHRT_MAX, perf_ustack_task_size(regs)); 8009 stack_size = min(stack_size, (u16) task_size); 8010 8011 /* Current header size plus static size and dynamic size. */ 8012 header_size += 2 * sizeof(u64); 8013 8014 /* Do we fit in with the current stack dump size? */ 8015 if ((u16) (header_size + stack_size) < header_size) { 8016 /* 8017 * If we overflow the maximum size for the sample, 8018 * we customize the stack dump size to fit in. 8019 */ 8020 stack_size = USHRT_MAX - header_size - sizeof(u64); 8021 stack_size = round_up(stack_size, sizeof(u64)); 8022 } 8023 8024 return stack_size; 8025 } 8026 8027 static void 8028 perf_output_sample_ustack(struct perf_output_handle *handle, u64 dump_size, 8029 struct pt_regs *regs) 8030 { 8031 /* Case of a kernel thread, nothing to dump */ 8032 if (!regs) { 8033 u64 size = 0; 8034 perf_output_put(handle, size); 8035 } else { 8036 unsigned long sp; 8037 unsigned int rem; 8038 u64 dyn_size; 8039 8040 /* 8041 * We dump: 8042 * static size 8043 * - the size requested by user or the best one we can fit 8044 * in to the sample max size 8045 * data 8046 * - user stack dump data 8047 * dynamic size 8048 * - the actual dumped size 8049 */ 8050 8051 /* Static size. */ 8052 perf_output_put(handle, dump_size); 8053 8054 /* Data. */ 8055 sp = perf_user_stack_pointer(regs); 8056 rem = __output_copy_user(handle, (void *) sp, dump_size); 8057 dyn_size = dump_size - rem; 8058 8059 perf_output_skip(handle, rem); 8060 8061 /* Dynamic size. */ 8062 perf_output_put(handle, dyn_size); 8063 } 8064 } 8065 8066 static unsigned long perf_prepare_sample_aux(struct perf_event *event, 8067 struct perf_sample_data *data, 8068 size_t size) 8069 { 8070 struct perf_event *sampler = event->aux_event; 8071 struct perf_buffer *rb; 8072 8073 data->aux_size = 0; 8074 8075 if (!sampler) 8076 goto out; 8077 8078 if (WARN_ON_ONCE(READ_ONCE(sampler->state) != PERF_EVENT_STATE_ACTIVE)) 8079 goto out; 8080 8081 if (WARN_ON_ONCE(READ_ONCE(sampler->oncpu) != smp_processor_id())) 8082 goto out; 8083 8084 rb = ring_buffer_get(sampler); 8085 if (!rb) 8086 goto out; 8087 8088 /* 8089 * If this is an NMI hit inside sampling code, don't take 8090 * the sample. See also perf_aux_sample_output(). 8091 */ 8092 if (READ_ONCE(rb->aux_in_sampling)) { 8093 data->aux_size = 0; 8094 } else { 8095 size = min_t(size_t, size, perf_aux_size(rb)); 8096 data->aux_size = ALIGN(size, sizeof(u64)); 8097 } 8098 ring_buffer_put(rb); 8099 8100 out: 8101 return data->aux_size; 8102 } 8103 8104 static long perf_pmu_snapshot_aux(struct perf_buffer *rb, 8105 struct perf_event *event, 8106 struct perf_output_handle *handle, 8107 unsigned long size) 8108 { 8109 unsigned long flags; 8110 long ret; 8111 8112 /* 8113 * Normal ->start()/->stop() callbacks run in IRQ mode in scheduler 8114 * paths. If we start calling them in NMI context, they may race with 8115 * the IRQ ones, that is, for example, re-starting an event that's just 8116 * been stopped, which is why we're using a separate callback that 8117 * doesn't change the event state. 8118 * 8119 * IRQs need to be disabled to prevent IPIs from racing with us. 8120 */ 8121 local_irq_save(flags); 8122 /* 8123 * Guard against NMI hits inside the critical section; 8124 * see also perf_prepare_sample_aux(). 8125 */ 8126 WRITE_ONCE(rb->aux_in_sampling, 1); 8127 barrier(); 8128 8129 ret = event->pmu->snapshot_aux(event, handle, size); 8130 8131 barrier(); 8132 WRITE_ONCE(rb->aux_in_sampling, 0); 8133 local_irq_restore(flags); 8134 8135 return ret; 8136 } 8137 8138 static void perf_aux_sample_output(struct perf_event *event, 8139 struct perf_output_handle *handle, 8140 struct perf_sample_data *data) 8141 { 8142 struct perf_event *sampler = event->aux_event; 8143 struct perf_buffer *rb; 8144 unsigned long pad; 8145 long size; 8146 8147 if (WARN_ON_ONCE(!sampler || !data->aux_size)) 8148 return; 8149 8150 rb = ring_buffer_get(sampler); 8151 if (!rb) 8152 return; 8153 8154 size = perf_pmu_snapshot_aux(rb, sampler, handle, data->aux_size); 8155 8156 /* 8157 * An error here means that perf_output_copy() failed (returned a 8158 * non-zero surplus that it didn't copy), which in its current 8159 * enlightened implementation is not possible. If that changes, we'd 8160 * like to know. 8161 */ 8162 if (WARN_ON_ONCE(size < 0)) 8163 goto out_put; 8164 8165 /* 8166 * The pad comes from ALIGN()ing data->aux_size up to u64 in 8167 * perf_prepare_sample_aux(), so should not be more than that. 8168 */ 8169 pad = data->aux_size - size; 8170 if (WARN_ON_ONCE(pad >= sizeof(u64))) 8171 pad = 8; 8172 8173 if (pad) { 8174 u64 zero = 0; 8175 perf_output_copy(handle, &zero, pad); 8176 } 8177 8178 out_put: 8179 ring_buffer_put(rb); 8180 } 8181 8182 /* 8183 * A set of common sample data types saved even for non-sample records 8184 * when event->attr.sample_id_all is set. 8185 */ 8186 #define PERF_SAMPLE_ID_ALL (PERF_SAMPLE_TID | PERF_SAMPLE_TIME | \ 8187 PERF_SAMPLE_ID | PERF_SAMPLE_STREAM_ID | \ 8188 PERF_SAMPLE_CPU | PERF_SAMPLE_IDENTIFIER) 8189 8190 static void __perf_event_header__init_id(struct perf_sample_data *data, 8191 struct perf_event *event, 8192 u64 sample_type) 8193 { 8194 data->type = event->attr.sample_type; 8195 data->sample_flags |= data->type & PERF_SAMPLE_ID_ALL; 8196 8197 if (sample_type & PERF_SAMPLE_TID) { 8198 /* namespace issues */ 8199 data->tid_entry.pid = perf_event_pid(event, current); 8200 data->tid_entry.tid = perf_event_tid(event, current); 8201 } 8202 8203 if (sample_type & PERF_SAMPLE_TIME) 8204 data->time = perf_event_clock(event); 8205 8206 if (sample_type & (PERF_SAMPLE_ID | PERF_SAMPLE_IDENTIFIER)) 8207 data->id = primary_event_id(event); 8208 8209 if (sample_type & PERF_SAMPLE_STREAM_ID) 8210 data->stream_id = event->id; 8211 8212 if (sample_type & PERF_SAMPLE_CPU) { 8213 data->cpu_entry.cpu = raw_smp_processor_id(); 8214 data->cpu_entry.reserved = 0; 8215 } 8216 } 8217 8218 void perf_event_header__init(struct perf_event_header *header, 8219 struct perf_sample_data *data, 8220 u32 type, u16 misc, u16 size, 8221 struct perf_event *event) 8222 { 8223 header->type = type; 8224 header->misc = misc; 8225 header->size = size; 8226 8227 if (event->attr.sample_id_all) { 8228 header->size += event->id_header_size; 8229 __perf_event_header__init_id(data, event, event->attr.sample_type); 8230 } 8231 } 8232 8233 static void __perf_event__output_id_sample(struct perf_output_handle *handle, 8234 struct perf_sample_data *data) 8235 { 8236 u64 sample_type = data->type; 8237 8238 if (sample_type & PERF_SAMPLE_TID) 8239 perf_output_put(handle, data->tid_entry); 8240 8241 if (sample_type & PERF_SAMPLE_TIME) 8242 perf_output_put(handle, data->time); 8243 8244 if (sample_type & PERF_SAMPLE_ID) 8245 perf_output_put(handle, data->id); 8246 8247 if (sample_type & PERF_SAMPLE_STREAM_ID) 8248 perf_output_put(handle, data->stream_id); 8249 8250 if (sample_type & PERF_SAMPLE_CPU) 8251 perf_output_put(handle, data->cpu_entry); 8252 8253 if (sample_type & PERF_SAMPLE_IDENTIFIER) 8254 perf_output_put(handle, data->id); 8255 } 8256 8257 void perf_event__output_id_sample(struct perf_event *event, 8258 struct perf_output_handle *handle, 8259 struct perf_sample_data *sample) 8260 { 8261 if (event->attr.sample_id_all) 8262 __perf_event__output_id_sample(handle, sample); 8263 } 8264 8265 static void perf_output_read_one(struct perf_output_handle *handle, 8266 struct perf_event *event, 8267 u64 enabled, u64 running) 8268 { 8269 u64 read_format = event->attr.read_format; 8270 u64 values[5]; 8271 int n = 0; 8272 8273 values[n++] = perf_event_count(event, has_inherit_and_sample_read(&event->attr)); 8274 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) { 8275 values[n++] = enabled + 8276 atomic64_read(&event->child_total_time_enabled); 8277 } 8278 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) { 8279 values[n++] = running + 8280 atomic64_read(&event->child_total_time_running); 8281 } 8282 if (read_format & PERF_FORMAT_ID) 8283 values[n++] = primary_event_id(event); 8284 if (read_format & PERF_FORMAT_LOST) 8285 values[n++] = atomic64_read(&event->lost_samples); 8286 8287 __output_copy(handle, values, n * sizeof(u64)); 8288 } 8289 8290 static void perf_output_read_group(struct perf_output_handle *handle, 8291 struct perf_event *event, 8292 u64 enabled, u64 running) 8293 { 8294 struct perf_event *leader = event->group_leader, *sub; 8295 u64 read_format = event->attr.read_format; 8296 unsigned long flags; 8297 u64 values[6]; 8298 int n = 0; 8299 bool self = has_inherit_and_sample_read(&event->attr); 8300 8301 /* 8302 * Disabling interrupts avoids all counter scheduling 8303 * (context switches, timer based rotation and IPIs). 8304 */ 8305 local_irq_save(flags); 8306 8307 values[n++] = 1 + leader->nr_siblings; 8308 8309 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) 8310 values[n++] = enabled; 8311 8312 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) 8313 values[n++] = running; 8314 8315 if ((leader != event) && !handle->skip_read) 8316 perf_pmu_read(leader); 8317 8318 values[n++] = perf_event_count(leader, self); 8319 if (read_format & PERF_FORMAT_ID) 8320 values[n++] = primary_event_id(leader); 8321 if (read_format & PERF_FORMAT_LOST) 8322 values[n++] = atomic64_read(&leader->lost_samples); 8323 8324 __output_copy(handle, values, n * sizeof(u64)); 8325 8326 for_each_sibling_event(sub, leader) { 8327 n = 0; 8328 8329 if ((sub != event) && !handle->skip_read) 8330 perf_pmu_read(sub); 8331 8332 values[n++] = perf_event_count(sub, self); 8333 if (read_format & PERF_FORMAT_ID) 8334 values[n++] = primary_event_id(sub); 8335 if (read_format & PERF_FORMAT_LOST) 8336 values[n++] = atomic64_read(&sub->lost_samples); 8337 8338 __output_copy(handle, values, n * sizeof(u64)); 8339 } 8340 8341 local_irq_restore(flags); 8342 } 8343 8344 #define PERF_FORMAT_TOTAL_TIMES (PERF_FORMAT_TOTAL_TIME_ENABLED|\ 8345 PERF_FORMAT_TOTAL_TIME_RUNNING) 8346 8347 /* 8348 * XXX PERF_SAMPLE_READ vs inherited events seems difficult. 8349 * 8350 * The problem is that its both hard and excessively expensive to iterate the 8351 * child list, not to mention that its impossible to IPI the children running 8352 * on another CPU, from interrupt/NMI context. 8353 * 8354 * Instead the combination of PERF_SAMPLE_READ and inherit will track per-thread 8355 * counts rather than attempting to accumulate some value across all children on 8356 * all cores. 8357 */ 8358 static void perf_output_read(struct perf_output_handle *handle, 8359 struct perf_event *event) 8360 { 8361 u64 enabled = 0, running = 0, now; 8362 u64 read_format = event->attr.read_format; 8363 8364 /* 8365 * Compute total_time_enabled, total_time_running based on snapshot 8366 * values taken when the event was last scheduled in. 8367 * 8368 * We cannot simply call update_context_time() because doing so would 8369 * lead to deadlock when called from NMI context. 8370 */ 8371 if (read_format & PERF_FORMAT_TOTAL_TIMES) 8372 calc_timer_values(event, &now, &enabled, &running); 8373 8374 if (event->attr.read_format & PERF_FORMAT_GROUP) 8375 perf_output_read_group(handle, event, enabled, running); 8376 else 8377 perf_output_read_one(handle, event, enabled, running); 8378 } 8379 8380 void perf_output_sample(struct perf_output_handle *handle, 8381 struct perf_event_header *header, 8382 struct perf_sample_data *data, 8383 struct perf_event *event) 8384 { 8385 u64 sample_type = data->type; 8386 8387 if (data->sample_flags & PERF_SAMPLE_READ) 8388 handle->skip_read = 1; 8389 8390 perf_output_put(handle, *header); 8391 8392 if (sample_type & PERF_SAMPLE_IDENTIFIER) 8393 perf_output_put(handle, data->id); 8394 8395 if (sample_type & PERF_SAMPLE_IP) 8396 perf_output_put(handle, data->ip); 8397 8398 if (sample_type & PERF_SAMPLE_TID) 8399 perf_output_put(handle, data->tid_entry); 8400 8401 if (sample_type & PERF_SAMPLE_TIME) 8402 perf_output_put(handle, data->time); 8403 8404 if (sample_type & PERF_SAMPLE_ADDR) 8405 perf_output_put(handle, data->addr); 8406 8407 if (sample_type & PERF_SAMPLE_ID) 8408 perf_output_put(handle, data->id); 8409 8410 if (sample_type & PERF_SAMPLE_STREAM_ID) 8411 perf_output_put(handle, data->stream_id); 8412 8413 if (sample_type & PERF_SAMPLE_CPU) 8414 perf_output_put(handle, data->cpu_entry); 8415 8416 if (sample_type & PERF_SAMPLE_PERIOD) 8417 perf_output_put(handle, data->period); 8418 8419 if (sample_type & PERF_SAMPLE_READ) 8420 perf_output_read(handle, event); 8421 8422 if (sample_type & PERF_SAMPLE_CALLCHAIN) { 8423 int size = 1; 8424 8425 size += data->callchain->nr; 8426 size *= sizeof(u64); 8427 __output_copy(handle, data->callchain, size); 8428 } 8429 8430 if (sample_type & PERF_SAMPLE_RAW) { 8431 struct perf_raw_record *raw = data->raw; 8432 8433 if (raw) { 8434 struct perf_raw_frag *frag = &raw->frag; 8435 8436 perf_output_put(handle, raw->size); 8437 do { 8438 if (frag->copy) { 8439 __output_custom(handle, frag->copy, 8440 frag->data, frag->size); 8441 } else { 8442 __output_copy(handle, frag->data, 8443 frag->size); 8444 } 8445 if (perf_raw_frag_last(frag)) 8446 break; 8447 frag = frag->next; 8448 } while (1); 8449 if (frag->pad) 8450 __output_skip(handle, NULL, frag->pad); 8451 } else { 8452 struct { 8453 u32 size; 8454 u32 data; 8455 } raw = { 8456 .size = sizeof(u32), 8457 .data = 0, 8458 }; 8459 perf_output_put(handle, raw); 8460 } 8461 } 8462 8463 if (sample_type & PERF_SAMPLE_BRANCH_STACK) { 8464 if (data->br_stack) { 8465 size_t size; 8466 8467 size = data->br_stack->nr 8468 * sizeof(struct perf_branch_entry); 8469 8470 perf_output_put(handle, data->br_stack->nr); 8471 if (branch_sample_hw_index(event)) 8472 perf_output_put(handle, data->br_stack->hw_idx); 8473 perf_output_copy(handle, data->br_stack->entries, size); 8474 /* 8475 * Add the extension space which is appended 8476 * right after the struct perf_branch_stack. 8477 */ 8478 if (data->br_stack_cntr) { 8479 size = data->br_stack->nr * sizeof(u64); 8480 perf_output_copy(handle, data->br_stack_cntr, size); 8481 } 8482 } else { 8483 /* 8484 * we always store at least the value of nr 8485 */ 8486 u64 nr = 0; 8487 perf_output_put(handle, nr); 8488 } 8489 } 8490 8491 if (sample_type & PERF_SAMPLE_REGS_USER) { 8492 u64 abi = data->regs_user.abi; 8493 8494 /* 8495 * If there are no regs to dump, notice it through 8496 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 8497 */ 8498 perf_output_put(handle, abi); 8499 8500 if (abi) { 8501 struct perf_event_attr *attr = &event->attr; 8502 u64 mask = attr->sample_regs_user; 8503 perf_output_sample_regs(handle, 8504 data->regs_user.regs, 8505 mask); 8506 if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { 8507 perf_output_sample_simd_regs(handle, event, 8508 data->regs_user.regs, 8509 attr->sample_simd_vec_reg_user, 8510 attr->sample_simd_pred_reg_user); 8511 } 8512 } 8513 } 8514 8515 if (sample_type & PERF_SAMPLE_STACK_USER) { 8516 perf_output_sample_ustack(handle, 8517 data->stack_user_size, 8518 data->regs_user.regs); 8519 } 8520 8521 if (sample_type & PERF_SAMPLE_WEIGHT_TYPE) 8522 perf_output_put(handle, data->weight.full); 8523 8524 if (sample_type & PERF_SAMPLE_DATA_SRC) 8525 perf_output_put(handle, data->data_src.val); 8526 8527 if (sample_type & PERF_SAMPLE_TRANSACTION) 8528 perf_output_put(handle, data->txn); 8529 8530 if (sample_type & PERF_SAMPLE_REGS_INTR) { 8531 u64 abi = data->regs_intr.abi; 8532 /* 8533 * If there are no regs to dump, notice it through 8534 * first u64 being zero (PERF_SAMPLE_REGS_ABI_NONE). 8535 */ 8536 perf_output_put(handle, abi); 8537 8538 if (abi) { 8539 struct perf_event_attr *attr = &event->attr; 8540 u64 mask = attr->sample_regs_intr; 8541 8542 perf_output_sample_regs(handle, 8543 data->regs_intr.regs, 8544 mask); 8545 if (abi & PERF_SAMPLE_REGS_ABI_SIMD) { 8546 perf_output_sample_simd_regs(handle, event, 8547 data->regs_intr.regs, 8548 attr->sample_simd_vec_reg_intr, 8549 attr->sample_simd_pred_reg_intr); 8550 } 8551 } 8552 } 8553 8554 if (sample_type & PERF_SAMPLE_PHYS_ADDR) 8555 perf_output_put(handle, data->phys_addr); 8556 8557 if (sample_type & PERF_SAMPLE_CGROUP) 8558 perf_output_put(handle, data->cgroup); 8559 8560 if (sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) 8561 perf_output_put(handle, data->data_page_size); 8562 8563 if (sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) 8564 perf_output_put(handle, data->code_page_size); 8565 8566 if (sample_type & PERF_SAMPLE_AUX) { 8567 perf_output_put(handle, data->aux_size); 8568 8569 if (data->aux_size) 8570 perf_aux_sample_output(event, handle, data); 8571 } 8572 8573 if (!event->attr.watermark) { 8574 int wakeup_events = event->attr.wakeup_events; 8575 8576 if (wakeup_events) { 8577 struct perf_buffer *rb = handle->rb; 8578 int events = local_inc_return(&rb->events); 8579 8580 if (events >= wakeup_events) { 8581 local_sub(wakeup_events, &rb->events); 8582 local_inc(&rb->wakeup); 8583 } 8584 } 8585 } 8586 } 8587 8588 static u64 perf_virt_to_phys(u64 virt) 8589 { 8590 u64 phys_addr = 0; 8591 8592 if (!virt) 8593 return 0; 8594 8595 if (virt >= TASK_SIZE) { 8596 /* If it's vmalloc()d memory, leave phys_addr as 0 */ 8597 if (virt_addr_valid((void *)(uintptr_t)virt) && 8598 !(virt >= VMALLOC_START && virt < VMALLOC_END)) 8599 phys_addr = (u64)virt_to_phys((void *)(uintptr_t)virt); 8600 } else { 8601 /* 8602 * Walking the pages tables for user address. 8603 * Interrupts are disabled, so it prevents any tear down 8604 * of the page tables. 8605 * Try IRQ-safe get_user_page_fast_only first. 8606 * If failed, leave phys_addr as 0. 8607 */ 8608 if (is_user_task(current)) { 8609 struct page *p; 8610 8611 pagefault_disable(); 8612 if (get_user_page_fast_only(virt, 0, &p)) { 8613 phys_addr = page_to_phys(p) + virt % PAGE_SIZE; 8614 put_page(p); 8615 } 8616 pagefault_enable(); 8617 } 8618 } 8619 8620 return phys_addr; 8621 } 8622 8623 /* 8624 * Return the pagetable size of a given virtual address. 8625 */ 8626 static u64 perf_get_pgtable_size(struct mm_struct *mm, unsigned long addr) 8627 { 8628 u64 size = 0; 8629 8630 #ifdef CONFIG_HAVE_GUP_FAST 8631 pgd_t *pgdp, pgd; 8632 p4d_t *p4dp, p4d; 8633 pud_t *pudp, pud; 8634 pmd_t *pmdp, pmd; 8635 pte_t *ptep, pte; 8636 8637 pgdp = pgd_offset(mm, addr); 8638 pgd = pgdp_get(pgdp); 8639 if (pgd_none(pgd)) 8640 return 0; 8641 8642 if (pgd_leaf(pgd)) 8643 return pgd_leaf_size(pgd); 8644 8645 p4dp = p4d_offset_lockless(pgdp, pgd, addr); 8646 p4d = p4dp_get(p4dp); 8647 if (!p4d_present(p4d)) 8648 return 0; 8649 8650 if (p4d_leaf(p4d)) 8651 return p4d_leaf_size(p4d); 8652 8653 pudp = pud_offset_lockless(p4dp, p4d, addr); 8654 pud = pudp_get(pudp); 8655 if (!pud_present(pud)) 8656 return 0; 8657 8658 if (pud_leaf(pud)) 8659 return pud_leaf_size(pud); 8660 8661 pmdp = pmd_offset_lockless(pudp, pud, addr); 8662 again: 8663 pmd = pmdp_get_lockless(pmdp); 8664 if (!pmd_present(pmd)) 8665 return 0; 8666 8667 if (pmd_leaf(pmd)) 8668 return pmd_leaf_size(pmd); 8669 8670 ptep = pte_offset_map(&pmd, addr); 8671 if (!ptep) 8672 goto again; 8673 8674 pte = ptep_get_lockless(ptep); 8675 if (pte_present(pte)) 8676 size = __pte_leaf_size(pmd, pte); 8677 pte_unmap(ptep); 8678 #endif /* CONFIG_HAVE_GUP_FAST */ 8679 8680 return size; 8681 } 8682 8683 static u64 perf_get_page_size(unsigned long addr) 8684 { 8685 struct mm_struct *mm; 8686 unsigned long flags; 8687 u64 size; 8688 8689 if (!addr) 8690 return 0; 8691 8692 /* 8693 * Software page-table walkers must disable IRQs, 8694 * which prevents any tear down of the page tables. 8695 */ 8696 local_irq_save(flags); 8697 8698 mm = current->mm; 8699 if (!mm) { 8700 /* 8701 * For kernel threads and the like, use init_mm so that 8702 * we can find kernel memory. 8703 */ 8704 mm = &init_mm; 8705 } 8706 8707 size = perf_get_pgtable_size(mm, addr); 8708 8709 local_irq_restore(flags); 8710 8711 return size; 8712 } 8713 8714 static struct perf_callchain_entry __empty_callchain = { .nr = 0, }; 8715 8716 static struct unwind_work perf_unwind_work; 8717 8718 struct perf_callchain_entry * 8719 perf_callchain(struct perf_event *event, struct pt_regs *regs) 8720 { 8721 bool kernel = !event->attr.exclude_callchain_kernel; 8722 bool user = !event->attr.exclude_callchain_user && 8723 is_user_task(current); 8724 /* Disallow cross-task user callchains. */ 8725 bool crosstask = event->ctx->task && event->ctx->task != current; 8726 bool defer_user = IS_ENABLED(CONFIG_UNWIND_USER) && user && 8727 event->attr.defer_callchain; 8728 const u32 max_stack = event->attr.sample_max_stack; 8729 struct perf_callchain_entry *callchain; 8730 u64 defer_cookie; 8731 8732 if (!current->mm) 8733 user = false; 8734 8735 if (!kernel && !user) 8736 return &__empty_callchain; 8737 8738 if (!(user && defer_user && !crosstask && 8739 unwind_deferred_request(&perf_unwind_work, &defer_cookie) >= 0)) 8740 defer_cookie = 0; 8741 8742 callchain = get_perf_callchain(regs, kernel, user, max_stack, 8743 crosstask, true, defer_cookie); 8744 8745 return callchain ?: &__empty_callchain; 8746 } 8747 8748 static __always_inline u64 __cond_set(u64 flags, u64 s, u64 d) 8749 { 8750 return d * !!(flags & s); 8751 } 8752 8753 u64 perf_update_xregs_size(struct perf_event *event, bool intr) 8754 { 8755 u16 pred_qwords = event->attr.sample_simd_pred_reg_qwords; 8756 u16 vec_qwords = event->attr.sample_simd_vec_reg_qwords; 8757 u64 pred_mask; 8758 u64 mask; 8759 int size; 8760 8761 if (intr) { 8762 mask = event->attr.sample_simd_vec_reg_intr; 8763 pred_mask = event->attr.sample_simd_pred_reg_intr; 8764 } else { 8765 mask = event->attr.sample_simd_vec_reg_user; 8766 pred_mask = event->attr.sample_simd_pred_reg_user; 8767 } 8768 8769 size = sizeof(u64) * 4; 8770 size += (hweight64(mask) * vec_qwords + 8771 hweight64(pred_mask) * pred_qwords) * sizeof(u64); 8772 8773 return size; 8774 } 8775 8776 void perf_prepare_sample(struct perf_sample_data *data, 8777 struct perf_event *event, 8778 struct pt_regs *regs) 8779 { 8780 u64 sample_type = event->attr.sample_type; 8781 u64 filtered_sample_type; 8782 8783 /* 8784 * Add the sample flags that are dependent to others. And clear the 8785 * sample flags that have already been done by the PMU driver. 8786 */ 8787 filtered_sample_type = sample_type; 8788 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_CODE_PAGE_SIZE, 8789 PERF_SAMPLE_IP); 8790 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_DATA_PAGE_SIZE | 8791 PERF_SAMPLE_PHYS_ADDR, PERF_SAMPLE_ADDR); 8792 filtered_sample_type |= __cond_set(sample_type, PERF_SAMPLE_STACK_USER, 8793 PERF_SAMPLE_REGS_USER); 8794 filtered_sample_type &= ~data->sample_flags; 8795 8796 if (filtered_sample_type == 0) { 8797 /* Make sure it has the correct data->type for output */ 8798 data->type = event->attr.sample_type; 8799 return; 8800 } 8801 8802 __perf_event_header__init_id(data, event, filtered_sample_type); 8803 8804 if (filtered_sample_type & PERF_SAMPLE_IP) { 8805 data->ip = perf_instruction_pointer(event, regs); 8806 data->sample_flags |= PERF_SAMPLE_IP; 8807 } 8808 8809 if (filtered_sample_type & PERF_SAMPLE_CALLCHAIN) 8810 perf_sample_save_callchain(data, event, regs); 8811 8812 if (filtered_sample_type & PERF_SAMPLE_RAW) { 8813 data->raw = NULL; 8814 data->dyn_size += sizeof(u64); 8815 data->sample_flags |= PERF_SAMPLE_RAW; 8816 } 8817 8818 if (filtered_sample_type & PERF_SAMPLE_BRANCH_STACK) { 8819 data->br_stack = NULL; 8820 data->dyn_size += sizeof(u64); 8821 data->sample_flags |= PERF_SAMPLE_BRANCH_STACK; 8822 } 8823 8824 if (filtered_sample_type & PERF_SAMPLE_REGS_USER) 8825 perf_sample_regs_user(&data->regs_user, regs); 8826 8827 /* 8828 * It cannot use the filtered_sample_type here as REGS_USER can be set 8829 * by STACK_USER (using __cond_set() above) and we don't want to update 8830 * the dyn_size if it's not requested by users. 8831 */ 8832 if ((sample_type & ~data->sample_flags) & PERF_SAMPLE_REGS_USER) { 8833 /* regs dump ABI info */ 8834 int size = sizeof(u64); 8835 8836 if (data->regs_user.regs) { 8837 u64 mask = event->attr.sample_regs_user; 8838 8839 size += hweight64(mask) * sizeof(u64); 8840 if (event_has_simd_regs(event)) { 8841 size += perf_update_xregs_size(event, false); 8842 data->regs_user.abi |= PERF_SAMPLE_REGS_ABI_SIMD; 8843 } 8844 } 8845 8846 data->dyn_size += size; 8847 data->sample_flags |= PERF_SAMPLE_REGS_USER; 8848 } 8849 8850 if (filtered_sample_type & PERF_SAMPLE_STACK_USER) { 8851 /* 8852 * Either we need PERF_SAMPLE_STACK_USER bit to be always 8853 * processed as the last one or have additional check added 8854 * in case new sample type is added, because we could eat 8855 * up the rest of the sample size. 8856 */ 8857 u16 stack_size = event->attr.sample_stack_user; 8858 u16 header_size = perf_sample_data_size(data, event); 8859 u16 size = sizeof(u64); 8860 8861 stack_size = perf_sample_ustack_size(stack_size, header_size, 8862 data->regs_user.regs); 8863 8864 /* 8865 * If there is something to dump, add space for the dump 8866 * itself and for the field that tells the dynamic size, 8867 * which is how many have been actually dumped. 8868 */ 8869 if (stack_size) 8870 size += sizeof(u64) + stack_size; 8871 8872 data->stack_user_size = stack_size; 8873 data->dyn_size += size; 8874 data->sample_flags |= PERF_SAMPLE_STACK_USER; 8875 } 8876 8877 if (filtered_sample_type & PERF_SAMPLE_WEIGHT_TYPE) { 8878 data->weight.full = 0; 8879 data->sample_flags |= PERF_SAMPLE_WEIGHT_TYPE; 8880 } 8881 8882 if (filtered_sample_type & PERF_SAMPLE_DATA_SRC) { 8883 data->data_src.val = PERF_MEM_NA; 8884 data->sample_flags |= PERF_SAMPLE_DATA_SRC; 8885 } 8886 8887 if (filtered_sample_type & PERF_SAMPLE_TRANSACTION) { 8888 data->txn = 0; 8889 data->sample_flags |= PERF_SAMPLE_TRANSACTION; 8890 } 8891 8892 if (filtered_sample_type & PERF_SAMPLE_ADDR) { 8893 data->addr = 0; 8894 data->sample_flags |= PERF_SAMPLE_ADDR; 8895 } 8896 8897 if (filtered_sample_type & PERF_SAMPLE_REGS_INTR) { 8898 /* regs dump ABI info */ 8899 int size = sizeof(u64); 8900 8901 perf_sample_regs_intr(&data->regs_intr, regs, 8902 event->attr.exclude_kernel); 8903 8904 if (data->regs_intr.regs) { 8905 u64 mask = event->attr.sample_regs_intr; 8906 8907 size += hweight64(mask) * sizeof(u64); 8908 if (event_has_simd_regs(event)) { 8909 size += perf_update_xregs_size(event, true); 8910 data->regs_intr.abi |= PERF_SAMPLE_REGS_ABI_SIMD; 8911 } 8912 } 8913 8914 data->dyn_size += size; 8915 data->sample_flags |= PERF_SAMPLE_REGS_INTR; 8916 } 8917 8918 if (filtered_sample_type & PERF_SAMPLE_PHYS_ADDR) { 8919 data->phys_addr = perf_virt_to_phys(data->addr); 8920 data->sample_flags |= PERF_SAMPLE_PHYS_ADDR; 8921 } 8922 8923 #ifdef CONFIG_CGROUP_PERF 8924 if (filtered_sample_type & PERF_SAMPLE_CGROUP) { 8925 struct cgroup *cgrp; 8926 8927 /* protected by RCU */ 8928 cgrp = task_css_check(current, perf_event_cgrp_id, 1)->cgroup; 8929 data->cgroup = cgroup_id(cgrp); 8930 data->sample_flags |= PERF_SAMPLE_CGROUP; 8931 } 8932 #endif 8933 8934 /* 8935 * PERF_DATA_PAGE_SIZE requires PERF_SAMPLE_ADDR. If the user doesn't 8936 * require PERF_SAMPLE_ADDR, kernel implicitly retrieve the data->addr, 8937 * but the value will not dump to the userspace. 8938 */ 8939 if (filtered_sample_type & PERF_SAMPLE_DATA_PAGE_SIZE) { 8940 data->data_page_size = perf_get_page_size(data->addr); 8941 data->sample_flags |= PERF_SAMPLE_DATA_PAGE_SIZE; 8942 } 8943 8944 if (filtered_sample_type & PERF_SAMPLE_CODE_PAGE_SIZE) { 8945 data->code_page_size = perf_get_page_size(data->ip); 8946 data->sample_flags |= PERF_SAMPLE_CODE_PAGE_SIZE; 8947 } 8948 8949 if (filtered_sample_type & PERF_SAMPLE_AUX) { 8950 u64 size; 8951 u16 header_size = perf_sample_data_size(data, event); 8952 8953 header_size += sizeof(u64); /* size */ 8954 8955 /* 8956 * Given the 16bit nature of header::size, an AUX sample can 8957 * easily overflow it, what with all the preceding sample bits. 8958 * Make sure this doesn't happen by using up to U16_MAX bytes 8959 * per sample in total (rounded down to 8 byte boundary). 8960 */ 8961 size = min_t(size_t, U16_MAX - header_size, 8962 event->attr.aux_sample_size); 8963 size = rounddown(size, 8); 8964 size = perf_prepare_sample_aux(event, data, size); 8965 8966 WARN_ON_ONCE(size + header_size > U16_MAX); 8967 data->dyn_size += size + sizeof(u64); /* size above */ 8968 data->sample_flags |= PERF_SAMPLE_AUX; 8969 } 8970 } 8971 8972 void perf_prepare_header(struct perf_event_header *header, 8973 struct perf_sample_data *data, 8974 struct perf_event *event, 8975 struct pt_regs *regs) 8976 { 8977 header->type = PERF_RECORD_SAMPLE; 8978 header->size = perf_sample_data_size(data, event); 8979 header->misc = perf_misc_flags(event, regs); 8980 8981 /* 8982 * If you're adding more sample types here, you likely need to do 8983 * something about the overflowing header::size, like repurpose the 8984 * lowest 3 bits of size, which should be always zero at the moment. 8985 * This raises a more important question, do we really need 512k sized 8986 * samples and why, so good argumentation is in order for whatever you 8987 * do here next. 8988 */ 8989 WARN_ON_ONCE(header->size & 7); 8990 } 8991 8992 static void __perf_event_aux_pause(struct perf_event *event, bool pause) 8993 { 8994 if (pause) { 8995 if (!event->hw.aux_paused) { 8996 event->hw.aux_paused = 1; 8997 event->pmu->stop(event, PERF_EF_PAUSE); 8998 } 8999 } else { 9000 if (event->hw.aux_paused) { 9001 event->hw.aux_paused = 0; 9002 event->pmu->start(event, PERF_EF_RESUME); 9003 } 9004 } 9005 } 9006 9007 static void perf_event_aux_pause(struct perf_event *event, bool pause) 9008 { 9009 struct perf_buffer *rb; 9010 9011 if (WARN_ON_ONCE(!event)) 9012 return; 9013 9014 rb = ring_buffer_get(event); 9015 if (!rb) 9016 return; 9017 9018 scoped_guard (irqsave) { 9019 /* 9020 * Guard against self-recursion here. Another event could trip 9021 * this same from NMI context. 9022 */ 9023 if (READ_ONCE(rb->aux_in_pause_resume)) 9024 break; 9025 9026 WRITE_ONCE(rb->aux_in_pause_resume, 1); 9027 barrier(); 9028 __perf_event_aux_pause(event, pause); 9029 barrier(); 9030 WRITE_ONCE(rb->aux_in_pause_resume, 0); 9031 } 9032 ring_buffer_put(rb); 9033 } 9034 9035 static __always_inline int 9036 __perf_event_output(struct perf_event *event, 9037 struct perf_sample_data *data, 9038 struct pt_regs *regs, 9039 int (*output_begin)(struct perf_output_handle *, 9040 struct perf_sample_data *, 9041 struct perf_event *, 9042 unsigned int)) 9043 { 9044 struct perf_output_handle handle; 9045 struct perf_event_header header; 9046 int err; 9047 9048 /* protect the callchain buffers */ 9049 rcu_read_lock(); 9050 9051 perf_prepare_sample(data, event, regs); 9052 perf_prepare_header(&header, data, event, regs); 9053 9054 err = output_begin(&handle, data, event, header.size); 9055 if (err) 9056 goto exit; 9057 9058 perf_output_sample(&handle, &header, data, event); 9059 9060 perf_output_end(&handle); 9061 9062 exit: 9063 rcu_read_unlock(); 9064 return err; 9065 } 9066 9067 void 9068 perf_event_output_forward(struct perf_event *event, 9069 struct perf_sample_data *data, 9070 struct pt_regs *regs) 9071 { 9072 __perf_event_output(event, data, regs, perf_output_begin_forward); 9073 } 9074 9075 void 9076 perf_event_output_backward(struct perf_event *event, 9077 struct perf_sample_data *data, 9078 struct pt_regs *regs) 9079 { 9080 __perf_event_output(event, data, regs, perf_output_begin_backward); 9081 } 9082 9083 int 9084 perf_event_output(struct perf_event *event, 9085 struct perf_sample_data *data, 9086 struct pt_regs *regs) 9087 { 9088 return __perf_event_output(event, data, regs, perf_output_begin); 9089 } 9090 9091 /* 9092 * read event_id 9093 */ 9094 9095 struct perf_read_event { 9096 struct perf_event_header header; 9097 9098 u32 pid; 9099 u32 tid; 9100 }; 9101 9102 static void 9103 perf_event_read_event(struct perf_event *event, 9104 struct task_struct *task) 9105 { 9106 struct perf_output_handle handle; 9107 struct perf_sample_data sample; 9108 struct perf_read_event read_event = { 9109 .pid = perf_event_pid(event, task), 9110 .tid = perf_event_tid(event, task), 9111 }; 9112 int ret; 9113 9114 perf_event_header__init(&read_event.header, &sample, 9115 PERF_RECORD_READ, 9116 /* misc= */ 0, 9117 sizeof(read_event) + event->read_size, 9118 event); 9119 ret = perf_output_begin(&handle, &sample, event, read_event.header.size); 9120 if (ret) 9121 return; 9122 9123 perf_output_put(&handle, read_event); 9124 perf_output_read(&handle, event); 9125 perf_event__output_id_sample(event, &handle, &sample); 9126 9127 perf_output_end(&handle); 9128 } 9129 9130 typedef void (perf_iterate_f)(struct perf_event *event, void *data); 9131 9132 static void 9133 perf_iterate_ctx(struct perf_event_context *ctx, 9134 perf_iterate_f output, 9135 void *data, bool all) 9136 { 9137 struct perf_event *event; 9138 9139 list_for_each_entry_rcu(event, &ctx->event_list, event_entry) { 9140 if (!all) { 9141 if (event->state < PERF_EVENT_STATE_INACTIVE) 9142 continue; 9143 if (!event_filter_match(event)) 9144 continue; 9145 } 9146 9147 output(event, data); 9148 } 9149 } 9150 9151 static void perf_iterate_sb_cpu(perf_iterate_f output, void *data) 9152 { 9153 struct pmu_event_list *pel = this_cpu_ptr(&pmu_sb_events); 9154 struct perf_event *event; 9155 9156 list_for_each_entry_rcu(event, &pel->list, sb_list) { 9157 /* 9158 * Skip events that are not fully formed yet; ensure that 9159 * if we observe event->ctx, both event and ctx will be 9160 * complete enough. See perf_install_in_context(). 9161 */ 9162 if (!smp_load_acquire(&event->ctx)) 9163 continue; 9164 9165 if (event->state < PERF_EVENT_STATE_INACTIVE) 9166 continue; 9167 if (!event_filter_match(event)) 9168 continue; 9169 output(event, data); 9170 } 9171 } 9172 9173 /* 9174 * Iterate all events that need to receive side-band events. 9175 * 9176 * For new callers; ensure that account_pmu_sb_event() includes 9177 * your event, otherwise it might not get delivered. 9178 */ 9179 static void 9180 perf_iterate_sb(perf_iterate_f output, void *data, 9181 struct perf_event_context *task_ctx) 9182 { 9183 struct perf_event_context *ctx; 9184 9185 rcu_read_lock(); 9186 preempt_disable(); 9187 9188 /* 9189 * If we have task_ctx != NULL we only notify the task context itself. 9190 * The task_ctx is set only for EXIT events before releasing task 9191 * context. 9192 */ 9193 if (task_ctx) { 9194 perf_iterate_ctx(task_ctx, output, data, false); 9195 goto done; 9196 } 9197 9198 perf_iterate_sb_cpu(output, data); 9199 9200 ctx = rcu_dereference(current->perf_event_ctxp); 9201 if (ctx) 9202 perf_iterate_ctx(ctx, output, data, false); 9203 done: 9204 preempt_enable(); 9205 rcu_read_unlock(); 9206 } 9207 9208 /* 9209 * Clear all file-based filters at exec, they'll have to be 9210 * re-instated when/if these objects are mmapped again. 9211 */ 9212 static void perf_event_addr_filters_exec(struct perf_event *event, void *data) 9213 { 9214 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 9215 struct perf_addr_filter *filter; 9216 unsigned int restart = 0, count = 0; 9217 unsigned long flags; 9218 9219 if (!has_addr_filter(event)) 9220 return; 9221 9222 raw_spin_lock_irqsave(&ifh->lock, flags); 9223 list_for_each_entry(filter, &ifh->list, entry) { 9224 if (filter->path.dentry) { 9225 event->addr_filter_ranges[count].start = 0; 9226 event->addr_filter_ranges[count].size = 0; 9227 restart++; 9228 } 9229 9230 count++; 9231 } 9232 9233 if (restart) 9234 event->addr_filters_gen++; 9235 raw_spin_unlock_irqrestore(&ifh->lock, flags); 9236 9237 if (restart) 9238 perf_event_stop(event, 1); 9239 } 9240 9241 void perf_event_exec(void) 9242 { 9243 struct perf_event_context *ctx; 9244 9245 ctx = perf_pin_task_context(current); 9246 if (!ctx) 9247 return; 9248 9249 perf_event_enable_on_exec(ctx); 9250 perf_event_remove_on_exec(ctx); 9251 scoped_guard(rcu) 9252 perf_iterate_ctx(ctx, perf_event_addr_filters_exec, NULL, true); 9253 9254 perf_unpin_context(ctx); 9255 put_ctx(ctx); 9256 } 9257 9258 struct remote_output { 9259 struct perf_buffer *rb; 9260 int err; 9261 }; 9262 9263 static void __perf_event_output_stop(struct perf_event *event, void *data) 9264 { 9265 struct perf_event *parent = event->parent; 9266 struct remote_output *ro = data; 9267 struct perf_buffer *rb = ro->rb; 9268 struct stop_event_data sd = { 9269 .event = event, 9270 }; 9271 9272 if (!has_aux(event)) 9273 return; 9274 9275 if (!parent) 9276 parent = event; 9277 9278 /* 9279 * In case of inheritance, it will be the parent that links to the 9280 * ring-buffer, but it will be the child that's actually using it. 9281 * 9282 * We are using event::rb to determine if the event should be stopped, 9283 * however this may race with ring_buffer_attach() (through set_output), 9284 * which will make us skip the event that actually needs to be stopped. 9285 * So ring_buffer_attach() has to stop an aux event before re-assigning 9286 * its rb pointer. 9287 */ 9288 if (rcu_dereference(parent->rb) == rb) 9289 ro->err = __perf_event_stop(&sd); 9290 } 9291 9292 static int __perf_pmu_output_stop(void *info) 9293 { 9294 struct perf_event *event = info; 9295 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 9296 struct remote_output ro = { 9297 .rb = event->rb, 9298 }; 9299 9300 rcu_read_lock(); 9301 perf_iterate_ctx(&cpuctx->ctx, __perf_event_output_stop, &ro, false); 9302 if (cpuctx->task_ctx) 9303 perf_iterate_ctx(cpuctx->task_ctx, __perf_event_output_stop, 9304 &ro, false); 9305 rcu_read_unlock(); 9306 9307 return ro.err; 9308 } 9309 9310 static void perf_pmu_output_stop(struct perf_event *event) 9311 { 9312 struct perf_event *iter; 9313 int err, cpu; 9314 9315 restart: 9316 rcu_read_lock(); 9317 list_for_each_entry_rcu(iter, &event->rb->event_list, rb_entry) { 9318 /* 9319 * For per-CPU events, we need to make sure that neither they 9320 * nor their children are running; for cpu==-1 events it's 9321 * sufficient to stop the event itself if it's active, since 9322 * it can't have children. 9323 */ 9324 cpu = iter->cpu; 9325 if (cpu == -1) 9326 cpu = READ_ONCE(iter->oncpu); 9327 9328 if (cpu == -1) 9329 continue; 9330 9331 err = cpu_function_call(cpu, __perf_pmu_output_stop, event); 9332 if (err == -EAGAIN) { 9333 rcu_read_unlock(); 9334 goto restart; 9335 } 9336 } 9337 rcu_read_unlock(); 9338 } 9339 9340 /* 9341 * task tracking -- fork/exit 9342 * 9343 * enabled by: attr.comm | attr.mmap | attr.mmap2 | attr.mmap_data | attr.task 9344 */ 9345 9346 struct perf_task_event { 9347 struct task_struct *task; 9348 struct perf_event_context *task_ctx; 9349 9350 struct { 9351 struct perf_event_header header; 9352 9353 u32 pid; 9354 u32 ppid; 9355 u32 tid; 9356 u32 ptid; 9357 u64 time; 9358 } event_id; 9359 int new; 9360 }; 9361 9362 static int perf_event_task_match(struct perf_event *event) 9363 { 9364 return event->attr.comm || event->attr.mmap || 9365 event->attr.mmap2 || event->attr.mmap_data || 9366 event->attr.task; 9367 } 9368 9369 static void perf_event_task_output(struct perf_event *event, 9370 void *data) 9371 { 9372 struct perf_task_event *task_event = data; 9373 struct perf_output_handle handle; 9374 struct perf_sample_data sample; 9375 struct task_struct *task = task_event->task; 9376 int ret; 9377 9378 if (!perf_event_task_match(event)) 9379 return; 9380 9381 perf_event_header__init(&task_event->event_id.header, &sample, 9382 task_event->new ? PERF_RECORD_FORK : PERF_RECORD_EXIT, 9383 /* misc= */ 0, 9384 sizeof(task_event->event_id), 9385 event); 9386 9387 ret = perf_output_begin(&handle, &sample, event, 9388 task_event->event_id.header.size); 9389 if (ret) 9390 return; 9391 9392 task_event->event_id.pid = perf_event_pid(event, task); 9393 task_event->event_id.tid = perf_event_tid(event, task); 9394 9395 if (task_event->event_id.header.type == PERF_RECORD_EXIT) { 9396 task_event->event_id.ppid = perf_event_pid(event, 9397 task->real_parent); 9398 task_event->event_id.ptid = perf_event_pid(event, 9399 task->real_parent); 9400 } else { /* PERF_RECORD_FORK */ 9401 task_event->event_id.ppid = perf_event_pid(event, current); 9402 task_event->event_id.ptid = perf_event_tid(event, current); 9403 } 9404 9405 task_event->event_id.time = perf_event_clock(event); 9406 9407 perf_output_put(&handle, task_event->event_id); 9408 9409 perf_event__output_id_sample(event, &handle, &sample); 9410 9411 perf_output_end(&handle); 9412 } 9413 9414 static void perf_event_task(struct task_struct *task, 9415 struct perf_event_context *task_ctx, 9416 int new) 9417 { 9418 struct perf_task_event task_event; 9419 9420 if (!atomic_read(&nr_comm_events) && 9421 !atomic_read(&nr_mmap_events) && 9422 !atomic_read(&nr_task_events)) 9423 return; 9424 9425 task_event = (struct perf_task_event){ 9426 .task = task, 9427 .task_ctx = task_ctx, 9428 .new = new, 9429 }; 9430 9431 perf_iterate_sb(perf_event_task_output, 9432 &task_event, 9433 task_ctx); 9434 } 9435 9436 /* 9437 * Allocate data for a new task when profiling system-wide 9438 * events which require PMU specific data 9439 */ 9440 static void 9441 perf_event_alloc_task_data(struct task_struct *child, 9442 struct task_struct *parent) 9443 { 9444 struct kmem_cache *ctx_cache = NULL; 9445 struct perf_ctx_data *cd; 9446 9447 if (!refcount_read(&global_ctx_data_ref)) 9448 return; 9449 9450 scoped_guard (rcu) { 9451 cd = rcu_dereference(parent->perf_ctx_data); 9452 if (cd) 9453 ctx_cache = cd->ctx_cache; 9454 } 9455 9456 if (!ctx_cache) 9457 return; 9458 9459 guard(percpu_read)(&global_ctx_data_rwsem); 9460 scoped_guard (rcu) { 9461 cd = rcu_dereference(child->perf_ctx_data); 9462 if (!cd) { 9463 /* 9464 * A system-wide event may be unaccount, 9465 * when attaching the perf_ctx_data. 9466 */ 9467 if (!refcount_read(&global_ctx_data_ref)) 9468 return; 9469 goto attach; 9470 } 9471 9472 if (!cd->global) { 9473 cd->global = 1; 9474 refcount_inc(&cd->refcount); 9475 } 9476 } 9477 9478 return; 9479 attach: 9480 attach_task_ctx_data(child, ctx_cache, true, GFP_KERNEL); 9481 } 9482 9483 void perf_event_fork(struct task_struct *task) 9484 { 9485 perf_event_task(task, NULL, 1); 9486 perf_event_namespaces(task); 9487 perf_event_alloc_task_data(task, current); 9488 } 9489 9490 /* 9491 * comm tracking 9492 */ 9493 9494 struct perf_comm_event { 9495 struct task_struct *task; 9496 char *comm; 9497 int comm_size; 9498 9499 struct { 9500 struct perf_event_header header; 9501 9502 u32 pid; 9503 u32 tid; 9504 } event_id; 9505 bool exec; 9506 }; 9507 9508 static int perf_event_comm_match(struct perf_event *event) 9509 { 9510 return event->attr.comm; 9511 } 9512 9513 static void perf_event_comm_output(struct perf_event *event, 9514 void *data) 9515 { 9516 struct perf_comm_event *comm_event = data; 9517 struct perf_output_handle handle; 9518 struct perf_sample_data sample; 9519 int ret; 9520 9521 if (!perf_event_comm_match(event)) 9522 return; 9523 9524 perf_event_header__init(&comm_event->event_id.header, &sample, 9525 PERF_RECORD_COMM, 9526 comm_event->exec ? PERF_RECORD_MISC_COMM_EXEC : 0, 9527 sizeof(comm_event->event_id) + comm_event->comm_size, 9528 event); 9529 ret = perf_output_begin(&handle, &sample, event, 9530 comm_event->event_id.header.size); 9531 9532 if (ret) 9533 return; 9534 9535 comm_event->event_id.pid = perf_event_pid(event, comm_event->task); 9536 comm_event->event_id.tid = perf_event_tid(event, comm_event->task); 9537 9538 perf_output_put(&handle, comm_event->event_id); 9539 __output_copy(&handle, comm_event->comm, 9540 comm_event->comm_size); 9541 9542 perf_event__output_id_sample(event, &handle, &sample); 9543 9544 perf_output_end(&handle); 9545 } 9546 9547 static void perf_event_comm_event(struct perf_comm_event *comm_event) 9548 { 9549 char comm[TASK_COMM_LEN]; 9550 unsigned int size; 9551 9552 memset(comm, 0, sizeof(comm)); 9553 strscpy(comm, comm_event->task->comm); 9554 size = ALIGN(strlen(comm)+1, sizeof(u64)); 9555 9556 comm_event->comm = comm; 9557 comm_event->comm_size = size; 9558 9559 perf_iterate_sb(perf_event_comm_output, 9560 comm_event, 9561 NULL); 9562 } 9563 9564 void perf_event_comm(struct task_struct *task, bool exec) 9565 { 9566 struct perf_comm_event comm_event; 9567 9568 if (!atomic_read(&nr_comm_events)) 9569 return; 9570 9571 comm_event = (struct perf_comm_event){ 9572 .task = task, 9573 /* .comm */ 9574 /* .comm_size */ 9575 /* .event_id */ 9576 .exec = exec, 9577 }; 9578 9579 perf_event_comm_event(&comm_event); 9580 } 9581 9582 /* 9583 * namespaces tracking 9584 */ 9585 9586 struct perf_namespaces_event { 9587 struct task_struct *task; 9588 9589 struct { 9590 struct perf_event_header header; 9591 9592 u32 pid; 9593 u32 tid; 9594 u64 nr_namespaces; 9595 struct perf_ns_link_info link_info[NR_NAMESPACES]; 9596 } event_id; 9597 }; 9598 9599 static int perf_event_namespaces_match(struct perf_event *event) 9600 { 9601 return event->attr.namespaces; 9602 } 9603 9604 static void perf_event_namespaces_output(struct perf_event *event, 9605 void *data) 9606 { 9607 struct perf_namespaces_event *namespaces_event = data; 9608 struct perf_output_handle handle; 9609 struct perf_sample_data sample; 9610 int ret; 9611 9612 if (!perf_event_namespaces_match(event)) 9613 return; 9614 9615 perf_event_header__init(&namespaces_event->event_id.header, &sample, 9616 PERF_RECORD_NAMESPACES, 9617 /* misc= */ 0, 9618 sizeof(namespaces_event->event_id), 9619 event); 9620 ret = perf_output_begin(&handle, &sample, event, 9621 namespaces_event->event_id.header.size); 9622 if (ret) 9623 return; 9624 9625 namespaces_event->event_id.pid = perf_event_pid(event, 9626 namespaces_event->task); 9627 namespaces_event->event_id.tid = perf_event_tid(event, 9628 namespaces_event->task); 9629 9630 perf_output_put(&handle, namespaces_event->event_id); 9631 9632 perf_event__output_id_sample(event, &handle, &sample); 9633 9634 perf_output_end(&handle); 9635 } 9636 9637 static void perf_fill_ns_link_info(struct perf_ns_link_info *ns_link_info, 9638 struct task_struct *task, 9639 const struct proc_ns_operations *ns_ops) 9640 { 9641 struct path ns_path; 9642 struct inode *ns_inode; 9643 int error; 9644 9645 error = ns_get_path(&ns_path, task, ns_ops); 9646 if (!error) { 9647 ns_inode = ns_path.dentry->d_inode; 9648 ns_link_info->dev = new_encode_dev(ns_inode->i_sb->s_dev); 9649 ns_link_info->ino = ns_inode->i_ino; 9650 path_put(&ns_path); 9651 } 9652 } 9653 9654 void perf_event_namespaces(struct task_struct *task) 9655 { 9656 struct perf_namespaces_event namespaces_event; 9657 struct perf_ns_link_info *ns_link_info; 9658 9659 if (!atomic_read(&nr_namespaces_events)) 9660 return; 9661 9662 namespaces_event = (struct perf_namespaces_event){ 9663 .task = task, 9664 .event_id = { 9665 /* .header */ 9666 /* .pid */ 9667 /* .tid */ 9668 .nr_namespaces = NR_NAMESPACES, 9669 /* .link_info[NR_NAMESPACES] */ 9670 }, 9671 }; 9672 9673 ns_link_info = namespaces_event.event_id.link_info; 9674 9675 perf_fill_ns_link_info(&ns_link_info[MNT_NS_INDEX], 9676 task, &mntns_operations); 9677 9678 #ifdef CONFIG_USER_NS 9679 perf_fill_ns_link_info(&ns_link_info[USER_NS_INDEX], 9680 task, &userns_operations); 9681 #endif 9682 #ifdef CONFIG_NET_NS 9683 perf_fill_ns_link_info(&ns_link_info[NET_NS_INDEX], 9684 task, &netns_operations); 9685 #endif 9686 #ifdef CONFIG_UTS_NS 9687 perf_fill_ns_link_info(&ns_link_info[UTS_NS_INDEX], 9688 task, &utsns_operations); 9689 #endif 9690 #ifdef CONFIG_IPC_NS 9691 perf_fill_ns_link_info(&ns_link_info[IPC_NS_INDEX], 9692 task, &ipcns_operations); 9693 #endif 9694 #ifdef CONFIG_PID_NS 9695 perf_fill_ns_link_info(&ns_link_info[PID_NS_INDEX], 9696 task, &pidns_operations); 9697 #endif 9698 #ifdef CONFIG_CGROUPS 9699 perf_fill_ns_link_info(&ns_link_info[CGROUP_NS_INDEX], 9700 task, &cgroupns_operations); 9701 #endif 9702 9703 perf_iterate_sb(perf_event_namespaces_output, 9704 &namespaces_event, 9705 NULL); 9706 } 9707 9708 /* 9709 * cgroup tracking 9710 */ 9711 #ifdef CONFIG_CGROUP_PERF 9712 9713 struct perf_cgroup_event { 9714 char *path; 9715 int path_size; 9716 struct { 9717 struct perf_event_header header; 9718 u64 id; 9719 char path[]; 9720 } event_id; 9721 }; 9722 9723 static int perf_event_cgroup_match(struct perf_event *event) 9724 { 9725 return event->attr.cgroup; 9726 } 9727 9728 static void perf_event_cgroup_output(struct perf_event *event, void *data) 9729 { 9730 struct perf_cgroup_event *cgroup_event = data; 9731 struct perf_output_handle handle; 9732 struct perf_sample_data sample; 9733 int ret; 9734 u16 size = sizeof(cgroup_event->event_id) + cgroup_event->path_size; 9735 9736 if (!perf_event_cgroup_match(event)) 9737 return; 9738 9739 perf_event_header__init(&cgroup_event->event_id.header, &sample, 9740 PERF_RECORD_CGROUP, /* misc= */ 0, size, 9741 event); 9742 ret = perf_output_begin(&handle, &sample, event, 9743 cgroup_event->event_id.header.size); 9744 if (ret) 9745 return; 9746 9747 perf_output_put(&handle, cgroup_event->event_id); 9748 __output_copy(&handle, cgroup_event->path, cgroup_event->path_size); 9749 9750 perf_event__output_id_sample(event, &handle, &sample); 9751 9752 perf_output_end(&handle); 9753 } 9754 9755 static void perf_event_cgroup(struct cgroup *cgrp) 9756 { 9757 struct perf_cgroup_event cgroup_event; 9758 char path_enomem[16] = "//enomem"; 9759 char *pathname; 9760 size_t size; 9761 9762 if (!atomic_read(&nr_cgroup_events)) 9763 return; 9764 9765 cgroup_event = (struct perf_cgroup_event){ 9766 .event_id = { 9767 .id = cgroup_id(cgrp), 9768 }, 9769 }; 9770 9771 pathname = kmalloc(PATH_MAX, GFP_KERNEL); 9772 if (pathname == NULL) { 9773 cgroup_event.path = path_enomem; 9774 } else { 9775 /* just to be sure to have enough space for alignment */ 9776 cgroup_path(cgrp, pathname, PATH_MAX - sizeof(u64)); 9777 cgroup_event.path = pathname; 9778 } 9779 9780 /* 9781 * Since our buffer works in 8 byte units we need to align our string 9782 * size to a multiple of 8. However, we must guarantee the tail end is 9783 * zero'd out to avoid leaking random bits to userspace. 9784 */ 9785 size = strlen(cgroup_event.path) + 1; 9786 while (!IS_ALIGNED(size, sizeof(u64))) 9787 cgroup_event.path[size++] = '\0'; 9788 9789 cgroup_event.path_size = size; 9790 9791 perf_iterate_sb(perf_event_cgroup_output, 9792 &cgroup_event, 9793 NULL); 9794 9795 kfree(pathname); 9796 } 9797 9798 #endif 9799 9800 /* 9801 * mmap tracking 9802 */ 9803 9804 struct perf_mmap_event { 9805 struct vm_area_struct *vma; 9806 9807 const char *file_name; 9808 int file_size; 9809 int maj, min; 9810 u64 ino; 9811 u64 ino_generation; 9812 u32 prot, flags; 9813 u8 build_id[BUILD_ID_SIZE_MAX]; 9814 u32 build_id_size; 9815 9816 struct { 9817 struct perf_event_header header; 9818 9819 u32 pid; 9820 u32 tid; 9821 u64 start; 9822 u64 len; 9823 u64 pgoff; 9824 } event_id; 9825 }; 9826 9827 static int perf_event_mmap_match(struct perf_event *event, 9828 void *data) 9829 { 9830 struct perf_mmap_event *mmap_event = data; 9831 struct vm_area_struct *vma = mmap_event->vma; 9832 int executable = vma->vm_flags & VM_EXEC; 9833 9834 return (!executable && event->attr.mmap_data) || 9835 (executable && (event->attr.mmap || event->attr.mmap2)); 9836 } 9837 9838 static void perf_event_mmap_output(struct perf_event *event, 9839 void *data) 9840 { 9841 struct perf_mmap_event *mmap_event = data; 9842 struct perf_output_handle handle; 9843 struct perf_sample_data sample; 9844 int size = sizeof(mmap_event->event_id) + mmap_event->file_size; 9845 u32 type = PERF_RECORD_MMAP; 9846 u16 misc = PERF_RECORD_MISC_USER; 9847 bool use_build_id = false; 9848 int ret; 9849 9850 if (!perf_event_mmap_match(event, data)) 9851 return; 9852 9853 if (event->attr.mmap2) { 9854 type = PERF_RECORD_MMAP2; 9855 size += sizeof(mmap_event->maj); 9856 size += sizeof(mmap_event->min); 9857 size += sizeof(mmap_event->ino); 9858 size += sizeof(mmap_event->ino_generation); 9859 size += sizeof(mmap_event->prot); 9860 size += sizeof(mmap_event->flags); 9861 use_build_id = event->attr.build_id && mmap_event->build_id_size; 9862 if (use_build_id) 9863 misc |= PERF_RECORD_MISC_MMAP_BUILD_ID; 9864 } 9865 if (!(mmap_event->vma->vm_flags & VM_EXEC)) 9866 misc |= PERF_RECORD_MISC_MMAP_DATA; 9867 9868 perf_event_header__init(&mmap_event->event_id.header, &sample, 9869 type, misc, size, event); 9870 ret = perf_output_begin(&handle, &sample, event, 9871 mmap_event->event_id.header.size); 9872 if (ret) 9873 return; 9874 9875 mmap_event->event_id.pid = perf_event_pid(event, current); 9876 mmap_event->event_id.tid = perf_event_tid(event, current); 9877 9878 perf_output_put(&handle, mmap_event->event_id); 9879 9880 if (event->attr.mmap2) { 9881 if (use_build_id) { 9882 u8 size[4] = { (u8) mmap_event->build_id_size, 0, 0, 0 }; 9883 9884 __output_copy(&handle, size, 4); 9885 __output_copy(&handle, mmap_event->build_id, BUILD_ID_SIZE_MAX); 9886 } else { 9887 perf_output_put(&handle, mmap_event->maj); 9888 perf_output_put(&handle, mmap_event->min); 9889 perf_output_put(&handle, mmap_event->ino); 9890 perf_output_put(&handle, mmap_event->ino_generation); 9891 } 9892 perf_output_put(&handle, mmap_event->prot); 9893 perf_output_put(&handle, mmap_event->flags); 9894 } 9895 9896 __output_copy(&handle, mmap_event->file_name, 9897 mmap_event->file_size); 9898 9899 perf_event__output_id_sample(event, &handle, &sample); 9900 9901 perf_output_end(&handle); 9902 } 9903 9904 static void perf_event_mmap_event(struct perf_mmap_event *mmap_event) 9905 { 9906 struct vm_area_struct *vma = mmap_event->vma; 9907 struct file *file = vma->vm_file; 9908 int maj = 0, min = 0; 9909 u64 ino = 0, gen = 0; 9910 u32 prot = 0, flags = 0; 9911 unsigned int size; 9912 char tmp[16]; 9913 char *buf = NULL; 9914 char *name = NULL; 9915 9916 if (vma->vm_flags & VM_READ) 9917 prot |= PROT_READ; 9918 if (vma->vm_flags & VM_WRITE) 9919 prot |= PROT_WRITE; 9920 if (vma->vm_flags & VM_EXEC) 9921 prot |= PROT_EXEC; 9922 9923 if (vma->vm_flags & VM_MAYSHARE) 9924 flags = MAP_SHARED; 9925 else 9926 flags = MAP_PRIVATE; 9927 9928 if (vma->vm_flags & VM_LOCKED) 9929 flags |= MAP_LOCKED; 9930 if (vma_is_hugetlb(vma)) 9931 flags |= MAP_HUGETLB; 9932 9933 if (file) { 9934 const struct inode *inode; 9935 dev_t dev; 9936 9937 buf = kmalloc(PATH_MAX, GFP_KERNEL); 9938 if (!buf) { 9939 name = "//enomem"; 9940 goto cpy_name; 9941 } 9942 /* 9943 * d_path() works from the end of the rb backwards, so we 9944 * need to add enough zero bytes after the string to handle 9945 * the 64bit alignment we do later. 9946 */ 9947 name = d_path(file_user_path(file), buf, PATH_MAX - sizeof(u64)); 9948 if (IS_ERR(name)) { 9949 name = "//toolong"; 9950 goto cpy_name; 9951 } 9952 inode = file_user_inode(vma->vm_file); 9953 dev = inode->i_sb->s_dev; 9954 ino = inode->i_ino; 9955 gen = inode->i_generation; 9956 maj = MAJOR(dev); 9957 min = MINOR(dev); 9958 9959 goto got_name; 9960 } else { 9961 if (vma->vm_ops && vma->vm_ops->name) 9962 name = (char *) vma->vm_ops->name(vma); 9963 if (!name) 9964 name = (char *)arch_vma_name(vma); 9965 if (!name) { 9966 if (vma_is_initial_heap(vma)) 9967 name = "[heap]"; 9968 else if (vma_is_initial_stack(vma)) 9969 name = "[stack]"; 9970 else 9971 name = "//anon"; 9972 } 9973 } 9974 9975 cpy_name: 9976 strscpy(tmp, name); 9977 name = tmp; 9978 got_name: 9979 /* 9980 * Since our buffer works in 8 byte units we need to align our string 9981 * size to a multiple of 8. However, we must guarantee the tail end is 9982 * zero'd out to avoid leaking random bits to userspace. 9983 */ 9984 size = strlen(name)+1; 9985 while (!IS_ALIGNED(size, sizeof(u64))) 9986 name[size++] = '\0'; 9987 9988 mmap_event->file_name = name; 9989 mmap_event->file_size = size; 9990 mmap_event->maj = maj; 9991 mmap_event->min = min; 9992 mmap_event->ino = ino; 9993 mmap_event->ino_generation = gen; 9994 mmap_event->prot = prot; 9995 mmap_event->flags = flags; 9996 9997 if (atomic_read(&nr_build_id_events)) 9998 build_id_parse_nofault(vma, mmap_event->build_id, &mmap_event->build_id_size); 9999 10000 perf_iterate_sb(perf_event_mmap_output, 10001 mmap_event, 10002 NULL); 10003 10004 kfree(buf); 10005 } 10006 10007 /* 10008 * Check whether inode and address range match filter criteria. 10009 */ 10010 static bool perf_addr_filter_match(struct perf_addr_filter *filter, 10011 struct file *file, unsigned long offset, 10012 unsigned long size) 10013 { 10014 /* d_inode(NULL) won't be equal to any mapped user-space file */ 10015 if (!filter->path.dentry) 10016 return false; 10017 10018 if (d_inode(filter->path.dentry) != file_user_inode(file)) 10019 return false; 10020 10021 if (filter->offset > offset + size) 10022 return false; 10023 10024 if (filter->offset + filter->size < offset) 10025 return false; 10026 10027 return true; 10028 } 10029 10030 static bool perf_addr_filter_vma_adjust(struct perf_addr_filter *filter, 10031 struct vm_area_struct *vma, 10032 struct perf_addr_filter_range *fr) 10033 { 10034 unsigned long vma_size = vma->vm_end - vma->vm_start; 10035 unsigned long off = vma_start_pgoff(vma) << PAGE_SHIFT; 10036 struct file *file = vma->vm_file; 10037 10038 if (!perf_addr_filter_match(filter, file, off, vma_size)) 10039 return false; 10040 10041 if (filter->offset < off) { 10042 fr->start = vma->vm_start; 10043 fr->size = min(vma_size, filter->size - (off - filter->offset)); 10044 } else { 10045 fr->start = vma->vm_start + filter->offset - off; 10046 fr->size = min(vma->vm_end - fr->start, filter->size); 10047 } 10048 10049 return true; 10050 } 10051 10052 static void __perf_addr_filters_adjust(struct perf_event *event, void *data) 10053 { 10054 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 10055 struct vm_area_struct *vma = data; 10056 struct perf_addr_filter *filter; 10057 unsigned int restart = 0, count = 0; 10058 unsigned long flags; 10059 10060 if (!has_addr_filter(event)) 10061 return; 10062 10063 if (!vma->vm_file) 10064 return; 10065 10066 raw_spin_lock_irqsave(&ifh->lock, flags); 10067 list_for_each_entry(filter, &ifh->list, entry) { 10068 if (perf_addr_filter_vma_adjust(filter, vma, 10069 &event->addr_filter_ranges[count])) 10070 restart++; 10071 10072 count++; 10073 } 10074 10075 if (restart) 10076 event->addr_filters_gen++; 10077 raw_spin_unlock_irqrestore(&ifh->lock, flags); 10078 10079 if (restart) 10080 perf_event_stop(event, 1); 10081 } 10082 10083 /* 10084 * Adjust all task's events' filters to the new vma 10085 */ 10086 static void perf_addr_filters_adjust(struct vm_area_struct *vma) 10087 { 10088 struct perf_event_context *ctx; 10089 10090 /* 10091 * Data tracing isn't supported yet and as such there is no need 10092 * to keep track of anything that isn't related to executable code: 10093 */ 10094 if (!(vma->vm_flags & VM_EXEC)) 10095 return; 10096 10097 rcu_read_lock(); 10098 ctx = rcu_dereference(current->perf_event_ctxp); 10099 if (ctx) 10100 perf_iterate_ctx(ctx, __perf_addr_filters_adjust, vma, true); 10101 rcu_read_unlock(); 10102 } 10103 10104 void perf_event_mmap(struct vm_area_struct *vma) 10105 { 10106 struct perf_mmap_event mmap_event; 10107 10108 if (!atomic_read(&nr_mmap_events)) 10109 return; 10110 10111 mmap_event = (struct perf_mmap_event){ 10112 .vma = vma, 10113 /* .file_name */ 10114 /* .file_size */ 10115 .event_id = { 10116 /* .header */ 10117 /* .pid */ 10118 /* .tid */ 10119 .start = vma->vm_start, 10120 .len = vma->vm_end - vma->vm_start, 10121 .pgoff = (u64)vma_start_pgoff(vma) << PAGE_SHIFT, 10122 }, 10123 /* .maj (attr_mmap2 only) */ 10124 /* .min (attr_mmap2 only) */ 10125 /* .ino (attr_mmap2 only) */ 10126 /* .ino_generation (attr_mmap2 only) */ 10127 /* .prot (attr_mmap2 only) */ 10128 /* .flags (attr_mmap2 only) */ 10129 }; 10130 10131 perf_addr_filters_adjust(vma); 10132 perf_event_mmap_event(&mmap_event); 10133 } 10134 10135 void perf_event_aux_event(struct perf_event *event, unsigned long head, 10136 unsigned long size, u64 flags) 10137 { 10138 struct perf_output_handle handle; 10139 struct perf_sample_data sample; 10140 struct perf_aux_event { 10141 struct perf_event_header header; 10142 u64 offset; 10143 u64 size; 10144 u64 flags; 10145 } rec = { 10146 .offset = head, 10147 .size = size, 10148 .flags = flags, 10149 }; 10150 int ret; 10151 10152 perf_event_header__init(&rec.header, &sample, 10153 PERF_RECORD_AUX, /* misc= */ 0, sizeof(rec), 10154 event); 10155 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10156 10157 if (ret) 10158 return; 10159 10160 perf_output_put(&handle, rec); 10161 perf_event__output_id_sample(event, &handle, &sample); 10162 10163 perf_output_end(&handle); 10164 } 10165 10166 /* 10167 * Lost/dropped samples logging 10168 */ 10169 void perf_log_lost_samples(struct perf_event *event, u64 lost) 10170 { 10171 struct perf_output_handle handle; 10172 struct perf_sample_data sample; 10173 int ret; 10174 10175 struct { 10176 struct perf_event_header header; 10177 u64 lost; 10178 } lost_samples_event = { 10179 .lost = lost, 10180 }; 10181 10182 perf_event_header__init(&lost_samples_event.header, &sample, 10183 PERF_RECORD_LOST_SAMPLES, 10184 /* misc= */ 0, 10185 sizeof(lost_samples_event), 10186 event); 10187 10188 ret = perf_output_begin(&handle, &sample, event, 10189 lost_samples_event.header.size); 10190 if (ret) 10191 return; 10192 10193 perf_output_put(&handle, lost_samples_event); 10194 perf_event__output_id_sample(event, &handle, &sample); 10195 perf_output_end(&handle); 10196 } 10197 10198 /* 10199 * context_switch tracking 10200 */ 10201 10202 struct perf_switch_event { 10203 struct task_struct *task; 10204 struct task_struct *next_prev; 10205 10206 struct { 10207 struct perf_event_header header; 10208 u32 next_prev_pid; 10209 u32 next_prev_tid; 10210 } event_id; 10211 bool sched_in; 10212 bool preempt; 10213 }; 10214 10215 static int perf_event_switch_match(struct perf_event *event) 10216 { 10217 return event->attr.context_switch; 10218 } 10219 10220 static void perf_event_switch_output(struct perf_event *event, void *data) 10221 { 10222 struct perf_switch_event *se = data; 10223 struct perf_output_handle handle; 10224 struct perf_sample_data sample; 10225 u32 type; 10226 u16 misc; 10227 u16 size; 10228 int ret; 10229 10230 if (!perf_event_switch_match(event)) 10231 return; 10232 10233 /* Only CPU-wide events are allowed to see next/prev pid/tid */ 10234 if (event->ctx->task) { 10235 type = PERF_RECORD_SWITCH; 10236 size = sizeof(se->event_id.header); 10237 } else { 10238 type = PERF_RECORD_SWITCH_CPU_WIDE; 10239 size = sizeof(se->event_id); 10240 se->event_id.next_prev_pid = 10241 perf_event_pid(event, se->next_prev); 10242 se->event_id.next_prev_tid = 10243 perf_event_tid(event, se->next_prev); 10244 } 10245 misc = se->sched_in ? 0 : PERF_RECORD_MISC_SWITCH_OUT; 10246 if (se->preempt) 10247 misc |= PERF_RECORD_MISC_SWITCH_OUT_PREEMPT; 10248 10249 perf_event_header__init(&se->event_id.header, &sample, 10250 type, misc, size, event); 10251 10252 ret = perf_output_begin(&handle, &sample, event, se->event_id.header.size); 10253 if (ret) 10254 return; 10255 10256 if (event->ctx->task) 10257 perf_output_put(&handle, se->event_id.header); 10258 else 10259 perf_output_put(&handle, se->event_id); 10260 10261 perf_event__output_id_sample(event, &handle, &sample); 10262 10263 perf_output_end(&handle); 10264 } 10265 10266 static void perf_event_switch(struct task_struct *task, 10267 struct task_struct *next_prev, bool sched_in) 10268 { 10269 struct perf_switch_event switch_event; 10270 10271 /* N.B. caller checks nr_switch_events != 0 */ 10272 10273 switch_event = (struct perf_switch_event){ 10274 .task = task, 10275 .next_prev = next_prev, 10276 /* .event_id */ 10277 .sched_in = sched_in, 10278 .preempt = !sched_in && task_is_runnable(task), 10279 }; 10280 10281 perf_iterate_sb(perf_event_switch_output, &switch_event, NULL); 10282 } 10283 10284 /* 10285 * IRQ throttle logging 10286 */ 10287 10288 static void perf_log_throttle(struct perf_event *event, int enable) 10289 { 10290 struct perf_output_handle handle; 10291 struct perf_sample_data sample; 10292 int ret; 10293 10294 struct { 10295 struct perf_event_header header; 10296 u64 time; 10297 u64 id; 10298 u64 stream_id; 10299 } throttle_event = { 10300 .time = perf_event_clock(event), 10301 .id = primary_event_id(event), 10302 .stream_id = event->id, 10303 }; 10304 10305 perf_event_header__init(&throttle_event.header, &sample, 10306 enable ? PERF_RECORD_UNTHROTTLE 10307 : PERF_RECORD_THROTTLE, 10308 /* misc= */ 0, 10309 sizeof(throttle_event), 10310 event); 10311 10312 ret = perf_output_begin(&handle, &sample, event, 10313 throttle_event.header.size); 10314 if (ret) 10315 return; 10316 10317 perf_output_put(&handle, throttle_event); 10318 perf_event__output_id_sample(event, &handle, &sample); 10319 perf_output_end(&handle); 10320 } 10321 10322 /* 10323 * ksymbol register/unregister tracking 10324 */ 10325 10326 struct perf_ksymbol_event { 10327 const char *name; 10328 int name_len; 10329 struct { 10330 struct perf_event_header header; 10331 u64 addr; 10332 u32 len; 10333 u16 ksym_type; 10334 u16 flags; 10335 } event_id; 10336 }; 10337 10338 static int perf_event_ksymbol_match(struct perf_event *event) 10339 { 10340 return event->attr.ksymbol; 10341 } 10342 10343 static void perf_event_ksymbol_output(struct perf_event *event, void *data) 10344 { 10345 struct perf_ksymbol_event *ksymbol_event = data; 10346 struct perf_output_handle handle; 10347 struct perf_sample_data sample; 10348 int ret; 10349 u16 size = sizeof(ksymbol_event->event_id) + ksymbol_event->name_len; 10350 10351 if (!perf_event_ksymbol_match(event)) 10352 return; 10353 10354 perf_event_header__init(&ksymbol_event->event_id.header, &sample, 10355 PERF_RECORD_KSYMBOL, /* misc= */ 0, size, 10356 event); 10357 ret = perf_output_begin(&handle, &sample, event, 10358 ksymbol_event->event_id.header.size); 10359 if (ret) 10360 return; 10361 10362 perf_output_put(&handle, ksymbol_event->event_id); 10363 __output_copy(&handle, ksymbol_event->name, ksymbol_event->name_len); 10364 perf_event__output_id_sample(event, &handle, &sample); 10365 10366 perf_output_end(&handle); 10367 } 10368 10369 void perf_event_ksymbol(u16 ksym_type, u64 addr, u32 len, bool unregister, 10370 const char *sym) 10371 { 10372 struct perf_ksymbol_event ksymbol_event; 10373 char name[KSYM_NAME_LEN]; 10374 u16 flags = 0; 10375 int name_len; 10376 10377 if (!atomic_read(&nr_ksymbol_events)) 10378 return; 10379 10380 if (ksym_type >= PERF_RECORD_KSYMBOL_TYPE_MAX || 10381 ksym_type == PERF_RECORD_KSYMBOL_TYPE_UNKNOWN) 10382 goto err; 10383 10384 strscpy(name, sym); 10385 name_len = strlen(name) + 1; 10386 while (!IS_ALIGNED(name_len, sizeof(u64))) 10387 name[name_len++] = '\0'; 10388 BUILD_BUG_ON(KSYM_NAME_LEN % sizeof(u64)); 10389 10390 if (unregister) 10391 flags |= PERF_RECORD_KSYMBOL_FLAGS_UNREGISTER; 10392 10393 ksymbol_event = (struct perf_ksymbol_event){ 10394 .name = name, 10395 .name_len = name_len, 10396 .event_id = { 10397 .addr = addr, 10398 .len = len, 10399 .ksym_type = ksym_type, 10400 .flags = flags, 10401 }, 10402 }; 10403 10404 perf_iterate_sb(perf_event_ksymbol_output, &ksymbol_event, NULL); 10405 return; 10406 err: 10407 WARN_ONCE(1, "%s: Invalid KSYMBOL type 0x%x\n", __func__, ksym_type); 10408 } 10409 10410 /* 10411 * bpf program load/unload tracking 10412 */ 10413 10414 struct perf_bpf_event { 10415 struct bpf_prog *prog; 10416 struct { 10417 struct perf_event_header header; 10418 u16 type; 10419 u16 flags; 10420 u32 id; 10421 u8 tag[BPF_TAG_SIZE]; 10422 } event_id; 10423 }; 10424 10425 static int perf_event_bpf_match(struct perf_event *event) 10426 { 10427 return event->attr.bpf_event; 10428 } 10429 10430 static void perf_event_bpf_output(struct perf_event *event, void *data) 10431 { 10432 struct perf_bpf_event *bpf_event = data; 10433 struct perf_output_handle handle; 10434 struct perf_sample_data sample; 10435 int ret; 10436 10437 if (!perf_event_bpf_match(event)) 10438 return; 10439 10440 perf_event_header__init(&bpf_event->event_id.header, &sample, 10441 PERF_RECORD_BPF_EVENT, 10442 /* misc= */ 0, 10443 sizeof(bpf_event->event_id), 10444 event); 10445 ret = perf_output_begin(&handle, &sample, event, 10446 bpf_event->event_id.header.size); 10447 if (ret) 10448 return; 10449 10450 perf_output_put(&handle, bpf_event->event_id); 10451 perf_event__output_id_sample(event, &handle, &sample); 10452 10453 perf_output_end(&handle); 10454 } 10455 10456 static void perf_event_bpf_emit_ksymbols(struct bpf_prog *prog, 10457 enum perf_bpf_event_type type) 10458 { 10459 bool unregister = type == PERF_BPF_EVENT_PROG_UNLOAD; 10460 int i; 10461 10462 perf_event_ksymbol(PERF_RECORD_KSYMBOL_TYPE_BPF, 10463 (u64)(unsigned long)prog->bpf_func, 10464 prog->jited_len, unregister, 10465 prog->aux->ksym.name); 10466 10467 for (i = 1; i < prog->aux->func_cnt; i++) { 10468 struct bpf_prog *subprog = prog->aux->func[i]; 10469 10470 perf_event_ksymbol( 10471 PERF_RECORD_KSYMBOL_TYPE_BPF, 10472 (u64)(unsigned long)subprog->bpf_func, 10473 subprog->jited_len, unregister, 10474 subprog->aux->ksym.name); 10475 } 10476 } 10477 10478 void perf_event_bpf_event(struct bpf_prog *prog, 10479 enum perf_bpf_event_type type, 10480 u16 flags) 10481 { 10482 struct perf_bpf_event bpf_event; 10483 10484 switch (type) { 10485 case PERF_BPF_EVENT_PROG_LOAD: 10486 case PERF_BPF_EVENT_PROG_UNLOAD: 10487 if (atomic_read(&nr_ksymbol_events)) 10488 perf_event_bpf_emit_ksymbols(prog, type); 10489 break; 10490 default: 10491 return; 10492 } 10493 10494 if (!atomic_read(&nr_bpf_events)) 10495 return; 10496 10497 bpf_event = (struct perf_bpf_event){ 10498 .prog = prog, 10499 .event_id = { 10500 .type = type, 10501 .flags = flags, 10502 .id = prog->aux->id, 10503 }, 10504 }; 10505 10506 BUILD_BUG_ON(BPF_TAG_SIZE % sizeof(u64)); 10507 10508 memcpy(bpf_event.event_id.tag, prog->tag, BPF_TAG_SIZE); 10509 perf_iterate_sb(perf_event_bpf_output, &bpf_event, NULL); 10510 } 10511 10512 struct perf_callchain_deferred_event { 10513 struct unwind_stacktrace *trace; 10514 struct { 10515 struct perf_event_header header; 10516 u64 cookie; 10517 u64 nr; 10518 u64 ips[]; 10519 } event; 10520 }; 10521 10522 static void perf_callchain_deferred_output(struct perf_event *event, void *data) 10523 { 10524 struct perf_callchain_deferred_event *deferred_event = data; 10525 struct perf_output_handle handle; 10526 struct perf_sample_data sample; 10527 int ret; 10528 u16 size = sizeof(deferred_event->event) + (deferred_event->trace->nr * sizeof(u64)); 10529 10530 if (!event->attr.defer_output) 10531 return; 10532 10533 /* XXX do we really need sample_id_all for this ??? */ 10534 perf_event_header__init(&deferred_event->event.header, &sample, 10535 PERF_RECORD_CALLCHAIN_DEFERRED, 10536 PERF_RECORD_MISC_USER, 10537 size, 10538 event); 10539 10540 ret = perf_output_begin(&handle, &sample, event, 10541 deferred_event->event.header.size); 10542 if (ret) 10543 return; 10544 10545 perf_output_put(&handle, deferred_event->event); 10546 for (int i = 0; i < deferred_event->trace->nr; i++) { 10547 u64 entry = deferred_event->trace->entries[i]; 10548 perf_output_put(&handle, entry); 10549 } 10550 perf_event__output_id_sample(event, &handle, &sample); 10551 10552 perf_output_end(&handle); 10553 } 10554 10555 static void perf_unwind_deferred_callback(struct unwind_work *work, 10556 struct unwind_stacktrace *trace, u64 cookie) 10557 { 10558 struct perf_callchain_deferred_event deferred_event = { 10559 .trace = trace, 10560 .event = { 10561 .cookie = cookie, 10562 .nr = trace->nr, 10563 }, 10564 }; 10565 10566 perf_iterate_sb(perf_callchain_deferred_output, &deferred_event, NULL); 10567 } 10568 10569 struct perf_text_poke_event { 10570 const void *old_bytes; 10571 const void *new_bytes; 10572 u16 tot; 10573 u16 pad; 10574 u16 old_len; 10575 u16 new_len; 10576 10577 struct { 10578 struct perf_event_header header; 10579 10580 u64 addr; 10581 } event_id; 10582 }; 10583 10584 static int perf_event_text_poke_match(struct perf_event *event) 10585 { 10586 return event->attr.text_poke; 10587 } 10588 10589 static void perf_event_text_poke_output(struct perf_event *event, void *data) 10590 { 10591 struct perf_text_poke_event *text_poke_event = data; 10592 struct perf_output_handle handle; 10593 struct perf_sample_data sample; 10594 u16 size = sizeof(text_poke_event->event_id) + text_poke_event->tot + text_poke_event->pad; 10595 u64 padding = 0; 10596 int ret; 10597 10598 if (!perf_event_text_poke_match(event)) 10599 return; 10600 10601 perf_event_header__init(&text_poke_event->event_id.header, &sample, 10602 PERF_RECORD_TEXT_POKE, 10603 PERF_RECORD_MISC_KERNEL, 10604 size, 10605 event); 10606 10607 ret = perf_output_begin(&handle, &sample, event, 10608 text_poke_event->event_id.header.size); 10609 if (ret) 10610 return; 10611 10612 perf_output_put(&handle, text_poke_event->event_id); 10613 perf_output_put(&handle, text_poke_event->old_len); 10614 perf_output_put(&handle, text_poke_event->new_len); 10615 10616 __output_copy(&handle, text_poke_event->old_bytes, text_poke_event->old_len); 10617 __output_copy(&handle, text_poke_event->new_bytes, text_poke_event->new_len); 10618 10619 if (text_poke_event->pad) 10620 __output_copy(&handle, &padding, text_poke_event->pad); 10621 10622 perf_event__output_id_sample(event, &handle, &sample); 10623 10624 perf_output_end(&handle); 10625 } 10626 10627 void perf_event_text_poke(const void *addr, const void *old_bytes, 10628 size_t old_len, const void *new_bytes, size_t new_len) 10629 { 10630 struct perf_text_poke_event text_poke_event; 10631 size_t tot, pad; 10632 10633 if (!atomic_read(&nr_text_poke_events)) 10634 return; 10635 10636 tot = sizeof(text_poke_event.old_len) + old_len; 10637 tot += sizeof(text_poke_event.new_len) + new_len; 10638 pad = ALIGN(tot, sizeof(u64)) - tot; 10639 10640 text_poke_event = (struct perf_text_poke_event){ 10641 .old_bytes = old_bytes, 10642 .new_bytes = new_bytes, 10643 .tot = tot, 10644 .pad = pad, 10645 .old_len = old_len, 10646 .new_len = new_len, 10647 .event_id = { 10648 .addr = (unsigned long)addr, 10649 }, 10650 }; 10651 10652 perf_iterate_sb(perf_event_text_poke_output, &text_poke_event, NULL); 10653 } 10654 10655 void perf_event_itrace_started(struct perf_event *event) 10656 { 10657 WRITE_ONCE(event->attach_state, event->attach_state | PERF_ATTACH_ITRACE); 10658 } 10659 EXPORT_SYMBOL_GPL(perf_event_itrace_started); 10660 10661 static void perf_log_itrace_start(struct perf_event *event) 10662 { 10663 struct perf_output_handle handle; 10664 struct perf_sample_data sample; 10665 struct perf_aux_event { 10666 struct perf_event_header header; 10667 u32 pid; 10668 u32 tid; 10669 } rec; 10670 int ret; 10671 10672 if (event->parent) 10673 event = event->parent; 10674 10675 if (!(event->pmu->capabilities & PERF_PMU_CAP_ITRACE) || 10676 event->attach_state & PERF_ATTACH_ITRACE) 10677 return; 10678 10679 rec.pid = perf_event_pid(event, current); 10680 rec.tid = perf_event_tid(event, current); 10681 10682 perf_event_header__init(&rec.header, &sample, 10683 PERF_RECORD_ITRACE_START, /* misc= */ 0, sizeof(rec), 10684 event); 10685 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10686 10687 if (ret) 10688 return; 10689 10690 perf_output_put(&handle, rec); 10691 perf_event__output_id_sample(event, &handle, &sample); 10692 10693 perf_output_end(&handle); 10694 } 10695 10696 void perf_report_aux_output_id(struct perf_event *event, u64 hw_id) 10697 { 10698 struct perf_output_handle handle; 10699 struct perf_sample_data sample; 10700 struct perf_aux_event { 10701 struct perf_event_header header; 10702 u64 hw_id; 10703 } rec; 10704 int ret; 10705 10706 if (event->parent) 10707 event = event->parent; 10708 10709 rec.hw_id = hw_id; 10710 perf_event_header__init(&rec.header, &sample, 10711 PERF_RECORD_AUX_OUTPUT_HW_ID, /* misc= */ 0, 10712 sizeof(rec), event); 10713 ret = perf_output_begin(&handle, &sample, event, rec.header.size); 10714 10715 if (ret) 10716 return; 10717 10718 perf_output_put(&handle, rec); 10719 perf_event__output_id_sample(event, &handle, &sample); 10720 10721 perf_output_end(&handle); 10722 } 10723 EXPORT_SYMBOL_GPL(perf_report_aux_output_id); 10724 10725 static int 10726 __perf_event_account_interrupt(struct perf_event *event, int throttle) 10727 { 10728 struct hw_perf_event *hwc = &event->hw; 10729 int ret = 0; 10730 u64 seq; 10731 10732 seq = __this_cpu_read(perf_throttled_seq); 10733 if (seq != hwc->interrupts_seq) { 10734 hwc->interrupts_seq = seq; 10735 hwc->interrupts = 1; 10736 } else { 10737 hwc->interrupts++; 10738 } 10739 10740 if (unlikely(throttle && hwc->interrupts >= max_samples_per_tick)) { 10741 __this_cpu_inc(perf_throttled_count); 10742 tick_dep_set_cpu(smp_processor_id(), TICK_DEP_BIT_PERF_EVENTS); 10743 perf_event_throttle_group(event); 10744 ret = 1; 10745 } 10746 10747 if (event->attr.freq) { 10748 u64 now = perf_clock(); 10749 s64 delta = now - hwc->freq_time_stamp; 10750 10751 hwc->freq_time_stamp = now; 10752 10753 if (delta > 0 && delta < 2*TICK_NSEC) 10754 perf_adjust_period(event, delta, hwc->last_period, true); 10755 } 10756 10757 return ret; 10758 } 10759 10760 int perf_event_account_interrupt(struct perf_event *event) 10761 { 10762 return __perf_event_account_interrupt(event, 1); 10763 } 10764 10765 static inline bool sample_is_allowed(struct perf_event *event, struct pt_regs *regs) 10766 { 10767 /* 10768 * Due to interrupt latency (AKA "skid"), we may enter the 10769 * kernel before taking an overflow, even if the PMU is only 10770 * counting user events. 10771 */ 10772 if (event->attr.exclude_kernel && !user_mode(regs)) 10773 return false; 10774 10775 return true; 10776 } 10777 10778 #ifdef CONFIG_BPF_SYSCALL 10779 static int bpf_overflow_handler(struct perf_event *event, 10780 struct perf_sample_data *data, 10781 struct pt_regs *regs) 10782 { 10783 struct bpf_perf_event_data_kern ctx = { 10784 .data = data, 10785 .event = event, 10786 }; 10787 struct bpf_prog *prog; 10788 int ret = 0; 10789 10790 ctx.regs = perf_arch_bpf_user_pt_regs(regs); 10791 if (unlikely(__this_cpu_inc_return(bpf_prog_active) != 1)) 10792 goto out; 10793 rcu_read_lock(); 10794 prog = READ_ONCE(event->prog); 10795 if (prog) { 10796 perf_prepare_sample(data, event, regs); 10797 ret = bpf_prog_run(prog, &ctx); 10798 } 10799 rcu_read_unlock(); 10800 out: 10801 __this_cpu_dec(bpf_prog_active); 10802 10803 return ret; 10804 } 10805 10806 static inline int perf_event_set_bpf_handler(struct perf_event *event, 10807 struct bpf_prog *prog, 10808 u64 bpf_cookie) 10809 { 10810 if (event->overflow_handler_context) 10811 /* hw breakpoint or kernel counter */ 10812 return -EINVAL; 10813 10814 if (event->prog) 10815 return -EEXIST; 10816 10817 if (prog->type != BPF_PROG_TYPE_PERF_EVENT) 10818 return -EINVAL; 10819 10820 if (event->attr.precise_ip && 10821 prog->call_get_stack && 10822 (!(event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) || 10823 event->attr.exclude_callchain_kernel || 10824 event->attr.exclude_callchain_user)) { 10825 /* 10826 * On perf_event with precise_ip, calling bpf_get_stack() 10827 * may trigger unwinder warnings and occasional crashes. 10828 * bpf_get_[stack|stackid] works around this issue by using 10829 * callchain attached to perf_sample_data. If the 10830 * perf_event does not full (kernel and user) callchain 10831 * attached to perf_sample_data, do not allow attaching BPF 10832 * program that calls bpf_get_[stack|stackid]. 10833 */ 10834 return -EPROTO; 10835 } 10836 10837 event->prog = prog; 10838 event->bpf_cookie = bpf_cookie; 10839 return 0; 10840 } 10841 10842 static inline void perf_event_free_bpf_handler(struct perf_event *event) 10843 { 10844 struct bpf_prog *prog = event->prog; 10845 10846 if (!prog) 10847 return; 10848 10849 event->prog = NULL; 10850 bpf_prog_put(prog); 10851 } 10852 #else 10853 static inline int bpf_overflow_handler(struct perf_event *event, 10854 struct perf_sample_data *data, 10855 struct pt_regs *regs) 10856 { 10857 return 1; 10858 } 10859 10860 static inline int perf_event_set_bpf_handler(struct perf_event *event, 10861 struct bpf_prog *prog, 10862 u64 bpf_cookie) 10863 { 10864 return -EOPNOTSUPP; 10865 } 10866 10867 static inline void perf_event_free_bpf_handler(struct perf_event *event) 10868 { 10869 } 10870 #endif 10871 10872 /* 10873 * Generic event overflow handling, sampling. 10874 */ 10875 10876 static int __perf_event_overflow(struct perf_event *event, 10877 int throttle, struct perf_sample_data *data, 10878 struct pt_regs *regs) 10879 { 10880 int events = atomic_read(&event->event_limit); 10881 int ret = 0; 10882 10883 /* 10884 * Non-sampling counters might still use the PMI to fold short 10885 * hardware counters, ignore those. 10886 */ 10887 if (unlikely(!is_sampling_event(event))) 10888 return 0; 10889 10890 ret = __perf_event_account_interrupt(event, throttle); 10891 10892 if (event->attr.aux_pause) 10893 perf_event_aux_pause(event->aux_event, true); 10894 10895 if (event->prog && event->prog->type == BPF_PROG_TYPE_PERF_EVENT && 10896 !bpf_overflow_handler(event, data, regs)) 10897 goto out; 10898 10899 /* 10900 * XXX event_limit might not quite work as expected on inherited 10901 * events 10902 */ 10903 10904 event->pending_kill = POLL_IN; 10905 if (events && atomic_dec_and_test(&event->event_limit)) { 10906 ret = 1; 10907 event->pending_kill = POLL_HUP; 10908 perf_event_disable_inatomic(event); 10909 event->pmu->stop(event, 0); 10910 } 10911 10912 if (event->attr.sigtrap) { 10913 /* 10914 * The desired behaviour of sigtrap vs invalid samples is a bit 10915 * tricky; on the one hand, one should not loose the SIGTRAP if 10916 * it is the first event, on the other hand, we should also not 10917 * trigger the WARN or override the data address. 10918 */ 10919 bool valid_sample = sample_is_allowed(event, regs); 10920 unsigned int pending_id = 1; 10921 enum task_work_notify_mode notify_mode; 10922 10923 if (regs) 10924 pending_id = hash32_ptr((void *)instruction_pointer(regs)) ?: 1; 10925 10926 notify_mode = in_nmi() ? TWA_NMI_CURRENT : TWA_RESUME; 10927 10928 if (!event->pending_work && 10929 !task_work_add(current, &event->pending_task, notify_mode)) { 10930 event->pending_work = pending_id; 10931 local_inc(&event->ctx->nr_no_switch_fast); 10932 WARN_ON_ONCE(!atomic_long_inc_not_zero(&event->refcount)); 10933 10934 event->pending_addr = 0; 10935 if (valid_sample && (data->sample_flags & PERF_SAMPLE_ADDR)) 10936 event->pending_addr = data->addr; 10937 10938 } else if (event->attr.exclude_kernel && valid_sample) { 10939 /* 10940 * Should not be able to return to user space without 10941 * consuming pending_work; with exceptions: 10942 * 10943 * 1. Where !exclude_kernel, events can overflow again 10944 * in the kernel without returning to user space. 10945 * 10946 * 2. Events that can overflow again before the IRQ- 10947 * work without user space progress (e.g. hrtimer). 10948 * To approximate progress (with false negatives), 10949 * check 32-bit hash of the current IP. 10950 */ 10951 WARN_ON_ONCE(event->pending_work != pending_id); 10952 } 10953 } 10954 10955 READ_ONCE(event->overflow_handler)(event, data, regs); 10956 10957 if (*perf_event_fasync(event) && event->pending_kill) { 10958 event->pending_wakeup = 1; 10959 irq_work_queue(&event->pending_irq); 10960 } 10961 out: 10962 if (event->attr.aux_resume) 10963 perf_event_aux_pause(event->aux_event, false); 10964 10965 return ret; 10966 } 10967 10968 int perf_event_overflow(struct perf_event *event, 10969 struct perf_sample_data *data, 10970 struct pt_regs *regs) 10971 { 10972 /* 10973 * Entry point from hardware PMI, interrupts should be disabled here. 10974 * This serializes us against perf_event_remove_from_context() in 10975 * things like perf_event_release_kernel(). 10976 */ 10977 lockdep_assert_irqs_disabled(); 10978 10979 return __perf_event_overflow(event, 1, data, regs); 10980 } 10981 10982 /* 10983 * Generic software event infrastructure 10984 */ 10985 10986 struct swevent_htable { 10987 struct swevent_hlist *swevent_hlist; 10988 struct mutex hlist_mutex; 10989 int hlist_refcount; 10990 }; 10991 static DEFINE_PER_CPU(struct swevent_htable, swevent_htable); 10992 10993 /* 10994 * We directly increment event->count and keep a second value in 10995 * event->hw.period_left to count intervals. This period event 10996 * is kept in the range [-sample_period, 0] so that we can use the 10997 * sign as trigger. 10998 */ 10999 11000 u64 perf_swevent_set_period(struct perf_event *event) 11001 { 11002 struct hw_perf_event *hwc = &event->hw; 11003 u64 period = hwc->last_period; 11004 u64 nr, offset; 11005 s64 old, val; 11006 11007 hwc->last_period = hwc->sample_period; 11008 11009 old = local64_read(&hwc->period_left); 11010 do { 11011 val = old; 11012 if (val < 0) 11013 return 0; 11014 11015 nr = div64_u64(period + val, period); 11016 offset = nr * period; 11017 val -= offset; 11018 } while (!local64_try_cmpxchg(&hwc->period_left, &old, val)); 11019 11020 return nr; 11021 } 11022 11023 static void perf_swevent_overflow(struct perf_event *event, u64 overflow, 11024 struct perf_sample_data *data, 11025 struct pt_regs *regs) 11026 { 11027 struct hw_perf_event *hwc = &event->hw; 11028 int throttle = 0; 11029 11030 if (!overflow) 11031 overflow = perf_swevent_set_period(event); 11032 11033 if (hwc->interrupts == MAX_INTERRUPTS) 11034 return; 11035 11036 for (; overflow; overflow--) { 11037 if (__perf_event_overflow(event, throttle, 11038 data, regs)) { 11039 /* 11040 * We inhibit the overflow from happening when 11041 * hwc->interrupts == MAX_INTERRUPTS. 11042 */ 11043 break; 11044 } 11045 throttle = 1; 11046 } 11047 } 11048 11049 static void perf_swevent_event(struct perf_event *event, u64 nr, 11050 struct perf_sample_data *data, 11051 struct pt_regs *regs) 11052 { 11053 struct hw_perf_event *hwc = &event->hw; 11054 11055 /* 11056 * This is: 11057 * - software preempt 11058 * - tracepoint preempt 11059 * - tp_target_task irq (ctx->lock) 11060 * - uprobes preempt/irq 11061 * - kprobes preempt/irq 11062 * - hw_breakpoint irq 11063 * 11064 * Any of these are sufficient to hold off RCU and thus ensure @event 11065 * exists. 11066 */ 11067 lockdep_assert_preemption_disabled(); 11068 local64_add(nr, &event->count); 11069 11070 if (!regs) 11071 return; 11072 11073 if (!is_sampling_event(event)) 11074 return; 11075 11076 /* 11077 * Serialize against event_function_call() IPIs like normal overflow 11078 * event handling. Specifically, must not allow 11079 * perf_event_release_kernel() -> perf_remove_from_context() to make 11080 * progress and 'release' the event from under us. 11081 */ 11082 guard(irqsave)(); 11083 if (event->state != PERF_EVENT_STATE_ACTIVE) 11084 return; 11085 11086 if ((event->attr.sample_type & PERF_SAMPLE_PERIOD) && !event->attr.freq) { 11087 data->period = nr; 11088 return perf_swevent_overflow(event, 1, data, regs); 11089 } else 11090 data->period = event->hw.last_period; 11091 11092 if (nr == 1 && hwc->sample_period == 1 && !event->attr.freq) 11093 return perf_swevent_overflow(event, 1, data, regs); 11094 11095 if (local64_add_negative(nr, &hwc->period_left)) 11096 return; 11097 11098 perf_swevent_overflow(event, 0, data, regs); 11099 } 11100 11101 int perf_exclude_event(struct perf_event *event, struct pt_regs *regs) 11102 { 11103 if (event->hw.state & PERF_HES_STOPPED) 11104 return 1; 11105 11106 if (regs) { 11107 if (event->attr.exclude_user && user_mode(regs)) 11108 return 1; 11109 11110 if (event->attr.exclude_kernel && !user_mode(regs)) 11111 return 1; 11112 } 11113 11114 return 0; 11115 } 11116 11117 static int perf_swevent_match(struct perf_event *event, 11118 enum perf_type_id type, 11119 u32 event_id, 11120 struct perf_sample_data *data, 11121 struct pt_regs *regs) 11122 { 11123 if (event->attr.type != type) 11124 return 0; 11125 11126 if (event->attr.config != event_id) 11127 return 0; 11128 11129 if (perf_exclude_event(event, regs)) 11130 return 0; 11131 11132 return 1; 11133 } 11134 11135 static inline u64 swevent_hash(u64 type, u32 event_id) 11136 { 11137 u64 val = event_id | (type << 32); 11138 11139 return hash_64(val, SWEVENT_HLIST_BITS); 11140 } 11141 11142 static inline struct hlist_head * 11143 __find_swevent_head(struct swevent_hlist *hlist, u64 type, u32 event_id) 11144 { 11145 u64 hash = swevent_hash(type, event_id); 11146 11147 return &hlist->heads[hash]; 11148 } 11149 11150 /* For the read side: events when they trigger */ 11151 static inline struct hlist_head * 11152 find_swevent_head_rcu(struct swevent_htable *swhash, u64 type, u32 event_id) 11153 { 11154 struct swevent_hlist *hlist; 11155 11156 hlist = rcu_dereference(swhash->swevent_hlist); 11157 if (!hlist) 11158 return NULL; 11159 11160 return __find_swevent_head(hlist, type, event_id); 11161 } 11162 11163 /* For the event head insertion and removal in the hlist */ 11164 static inline struct hlist_head * 11165 find_swevent_head(struct swevent_htable *swhash, struct perf_event *event) 11166 { 11167 struct swevent_hlist *hlist; 11168 u32 event_id = event->attr.config; 11169 u64 type = event->attr.type; 11170 11171 /* 11172 * Event scheduling is always serialized against hlist allocation 11173 * and release. Which makes the protected version suitable here. 11174 * The context lock guarantees that. 11175 */ 11176 hlist = rcu_dereference_protected(swhash->swevent_hlist, 11177 lockdep_is_held(&event->ctx->lock)); 11178 if (!hlist) 11179 return NULL; 11180 11181 return __find_swevent_head(hlist, type, event_id); 11182 } 11183 11184 static void do_perf_sw_event(enum perf_type_id type, u32 event_id, 11185 u64 nr, 11186 struct perf_sample_data *data, 11187 struct pt_regs *regs) 11188 { 11189 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 11190 struct perf_event *event; 11191 struct hlist_head *head; 11192 11193 rcu_read_lock(); 11194 head = find_swevent_head_rcu(swhash, type, event_id); 11195 if (!head) 11196 goto end; 11197 11198 hlist_for_each_entry_rcu(event, head, hlist_entry) { 11199 if (perf_swevent_match(event, type, event_id, data, regs)) 11200 perf_swevent_event(event, nr, data, regs); 11201 } 11202 end: 11203 rcu_read_unlock(); 11204 } 11205 11206 DEFINE_PER_CPU(struct pt_regs, __perf_regs[4]); 11207 11208 int perf_swevent_get_recursion_context(void) 11209 { 11210 return get_recursion_context(current->perf_recursion); 11211 } 11212 EXPORT_SYMBOL_GPL(perf_swevent_get_recursion_context); 11213 11214 void perf_swevent_put_recursion_context(int rctx) 11215 { 11216 put_recursion_context(current->perf_recursion, rctx); 11217 } 11218 11219 void ___perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 11220 { 11221 struct perf_sample_data data; 11222 11223 if (WARN_ON_ONCE(!regs)) 11224 return; 11225 11226 perf_sample_data_init(&data, addr, 0); 11227 do_perf_sw_event(PERF_TYPE_SOFTWARE, event_id, nr, &data, regs); 11228 } 11229 11230 void __perf_sw_event(u32 event_id, u64 nr, struct pt_regs *regs, u64 addr) 11231 { 11232 int rctx; 11233 11234 preempt_disable_notrace(); 11235 rctx = perf_swevent_get_recursion_context(); 11236 if (unlikely(rctx < 0)) 11237 goto fail; 11238 11239 ___perf_sw_event(event_id, nr, regs, addr); 11240 11241 perf_swevent_put_recursion_context(rctx); 11242 fail: 11243 preempt_enable_notrace(); 11244 } 11245 11246 static void perf_swevent_read(struct perf_event *event) 11247 { 11248 } 11249 11250 static int perf_swevent_add(struct perf_event *event, int flags) 11251 { 11252 struct swevent_htable *swhash = this_cpu_ptr(&swevent_htable); 11253 struct hw_perf_event *hwc = &event->hw; 11254 struct hlist_head *head; 11255 11256 if (is_sampling_event(event)) { 11257 hwc->last_period = hwc->sample_period; 11258 perf_swevent_set_period(event); 11259 } 11260 11261 hwc->state = !(flags & PERF_EF_START); 11262 11263 head = find_swevent_head(swhash, event); 11264 if (WARN_ON_ONCE(!head)) 11265 return -EINVAL; 11266 11267 hlist_add_head_rcu(&event->hlist_entry, head); 11268 perf_event_update_userpage(event); 11269 11270 return 0; 11271 } 11272 11273 static void perf_swevent_del(struct perf_event *event, int flags) 11274 { 11275 hlist_del_rcu(&event->hlist_entry); 11276 } 11277 11278 static void perf_swevent_start(struct perf_event *event, int flags) 11279 { 11280 event->hw.state = 0; 11281 } 11282 11283 static void perf_swevent_stop(struct perf_event *event, int flags) 11284 { 11285 event->hw.state = PERF_HES_STOPPED; 11286 } 11287 11288 /* Deref the hlist from the update side */ 11289 static inline struct swevent_hlist * 11290 swevent_hlist_deref(struct swevent_htable *swhash) 11291 { 11292 return rcu_dereference_protected(swhash->swevent_hlist, 11293 lockdep_is_held(&swhash->hlist_mutex)); 11294 } 11295 11296 static void swevent_hlist_release(struct swevent_htable *swhash) 11297 { 11298 struct swevent_hlist *hlist = swevent_hlist_deref(swhash); 11299 11300 if (!hlist) 11301 return; 11302 11303 RCU_INIT_POINTER(swhash->swevent_hlist, NULL); 11304 kfree_rcu(hlist, rcu_head); 11305 } 11306 11307 static void swevent_hlist_put_cpu(int cpu) 11308 { 11309 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 11310 11311 mutex_lock(&swhash->hlist_mutex); 11312 11313 if (!--swhash->hlist_refcount) 11314 swevent_hlist_release(swhash); 11315 11316 mutex_unlock(&swhash->hlist_mutex); 11317 } 11318 11319 static void swevent_hlist_put(void) 11320 { 11321 int cpu; 11322 11323 for_each_possible_cpu(cpu) 11324 swevent_hlist_put_cpu(cpu); 11325 } 11326 11327 static int swevent_hlist_get_cpu(int cpu) 11328 { 11329 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 11330 int err = 0; 11331 11332 mutex_lock(&swhash->hlist_mutex); 11333 if (!swevent_hlist_deref(swhash) && 11334 cpumask_test_cpu(cpu, perf_online_mask)) { 11335 struct swevent_hlist *hlist; 11336 11337 hlist = kzalloc_obj(*hlist); 11338 if (!hlist) { 11339 err = -ENOMEM; 11340 goto exit; 11341 } 11342 rcu_assign_pointer(swhash->swevent_hlist, hlist); 11343 } 11344 swhash->hlist_refcount++; 11345 exit: 11346 mutex_unlock(&swhash->hlist_mutex); 11347 11348 return err; 11349 } 11350 11351 static int swevent_hlist_get(void) 11352 { 11353 int err, cpu, failed_cpu; 11354 11355 mutex_lock(&pmus_lock); 11356 for_each_possible_cpu(cpu) { 11357 err = swevent_hlist_get_cpu(cpu); 11358 if (err) { 11359 failed_cpu = cpu; 11360 goto fail; 11361 } 11362 } 11363 mutex_unlock(&pmus_lock); 11364 return 0; 11365 fail: 11366 for_each_possible_cpu(cpu) { 11367 if (cpu == failed_cpu) 11368 break; 11369 swevent_hlist_put_cpu(cpu); 11370 } 11371 mutex_unlock(&pmus_lock); 11372 return err; 11373 } 11374 11375 struct static_key perf_swevent_enabled[PERF_COUNT_SW_MAX]; 11376 11377 static void sw_perf_event_destroy(struct perf_event *event) 11378 { 11379 u64 event_id = event->attr.config; 11380 11381 WARN_ON(event->parent); 11382 11383 static_key_slow_dec(&perf_swevent_enabled[event_id]); 11384 swevent_hlist_put(); 11385 } 11386 11387 static struct pmu perf_cpu_clock; /* fwd declaration */ 11388 static struct pmu perf_task_clock; 11389 11390 static int perf_swevent_init(struct perf_event *event) 11391 { 11392 u64 event_id = event->attr.config; 11393 11394 if (event->attr.type != PERF_TYPE_SOFTWARE) 11395 return -ENOENT; 11396 11397 /* 11398 * no branch sampling for software events 11399 */ 11400 if (has_branch_stack(event)) 11401 return -EOPNOTSUPP; 11402 11403 switch (event_id) { 11404 case PERF_COUNT_SW_CPU_CLOCK: 11405 event->attr.type = perf_cpu_clock.type; 11406 return -ENOENT; 11407 case PERF_COUNT_SW_TASK_CLOCK: 11408 event->attr.type = perf_task_clock.type; 11409 return -ENOENT; 11410 11411 default: 11412 break; 11413 } 11414 11415 if (event_id >= PERF_COUNT_SW_MAX) 11416 return -ENOENT; 11417 11418 if (!event->parent) { 11419 int err; 11420 11421 err = swevent_hlist_get(); 11422 if (err) 11423 return err; 11424 11425 static_key_slow_inc(&perf_swevent_enabled[event_id]); 11426 event->destroy = sw_perf_event_destroy; 11427 } 11428 11429 return 0; 11430 } 11431 11432 static struct pmu perf_swevent = { 11433 .task_ctx_nr = perf_sw_context, 11434 11435 .capabilities = PERF_PMU_CAP_NO_NMI, 11436 11437 .event_init = perf_swevent_init, 11438 .add = perf_swevent_add, 11439 .del = perf_swevent_del, 11440 .start = perf_swevent_start, 11441 .stop = perf_swevent_stop, 11442 .read = perf_swevent_read, 11443 }; 11444 11445 #ifdef CONFIG_EVENT_TRACING 11446 11447 static void tp_perf_event_destroy(struct perf_event *event) 11448 { 11449 perf_trace_destroy(event); 11450 } 11451 11452 static int perf_tp_event_init(struct perf_event *event) 11453 { 11454 int err; 11455 11456 if (event->attr.type != PERF_TYPE_TRACEPOINT) 11457 return -ENOENT; 11458 11459 /* 11460 * no branch sampling for tracepoint events 11461 */ 11462 if (has_branch_stack(event)) 11463 return -EOPNOTSUPP; 11464 11465 err = perf_trace_init(event); 11466 if (err) 11467 return err; 11468 11469 event->destroy = tp_perf_event_destroy; 11470 11471 return 0; 11472 } 11473 11474 static struct pmu perf_tracepoint = { 11475 .task_ctx_nr = perf_sw_context, 11476 11477 .event_init = perf_tp_event_init, 11478 .add = perf_trace_add, 11479 .del = perf_trace_del, 11480 .start = perf_swevent_start, 11481 .stop = perf_swevent_stop, 11482 .read = perf_swevent_read, 11483 }; 11484 11485 static int perf_tp_filter_match(struct perf_event *event, 11486 struct perf_raw_record *raw) 11487 { 11488 void *record = raw->frag.data; 11489 11490 /* only top level events have filters set */ 11491 if (event->parent) 11492 event = event->parent; 11493 11494 if (likely(!event->filter) || filter_match_preds(event->filter, record)) 11495 return 1; 11496 return 0; 11497 } 11498 11499 static int perf_tp_event_match(struct perf_event *event, 11500 struct perf_raw_record *raw, 11501 struct pt_regs *regs) 11502 { 11503 if (event->hw.state & PERF_HES_STOPPED) 11504 return 0; 11505 /* 11506 * If exclude_kernel, only trace user-space tracepoints (uprobes) 11507 */ 11508 if (event->attr.exclude_kernel && !user_mode(regs)) 11509 return 0; 11510 11511 if (!perf_tp_filter_match(event, raw)) 11512 return 0; 11513 11514 return 1; 11515 } 11516 11517 void perf_trace_run_bpf_submit(void *raw_data, int size, int rctx, 11518 struct trace_event_call *call, u64 count, 11519 struct pt_regs *regs, struct hlist_head *head, 11520 struct task_struct *task) 11521 { 11522 if (bpf_prog_array_valid(call)) { 11523 *(struct pt_regs **)raw_data = regs; 11524 if (!trace_call_bpf(call, raw_data) || hlist_empty(head)) { 11525 perf_swevent_put_recursion_context(rctx); 11526 return; 11527 } 11528 } 11529 perf_tp_event(call->event.type, count, raw_data, size, regs, head, 11530 rctx, task); 11531 } 11532 EXPORT_SYMBOL_GPL(perf_trace_run_bpf_submit); 11533 11534 static void __perf_tp_event_target_task(u64 count, void *record, 11535 struct pt_regs *regs, 11536 struct perf_sample_data *data, 11537 struct perf_raw_record *raw, 11538 struct perf_event *event) 11539 { 11540 struct trace_entry *entry = record; 11541 11542 if (event->attr.config != entry->type) 11543 return; 11544 /* Cannot deliver synchronous signal to other task. */ 11545 if (event->attr.sigtrap) 11546 return; 11547 if (perf_tp_event_match(event, raw, regs)) { 11548 perf_sample_data_init(data, 0, 0); 11549 perf_sample_save_raw_data(data, event, raw); 11550 perf_swevent_event(event, count, data, regs); 11551 } 11552 } 11553 11554 static void perf_tp_event_target_task(u64 count, void *record, 11555 struct pt_regs *regs, 11556 struct perf_sample_data *data, 11557 struct perf_raw_record *raw, 11558 struct perf_event_context *ctx) 11559 { 11560 unsigned int cpu = smp_processor_id(); 11561 struct pmu *pmu = &perf_tracepoint; 11562 struct perf_event *event, *sibling; 11563 11564 perf_event_groups_for_cpu_pmu(event, &ctx->pinned_groups, cpu, pmu) { 11565 __perf_tp_event_target_task(count, record, regs, data, raw, event); 11566 for_each_sibling_event(sibling, event) 11567 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 11568 } 11569 11570 perf_event_groups_for_cpu_pmu(event, &ctx->flexible_groups, cpu, pmu) { 11571 __perf_tp_event_target_task(count, record, regs, data, raw, event); 11572 for_each_sibling_event(sibling, event) 11573 __perf_tp_event_target_task(count, record, regs, data, raw, sibling); 11574 } 11575 } 11576 11577 void perf_tp_event(u16 event_type, u64 count, void *record, int entry_size, 11578 struct pt_regs *regs, struct hlist_head *head, int rctx, 11579 struct task_struct *task) 11580 { 11581 struct perf_sample_data data; 11582 struct perf_event *event; 11583 11584 /* 11585 * Per being a tracepoint, this runs with preemption disabled. 11586 */ 11587 lockdep_assert_preemption_disabled(); 11588 11589 struct perf_raw_record raw = { 11590 .frag = { 11591 .size = entry_size, 11592 .data = record, 11593 }, 11594 }; 11595 11596 perf_trace_buf_update(record, event_type); 11597 11598 hlist_for_each_entry_rcu(event, head, hlist_entry) { 11599 if (perf_tp_event_match(event, &raw, regs)) { 11600 /* 11601 * Here use the same on-stack perf_sample_data, 11602 * some members in data are event-specific and 11603 * need to be re-computed for different sweveents. 11604 * Re-initialize data->sample_flags safely to avoid 11605 * the problem that next event skips preparing data 11606 * because data->sample_flags is set. 11607 */ 11608 perf_sample_data_init(&data, 0, 0); 11609 perf_sample_save_raw_data(&data, event, &raw); 11610 perf_swevent_event(event, count, &data, regs); 11611 } 11612 } 11613 11614 /* 11615 * If we got specified a target task, also iterate its context and 11616 * deliver this event there too. 11617 */ 11618 if (task && task != current) { 11619 struct perf_event_context *ctx; 11620 11621 rcu_read_lock(); 11622 ctx = rcu_dereference(task->perf_event_ctxp); 11623 if (!ctx) 11624 goto unlock; 11625 11626 raw_spin_lock(&ctx->lock); 11627 perf_tp_event_target_task(count, record, regs, &data, &raw, ctx); 11628 raw_spin_unlock(&ctx->lock); 11629 unlock: 11630 rcu_read_unlock(); 11631 } 11632 11633 perf_swevent_put_recursion_context(rctx); 11634 } 11635 EXPORT_SYMBOL_GPL(perf_tp_event); 11636 11637 #if defined(CONFIG_KPROBE_EVENTS) || defined(CONFIG_UPROBE_EVENTS) 11638 /* 11639 * Flags in config, used by dynamic PMU kprobe and uprobe 11640 * The flags should match following PMU_FORMAT_ATTR(). 11641 * 11642 * PERF_PROBE_CONFIG_IS_RETPROBE if set, create kretprobe/uretprobe 11643 * if not set, create kprobe/uprobe 11644 * 11645 * The following values specify a reference counter (or semaphore in the 11646 * terminology of tools like dtrace, systemtap, etc.) Userspace Statically 11647 * Defined Tracepoints (USDT). Currently, we use 40 bit for the offset. 11648 * 11649 * PERF_UPROBE_REF_CTR_OFFSET_BITS # of bits in config as th offset 11650 * PERF_UPROBE_REF_CTR_OFFSET_SHIFT # of bits to shift left 11651 */ 11652 enum perf_probe_config { 11653 PERF_PROBE_CONFIG_IS_RETPROBE = 1U << 0, /* [k,u]retprobe */ 11654 PERF_UPROBE_REF_CTR_OFFSET_BITS = 32, 11655 PERF_UPROBE_REF_CTR_OFFSET_SHIFT = 64 - PERF_UPROBE_REF_CTR_OFFSET_BITS, 11656 }; 11657 11658 PMU_FORMAT_ATTR(retprobe, "config:0"); 11659 #endif 11660 11661 #ifdef CONFIG_KPROBE_EVENTS 11662 static struct attribute *kprobe_attrs[] = { 11663 &format_attr_retprobe.attr, 11664 NULL, 11665 }; 11666 11667 static struct attribute_group kprobe_format_group = { 11668 .name = "format", 11669 .attrs = kprobe_attrs, 11670 }; 11671 11672 static const struct attribute_group *kprobe_attr_groups[] = { 11673 &kprobe_format_group, 11674 NULL, 11675 }; 11676 11677 static int perf_kprobe_event_init(struct perf_event *event); 11678 static struct pmu perf_kprobe = { 11679 .task_ctx_nr = perf_sw_context, 11680 .event_init = perf_kprobe_event_init, 11681 .add = perf_trace_add, 11682 .del = perf_trace_del, 11683 .start = perf_swevent_start, 11684 .stop = perf_swevent_stop, 11685 .read = perf_swevent_read, 11686 .attr_groups = kprobe_attr_groups, 11687 }; 11688 11689 static int perf_kprobe_event_init(struct perf_event *event) 11690 { 11691 int err; 11692 bool is_retprobe; 11693 11694 if (event->attr.type != perf_kprobe.type) 11695 return -ENOENT; 11696 11697 if (!perfmon_capable()) 11698 return -EACCES; 11699 11700 /* 11701 * no branch sampling for probe events 11702 */ 11703 if (has_branch_stack(event)) 11704 return -EOPNOTSUPP; 11705 11706 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 11707 err = perf_kprobe_init(event, is_retprobe); 11708 if (err) 11709 return err; 11710 11711 event->destroy = perf_kprobe_destroy; 11712 11713 return 0; 11714 } 11715 #endif /* CONFIG_KPROBE_EVENTS */ 11716 11717 #ifdef CONFIG_UPROBE_EVENTS 11718 PMU_FORMAT_ATTR(ref_ctr_offset, "config:32-63"); 11719 11720 static struct attribute *uprobe_attrs[] = { 11721 &format_attr_retprobe.attr, 11722 &format_attr_ref_ctr_offset.attr, 11723 NULL, 11724 }; 11725 11726 static struct attribute_group uprobe_format_group = { 11727 .name = "format", 11728 .attrs = uprobe_attrs, 11729 }; 11730 11731 static const struct attribute_group *uprobe_attr_groups[] = { 11732 &uprobe_format_group, 11733 NULL, 11734 }; 11735 11736 static int perf_uprobe_event_init(struct perf_event *event); 11737 static struct pmu perf_uprobe = { 11738 .task_ctx_nr = perf_sw_context, 11739 .event_init = perf_uprobe_event_init, 11740 .add = perf_trace_add, 11741 .del = perf_trace_del, 11742 .start = perf_swevent_start, 11743 .stop = perf_swevent_stop, 11744 .read = perf_swevent_read, 11745 .attr_groups = uprobe_attr_groups, 11746 }; 11747 11748 static int perf_uprobe_event_init(struct perf_event *event) 11749 { 11750 int err; 11751 unsigned long ref_ctr_offset; 11752 bool is_retprobe; 11753 11754 if (event->attr.type != perf_uprobe.type) 11755 return -ENOENT; 11756 11757 if (!capable(CAP_SYS_ADMIN)) 11758 return -EACCES; 11759 11760 /* 11761 * no branch sampling for probe events 11762 */ 11763 if (has_branch_stack(event)) 11764 return -EOPNOTSUPP; 11765 11766 is_retprobe = event->attr.config & PERF_PROBE_CONFIG_IS_RETPROBE; 11767 ref_ctr_offset = event->attr.config >> PERF_UPROBE_REF_CTR_OFFSET_SHIFT; 11768 err = perf_uprobe_init(event, ref_ctr_offset, is_retprobe); 11769 if (err) 11770 return err; 11771 11772 event->destroy = perf_uprobe_destroy; 11773 11774 return 0; 11775 } 11776 #endif /* CONFIG_UPROBE_EVENTS */ 11777 11778 static inline void perf_tp_register(void) 11779 { 11780 perf_pmu_register(&perf_tracepoint, "tracepoint", PERF_TYPE_TRACEPOINT); 11781 #ifdef CONFIG_KPROBE_EVENTS 11782 perf_pmu_register(&perf_kprobe, "kprobe", -1); 11783 #endif 11784 #ifdef CONFIG_UPROBE_EVENTS 11785 perf_pmu_register(&perf_uprobe, "uprobe", -1); 11786 #endif 11787 } 11788 11789 static void perf_event_free_filter(struct perf_event *event) 11790 { 11791 ftrace_profile_free_filter(event); 11792 } 11793 11794 /* 11795 * returns true if the event is a tracepoint, or a kprobe/upprobe created 11796 * with perf_event_open() 11797 */ 11798 static inline bool perf_event_is_tracing(struct perf_event *event) 11799 { 11800 if (event->pmu == &perf_tracepoint) 11801 return true; 11802 #ifdef CONFIG_KPROBE_EVENTS 11803 if (event->pmu == &perf_kprobe) 11804 return true; 11805 #endif 11806 #ifdef CONFIG_UPROBE_EVENTS 11807 if (event->pmu == &perf_uprobe) 11808 return true; 11809 #endif 11810 return false; 11811 } 11812 11813 static int __perf_event_set_bpf_prog(struct perf_event *event, 11814 struct bpf_prog *prog, 11815 u64 bpf_cookie) 11816 { 11817 bool is_kprobe, is_uprobe, is_tracepoint, is_syscall_tp; 11818 11819 if (event->state <= PERF_EVENT_STATE_REVOKED) 11820 return -ENODEV; 11821 11822 if (!perf_event_is_tracing(event)) 11823 return perf_event_set_bpf_handler(event, prog, bpf_cookie); 11824 11825 is_kprobe = event->tp_event->flags & TRACE_EVENT_FL_KPROBE; 11826 is_uprobe = event->tp_event->flags & TRACE_EVENT_FL_UPROBE; 11827 is_tracepoint = event->tp_event->flags & TRACE_EVENT_FL_TRACEPOINT; 11828 is_syscall_tp = is_syscall_trace_event(event->tp_event); 11829 if (!is_kprobe && !is_uprobe && !is_tracepoint && !is_syscall_tp) 11830 /* bpf programs can only be attached to u/kprobe or tracepoint */ 11831 return -EINVAL; 11832 11833 if (((is_kprobe || is_uprobe) && prog->type != BPF_PROG_TYPE_KPROBE) || 11834 (is_tracepoint && prog->type != BPF_PROG_TYPE_TRACEPOINT) || 11835 (is_syscall_tp && prog->type != BPF_PROG_TYPE_TRACEPOINT)) 11836 return -EINVAL; 11837 11838 if (prog->type == BPF_PROG_TYPE_KPROBE && prog->sleepable && !is_uprobe) 11839 /* only uprobe programs are allowed to be sleepable */ 11840 return -EINVAL; 11841 11842 if (prog->type == BPF_PROG_TYPE_TRACEPOINT && prog->sleepable) { 11843 /* 11844 * Sleepable tracepoint programs can only attach to faultable 11845 * tracepoints. Currently only syscall tracepoints are faultable. 11846 */ 11847 if (!is_syscall_tp) 11848 return -EINVAL; 11849 } 11850 11851 /* Kprobe override only works for kprobes, not uprobes. */ 11852 if (prog->kprobe_override && !is_kprobe) 11853 return -EINVAL; 11854 11855 /* Writing to context allowed only for uprobes. */ 11856 if (prog->aux->kprobe_write_ctx && !is_uprobe) 11857 return -EINVAL; 11858 11859 if (is_tracepoint || is_syscall_tp) { 11860 int off = trace_event_get_offsets(event->tp_event); 11861 11862 if (prog->aux->max_ctx_offset > off) 11863 return -EACCES; 11864 } 11865 11866 return perf_event_attach_bpf_prog(event, prog, bpf_cookie); 11867 } 11868 11869 int perf_event_set_bpf_prog(struct perf_event *event, 11870 struct bpf_prog *prog, 11871 u64 bpf_cookie) 11872 { 11873 struct perf_event_context *ctx; 11874 int ret; 11875 11876 ctx = perf_event_ctx_lock(event); 11877 ret = __perf_event_set_bpf_prog(event, prog, bpf_cookie); 11878 perf_event_ctx_unlock(event, ctx); 11879 11880 return ret; 11881 } 11882 11883 void perf_event_free_bpf_prog(struct perf_event *event) 11884 { 11885 if (!event->prog) 11886 return; 11887 11888 if (!perf_event_is_tracing(event)) { 11889 perf_event_free_bpf_handler(event); 11890 return; 11891 } 11892 perf_event_detach_bpf_prog(event); 11893 } 11894 11895 #else 11896 11897 static inline void perf_tp_register(void) 11898 { 11899 } 11900 11901 static void perf_event_free_filter(struct perf_event *event) 11902 { 11903 } 11904 11905 static int __perf_event_set_bpf_prog(struct perf_event *event, 11906 struct bpf_prog *prog, 11907 u64 bpf_cookie) 11908 { 11909 return -ENOENT; 11910 } 11911 11912 int perf_event_set_bpf_prog(struct perf_event *event, 11913 struct bpf_prog *prog, 11914 u64 bpf_cookie) 11915 { 11916 return -ENOENT; 11917 } 11918 11919 void perf_event_free_bpf_prog(struct perf_event *event) 11920 { 11921 } 11922 #endif /* CONFIG_EVENT_TRACING */ 11923 11924 #ifdef CONFIG_HAVE_HW_BREAKPOINT 11925 void perf_bp_event(struct perf_event *bp, void *data) 11926 { 11927 struct perf_sample_data sample; 11928 struct pt_regs *regs = data; 11929 11930 /* 11931 * Exception context, will have interrupts disabled. 11932 */ 11933 lockdep_assert_irqs_disabled(); 11934 11935 perf_sample_data_init(&sample, bp->attr.bp_addr, 0); 11936 11937 if (!bp->hw.state && !perf_exclude_event(bp, regs)) 11938 perf_swevent_event(bp, 1, &sample, regs); 11939 } 11940 #endif 11941 11942 /* 11943 * Allocate a new address filter 11944 */ 11945 static struct perf_addr_filter * 11946 perf_addr_filter_new(struct perf_event *event, struct list_head *filters) 11947 { 11948 int node = cpu_to_node(event->cpu == -1 ? 0 : event->cpu); 11949 struct perf_addr_filter *filter; 11950 11951 filter = kzalloc_node(sizeof(*filter), GFP_KERNEL, node); 11952 if (!filter) 11953 return NULL; 11954 11955 INIT_LIST_HEAD(&filter->entry); 11956 list_add_tail(&filter->entry, filters); 11957 11958 return filter; 11959 } 11960 11961 static void free_filters_list(struct list_head *filters) 11962 { 11963 struct perf_addr_filter *filter, *iter; 11964 11965 list_for_each_entry_safe(filter, iter, filters, entry) { 11966 path_put(&filter->path); 11967 list_del(&filter->entry); 11968 kfree(filter); 11969 } 11970 } 11971 11972 /* 11973 * Free existing address filters and optionally install new ones 11974 */ 11975 static void perf_addr_filters_splice(struct perf_event *event, 11976 struct list_head *head) 11977 { 11978 unsigned long flags; 11979 LIST_HEAD(list); 11980 11981 if (!has_addr_filter(event)) 11982 return; 11983 11984 /* don't bother with children, they don't have their own filters */ 11985 if (event->parent) 11986 return; 11987 11988 raw_spin_lock_irqsave(&event->addr_filters.lock, flags); 11989 11990 list_splice_init(&event->addr_filters.list, &list); 11991 if (head) 11992 list_splice(head, &event->addr_filters.list); 11993 11994 raw_spin_unlock_irqrestore(&event->addr_filters.lock, flags); 11995 11996 free_filters_list(&list); 11997 } 11998 11999 static void perf_free_addr_filters(struct perf_event *event) 12000 { 12001 /* 12002 * Used during free paths, there is no concurrency. 12003 */ 12004 if (list_empty(&event->addr_filters.list)) 12005 return; 12006 12007 perf_addr_filters_splice(event, NULL); 12008 } 12009 12010 /* 12011 * Scan through mm's vmas and see if one of them matches the 12012 * @filter; if so, adjust filter's address range. 12013 * Called with mm::mmap_lock down for reading. 12014 */ 12015 static void perf_addr_filter_apply(struct perf_addr_filter *filter, 12016 struct mm_struct *mm, 12017 struct perf_addr_filter_range *fr) 12018 { 12019 struct vm_area_struct *vma; 12020 VMA_ITERATOR(vmi, mm, 0); 12021 12022 for_each_vma(vmi, vma) { 12023 if (!vma->vm_file) 12024 continue; 12025 12026 if (perf_addr_filter_vma_adjust(filter, vma, fr)) 12027 return; 12028 } 12029 } 12030 12031 /* 12032 * Update event's address range filters based on the 12033 * task's existing mappings, if any. 12034 */ 12035 static void perf_event_addr_filters_apply(struct perf_event *event) 12036 { 12037 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 12038 struct task_struct *task = READ_ONCE(event->ctx->task); 12039 struct perf_addr_filter *filter; 12040 struct mm_struct *mm = NULL; 12041 unsigned int count = 0; 12042 unsigned long flags; 12043 12044 /* 12045 * We may observe TASK_TOMBSTONE, which means that the event tear-down 12046 * will stop on the parent's child_mutex that our caller is also holding 12047 */ 12048 if (task == TASK_TOMBSTONE) 12049 return; 12050 12051 if (ifh->nr_file_filters) { 12052 mm = get_task_mm(task); 12053 if (!mm) 12054 goto restart; 12055 12056 mmap_read_lock(mm); 12057 } 12058 12059 raw_spin_lock_irqsave(&ifh->lock, flags); 12060 list_for_each_entry(filter, &ifh->list, entry) { 12061 if (filter->path.dentry) { 12062 /* 12063 * Adjust base offset if the filter is associated to a 12064 * binary that needs to be mapped: 12065 */ 12066 event->addr_filter_ranges[count].start = 0; 12067 event->addr_filter_ranges[count].size = 0; 12068 12069 perf_addr_filter_apply(filter, mm, &event->addr_filter_ranges[count]); 12070 } else { 12071 event->addr_filter_ranges[count].start = filter->offset; 12072 event->addr_filter_ranges[count].size = filter->size; 12073 } 12074 12075 count++; 12076 } 12077 12078 event->addr_filters_gen++; 12079 raw_spin_unlock_irqrestore(&ifh->lock, flags); 12080 12081 if (ifh->nr_file_filters) { 12082 mmap_read_unlock(mm); 12083 12084 mmput(mm); 12085 } 12086 12087 restart: 12088 perf_event_stop(event, 1); 12089 } 12090 12091 /* 12092 * Address range filtering: limiting the data to certain 12093 * instruction address ranges. Filters are ioctl()ed to us from 12094 * userspace as ascii strings. 12095 * 12096 * Filter string format: 12097 * 12098 * ACTION RANGE_SPEC 12099 * where ACTION is one of the 12100 * * "filter": limit the trace to this region 12101 * * "start": start tracing from this address 12102 * * "stop": stop tracing at this address/region; 12103 * RANGE_SPEC is 12104 * * for kernel addresses: <start address>[/<size>] 12105 * * for object files: <start address>[/<size>]@</path/to/object/file> 12106 * 12107 * if <size> is not specified or is zero, the range is treated as a single 12108 * address; not valid for ACTION=="filter". 12109 */ 12110 enum { 12111 IF_ACT_NONE = -1, 12112 IF_ACT_FILTER, 12113 IF_ACT_START, 12114 IF_ACT_STOP, 12115 IF_SRC_FILE, 12116 IF_SRC_KERNEL, 12117 IF_SRC_FILEADDR, 12118 IF_SRC_KERNELADDR, 12119 }; 12120 12121 enum { 12122 IF_STATE_ACTION = 0, 12123 IF_STATE_SOURCE, 12124 IF_STATE_END, 12125 }; 12126 12127 static const match_table_t if_tokens = { 12128 { IF_ACT_FILTER, "filter" }, 12129 { IF_ACT_START, "start" }, 12130 { IF_ACT_STOP, "stop" }, 12131 { IF_SRC_FILE, "%u/%u@%s" }, 12132 { IF_SRC_KERNEL, "%u/%u" }, 12133 { IF_SRC_FILEADDR, "%u@%s" }, 12134 { IF_SRC_KERNELADDR, "%u" }, 12135 { IF_ACT_NONE, NULL }, 12136 }; 12137 12138 /* 12139 * Address filter string parser 12140 */ 12141 static int 12142 perf_event_parse_addr_filter(struct perf_event *event, char *fstr, 12143 struct list_head *filters) 12144 { 12145 struct perf_addr_filter *filter = NULL; 12146 char *start, *orig, *filename = NULL; 12147 substring_t args[MAX_OPT_ARGS]; 12148 int state = IF_STATE_ACTION, token; 12149 unsigned int kernel = 0; 12150 int ret = -EINVAL; 12151 12152 orig = fstr = kstrdup(fstr, GFP_KERNEL); 12153 if (!fstr) 12154 return -ENOMEM; 12155 12156 while ((start = strsep(&fstr, " ,\n")) != NULL) { 12157 static const enum perf_addr_filter_action_t actions[] = { 12158 [IF_ACT_FILTER] = PERF_ADDR_FILTER_ACTION_FILTER, 12159 [IF_ACT_START] = PERF_ADDR_FILTER_ACTION_START, 12160 [IF_ACT_STOP] = PERF_ADDR_FILTER_ACTION_STOP, 12161 }; 12162 ret = -EINVAL; 12163 12164 if (!*start) 12165 continue; 12166 12167 /* filter definition begins */ 12168 if (state == IF_STATE_ACTION) { 12169 filter = perf_addr_filter_new(event, filters); 12170 if (!filter) 12171 goto fail; 12172 } 12173 12174 token = match_token(start, if_tokens, args); 12175 switch (token) { 12176 case IF_ACT_FILTER: 12177 case IF_ACT_START: 12178 case IF_ACT_STOP: 12179 if (state != IF_STATE_ACTION) 12180 goto fail; 12181 12182 filter->action = actions[token]; 12183 state = IF_STATE_SOURCE; 12184 break; 12185 12186 case IF_SRC_KERNELADDR: 12187 case IF_SRC_KERNEL: 12188 kernel = 1; 12189 fallthrough; 12190 12191 case IF_SRC_FILEADDR: 12192 case IF_SRC_FILE: 12193 if (state != IF_STATE_SOURCE) 12194 goto fail; 12195 12196 *args[0].to = 0; 12197 ret = kstrtoul(args[0].from, 0, &filter->offset); 12198 if (ret) 12199 goto fail; 12200 12201 if (token == IF_SRC_KERNEL || token == IF_SRC_FILE) { 12202 *args[1].to = 0; 12203 ret = kstrtoul(args[1].from, 0, &filter->size); 12204 if (ret) 12205 goto fail; 12206 } 12207 12208 if (token == IF_SRC_FILE || token == IF_SRC_FILEADDR) { 12209 int fpos = token == IF_SRC_FILE ? 2 : 1; 12210 12211 kfree(filename); 12212 filename = match_strdup(&args[fpos]); 12213 if (!filename) { 12214 ret = -ENOMEM; 12215 goto fail; 12216 } 12217 } 12218 12219 state = IF_STATE_END; 12220 break; 12221 12222 default: 12223 goto fail; 12224 } 12225 12226 /* 12227 * Filter definition is fully parsed, validate and install it. 12228 * Make sure that it doesn't contradict itself or the event's 12229 * attribute. 12230 */ 12231 if (state == IF_STATE_END) { 12232 ret = -EINVAL; 12233 12234 /* 12235 * ACTION "filter" must have a non-zero length region 12236 * specified. 12237 */ 12238 if (filter->action == PERF_ADDR_FILTER_ACTION_FILTER && 12239 !filter->size) 12240 goto fail; 12241 12242 if (!kernel) { 12243 if (!filename) 12244 goto fail; 12245 12246 /* 12247 * For now, we only support file-based filters 12248 * in per-task events; doing so for CPU-wide 12249 * events requires additional context switching 12250 * trickery, since same object code will be 12251 * mapped at different virtual addresses in 12252 * different processes. 12253 */ 12254 ret = -EOPNOTSUPP; 12255 if (!event->ctx->task) 12256 goto fail; 12257 12258 /* look up the path and grab its inode */ 12259 ret = kern_path(filename, LOOKUP_FOLLOW, 12260 &filter->path); 12261 if (ret) 12262 goto fail; 12263 12264 ret = -EINVAL; 12265 if (!filter->path.dentry || 12266 !S_ISREG(d_inode(filter->path.dentry) 12267 ->i_mode)) 12268 goto fail; 12269 12270 event->addr_filters.nr_file_filters++; 12271 } 12272 12273 /* ready to consume more filters */ 12274 kfree(filename); 12275 filename = NULL; 12276 state = IF_STATE_ACTION; 12277 filter = NULL; 12278 kernel = 0; 12279 } 12280 } 12281 12282 if (state != IF_STATE_ACTION) 12283 goto fail; 12284 12285 kfree(filename); 12286 kfree(orig); 12287 12288 return 0; 12289 12290 fail: 12291 kfree(filename); 12292 free_filters_list(filters); 12293 kfree(orig); 12294 12295 return ret; 12296 } 12297 12298 static int 12299 perf_event_set_addr_filter(struct perf_event *event, char *filter_str) 12300 { 12301 LIST_HEAD(filters); 12302 int ret; 12303 12304 /* 12305 * Since this is called in perf_ioctl() path, we're already holding 12306 * ctx::mutex. 12307 */ 12308 lockdep_assert_held(&event->ctx->mutex); 12309 12310 if (WARN_ON_ONCE(event->parent)) 12311 return -EINVAL; 12312 12313 ret = perf_event_parse_addr_filter(event, filter_str, &filters); 12314 if (ret) 12315 goto fail_clear_files; 12316 12317 ret = event->pmu->addr_filters_validate(&filters); 12318 if (ret) 12319 goto fail_free_filters; 12320 12321 /* remove existing filters, if any */ 12322 perf_addr_filters_splice(event, &filters); 12323 12324 /* install new filters */ 12325 perf_event_for_each_child(event, perf_event_addr_filters_apply); 12326 12327 return ret; 12328 12329 fail_free_filters: 12330 free_filters_list(&filters); 12331 12332 fail_clear_files: 12333 event->addr_filters.nr_file_filters = 0; 12334 12335 return ret; 12336 } 12337 12338 static int perf_event_set_filter(struct perf_event *event, void __user *arg) 12339 { 12340 int ret = -EINVAL; 12341 char *filter_str; 12342 12343 filter_str = strndup_user(arg, PAGE_SIZE); 12344 if (IS_ERR(filter_str)) 12345 return PTR_ERR(filter_str); 12346 12347 #ifdef CONFIG_EVENT_TRACING 12348 if (perf_event_is_tracing(event)) { 12349 struct perf_event_context *ctx = event->ctx; 12350 12351 /* 12352 * Beware, here be dragons!! 12353 * 12354 * the tracepoint muck will deadlock against ctx->mutex, but 12355 * the tracepoint stuff does not actually need it. So 12356 * temporarily drop ctx->mutex. As per perf_event_ctx_lock() we 12357 * already have a reference on ctx. 12358 * 12359 * This can result in event getting moved to a different ctx, 12360 * but that does not affect the tracepoint state. 12361 */ 12362 mutex_unlock(&ctx->mutex); 12363 ret = ftrace_profile_set_filter(event, event->attr.config, filter_str); 12364 mutex_lock(&ctx->mutex); 12365 } else 12366 #endif 12367 if (has_addr_filter(event)) 12368 ret = perf_event_set_addr_filter(event, filter_str); 12369 12370 kfree(filter_str); 12371 return ret; 12372 } 12373 12374 /* 12375 * hrtimer based swevent callback 12376 */ 12377 12378 static enum hrtimer_restart perf_swevent_hrtimer(struct hrtimer *hrtimer) 12379 { 12380 enum hrtimer_restart ret = HRTIMER_RESTART; 12381 struct perf_sample_data data; 12382 struct pt_regs *regs; 12383 struct perf_event *event; 12384 u64 period; 12385 12386 event = container_of(hrtimer, struct perf_event, hw.hrtimer); 12387 12388 if (event->state != PERF_EVENT_STATE_ACTIVE || 12389 event->hw.state & PERF_HES_STOPPED) 12390 return HRTIMER_NORESTART; 12391 12392 event->pmu->read(event); 12393 12394 perf_sample_data_init(&data, 0, event->hw.last_period); 12395 regs = get_irq_regs(); 12396 12397 if (regs && !perf_exclude_event(event, regs)) { 12398 if (!(event->attr.exclude_idle && is_idle_task(current))) 12399 if (perf_event_overflow(event, &data, regs)) 12400 ret = HRTIMER_NORESTART; 12401 } 12402 12403 period = max_t(u64, 10000, event->hw.sample_period); 12404 hrtimer_forward_now(hrtimer, ns_to_ktime(period)); 12405 12406 return ret; 12407 } 12408 12409 static void perf_swevent_start_hrtimer(struct perf_event *event) 12410 { 12411 struct hw_perf_event *hwc = &event->hw; 12412 s64 period; 12413 12414 if (!is_sampling_event(event)) 12415 return; 12416 12417 period = local64_read(&hwc->period_left); 12418 if (period) { 12419 if (period < 0) 12420 period = 10000; 12421 12422 local64_set(&hwc->period_left, 0); 12423 } else { 12424 period = max_t(u64, 10000, hwc->sample_period); 12425 } 12426 hrtimer_start(&hwc->hrtimer, ns_to_ktime(period), 12427 HRTIMER_MODE_REL_PINNED_HARD); 12428 } 12429 12430 static void perf_swevent_cancel_hrtimer(struct perf_event *event) 12431 { 12432 struct hw_perf_event *hwc = &event->hw; 12433 12434 /* 12435 * Careful: this function can be triggered in the hrtimer handler, 12436 * for cpu-clock events, so hrtimer_cancel() would cause a 12437 * deadlock. 12438 * 12439 * So use hrtimer_try_to_cancel() to try to stop the hrtimer, 12440 * and the cpu-clock handler also sets the PERF_HES_STOPPED flag, 12441 * which guarantees that perf_swevent_hrtimer() will stop the 12442 * hrtimer once it sees the PERF_HES_STOPPED flag. 12443 */ 12444 if (is_sampling_event(event) && (hwc->interrupts != MAX_INTERRUPTS)) { 12445 ktime_t remaining = hrtimer_get_remaining(&hwc->hrtimer); 12446 local64_set(&hwc->period_left, ktime_to_ns(remaining)); 12447 12448 hrtimer_try_to_cancel(&hwc->hrtimer); 12449 } 12450 } 12451 12452 static void perf_swevent_destroy_hrtimer(struct perf_event *event) 12453 { 12454 hrtimer_cancel(&event->hw.hrtimer); 12455 } 12456 12457 static void perf_swevent_init_hrtimer(struct perf_event *event) 12458 { 12459 struct hw_perf_event *hwc = &event->hw; 12460 12461 if (!is_sampling_event(event)) 12462 return; 12463 12464 hrtimer_setup(&hwc->hrtimer, perf_swevent_hrtimer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD); 12465 event->destroy = perf_swevent_destroy_hrtimer; 12466 12467 /* 12468 * Since hrtimers have a fixed rate, we can do a static freq->period 12469 * mapping and avoid the whole period adjust feedback stuff. 12470 */ 12471 if (event->attr.freq) { 12472 long freq = event->attr.sample_freq; 12473 12474 event->attr.sample_period = NSEC_PER_SEC / freq; 12475 hwc->sample_period = event->attr.sample_period; 12476 local64_set(&hwc->period_left, hwc->sample_period); 12477 hwc->last_period = hwc->sample_period; 12478 event->attr.freq = 0; 12479 } 12480 } 12481 12482 /* 12483 * Software event: cpu wall time clock 12484 */ 12485 12486 static void cpu_clock_event_update(struct perf_event *event) 12487 { 12488 s64 prev; 12489 u64 now; 12490 12491 now = local_clock(); 12492 prev = local64_xchg(&event->hw.prev_count, now); 12493 local64_add(now - prev, &event->count); 12494 } 12495 12496 static void cpu_clock_event_start(struct perf_event *event, int flags) 12497 { 12498 event->hw.state = 0; 12499 local64_set(&event->hw.prev_count, local_clock()); 12500 perf_swevent_start_hrtimer(event); 12501 } 12502 12503 static void cpu_clock_event_stop(struct perf_event *event, int flags) 12504 { 12505 event->hw.state = PERF_HES_STOPPED; 12506 perf_swevent_cancel_hrtimer(event); 12507 if (flags & PERF_EF_UPDATE) 12508 cpu_clock_event_update(event); 12509 } 12510 12511 static int cpu_clock_event_add(struct perf_event *event, int flags) 12512 { 12513 if (flags & PERF_EF_START) 12514 cpu_clock_event_start(event, flags); 12515 perf_event_update_userpage(event); 12516 12517 return 0; 12518 } 12519 12520 static void cpu_clock_event_del(struct perf_event *event, int flags) 12521 { 12522 cpu_clock_event_stop(event, PERF_EF_UPDATE); 12523 } 12524 12525 static void cpu_clock_event_read(struct perf_event *event) 12526 { 12527 cpu_clock_event_update(event); 12528 } 12529 12530 static int cpu_clock_event_init(struct perf_event *event) 12531 { 12532 if (event->attr.type != perf_cpu_clock.type) 12533 return -ENOENT; 12534 12535 if (event->attr.config != PERF_COUNT_SW_CPU_CLOCK) 12536 return -ENOENT; 12537 12538 /* 12539 * no branch sampling for software events 12540 */ 12541 if (has_branch_stack(event)) 12542 return -EOPNOTSUPP; 12543 12544 perf_swevent_init_hrtimer(event); 12545 12546 return 0; 12547 } 12548 12549 static struct pmu perf_cpu_clock = { 12550 .task_ctx_nr = perf_sw_context, 12551 12552 .capabilities = PERF_PMU_CAP_NO_NMI, 12553 .dev = PMU_NULL_DEV, 12554 12555 .event_init = cpu_clock_event_init, 12556 .add = cpu_clock_event_add, 12557 .del = cpu_clock_event_del, 12558 .start = cpu_clock_event_start, 12559 .stop = cpu_clock_event_stop, 12560 .read = cpu_clock_event_read, 12561 }; 12562 12563 /* 12564 * Software event: task time clock 12565 */ 12566 12567 static void task_clock_event_update(struct perf_event *event, u64 now) 12568 { 12569 u64 prev; 12570 s64 delta; 12571 12572 prev = local64_xchg(&event->hw.prev_count, now); 12573 delta = now - prev; 12574 local64_add(delta, &event->count); 12575 } 12576 12577 static void task_clock_event_start(struct perf_event *event, int flags) 12578 { 12579 event->hw.state = 0; 12580 local64_set(&event->hw.prev_count, event->ctx->time.time); 12581 perf_swevent_start_hrtimer(event); 12582 } 12583 12584 static void task_clock_event_stop(struct perf_event *event, int flags) 12585 { 12586 event->hw.state = PERF_HES_STOPPED; 12587 perf_swevent_cancel_hrtimer(event); 12588 if (flags & PERF_EF_UPDATE) 12589 task_clock_event_update(event, event->ctx->time.time); 12590 } 12591 12592 static int task_clock_event_add(struct perf_event *event, int flags) 12593 { 12594 if (flags & PERF_EF_START) 12595 task_clock_event_start(event, flags); 12596 perf_event_update_userpage(event); 12597 12598 return 0; 12599 } 12600 12601 static void task_clock_event_del(struct perf_event *event, int flags) 12602 { 12603 task_clock_event_stop(event, PERF_EF_UPDATE); 12604 } 12605 12606 static void task_clock_event_read(struct perf_event *event) 12607 { 12608 u64 now = perf_clock(); 12609 u64 delta = now - event->ctx->time.stamp; 12610 u64 time = event->ctx->time.time + delta; 12611 12612 task_clock_event_update(event, time); 12613 } 12614 12615 static int task_clock_event_init(struct perf_event *event) 12616 { 12617 if (event->attr.type != perf_task_clock.type) 12618 return -ENOENT; 12619 12620 if (event->attr.config != PERF_COUNT_SW_TASK_CLOCK) 12621 return -ENOENT; 12622 12623 /* 12624 * no branch sampling for software events 12625 */ 12626 if (has_branch_stack(event)) 12627 return -EOPNOTSUPP; 12628 12629 perf_swevent_init_hrtimer(event); 12630 12631 return 0; 12632 } 12633 12634 static struct pmu perf_task_clock = { 12635 .task_ctx_nr = perf_sw_context, 12636 12637 .capabilities = PERF_PMU_CAP_NO_NMI, 12638 .dev = PMU_NULL_DEV, 12639 12640 .event_init = task_clock_event_init, 12641 .add = task_clock_event_add, 12642 .del = task_clock_event_del, 12643 .start = task_clock_event_start, 12644 .stop = task_clock_event_stop, 12645 .read = task_clock_event_read, 12646 }; 12647 12648 static void perf_pmu_nop_void(struct pmu *pmu) 12649 { 12650 } 12651 12652 static void perf_pmu_nop_txn(struct pmu *pmu, unsigned int flags) 12653 { 12654 } 12655 12656 static int perf_pmu_nop_int(struct pmu *pmu) 12657 { 12658 return 0; 12659 } 12660 12661 static int perf_event_nop_int(struct perf_event *event, u64 value) 12662 { 12663 return 0; 12664 } 12665 12666 static DEFINE_PER_CPU(unsigned int, nop_txn_flags); 12667 12668 static void perf_pmu_start_txn(struct pmu *pmu, unsigned int flags) 12669 { 12670 __this_cpu_write(nop_txn_flags, flags); 12671 12672 if (flags & ~PERF_PMU_TXN_ADD) 12673 return; 12674 12675 perf_pmu_disable(pmu); 12676 } 12677 12678 static int perf_pmu_commit_txn(struct pmu *pmu) 12679 { 12680 unsigned int flags = __this_cpu_read(nop_txn_flags); 12681 12682 __this_cpu_write(nop_txn_flags, 0); 12683 12684 if (flags & ~PERF_PMU_TXN_ADD) 12685 return 0; 12686 12687 perf_pmu_enable(pmu); 12688 return 0; 12689 } 12690 12691 static void perf_pmu_cancel_txn(struct pmu *pmu) 12692 { 12693 unsigned int flags = __this_cpu_read(nop_txn_flags); 12694 12695 __this_cpu_write(nop_txn_flags, 0); 12696 12697 if (flags & ~PERF_PMU_TXN_ADD) 12698 return; 12699 12700 perf_pmu_enable(pmu); 12701 } 12702 12703 static int perf_event_idx_default(struct perf_event *event) 12704 { 12705 return 0; 12706 } 12707 12708 /* 12709 * Let userspace know that this PMU supports address range filtering: 12710 */ 12711 static ssize_t nr_addr_filters_show(struct device *dev, 12712 struct device_attribute *attr, 12713 char *page) 12714 { 12715 struct pmu *pmu = dev_get_drvdata(dev); 12716 12717 return sysfs_emit(page, "%d\n", pmu->nr_addr_filters); 12718 } 12719 DEVICE_ATTR_RO(nr_addr_filters); 12720 12721 static struct idr pmu_idr; 12722 12723 static ssize_t 12724 type_show(struct device *dev, struct device_attribute *attr, char *page) 12725 { 12726 struct pmu *pmu = dev_get_drvdata(dev); 12727 12728 return sysfs_emit(page, "%d\n", pmu->type); 12729 } 12730 static DEVICE_ATTR_RO(type); 12731 12732 static ssize_t 12733 perf_event_mux_interval_ms_show(struct device *dev, 12734 struct device_attribute *attr, 12735 char *page) 12736 { 12737 struct pmu *pmu = dev_get_drvdata(dev); 12738 12739 return sysfs_emit(page, "%d\n", pmu->hrtimer_interval_ms); 12740 } 12741 12742 static DEFINE_MUTEX(mux_interval_mutex); 12743 12744 static ssize_t 12745 perf_event_mux_interval_ms_store(struct device *dev, 12746 struct device_attribute *attr, 12747 const char *buf, size_t count) 12748 { 12749 struct pmu *pmu = dev_get_drvdata(dev); 12750 int timer, cpu, ret; 12751 12752 ret = kstrtoint(buf, 0, &timer); 12753 if (ret) 12754 return ret; 12755 12756 if (timer < 1) 12757 return -EINVAL; 12758 12759 /* same value, noting to do */ 12760 if (timer == pmu->hrtimer_interval_ms) 12761 return count; 12762 12763 mutex_lock(&mux_interval_mutex); 12764 pmu->hrtimer_interval_ms = timer; 12765 12766 /* update all cpuctx for this PMU */ 12767 cpus_read_lock(); 12768 for_each_online_cpu(cpu) { 12769 struct perf_cpu_pmu_context *cpc; 12770 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); 12771 cpc->hrtimer_interval = ns_to_ktime(NSEC_PER_MSEC * timer); 12772 12773 cpu_function_call(cpu, perf_mux_hrtimer_restart_ipi, cpc); 12774 } 12775 cpus_read_unlock(); 12776 mutex_unlock(&mux_interval_mutex); 12777 12778 return count; 12779 } 12780 static DEVICE_ATTR_RW(perf_event_mux_interval_ms); 12781 12782 static inline const struct cpumask *perf_scope_cpu_topology_cpumask(unsigned int scope, int cpu) 12783 { 12784 switch (scope) { 12785 case PERF_PMU_SCOPE_CORE: 12786 return topology_sibling_cpumask(cpu); 12787 case PERF_PMU_SCOPE_DIE: 12788 return topology_die_cpumask(cpu); 12789 case PERF_PMU_SCOPE_CLUSTER: 12790 return topology_cluster_cpumask(cpu); 12791 case PERF_PMU_SCOPE_PKG: 12792 return topology_core_cpumask(cpu); 12793 case PERF_PMU_SCOPE_SYS_WIDE: 12794 return cpu_online_mask; 12795 } 12796 12797 return NULL; 12798 } 12799 12800 static inline struct cpumask *perf_scope_cpumask(unsigned int scope) 12801 { 12802 switch (scope) { 12803 case PERF_PMU_SCOPE_CORE: 12804 return perf_online_core_mask; 12805 case PERF_PMU_SCOPE_DIE: 12806 return perf_online_die_mask; 12807 case PERF_PMU_SCOPE_CLUSTER: 12808 return perf_online_cluster_mask; 12809 case PERF_PMU_SCOPE_PKG: 12810 return perf_online_pkg_mask; 12811 case PERF_PMU_SCOPE_SYS_WIDE: 12812 return perf_online_sys_mask; 12813 } 12814 12815 return NULL; 12816 } 12817 12818 static ssize_t cpumask_show(struct device *dev, struct device_attribute *attr, 12819 char *buf) 12820 { 12821 struct pmu *pmu = dev_get_drvdata(dev); 12822 struct cpumask *mask = perf_scope_cpumask(pmu->scope); 12823 12824 if (mask) 12825 return sysfs_emit(buf, "%*pbl\n", cpumask_pr_args(mask)); 12826 return 0; 12827 } 12828 12829 static DEVICE_ATTR_RO(cpumask); 12830 12831 static struct attribute *pmu_dev_attrs[] = { 12832 &dev_attr_type.attr, 12833 &dev_attr_perf_event_mux_interval_ms.attr, 12834 &dev_attr_nr_addr_filters.attr, 12835 &dev_attr_cpumask.attr, 12836 NULL, 12837 }; 12838 12839 static umode_t pmu_dev_is_visible(struct kobject *kobj, struct attribute *a, int n) 12840 { 12841 struct device *dev = kobj_to_dev(kobj); 12842 struct pmu *pmu = dev_get_drvdata(dev); 12843 12844 if (n == 2 && !pmu->nr_addr_filters) 12845 return 0; 12846 12847 /* cpumask */ 12848 if (n == 3 && pmu->scope == PERF_PMU_SCOPE_NONE) 12849 return 0; 12850 12851 return a->mode; 12852 } 12853 12854 static struct attribute_group pmu_dev_attr_group = { 12855 .is_visible = pmu_dev_is_visible, 12856 .attrs = pmu_dev_attrs, 12857 }; 12858 12859 static const struct attribute_group *pmu_dev_groups[] = { 12860 &pmu_dev_attr_group, 12861 NULL, 12862 }; 12863 12864 static int pmu_bus_running; 12865 static const struct bus_type pmu_bus = { 12866 .name = "event_source", 12867 .dev_groups = pmu_dev_groups, 12868 }; 12869 12870 static void pmu_dev_release(struct device *dev) 12871 { 12872 kfree(dev); 12873 } 12874 12875 static int pmu_dev_alloc(struct pmu *pmu) 12876 { 12877 int ret = -ENOMEM; 12878 12879 pmu->dev = kzalloc_obj(struct device); 12880 if (!pmu->dev) 12881 goto out; 12882 12883 pmu->dev->groups = pmu->attr_groups; 12884 device_initialize(pmu->dev); 12885 12886 dev_set_drvdata(pmu->dev, pmu); 12887 pmu->dev->bus = &pmu_bus; 12888 pmu->dev->parent = pmu->parent; 12889 pmu->dev->release = pmu_dev_release; 12890 12891 ret = dev_set_name(pmu->dev, "%s", pmu->name); 12892 if (ret) 12893 goto free_dev; 12894 12895 ret = device_add(pmu->dev); 12896 if (ret) 12897 goto free_dev; 12898 12899 if (pmu->attr_update) { 12900 ret = sysfs_update_groups(&pmu->dev->kobj, pmu->attr_update); 12901 if (ret) 12902 goto del_dev; 12903 } 12904 12905 out: 12906 return ret; 12907 12908 del_dev: 12909 device_del(pmu->dev); 12910 12911 free_dev: 12912 put_device(pmu->dev); 12913 pmu->dev = NULL; 12914 goto out; 12915 } 12916 12917 static struct lock_class_key cpuctx_mutex; 12918 static struct lock_class_key cpuctx_lock; 12919 12920 static bool idr_cmpxchg(struct idr *idr, unsigned long id, void *old, void *new) 12921 { 12922 void *tmp, *val = idr_find(idr, id); 12923 12924 if (val != old) 12925 return false; 12926 12927 tmp = idr_replace(idr, new, id); 12928 if (IS_ERR(tmp)) 12929 return false; 12930 12931 WARN_ON_ONCE(tmp != val); 12932 return true; 12933 } 12934 12935 static void perf_pmu_free(struct pmu *pmu) 12936 { 12937 if (pmu_bus_running && pmu->dev && pmu->dev != PMU_NULL_DEV) { 12938 if (pmu->nr_addr_filters) 12939 device_remove_file(pmu->dev, &dev_attr_nr_addr_filters); 12940 device_del(pmu->dev); 12941 put_device(pmu->dev); 12942 } 12943 12944 if (pmu->cpu_pmu_context) { 12945 int cpu; 12946 12947 for_each_possible_cpu(cpu) { 12948 struct perf_cpu_pmu_context *cpc; 12949 12950 cpc = *per_cpu_ptr(pmu->cpu_pmu_context, cpu); 12951 if (!cpc) 12952 continue; 12953 if (cpc->epc.embedded) { 12954 /* refcount managed */ 12955 put_pmu_ctx(&cpc->epc); 12956 continue; 12957 } 12958 kfree(cpc); 12959 } 12960 free_percpu(pmu->cpu_pmu_context); 12961 } 12962 } 12963 12964 DEFINE_FREE(pmu_unregister, struct pmu *, if (_T) perf_pmu_free(_T)) 12965 12966 int perf_pmu_register(struct pmu *_pmu, const char *name, int type) 12967 { 12968 int cpu, max = PERF_TYPE_MAX; 12969 12970 struct pmu *pmu __free(pmu_unregister) = _pmu; 12971 guard(mutex)(&pmus_lock); 12972 12973 if (WARN_ONCE(!name, "Can not register anonymous pmu.\n")) 12974 return -EINVAL; 12975 12976 if (WARN_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE, 12977 "Can not register a pmu with an invalid scope.\n")) 12978 return -EINVAL; 12979 12980 pmu->name = name; 12981 12982 if (type >= 0) 12983 max = type; 12984 12985 CLASS(idr_alloc, pmu_type)(&pmu_idr, NULL, max, 0, GFP_KERNEL); 12986 if (pmu_type.id < 0) 12987 return pmu_type.id; 12988 12989 WARN_ON(type >= 0 && pmu_type.id != type); 12990 12991 pmu->type = pmu_type.id; 12992 atomic_set(&pmu->exclusive_cnt, 0); 12993 12994 if (pmu_bus_running && !pmu->dev) { 12995 int ret = pmu_dev_alloc(pmu); 12996 if (ret) 12997 return ret; 12998 } 12999 13000 pmu->cpu_pmu_context = alloc_percpu(struct perf_cpu_pmu_context *); 13001 if (!pmu->cpu_pmu_context) 13002 return -ENOMEM; 13003 13004 for_each_possible_cpu(cpu) { 13005 struct perf_cpu_pmu_context *cpc = 13006 kmalloc_node(sizeof(struct perf_cpu_pmu_context), 13007 GFP_KERNEL | __GFP_ZERO, 13008 cpu_to_node(cpu)); 13009 13010 if (!cpc) 13011 return -ENOMEM; 13012 13013 *per_cpu_ptr(pmu->cpu_pmu_context, cpu) = cpc; 13014 __perf_init_event_pmu_context(&cpc->epc, pmu); 13015 __perf_mux_hrtimer_init(cpc, cpu); 13016 } 13017 13018 if (!pmu->start_txn) { 13019 if (pmu->pmu_enable) { 13020 /* 13021 * If we have pmu_enable/pmu_disable calls, install 13022 * transaction stubs that use that to try and batch 13023 * hardware accesses. 13024 */ 13025 pmu->start_txn = perf_pmu_start_txn; 13026 pmu->commit_txn = perf_pmu_commit_txn; 13027 pmu->cancel_txn = perf_pmu_cancel_txn; 13028 } else { 13029 pmu->start_txn = perf_pmu_nop_txn; 13030 pmu->commit_txn = perf_pmu_nop_int; 13031 pmu->cancel_txn = perf_pmu_nop_void; 13032 } 13033 } 13034 13035 if (!pmu->pmu_enable) { 13036 pmu->pmu_enable = perf_pmu_nop_void; 13037 pmu->pmu_disable = perf_pmu_nop_void; 13038 } 13039 13040 if (!pmu->check_period) 13041 pmu->check_period = perf_event_nop_int; 13042 13043 if (!pmu->event_idx) 13044 pmu->event_idx = perf_event_idx_default; 13045 13046 INIT_LIST_HEAD(&pmu->events); 13047 spin_lock_init(&pmu->events_lock); 13048 13049 /* 13050 * Now that the PMU is complete, make it visible to perf_try_init_event(). 13051 */ 13052 if (!idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu)) 13053 return -EINVAL; 13054 list_add_rcu(&pmu->entry, &pmus); 13055 13056 take_idr_id(pmu_type); 13057 _pmu = no_free_ptr(pmu); // let it rip 13058 return 0; 13059 } 13060 EXPORT_SYMBOL_GPL(perf_pmu_register); 13061 13062 static void __pmu_detach_event(struct pmu *pmu, struct perf_event *event, 13063 struct perf_event_context *ctx) 13064 { 13065 /* 13066 * De-schedule the event and mark it REVOKED. 13067 */ 13068 perf_event_exit_event(event, ctx, ctx->task, DETACH_REVOKE); 13069 13070 /* 13071 * All _free_event() bits that rely on event->pmu: 13072 * 13073 * Notably, perf_mmap() relies on the ordering here. 13074 */ 13075 scoped_guard (mutex, &event->mmap_mutex) { 13076 WARN_ON_ONCE(pmu->event_unmapped); 13077 /* 13078 * Mostly an empty lock sequence, such that perf_mmap(), which 13079 * relies on mmap_mutex, is sure to observe the state change. 13080 */ 13081 } 13082 13083 perf_event_free_bpf_prog(event); 13084 perf_free_addr_filters(event); 13085 13086 if (event->destroy) { 13087 event->destroy(event); 13088 event->destroy = NULL; 13089 } 13090 13091 if (event->pmu_ctx) { 13092 put_pmu_ctx(event->pmu_ctx); 13093 event->pmu_ctx = NULL; 13094 } 13095 13096 exclusive_event_destroy(event); 13097 module_put(pmu->module); 13098 13099 mediated_pmu_unaccount_event(event); 13100 event->pmu = NULL; /* force fault instead of UAF */ 13101 } 13102 13103 static void pmu_detach_event(struct pmu *pmu, struct perf_event *event) 13104 { 13105 struct perf_event_context *ctx; 13106 13107 ctx = perf_event_ctx_lock(event); 13108 __pmu_detach_event(pmu, event, ctx); 13109 perf_event_ctx_unlock(event, ctx); 13110 13111 scoped_guard (spinlock, &pmu->events_lock) 13112 list_del(&event->pmu_list); 13113 } 13114 13115 static struct perf_event *pmu_get_event(struct pmu *pmu) 13116 { 13117 struct perf_event *event; 13118 13119 guard(spinlock)(&pmu->events_lock); 13120 list_for_each_entry(event, &pmu->events, pmu_list) { 13121 if (atomic_long_inc_not_zero(&event->refcount)) 13122 return event; 13123 } 13124 13125 return NULL; 13126 } 13127 13128 static bool pmu_empty(struct pmu *pmu) 13129 { 13130 guard(spinlock)(&pmu->events_lock); 13131 return list_empty(&pmu->events); 13132 } 13133 13134 static void pmu_detach_events(struct pmu *pmu) 13135 { 13136 struct perf_event *event; 13137 13138 for (;;) { 13139 event = pmu_get_event(pmu); 13140 if (!event) 13141 break; 13142 13143 pmu_detach_event(pmu, event); 13144 put_event(event); 13145 } 13146 13147 /* 13148 * wait for pending _free_event()s 13149 */ 13150 wait_var_event(pmu, pmu_empty(pmu)); 13151 } 13152 13153 int perf_pmu_unregister(struct pmu *pmu) 13154 { 13155 scoped_guard (mutex, &pmus_lock) { 13156 if (!idr_cmpxchg(&pmu_idr, pmu->type, pmu, NULL)) 13157 return -EINVAL; 13158 13159 list_del_rcu(&pmu->entry); 13160 } 13161 13162 /* 13163 * We dereference the pmu list under both SRCU and regular RCU, so 13164 * synchronize against both of those. 13165 * 13166 * Notably, the entirety of event creation, from perf_init_event() 13167 * (which will now fail, because of the above) until 13168 * perf_install_in_context() should be under SRCU such that 13169 * this synchronizes against event creation. This avoids trying to 13170 * detach events that are not fully formed. 13171 */ 13172 synchronize_srcu(&pmus_srcu); 13173 synchronize_rcu(); 13174 13175 if (pmu->event_unmapped && !pmu_empty(pmu)) { 13176 /* 13177 * Can't force remove events when pmu::event_unmapped() 13178 * is used in perf_mmap_close(). 13179 */ 13180 guard(mutex)(&pmus_lock); 13181 idr_cmpxchg(&pmu_idr, pmu->type, NULL, pmu); 13182 list_add_rcu(&pmu->entry, &pmus); 13183 return -EBUSY; 13184 } 13185 13186 scoped_guard (mutex, &pmus_lock) 13187 idr_remove(&pmu_idr, pmu->type); 13188 13189 /* 13190 * PMU is removed from the pmus list, so no new events will 13191 * be created, now take care of the existing ones. 13192 */ 13193 pmu_detach_events(pmu); 13194 13195 /* 13196 * PMU is unused, make it go away. 13197 */ 13198 perf_pmu_free(pmu); 13199 return 0; 13200 } 13201 EXPORT_SYMBOL_GPL(perf_pmu_unregister); 13202 13203 static int perf_try_init_event(struct pmu *pmu, struct perf_event *event) 13204 { 13205 struct perf_event_context *ctx = NULL; 13206 int ret; 13207 13208 if (!try_module_get(pmu->module)) 13209 return -ENODEV; 13210 13211 /* 13212 * A number of pmu->event_init() methods iterate the sibling_list to, 13213 * for example, validate if the group fits on the PMU. Therefore, 13214 * if this is a sibling event, acquire the ctx->mutex to protect 13215 * the sibling_list. 13216 */ 13217 if (event->group_leader != event && pmu->task_ctx_nr != perf_sw_context) { 13218 /* 13219 * This ctx->mutex can nest when we're called through 13220 * inheritance. See the perf_event_ctx_lock_nested() comment. 13221 */ 13222 ctx = perf_event_ctx_lock_nested(event->group_leader, 13223 SINGLE_DEPTH_NESTING); 13224 BUG_ON(!ctx); 13225 } 13226 13227 event->pmu = pmu; 13228 ret = pmu->event_init(event); 13229 13230 if (ctx) 13231 perf_event_ctx_unlock(event->group_leader, ctx); 13232 13233 if (ret) 13234 goto err_pmu; 13235 13236 if (!(pmu->capabilities & PERF_PMU_CAP_SIMD_REGS) && 13237 event_has_simd_regs(event)) { 13238 ret = -EOPNOTSUPP; 13239 goto err_destroy; 13240 } 13241 13242 if (!(pmu->capabilities & PERF_PMU_CAP_EXTENDED_REGS) && 13243 event_has_extended_regs(event)) { 13244 ret = -EOPNOTSUPP; 13245 goto err_destroy; 13246 } 13247 13248 if (pmu->capabilities & PERF_PMU_CAP_NO_EXCLUDE && 13249 event_has_any_exclude_flag(event)) { 13250 ret = -EINVAL; 13251 goto err_destroy; 13252 } 13253 13254 if (pmu->scope != PERF_PMU_SCOPE_NONE && event->cpu >= 0) { 13255 const struct cpumask *cpumask; 13256 struct cpumask *pmu_cpumask; 13257 int cpu; 13258 13259 cpumask = perf_scope_cpu_topology_cpumask(pmu->scope, event->cpu); 13260 pmu_cpumask = perf_scope_cpumask(pmu->scope); 13261 13262 ret = -ENODEV; 13263 if (!pmu_cpumask || !cpumask) 13264 goto err_destroy; 13265 13266 cpu = cpumask_any_and(pmu_cpumask, cpumask); 13267 if (cpu >= nr_cpu_ids) 13268 goto err_destroy; 13269 13270 event->event_caps |= PERF_EV_CAP_READ_SCOPE; 13271 } 13272 13273 return 0; 13274 13275 err_destroy: 13276 if (event->destroy) { 13277 event->destroy(event); 13278 event->destroy = NULL; 13279 } 13280 13281 err_pmu: 13282 event->pmu = NULL; 13283 module_put(pmu->module); 13284 return ret; 13285 } 13286 13287 static struct pmu *perf_init_event(struct perf_event *event) 13288 { 13289 bool extended_type = false; 13290 struct pmu *pmu; 13291 int type, ret; 13292 13293 guard(srcu)(&pmus_srcu); /* pmu idr/list access */ 13294 13295 /* 13296 * Save original type before calling pmu->event_init() since certain 13297 * pmus overwrites event->attr.type to forward event to another pmu. 13298 */ 13299 event->orig_type = event->attr.type; 13300 13301 /* Try parent's PMU first: */ 13302 if (event->parent && event->parent->pmu) { 13303 pmu = event->parent->pmu; 13304 ret = perf_try_init_event(pmu, event); 13305 if (!ret) 13306 return pmu; 13307 } 13308 13309 /* 13310 * PERF_TYPE_HARDWARE and PERF_TYPE_HW_CACHE 13311 * are often aliases for PERF_TYPE_RAW. 13312 */ 13313 type = event->attr.type; 13314 if (type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) { 13315 type = event->attr.config >> PERF_PMU_TYPE_SHIFT; 13316 if (!type) { 13317 type = PERF_TYPE_RAW; 13318 } else { 13319 extended_type = true; 13320 event->attr.config &= PERF_HW_EVENT_MASK; 13321 } 13322 } 13323 13324 again: 13325 scoped_guard (rcu) 13326 pmu = idr_find(&pmu_idr, type); 13327 if (pmu) { 13328 if (event->attr.type != type && type != PERF_TYPE_RAW && 13329 !(pmu->capabilities & PERF_PMU_CAP_EXTENDED_HW_TYPE)) 13330 return ERR_PTR(-ENOENT); 13331 13332 ret = perf_try_init_event(pmu, event); 13333 if (ret == -ENOENT && event->attr.type != type && !extended_type) { 13334 type = event->attr.type; 13335 goto again; 13336 } 13337 13338 if (ret) 13339 return ERR_PTR(ret); 13340 13341 return pmu; 13342 } 13343 13344 list_for_each_entry_rcu(pmu, &pmus, entry, lockdep_is_held(&pmus_srcu)) { 13345 ret = perf_try_init_event(pmu, event); 13346 if (!ret) 13347 return pmu; 13348 13349 if (ret != -ENOENT) 13350 return ERR_PTR(ret); 13351 } 13352 13353 return ERR_PTR(-ENOENT); 13354 } 13355 13356 static void attach_sb_event(struct perf_event *event) 13357 { 13358 struct pmu_event_list *pel = per_cpu_ptr(&pmu_sb_events, event->cpu); 13359 13360 raw_spin_lock(&pel->lock); 13361 list_add_rcu(&event->sb_list, &pel->list); 13362 raw_spin_unlock(&pel->lock); 13363 } 13364 13365 /* 13366 * We keep a list of all !task (and therefore per-cpu) events 13367 * that need to receive side-band records. 13368 * 13369 * This avoids having to scan all the various PMU per-cpu contexts 13370 * looking for them. 13371 */ 13372 static void account_pmu_sb_event(struct perf_event *event) 13373 { 13374 if (is_sb_event(event)) 13375 attach_sb_event(event); 13376 } 13377 13378 /* Freq events need the tick to stay alive (see perf_event_task_tick). */ 13379 static void account_freq_event_nohz(void) 13380 { 13381 #ifdef CONFIG_NO_HZ_FULL 13382 /* Lock so we don't race with concurrent unaccount */ 13383 spin_lock(&nr_freq_lock); 13384 if (atomic_inc_return(&nr_freq_events) == 1) 13385 tick_nohz_dep_set(TICK_DEP_BIT_PERF_EVENTS); 13386 spin_unlock(&nr_freq_lock); 13387 #endif 13388 } 13389 13390 static void account_freq_event(void) 13391 { 13392 if (tick_nohz_full_enabled()) 13393 account_freq_event_nohz(); 13394 else 13395 atomic_inc(&nr_freq_events); 13396 } 13397 13398 13399 static void account_event(struct perf_event *event) 13400 { 13401 bool inc = false; 13402 13403 if (event->parent) 13404 return; 13405 13406 if (event->attach_state & (PERF_ATTACH_TASK | PERF_ATTACH_SCHED_CB)) 13407 inc = true; 13408 if (event->attr.mmap || event->attr.mmap_data) 13409 atomic_inc(&nr_mmap_events); 13410 if (event->attr.build_id) 13411 atomic_inc(&nr_build_id_events); 13412 if (event->attr.comm) 13413 atomic_inc(&nr_comm_events); 13414 if (event->attr.namespaces) 13415 atomic_inc(&nr_namespaces_events); 13416 if (event->attr.cgroup) 13417 atomic_inc(&nr_cgroup_events); 13418 if (event->attr.task) 13419 atomic_inc(&nr_task_events); 13420 if (event->attr.freq) 13421 account_freq_event(); 13422 if (event->attr.context_switch) { 13423 atomic_inc(&nr_switch_events); 13424 inc = true; 13425 } 13426 if (has_branch_stack(event)) 13427 inc = true; 13428 if (is_cgroup_event(event)) 13429 inc = true; 13430 if (event->attr.ksymbol) 13431 atomic_inc(&nr_ksymbol_events); 13432 if (event->attr.bpf_event) 13433 atomic_inc(&nr_bpf_events); 13434 if (event->attr.text_poke) 13435 atomic_inc(&nr_text_poke_events); 13436 13437 if (inc) { 13438 /* 13439 * We need the mutex here because static_branch_enable() 13440 * must complete *before* the perf_sched_count increment 13441 * becomes visible. 13442 */ 13443 if (atomic_inc_not_zero(&perf_sched_count)) 13444 goto enabled; 13445 13446 mutex_lock(&perf_sched_mutex); 13447 if (!atomic_read(&perf_sched_count)) { 13448 static_branch_enable(&perf_sched_events); 13449 /* 13450 * Guarantee that all CPUs observe they key change and 13451 * call the perf scheduling hooks before proceeding to 13452 * install events that need them. 13453 */ 13454 synchronize_rcu(); 13455 } 13456 /* 13457 * Now that we have waited for the sync_sched(), allow further 13458 * increments to by-pass the mutex. 13459 */ 13460 atomic_inc(&perf_sched_count); 13461 mutex_unlock(&perf_sched_mutex); 13462 } 13463 enabled: 13464 13465 account_pmu_sb_event(event); 13466 } 13467 13468 /* 13469 * Allocate and initialize an event structure 13470 */ 13471 static struct perf_event * 13472 perf_event_alloc(struct perf_event_attr *attr, int cpu, 13473 struct task_struct *task, 13474 struct perf_event *group_leader, 13475 struct perf_event *parent_event, 13476 perf_overflow_handler_t overflow_handler, 13477 void *context, int cgroup_fd) 13478 { 13479 struct pmu *pmu; 13480 struct hw_perf_event *hwc; 13481 long err = -EINVAL; 13482 int node; 13483 13484 if ((unsigned)cpu >= nr_cpu_ids) { 13485 if (!task || cpu != -1) 13486 return ERR_PTR(-EINVAL); 13487 } 13488 if (attr->sigtrap && !task) { 13489 /* Requires a task: avoid signalling random tasks. */ 13490 return ERR_PTR(-EINVAL); 13491 } 13492 13493 node = (cpu >= 0) ? cpu_to_node(cpu) : -1; 13494 struct perf_event *event __free(__free_event) = 13495 kmem_cache_alloc_node(perf_event_cache, GFP_KERNEL | __GFP_ZERO, node); 13496 if (!event) 13497 return ERR_PTR(-ENOMEM); 13498 13499 /* 13500 * Single events are their own group leaders, with an 13501 * empty sibling list: 13502 */ 13503 if (!group_leader) 13504 group_leader = event; 13505 13506 mutex_init(&event->child_mutex); 13507 INIT_LIST_HEAD(&event->child_list); 13508 13509 INIT_LIST_HEAD(&event->event_entry); 13510 INIT_LIST_HEAD(&event->sibling_list); 13511 INIT_LIST_HEAD(&event->active_list); 13512 init_event_group(event); 13513 INIT_LIST_HEAD(&event->rb_entry); 13514 INIT_LIST_HEAD(&event->active_entry); 13515 INIT_LIST_HEAD(&event->addr_filters.list); 13516 INIT_HLIST_NODE(&event->hlist_entry); 13517 INIT_LIST_HEAD(&event->pmu_list); 13518 13519 13520 init_waitqueue_head(&event->waitq); 13521 init_irq_work(&event->pending_irq, perf_pending_irq); 13522 event->pending_disable_irq = IRQ_WORK_INIT_HARD(perf_pending_disable); 13523 init_task_work(&event->pending_task, perf_pending_task); 13524 13525 mutex_init(&event->mmap_mutex); 13526 raw_spin_lock_init(&event->addr_filters.lock); 13527 13528 atomic_long_set(&event->refcount, 1); 13529 event->cpu = cpu; 13530 event->attr = *attr; 13531 event->group_leader = group_leader; 13532 event->pmu = NULL; 13533 event->oncpu = -1; 13534 13535 event->parent = parent_event; 13536 13537 event->ns = get_pid_ns(task_active_pid_ns(current)); 13538 event->id = atomic64_inc_return(&perf_event_id); 13539 13540 event->state = PERF_EVENT_STATE_INACTIVE; 13541 13542 if (parent_event) 13543 event->event_caps = parent_event->event_caps; 13544 13545 if (task) { 13546 event->attach_state = PERF_ATTACH_TASK; 13547 /* 13548 * XXX pmu::event_init needs to know what task to account to 13549 * and we cannot use the ctx information because we need the 13550 * pmu before we get a ctx. 13551 */ 13552 event->hw.target = get_task_struct(task); 13553 } 13554 13555 event->clock = &local_clock; 13556 if (parent_event) 13557 event->clock = parent_event->clock; 13558 13559 if (!overflow_handler && parent_event) { 13560 overflow_handler = parent_event->overflow_handler; 13561 context = parent_event->overflow_handler_context; 13562 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_EVENT_TRACING) 13563 if (parent_event->prog) { 13564 struct bpf_prog *prog = parent_event->prog; 13565 13566 bpf_prog_inc(prog); 13567 event->prog = prog; 13568 } 13569 #endif 13570 } 13571 13572 if (overflow_handler) { 13573 event->overflow_handler = overflow_handler; 13574 event->overflow_handler_context = context; 13575 } else if (is_write_backward(event)){ 13576 event->overflow_handler = perf_event_output_backward; 13577 event->overflow_handler_context = NULL; 13578 } else { 13579 event->overflow_handler = perf_event_output_forward; 13580 event->overflow_handler_context = NULL; 13581 } 13582 13583 perf_event__state_init(event); 13584 13585 pmu = NULL; 13586 13587 hwc = &event->hw; 13588 hwc->sample_period = attr->sample_period; 13589 if (is_event_in_freq_mode(event)) 13590 hwc->sample_period = 1; 13591 hwc->last_period = hwc->sample_period; 13592 13593 local64_set(&hwc->period_left, hwc->sample_period); 13594 13595 /* 13596 * We do not support PERF_SAMPLE_READ on inherited events unless 13597 * PERF_SAMPLE_TID is also selected, which allows inherited events to 13598 * collect per-thread samples. 13599 * See perf_output_read(). 13600 */ 13601 if (has_inherit_and_sample_read(attr) && !(attr->sample_type & PERF_SAMPLE_TID)) 13602 return ERR_PTR(-EINVAL); 13603 13604 if (!has_branch_stack(event)) 13605 event->attr.branch_sample_type = 0; 13606 13607 pmu = perf_init_event(event); 13608 if (IS_ERR(pmu)) 13609 return (void*)pmu; 13610 13611 /* 13612 * The PERF_ATTACH_TASK_DATA is set in the event_init()->hw_config(). 13613 * The attach should be right after the perf_init_event(). 13614 * Otherwise, the __free_event() would mistakenly detach the non-exist 13615 * perf_ctx_data because of the other errors between them. 13616 */ 13617 if (event->attach_state & PERF_ATTACH_TASK_DATA) { 13618 err = attach_perf_ctx_data(event); 13619 if (err) 13620 return ERR_PTR(err); 13621 } 13622 13623 /* 13624 * Disallow uncore-task events. Similarly, disallow uncore-cgroup 13625 * events (they don't make sense as the cgroup will be different 13626 * on other CPUs in the uncore mask). 13627 */ 13628 if (pmu->task_ctx_nr == perf_invalid_context && (task || cgroup_fd != -1)) 13629 return ERR_PTR(-EINVAL); 13630 13631 if (event->attr.aux_output && 13632 (!(pmu->capabilities & PERF_PMU_CAP_AUX_OUTPUT) || 13633 event->attr.aux_pause || event->attr.aux_resume)) 13634 return ERR_PTR(-EOPNOTSUPP); 13635 13636 if (event->attr.aux_pause && event->attr.aux_resume) 13637 return ERR_PTR(-EINVAL); 13638 13639 if (event->attr.aux_start_paused) { 13640 if (!(pmu->capabilities & PERF_PMU_CAP_AUX_PAUSE)) 13641 return ERR_PTR(-EOPNOTSUPP); 13642 event->hw.aux_paused = 1; 13643 } 13644 13645 if (cgroup_fd != -1) { 13646 err = perf_cgroup_connect(cgroup_fd, event, attr, group_leader); 13647 if (err) 13648 return ERR_PTR(err); 13649 } 13650 13651 err = exclusive_event_init(event); 13652 if (err) 13653 return ERR_PTR(err); 13654 13655 if (has_addr_filter(event)) { 13656 event->addr_filter_ranges = kzalloc_objs(struct perf_addr_filter_range, 13657 pmu->nr_addr_filters); 13658 if (!event->addr_filter_ranges) 13659 return ERR_PTR(-ENOMEM); 13660 13661 /* 13662 * Clone the parent's vma offsets: they are valid until exec() 13663 * even if the mm is not shared with the parent. 13664 */ 13665 if (event->parent) { 13666 struct perf_addr_filters_head *ifh = perf_event_addr_filters(event); 13667 13668 raw_spin_lock_irq(&ifh->lock); 13669 memcpy(event->addr_filter_ranges, 13670 event->parent->addr_filter_ranges, 13671 pmu->nr_addr_filters * sizeof(struct perf_addr_filter_range)); 13672 raw_spin_unlock_irq(&ifh->lock); 13673 } 13674 13675 /* force hw sync on the address filters */ 13676 event->addr_filters_gen = 1; 13677 } 13678 13679 if (!event->parent) { 13680 if (event->attr.sample_type & PERF_SAMPLE_CALLCHAIN) { 13681 err = get_callchain_buffers(attr->sample_max_stack); 13682 if (err) 13683 return ERR_PTR(err); 13684 event->attach_state |= PERF_ATTACH_CALLCHAIN; 13685 } 13686 } 13687 13688 err = security_perf_event_alloc(event); 13689 if (err) 13690 return ERR_PTR(err); 13691 13692 err = mediated_pmu_account_event(event); 13693 if (err) 13694 return ERR_PTR(err); 13695 13696 /* symmetric to unaccount_event() in _free_event() */ 13697 account_event(event); 13698 13699 /* 13700 * Event creation should be under SRCU, see perf_pmu_unregister(). 13701 */ 13702 lockdep_assert_held(&pmus_srcu); 13703 scoped_guard (spinlock, &pmu->events_lock) 13704 list_add(&event->pmu_list, &pmu->events); 13705 13706 return_ptr(event); 13707 } 13708 13709 static int perf_copy_attr(struct perf_event_attr __user *uattr, 13710 struct perf_event_attr *attr) 13711 { 13712 u32 size; 13713 int ret; 13714 13715 /* Zero the full structure, so that a short copy will be nice. */ 13716 memset(attr, 0, sizeof(*attr)); 13717 13718 ret = get_user(size, &uattr->size); 13719 if (ret) 13720 return ret; 13721 13722 /* ABI compatibility quirk: */ 13723 if (!size) 13724 size = PERF_ATTR_SIZE_VER0; 13725 if (size < PERF_ATTR_SIZE_VER0 || size > PAGE_SIZE) 13726 goto err_size; 13727 13728 ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size); 13729 if (ret) { 13730 if (ret == -E2BIG) 13731 goto err_size; 13732 return ret; 13733 } 13734 13735 attr->size = size; 13736 13737 if (attr->__reserved_1 || attr->__reserved_2 || 13738 attr->__reserved_3 || attr->__reserved_4) 13739 return -EINVAL; 13740 13741 if (attr->sample_type & ~(PERF_SAMPLE_MAX-1)) 13742 return -EINVAL; 13743 13744 if (attr->read_format & ~(PERF_FORMAT_MAX-1)) 13745 return -EINVAL; 13746 13747 if (attr->sample_type & PERF_SAMPLE_BRANCH_STACK) { 13748 u64 mask = attr->branch_sample_type; 13749 13750 /* only using defined bits */ 13751 if (mask & ~(PERF_SAMPLE_BRANCH_MAX-1)) 13752 return -EINVAL; 13753 13754 /* at least one branch bit must be set */ 13755 if (!(mask & ~PERF_SAMPLE_BRANCH_PLM_ALL)) 13756 return -EINVAL; 13757 13758 /* propagate priv level, when not set for branch */ 13759 if (!(mask & PERF_SAMPLE_BRANCH_PLM_ALL)) { 13760 13761 /* exclude_kernel checked on syscall entry */ 13762 if (!attr->exclude_kernel) 13763 mask |= PERF_SAMPLE_BRANCH_KERNEL; 13764 13765 if (!attr->exclude_user) 13766 mask |= PERF_SAMPLE_BRANCH_USER; 13767 13768 if (!attr->exclude_hv) 13769 mask |= PERF_SAMPLE_BRANCH_HV; 13770 /* 13771 * adjust user setting (for HW filter setup) 13772 */ 13773 attr->branch_sample_type = mask; 13774 } 13775 /* privileged levels capture (kernel, hv): check permissions */ 13776 if (mask & PERF_SAMPLE_BRANCH_PERM_PLM) { 13777 ret = perf_allow_kernel(); 13778 if (ret) 13779 return ret; 13780 } 13781 } 13782 13783 if (attr->sample_type & PERF_SAMPLE_REGS_USER) { 13784 ret = perf_reg_validate(attr->sample_regs_user, 13785 attr->sample_simd_regs_enabled); 13786 if (ret) 13787 return ret; 13788 if (attr->sample_simd_regs_enabled) { 13789 ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, 13790 attr->sample_simd_vec_reg_user, 13791 attr->sample_simd_pred_reg_qwords, 13792 attr->sample_simd_pred_reg_user); 13793 if (ret) 13794 return ret; 13795 } 13796 } 13797 13798 if (attr->sample_type & PERF_SAMPLE_STACK_USER) { 13799 if (!arch_perf_have_user_stack_dump()) 13800 return -ENOSYS; 13801 13802 /* 13803 * We have __u32 type for the size, but so far 13804 * we can only use __u16 as maximum due to the 13805 * __u16 sample size limit. 13806 */ 13807 if (attr->sample_stack_user >= USHRT_MAX) 13808 return -EINVAL; 13809 else if (!IS_ALIGNED(attr->sample_stack_user, sizeof(u64))) 13810 return -EINVAL; 13811 } 13812 13813 if (!attr->sample_max_stack) 13814 attr->sample_max_stack = sysctl_perf_event_max_stack; 13815 13816 if (attr->sample_type & PERF_SAMPLE_REGS_INTR) { 13817 ret = perf_reg_validate(attr->sample_regs_intr, 13818 attr->sample_simd_regs_enabled); 13819 if (ret) 13820 return ret; 13821 if (attr->sample_simd_regs_enabled) { 13822 ret = perf_simd_reg_validate(attr->sample_simd_vec_reg_qwords, 13823 attr->sample_simd_vec_reg_intr, 13824 attr->sample_simd_pred_reg_qwords, 13825 attr->sample_simd_pred_reg_intr); 13826 if (ret) 13827 return ret; 13828 } 13829 } 13830 13831 #ifndef CONFIG_CGROUP_PERF 13832 if (attr->sample_type & PERF_SAMPLE_CGROUP) 13833 return -EINVAL; 13834 #endif 13835 if ((attr->sample_type & PERF_SAMPLE_WEIGHT) && 13836 (attr->sample_type & PERF_SAMPLE_WEIGHT_STRUCT)) 13837 return -EINVAL; 13838 13839 if (!attr->inherit && attr->inherit_thread) 13840 return -EINVAL; 13841 13842 if (attr->remove_on_exec && attr->enable_on_exec) 13843 return -EINVAL; 13844 13845 if (attr->sigtrap && !attr->remove_on_exec) 13846 return -EINVAL; 13847 13848 out: 13849 return ret; 13850 13851 err_size: 13852 put_user(sizeof(*attr), &uattr->size); 13853 ret = -E2BIG; 13854 goto out; 13855 } 13856 13857 static void mutex_lock_double(struct mutex *a, struct mutex *b) 13858 { 13859 if (b < a) 13860 swap(a, b); 13861 13862 mutex_lock(a); 13863 mutex_lock_nested(b, SINGLE_DEPTH_NESTING); 13864 } 13865 13866 static int 13867 perf_event_set_output(struct perf_event *event, struct perf_event *output_event) 13868 { 13869 struct perf_buffer *rb = NULL; 13870 int ret = -EINVAL; 13871 13872 if (!output_event) { 13873 mutex_lock(&event->mmap_mutex); 13874 goto set; 13875 } 13876 13877 /* don't allow circular references */ 13878 if (event == output_event) 13879 goto out; 13880 13881 /* 13882 * Don't allow cross-cpu buffers 13883 */ 13884 if (output_event->cpu != event->cpu) 13885 goto out; 13886 13887 /* 13888 * If its not a per-cpu rb, it must be the same task. 13889 */ 13890 if (output_event->cpu == -1 && output_event->hw.target != event->hw.target) 13891 goto out; 13892 13893 /* 13894 * Mixing clocks in the same buffer is trouble you don't need. 13895 */ 13896 if (output_event->clock != event->clock) 13897 goto out; 13898 13899 /* 13900 * Either writing ring buffer from beginning or from end. 13901 * Mixing is not allowed. 13902 */ 13903 if (is_write_backward(output_event) != is_write_backward(event)) 13904 goto out; 13905 13906 /* 13907 * If both events generate aux data, they must be on the same PMU 13908 */ 13909 if (has_aux(event) && has_aux(output_event) && 13910 event->pmu != output_event->pmu) 13911 goto out; 13912 13913 /* 13914 * Hold both mmap_mutex to serialize against perf_mmap_close(). Since 13915 * output_event is already on rb->event_list, and the list iteration 13916 * restarts after every removal, it is guaranteed this new event is 13917 * observed *OR* if output_event is already removed, it's guaranteed we 13918 * observe !rb->mmap_count. 13919 */ 13920 mutex_lock_double(&event->mmap_mutex, &output_event->mmap_mutex); 13921 set: 13922 /* Can't redirect output if we've got an active mmap() */ 13923 if (refcount_read(&event->mmap_count)) 13924 goto unlock; 13925 13926 if (output_event) { 13927 if (output_event->state <= PERF_EVENT_STATE_REVOKED) 13928 goto unlock; 13929 13930 /* get the rb we want to redirect to */ 13931 rb = ring_buffer_get(output_event); 13932 if (!rb) 13933 goto unlock; 13934 13935 /* did we race against perf_mmap_close() */ 13936 if (!refcount_read(&rb->mmap_count)) { 13937 ring_buffer_put(rb); 13938 goto unlock; 13939 } 13940 } 13941 13942 ring_buffer_attach(event, rb); 13943 13944 ret = 0; 13945 unlock: 13946 mutex_unlock(&event->mmap_mutex); 13947 if (output_event) 13948 mutex_unlock(&output_event->mmap_mutex); 13949 13950 out: 13951 return ret; 13952 } 13953 13954 static int perf_event_set_clock(struct perf_event *event, clockid_t clk_id) 13955 { 13956 bool nmi_safe = false; 13957 13958 switch (clk_id) { 13959 case CLOCK_MONOTONIC: 13960 event->clock = &ktime_get_mono_fast_ns; 13961 nmi_safe = true; 13962 break; 13963 13964 case CLOCK_MONOTONIC_RAW: 13965 event->clock = &ktime_get_raw_fast_ns; 13966 nmi_safe = true; 13967 break; 13968 13969 case CLOCK_REALTIME: 13970 event->clock = &ktime_get_real_ns; 13971 break; 13972 13973 case CLOCK_BOOTTIME: 13974 event->clock = &ktime_get_boottime_ns; 13975 break; 13976 13977 case CLOCK_TAI: 13978 event->clock = &ktime_get_clocktai_ns; 13979 break; 13980 13981 default: 13982 return -EINVAL; 13983 } 13984 13985 if (!nmi_safe && !(event->pmu->capabilities & PERF_PMU_CAP_NO_NMI)) 13986 return -EINVAL; 13987 13988 return 0; 13989 } 13990 13991 static bool 13992 perf_check_permission(struct perf_event_attr *attr, struct task_struct *task) 13993 { 13994 unsigned int ptrace_mode = PTRACE_MODE_READ_REALCREDS; 13995 bool is_capable = perfmon_capable(); 13996 13997 if (attr->sigtrap) { 13998 /* 13999 * perf_event_attr::sigtrap sends signals to the other task. 14000 * Require the current task to also have CAP_KILL. 14001 */ 14002 rcu_read_lock(); 14003 is_capable &= ns_capable(__task_cred(task)->user_ns, CAP_KILL); 14004 rcu_read_unlock(); 14005 14006 /* 14007 * If the required capabilities aren't available, checks for 14008 * ptrace permissions: upgrade to ATTACH, since sending signals 14009 * can effectively change the target task. 14010 */ 14011 ptrace_mode = PTRACE_MODE_ATTACH_REALCREDS; 14012 } 14013 14014 /* 14015 * Preserve ptrace permission check for backwards compatibility. The 14016 * ptrace check also includes checks that the current task and other 14017 * task have matching uids, and is therefore not done here explicitly. 14018 */ 14019 return is_capable || ptrace_may_access(task, ptrace_mode); 14020 } 14021 14022 /** 14023 * sys_perf_event_open - open a performance event, associate it to a task/cpu 14024 * 14025 * @attr_uptr: event_id type attributes for monitoring/sampling 14026 * @pid: target pid 14027 * @cpu: target cpu 14028 * @group_fd: group leader event fd 14029 * @flags: perf event open flags 14030 */ 14031 SYSCALL_DEFINE5(perf_event_open, 14032 struct perf_event_attr __user *, attr_uptr, 14033 pid_t, pid, int, cpu, int, group_fd, unsigned long, flags) 14034 { 14035 struct perf_event *group_leader = NULL, *output_event = NULL; 14036 struct perf_event_pmu_context *pmu_ctx; 14037 struct perf_event *event, *sibling; 14038 struct perf_event_attr attr; 14039 struct perf_event_context *ctx; 14040 struct file *event_file = NULL; 14041 struct task_struct *task = NULL; 14042 struct pmu *pmu; 14043 int event_fd; 14044 int move_group = 0; 14045 int err; 14046 int f_flags = O_RDWR; 14047 int cgroup_fd = -1; 14048 14049 /* for future expandability... */ 14050 if (flags & ~PERF_FLAG_ALL) 14051 return -EINVAL; 14052 14053 err = perf_copy_attr(attr_uptr, &attr); 14054 if (err) 14055 return err; 14056 14057 /* Do we allow access to perf_event_open(2) ? */ 14058 err = security_perf_event_open(PERF_SECURITY_OPEN); 14059 if (err) 14060 return err; 14061 14062 if (!attr.exclude_kernel || attr.text_poke || 14063 ((attr.sample_type & PERF_SAMPLE_CALLCHAIN) && 14064 !attr.exclude_callchain_kernel)) { 14065 err = perf_allow_kernel(); 14066 if (err) 14067 return err; 14068 } 14069 14070 if (attr.namespaces) { 14071 if (!perfmon_capable()) 14072 return -EACCES; 14073 } 14074 14075 if (attr.freq) { 14076 if (attr.sample_freq > sysctl_perf_event_sample_rate) 14077 return -EINVAL; 14078 } else { 14079 if (attr.sample_period & (1ULL << 63)) 14080 return -EINVAL; 14081 } 14082 14083 /* Only privileged users can get physical addresses */ 14084 if ((attr.sample_type & PERF_SAMPLE_PHYS_ADDR)) { 14085 err = perf_allow_kernel(); 14086 if (err) 14087 return err; 14088 } 14089 14090 /* REGS_INTR can leak data, lockdown must prevent this */ 14091 if (attr.sample_type & PERF_SAMPLE_REGS_INTR) { 14092 err = security_locked_down(LOCKDOWN_PERF); 14093 if (err) 14094 return err; 14095 } 14096 14097 /* 14098 * In cgroup mode, the pid argument is used to pass the fd 14099 * opened to the cgroup directory in cgroupfs. The cpu argument 14100 * designates the cpu on which to monitor threads from that 14101 * cgroup. 14102 */ 14103 if ((flags & PERF_FLAG_PID_CGROUP) && (pid == -1 || cpu == -1)) 14104 return -EINVAL; 14105 14106 if (flags & PERF_FLAG_FD_CLOEXEC) 14107 f_flags |= O_CLOEXEC; 14108 14109 event_fd = get_unused_fd_flags(f_flags); 14110 if (event_fd < 0) 14111 return event_fd; 14112 14113 /* 14114 * Event creation should be under SRCU, see perf_pmu_unregister(). 14115 */ 14116 guard(srcu)(&pmus_srcu); 14117 14118 CLASS(fd, group)(group_fd); // group_fd == -1 => empty 14119 if (group_fd != -1) { 14120 if (!is_perf_file(group)) { 14121 err = -EBADF; 14122 goto err_fd; 14123 } 14124 group_leader = fd_file(group)->private_data; 14125 if (group_leader->state <= PERF_EVENT_STATE_EXIT) { 14126 err = -ENODEV; 14127 goto err_fd; 14128 } 14129 if (flags & PERF_FLAG_FD_OUTPUT) 14130 output_event = group_leader; 14131 if (flags & PERF_FLAG_FD_NO_GROUP) 14132 group_leader = NULL; 14133 } 14134 14135 if (pid != -1 && !(flags & PERF_FLAG_PID_CGROUP)) { 14136 task = find_lively_task_by_vpid(pid); 14137 if (IS_ERR(task)) { 14138 err = PTR_ERR(task); 14139 goto err_fd; 14140 } 14141 } 14142 14143 if (task && group_leader && 14144 group_leader->attr.inherit != attr.inherit) { 14145 err = -EINVAL; 14146 goto err_task; 14147 } 14148 14149 if (flags & PERF_FLAG_PID_CGROUP) 14150 cgroup_fd = pid; 14151 14152 event = perf_event_alloc(&attr, cpu, task, group_leader, NULL, 14153 NULL, NULL, cgroup_fd); 14154 if (IS_ERR(event)) { 14155 err = PTR_ERR(event); 14156 goto err_task; 14157 } 14158 14159 if (is_sampling_event(event)) { 14160 if (event->pmu->capabilities & PERF_PMU_CAP_NO_INTERRUPT) { 14161 err = -EOPNOTSUPP; 14162 goto err_alloc; 14163 } 14164 } 14165 14166 /* 14167 * Special case software events and allow them to be part of 14168 * any hardware group. 14169 */ 14170 pmu = event->pmu; 14171 14172 if (attr.use_clockid) { 14173 err = perf_event_set_clock(event, attr.clockid); 14174 if (err) 14175 goto err_alloc; 14176 } 14177 14178 if (pmu->task_ctx_nr == perf_sw_context) 14179 event->event_caps |= PERF_EV_CAP_SOFTWARE; 14180 14181 if (task) { 14182 err = down_read_interruptible(&task->signal->exec_update_lock); 14183 if (err) 14184 goto err_alloc; 14185 14186 /* 14187 * We must hold exec_update_lock across this and any potential 14188 * perf_install_in_context() call for this new event to 14189 * serialize against exec() altering our credentials (and the 14190 * perf_event_exit_task() that could imply). 14191 */ 14192 err = -EACCES; 14193 if (!perf_check_permission(&attr, task)) 14194 goto err_cred; 14195 } 14196 14197 /* 14198 * Get the target context (task or percpu): 14199 */ 14200 ctx = find_get_context(task, event); 14201 if (IS_ERR(ctx)) { 14202 err = PTR_ERR(ctx); 14203 goto err_cred; 14204 } 14205 14206 mutex_lock(&ctx->mutex); 14207 14208 if (ctx->task == TASK_TOMBSTONE) { 14209 err = -ESRCH; 14210 goto err_locked; 14211 } 14212 14213 if (!task) { 14214 /* 14215 * Check if the @cpu we're creating an event for is online. 14216 * 14217 * We use the perf_cpu_context::ctx::mutex to serialize against 14218 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 14219 */ 14220 struct perf_cpu_context *cpuctx = per_cpu_ptr(&perf_cpu_context, event->cpu); 14221 14222 if (!cpuctx->online) { 14223 err = -ENODEV; 14224 goto err_locked; 14225 } 14226 } 14227 14228 if (group_leader) { 14229 err = -EINVAL; 14230 14231 /* 14232 * Do not allow a recursive hierarchy (this new sibling 14233 * becoming part of another group-sibling): 14234 */ 14235 if (group_leader->group_leader != group_leader) 14236 goto err_locked; 14237 14238 /* All events in a group should have the same clock */ 14239 if (group_leader->clock != event->clock) 14240 goto err_locked; 14241 14242 /* 14243 * Make sure we're both events for the same CPU; 14244 * grouping events for different CPUs is broken; since 14245 * you can never concurrently schedule them anyhow. 14246 */ 14247 if (group_leader->cpu != event->cpu) 14248 goto err_locked; 14249 14250 /* 14251 * Make sure we're both on the same context; either task or cpu. 14252 */ 14253 if (group_leader->ctx != ctx) 14254 goto err_locked; 14255 14256 /* Recheck under ctx::mutex to serialize against remove-on-exec. */ 14257 if (group_leader->state <= PERF_EVENT_STATE_EXIT) { 14258 err = -ENODEV; 14259 goto err_locked; 14260 } 14261 14262 /* 14263 * Only a group leader can be exclusive or pinned 14264 */ 14265 if (attr.exclusive || attr.pinned) 14266 goto err_locked; 14267 14268 if (is_software_event(event) && 14269 !in_software_context(group_leader)) { 14270 /* 14271 * If the event is a sw event, but the group_leader 14272 * is on hw context. 14273 * 14274 * Allow the addition of software events to hw 14275 * groups, this is safe because software events 14276 * never fail to schedule. 14277 * 14278 * Note the comment that goes with struct 14279 * perf_event_pmu_context. 14280 */ 14281 pmu = group_leader->pmu_ctx->pmu; 14282 } else if (!is_software_event(event)) { 14283 if (is_software_event(group_leader) && 14284 (group_leader->group_caps & PERF_EV_CAP_SOFTWARE)) { 14285 /* 14286 * In case the group is a pure software group, and we 14287 * try to add a hardware event, move the whole group to 14288 * the hardware context. 14289 */ 14290 move_group = 1; 14291 } 14292 14293 /* Don't allow group of multiple hw events from different pmus */ 14294 if (!in_software_context(group_leader) && 14295 group_leader->pmu_ctx->pmu != pmu) 14296 goto err_locked; 14297 } 14298 } 14299 14300 /* 14301 * Now that we're certain of the pmu; find the pmu_ctx. 14302 */ 14303 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 14304 if (IS_ERR(pmu_ctx)) { 14305 err = PTR_ERR(pmu_ctx); 14306 goto err_locked; 14307 } 14308 event->pmu_ctx = pmu_ctx; 14309 14310 if (output_event) { 14311 err = perf_event_set_output(event, output_event); 14312 if (err) 14313 goto err_context; 14314 } 14315 14316 if (!perf_event_validate_size(event)) { 14317 err = -E2BIG; 14318 goto err_context; 14319 } 14320 14321 if (perf_need_aux_event(event) && !perf_get_aux_event(event, group_leader)) { 14322 err = -EINVAL; 14323 goto err_context; 14324 } 14325 14326 /* 14327 * Must be under the same ctx::mutex as perf_install_in_context(), 14328 * because we need to serialize with concurrent event creation. 14329 */ 14330 if (!exclusive_event_installable(event, ctx)) { 14331 err = -EBUSY; 14332 goto err_context; 14333 } 14334 14335 WARN_ON_ONCE(ctx->parent_ctx); 14336 14337 event_file = anon_inode_getfile("[perf_event]", &perf_fops, event, f_flags); 14338 if (IS_ERR(event_file)) { 14339 err = PTR_ERR(event_file); 14340 event_file = NULL; 14341 goto err_context; 14342 } 14343 14344 /* 14345 * This is the point on no return; we cannot fail hereafter. This is 14346 * where we start modifying current state. 14347 */ 14348 14349 if (move_group) { 14350 perf_remove_from_context(group_leader, 0); 14351 put_pmu_ctx(group_leader->pmu_ctx); 14352 14353 for_each_sibling_event(sibling, group_leader) { 14354 perf_remove_from_context(sibling, 0); 14355 put_pmu_ctx(sibling->pmu_ctx); 14356 } 14357 14358 /* 14359 * Install the group siblings before the group leader. 14360 * 14361 * Because a group leader will try and install the entire group 14362 * (through the sibling list, which is still in-tact), we can 14363 * end up with siblings installed in the wrong context. 14364 * 14365 * By installing siblings first we NO-OP because they're not 14366 * reachable through the group lists. 14367 */ 14368 for_each_sibling_event(sibling, group_leader) { 14369 sibling->pmu_ctx = pmu_ctx; 14370 get_pmu_ctx(pmu_ctx); 14371 perf_event__state_init(sibling); 14372 perf_install_in_context(ctx, sibling, sibling->cpu); 14373 } 14374 14375 /* 14376 * Removing from the context ends up with disabled 14377 * event. What we want here is event in the initial 14378 * startup state, ready to be add into new context. 14379 */ 14380 group_leader->pmu_ctx = pmu_ctx; 14381 get_pmu_ctx(pmu_ctx); 14382 perf_event__state_init(group_leader); 14383 perf_install_in_context(ctx, group_leader, group_leader->cpu); 14384 } 14385 14386 /* 14387 * Precalculate sample_data sizes; do while holding ctx::mutex such 14388 * that we're serialized against further additions and before 14389 * perf_install_in_context() which is the point the event is active and 14390 * can use these values. 14391 */ 14392 perf_event__header_size(event); 14393 perf_event__id_header_size(event); 14394 14395 event->owner = current; 14396 14397 perf_install_in_context(ctx, event, event->cpu); 14398 perf_unpin_context(ctx); 14399 14400 mutex_unlock(&ctx->mutex); 14401 14402 if (task) { 14403 up_read(&task->signal->exec_update_lock); 14404 put_task_struct(task); 14405 } 14406 14407 mutex_lock(¤t->perf_event_mutex); 14408 list_add_tail(&event->owner_entry, ¤t->perf_event_list); 14409 mutex_unlock(¤t->perf_event_mutex); 14410 14411 /* 14412 * File reference in group guarantees that group_leader has been 14413 * kept alive until we place the new event on the sibling_list. 14414 * This ensures destruction of the group leader will find 14415 * the pointer to itself in perf_group_detach(). 14416 */ 14417 fd_install(event_fd, event_file); 14418 return event_fd; 14419 14420 err_context: 14421 put_pmu_ctx(event->pmu_ctx); 14422 event->pmu_ctx = NULL; /* _free_event() */ 14423 err_locked: 14424 mutex_unlock(&ctx->mutex); 14425 perf_unpin_context(ctx); 14426 put_ctx(ctx); 14427 err_cred: 14428 if (task) 14429 up_read(&task->signal->exec_update_lock); 14430 err_alloc: 14431 put_event(event); 14432 err_task: 14433 if (task) 14434 put_task_struct(task); 14435 err_fd: 14436 put_unused_fd(event_fd); 14437 return err; 14438 } 14439 14440 /** 14441 * perf_event_create_kernel_counter 14442 * 14443 * @attr: attributes of the counter to create 14444 * @cpu: cpu in which the counter is bound 14445 * @task: task to profile (NULL for percpu) 14446 * @overflow_handler: callback to trigger when we hit the event 14447 * @context: context data could be used in overflow_handler callback 14448 */ 14449 struct perf_event * 14450 perf_event_create_kernel_counter(struct perf_event_attr *attr, int cpu, 14451 struct task_struct *task, 14452 perf_overflow_handler_t overflow_handler, 14453 void *context) 14454 { 14455 struct perf_event_pmu_context *pmu_ctx; 14456 struct perf_event_context *ctx; 14457 struct perf_event *event; 14458 struct pmu *pmu; 14459 int err; 14460 14461 /* 14462 * Grouping is not supported for kernel events, neither is 'AUX', 14463 * make sure the caller's intentions are adjusted. 14464 */ 14465 if (attr->aux_output || attr->aux_action) 14466 return ERR_PTR(-EINVAL); 14467 14468 /* 14469 * Event creation should be under SRCU, see perf_pmu_unregister(). 14470 */ 14471 guard(srcu)(&pmus_srcu); 14472 14473 event = perf_event_alloc(attr, cpu, task, NULL, NULL, 14474 overflow_handler, context, -1); 14475 if (IS_ERR(event)) { 14476 err = PTR_ERR(event); 14477 goto err; 14478 } 14479 14480 /* Mark owner so we could distinguish it from user events. */ 14481 event->owner = TASK_TOMBSTONE; 14482 pmu = event->pmu; 14483 14484 if (pmu->task_ctx_nr == perf_sw_context) 14485 event->event_caps |= PERF_EV_CAP_SOFTWARE; 14486 14487 /* 14488 * Get the target context (task or percpu): 14489 */ 14490 ctx = find_get_context(task, event); 14491 if (IS_ERR(ctx)) { 14492 err = PTR_ERR(ctx); 14493 goto err_alloc; 14494 } 14495 14496 WARN_ON_ONCE(ctx->parent_ctx); 14497 mutex_lock(&ctx->mutex); 14498 if (ctx->task == TASK_TOMBSTONE) { 14499 err = -ESRCH; 14500 goto err_unlock; 14501 } 14502 14503 pmu_ctx = find_get_pmu_context(pmu, ctx, event); 14504 if (IS_ERR(pmu_ctx)) { 14505 err = PTR_ERR(pmu_ctx); 14506 goto err_unlock; 14507 } 14508 event->pmu_ctx = pmu_ctx; 14509 14510 if (!task) { 14511 /* 14512 * Check if the @cpu we're creating an event for is online. 14513 * 14514 * We use the perf_cpu_context::ctx::mutex to serialize against 14515 * the hotplug notifiers. See perf_event_{init,exit}_cpu(). 14516 */ 14517 struct perf_cpu_context *cpuctx = 14518 container_of(ctx, struct perf_cpu_context, ctx); 14519 if (!cpuctx->online) { 14520 err = -ENODEV; 14521 goto err_pmu_ctx; 14522 } 14523 } 14524 14525 if (!exclusive_event_installable(event, ctx)) { 14526 err = -EBUSY; 14527 goto err_pmu_ctx; 14528 } 14529 14530 perf_install_in_context(ctx, event, event->cpu); 14531 perf_unpin_context(ctx); 14532 mutex_unlock(&ctx->mutex); 14533 14534 return event; 14535 14536 err_pmu_ctx: 14537 put_pmu_ctx(pmu_ctx); 14538 event->pmu_ctx = NULL; /* _free_event() */ 14539 err_unlock: 14540 mutex_unlock(&ctx->mutex); 14541 perf_unpin_context(ctx); 14542 put_ctx(ctx); 14543 err_alloc: 14544 put_event(event); 14545 err: 14546 return ERR_PTR(err); 14547 } 14548 EXPORT_SYMBOL_GPL(perf_event_create_kernel_counter); 14549 14550 static void __perf_pmu_remove(struct perf_event_context *ctx, struct pmu *pmu, 14551 struct list_head *events) 14552 { 14553 struct perf_event *event, *tmp; 14554 14555 list_for_each_entry_safe(event, tmp, &ctx->event_list, event_entry) { 14556 if (event->pmu_ctx->pmu != pmu) 14557 continue; 14558 14559 perf_remove_from_context(event, 0); 14560 put_pmu_ctx(event->pmu_ctx); 14561 list_add(&event->migrate_entry, events); 14562 } 14563 } 14564 14565 static void __perf_pmu_install_event(struct pmu *pmu, 14566 struct perf_event_context *ctx, 14567 int cpu, struct perf_event *event) 14568 { 14569 struct perf_event_pmu_context *epc; 14570 struct perf_event_context *old_ctx = event->ctx; 14571 14572 get_ctx(ctx); /* normally find_get_context() */ 14573 14574 event->cpu = cpu; 14575 epc = find_get_pmu_context(pmu, ctx, event); 14576 event->pmu_ctx = epc; 14577 14578 if (event->state >= PERF_EVENT_STATE_OFF) 14579 event->state = PERF_EVENT_STATE_INACTIVE; 14580 perf_install_in_context(ctx, event, cpu); 14581 14582 /* 14583 * Now that event->ctx is updated and visible, put the old ctx. 14584 */ 14585 put_ctx(old_ctx); 14586 } 14587 14588 static void __perf_pmu_install(struct perf_event_context *ctx, 14589 int cpu, struct pmu *pmu, struct list_head *events) 14590 { 14591 struct perf_event *event, *tmp; 14592 14593 /* 14594 * Re-instate events in 2 passes. 14595 * 14596 * Skip over group leaders and only install siblings on this first 14597 * pass, siblings will not get enabled without a leader, however a 14598 * leader will enable its siblings, even if those are still on the old 14599 * context. 14600 */ 14601 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 14602 if (event->group_leader == event) 14603 continue; 14604 14605 list_del(&event->migrate_entry); 14606 __perf_pmu_install_event(pmu, ctx, cpu, event); 14607 } 14608 14609 /* 14610 * Once all the siblings are setup properly, install the group leaders 14611 * to make it go. 14612 */ 14613 list_for_each_entry_safe(event, tmp, events, migrate_entry) { 14614 list_del(&event->migrate_entry); 14615 __perf_pmu_install_event(pmu, ctx, cpu, event); 14616 } 14617 } 14618 14619 void perf_pmu_migrate_context(struct pmu *pmu, int src_cpu, int dst_cpu) 14620 { 14621 struct perf_event_context *src_ctx, *dst_ctx; 14622 LIST_HEAD(events); 14623 14624 /* 14625 * Since per-cpu context is persistent, no need to grab an extra 14626 * reference. 14627 */ 14628 src_ctx = &per_cpu_ptr(&perf_cpu_context, src_cpu)->ctx; 14629 dst_ctx = &per_cpu_ptr(&perf_cpu_context, dst_cpu)->ctx; 14630 14631 /* 14632 * See perf_event_ctx_lock() for comments on the details 14633 * of swizzling perf_event::ctx. 14634 */ 14635 mutex_lock_double(&src_ctx->mutex, &dst_ctx->mutex); 14636 14637 __perf_pmu_remove(src_ctx, pmu, &events); 14638 14639 if (!list_empty(&events)) { 14640 /* 14641 * Wait for the events to quiesce before re-instating them. 14642 */ 14643 synchronize_rcu(); 14644 14645 __perf_pmu_install(dst_ctx, dst_cpu, pmu, &events); 14646 } 14647 14648 mutex_unlock(&dst_ctx->mutex); 14649 mutex_unlock(&src_ctx->mutex); 14650 } 14651 EXPORT_SYMBOL_GPL(perf_pmu_migrate_context); 14652 14653 static void sync_child_event(struct perf_event *child_event, 14654 struct task_struct *task) 14655 { 14656 struct perf_event *parent_event = child_event->parent; 14657 u64 child_val; 14658 14659 if (child_event->attr.inherit_stat) { 14660 if (task && task != TASK_TOMBSTONE) 14661 perf_event_read_event(child_event, task); 14662 } 14663 14664 child_val = perf_event_count(child_event, false); 14665 14666 /* 14667 * Add back the child's count to the parent's count: 14668 */ 14669 atomic64_add(child_val, &parent_event->child_count); 14670 atomic64_add(child_event->total_time_enabled, 14671 &parent_event->child_total_time_enabled); 14672 atomic64_add(child_event->total_time_running, 14673 &parent_event->child_total_time_running); 14674 } 14675 14676 static void 14677 perf_event_exit_event(struct perf_event *event, 14678 struct perf_event_context *ctx, 14679 struct task_struct *task, 14680 unsigned long detach_flags) 14681 { 14682 struct perf_event *parent_event = event->parent; 14683 unsigned int attach_state; 14684 14685 detach_flags |= DETACH_EXIT; 14686 14687 if (parent_event) { 14688 /* 14689 * Do not destroy the 'original' grouping; because of the 14690 * context switch optimization the original events could've 14691 * ended up in a random child task. 14692 * 14693 * If we were to destroy the original group, all group related 14694 * operations would cease to function properly after this 14695 * random child dies. 14696 * 14697 * Do destroy all inherited groups, we don't care about those 14698 * and being thorough is better. 14699 */ 14700 detach_flags |= DETACH_GROUP | DETACH_CHILD; 14701 mutex_lock(&parent_event->child_mutex); 14702 /* PERF_ATTACH_ITRACE might be set concurrently */ 14703 attach_state = READ_ONCE(event->attach_state); 14704 14705 if (attach_state & PERF_ATTACH_CHILD) 14706 sync_child_event(event, task); 14707 } 14708 14709 if (detach_flags & DETACH_REVOKE) 14710 detach_flags |= DETACH_GROUP; 14711 14712 perf_remove_from_context(event, detach_flags); 14713 /* 14714 * Child events can be freed. 14715 */ 14716 if (parent_event) { 14717 mutex_unlock(&parent_event->child_mutex); 14718 14719 /* 14720 * Match the refcount initialization. Make sure it doesn't happen 14721 * twice if pmu_detach_event() calls it on an already exited task. 14722 */ 14723 if (attach_state & PERF_ATTACH_CHILD) { 14724 /* 14725 * Kick perf_poll() for is_event_hup(); 14726 */ 14727 perf_event_wakeup(parent_event); 14728 /* 14729 * pmu_detach_event() will have an extra refcount. 14730 * perf_pending_task() might have one too. 14731 */ 14732 put_event(event); 14733 } 14734 14735 return; 14736 } 14737 14738 /* 14739 * Parent events are governed by their filedesc, retain them. 14740 */ 14741 perf_event_wakeup(event); 14742 } 14743 14744 static void perf_event_exit_task_context(struct task_struct *task, bool exit) 14745 { 14746 struct perf_event_context *ctx, *clone_ctx = NULL; 14747 struct perf_event *child_event, *next; 14748 14749 ctx = perf_pin_task_context(task); 14750 if (!ctx) 14751 return; 14752 14753 /* 14754 * In order to reduce the amount of tricky in ctx tear-down, we hold 14755 * ctx::mutex over the entire thing. This serializes against almost 14756 * everything that wants to access the ctx. 14757 * 14758 * The exception is sys_perf_event_open() / 14759 * perf_event_create_kernel_count() which does find_get_context() 14760 * without ctx::mutex (it cannot because of the move_group double mutex 14761 * lock thing). See the comments in perf_install_in_context(). 14762 */ 14763 mutex_lock(&ctx->mutex); 14764 14765 /* 14766 * In a single ctx::lock section, de-schedule the events and detach the 14767 * context from the task such that we cannot ever get it scheduled back 14768 * in. 14769 */ 14770 raw_spin_lock_irq(&ctx->lock); 14771 if (exit) 14772 task_ctx_sched_out(ctx, NULL, EVENT_ALL); 14773 14774 /* 14775 * Now that the context is inactive, destroy the task <-> ctx relation 14776 * and mark the context dead. 14777 */ 14778 RCU_INIT_POINTER(task->perf_event_ctxp, NULL); 14779 put_ctx(ctx); /* cannot be last */ 14780 WRITE_ONCE(ctx->task, TASK_TOMBSTONE); 14781 put_task_struct(task); /* cannot be last */ 14782 14783 clone_ctx = unclone_ctx(ctx); 14784 raw_spin_unlock_irq(&ctx->lock); 14785 14786 if (clone_ctx) 14787 put_ctx(clone_ctx); 14788 14789 /* 14790 * Report the task dead after unscheduling the events so that we 14791 * won't get any samples after PERF_RECORD_EXIT. We can however still 14792 * get a few PERF_RECORD_READ events. 14793 */ 14794 if (exit) 14795 perf_event_task(task, ctx, 0); 14796 14797 list_for_each_entry_safe(child_event, next, &ctx->event_list, event_entry) 14798 perf_event_exit_event(child_event, ctx, exit ? task : NULL, 0); 14799 14800 mutex_unlock(&ctx->mutex); 14801 14802 if (!exit) { 14803 /* 14804 * perf_event_release_kernel() could still have a reference on 14805 * this context. In that case we must wait for these events to 14806 * have been freed (in particular all their references to this 14807 * task must've been dropped). 14808 * 14809 * Without this copy_process() will unconditionally free this 14810 * task (irrespective of its reference count) and 14811 * _free_event()'s put_task_struct(event->hw.target) will be a 14812 * use-after-free. 14813 * 14814 * Wait for all events to drop their context reference. 14815 */ 14816 wait_var_event(&ctx->refcount, 14817 refcount_read(&ctx->refcount) == 1); 14818 } 14819 put_ctx(ctx); 14820 } 14821 14822 /* 14823 * When a task exits, feed back event values to parent events. 14824 * 14825 * Can be called with exec_update_lock held when called from 14826 * setup_new_exec(). 14827 */ 14828 void perf_event_exit_task(struct task_struct *task) 14829 { 14830 struct perf_event *event, *tmp; 14831 14832 WARN_ON_ONCE(task != current); 14833 14834 mutex_lock(&task->perf_event_mutex); 14835 list_for_each_entry_safe(event, tmp, &task->perf_event_list, 14836 owner_entry) { 14837 list_del_init(&event->owner_entry); 14838 14839 /* 14840 * Ensure the list deletion is visible before we clear 14841 * the owner, closes a race against perf_release() where 14842 * we need to serialize on the owner->perf_event_mutex. 14843 */ 14844 smp_store_release(&event->owner, NULL); 14845 } 14846 mutex_unlock(&task->perf_event_mutex); 14847 14848 perf_event_exit_task_context(task, true); 14849 14850 /* 14851 * The perf_event_exit_task_context calls perf_event_task 14852 * with task's task_ctx, which generates EXIT events for 14853 * task contexts and sets task->perf_event_ctxp[] to NULL. 14854 * At this point we need to send EXIT events to cpu contexts. 14855 */ 14856 perf_event_task(task, NULL, 0); 14857 14858 /* 14859 * Detach the perf_ctx_data for the system-wide event. 14860 * 14861 * Done without holding global_ctx_data_rwsem; typically 14862 * attach_global_ctx_data() will skip over this task, but otherwise 14863 * attach_task_ctx_data() will observe PF_EXITING. 14864 */ 14865 detach_task_ctx_data(task); 14866 } 14867 14868 /* 14869 * Free a context as created by inheritance by perf_event_init_task() below, 14870 * used by fork() in case of fail. 14871 * 14872 * Even though the task has never lived, the context and events have been 14873 * exposed through the child_list, so we must take care tearing it all down. 14874 */ 14875 void perf_event_free_task(struct task_struct *task) 14876 { 14877 perf_event_exit_task_context(task, false); 14878 } 14879 14880 void perf_event_delayed_put(struct task_struct *task) 14881 { 14882 WARN_ON_ONCE(task->perf_event_ctxp); 14883 } 14884 14885 struct file *perf_event_get(unsigned int fd) 14886 { 14887 struct file *file = fget(fd); 14888 if (!file) 14889 return ERR_PTR(-EBADF); 14890 14891 if (file->f_op != &perf_fops) { 14892 fput(file); 14893 return ERR_PTR(-EBADF); 14894 } 14895 14896 return file; 14897 } 14898 14899 const struct perf_event *perf_get_event(struct file *file) 14900 { 14901 if (file->f_op != &perf_fops) 14902 return ERR_PTR(-EINVAL); 14903 14904 return file->private_data; 14905 } 14906 14907 const struct perf_event_attr *perf_event_attrs(struct perf_event *event) 14908 { 14909 if (!event) 14910 return ERR_PTR(-EINVAL); 14911 14912 return &event->attr; 14913 } 14914 14915 int perf_allow_kernel(void) 14916 { 14917 if (sysctl_perf_event_paranoid > 1 && !perfmon_capable()) 14918 return -EACCES; 14919 14920 return security_perf_event_open(PERF_SECURITY_KERNEL); 14921 } 14922 EXPORT_SYMBOL_GPL(perf_allow_kernel); 14923 14924 int perf_allow_cpu(void) 14925 { 14926 if (sysctl_perf_event_paranoid > 0 && !perfmon_capable()) 14927 return -EACCES; 14928 14929 return security_perf_event_open(PERF_SECURITY_CPU); 14930 } 14931 EXPORT_SYMBOL_GPL(perf_allow_cpu); 14932 14933 int perf_allow_tracepoint(void) 14934 { 14935 if (sysctl_perf_event_paranoid > -1 && !perfmon_capable()) 14936 return -EPERM; 14937 14938 return security_perf_event_open(PERF_SECURITY_TRACEPOINT); 14939 } 14940 EXPORT_SYMBOL_GPL(perf_allow_tracepoint); 14941 14942 /* 14943 * Inherit an event from parent task to child task. 14944 * 14945 * Returns: 14946 * - valid pointer on success 14947 * - NULL for orphaned events 14948 * - IS_ERR() on error 14949 */ 14950 static struct perf_event * 14951 inherit_event(struct perf_event *parent_event, 14952 struct task_struct *parent, 14953 struct perf_event_context *parent_ctx, 14954 struct task_struct *child, 14955 struct perf_event *group_leader, 14956 struct perf_event_context *child_ctx) 14957 { 14958 enum perf_event_state parent_state = parent_event->state; 14959 struct perf_event_pmu_context *pmu_ctx; 14960 struct perf_event *child_event; 14961 unsigned long flags; 14962 14963 /* 14964 * Instead of creating recursive hierarchies of events, 14965 * we link inherited events back to the original parent, 14966 * which has a filp for sure, which we use as the reference 14967 * count: 14968 */ 14969 if (parent_event->parent) 14970 parent_event = parent_event->parent; 14971 14972 if (parent_event->state <= PERF_EVENT_STATE_REVOKED) 14973 return NULL; 14974 14975 /* 14976 * Event creation should be under SRCU, see perf_pmu_unregister(). 14977 */ 14978 guard(srcu)(&pmus_srcu); 14979 14980 child_event = perf_event_alloc(&parent_event->attr, 14981 parent_event->cpu, 14982 child, 14983 group_leader, parent_event, 14984 NULL, NULL, -1); 14985 if (IS_ERR(child_event)) 14986 return child_event; 14987 14988 get_ctx(child_ctx); 14989 child_event->ctx = child_ctx; 14990 14991 pmu_ctx = find_get_pmu_context(parent_event->pmu_ctx->pmu, child_ctx, child_event); 14992 if (IS_ERR(pmu_ctx)) { 14993 free_event(child_event); 14994 return ERR_CAST(pmu_ctx); 14995 } 14996 child_event->pmu_ctx = pmu_ctx; 14997 14998 /* 14999 * is_orphaned_event() and list_add_tail(&parent_event->child_list) 15000 * must be under the same lock in order to serialize against 15001 * perf_event_release_kernel(), such that either we must observe 15002 * is_orphaned_event() or they will observe us on the child_list. 15003 */ 15004 mutex_lock(&parent_event->child_mutex); 15005 if (is_orphaned_event(parent_event) || 15006 !atomic_long_inc_not_zero(&parent_event->refcount)) { 15007 mutex_unlock(&parent_event->child_mutex); 15008 free_event(child_event); 15009 return NULL; 15010 } 15011 15012 /* 15013 * Make the child state follow the state of the parent event, 15014 * not its attr.disabled bit. We hold the parent's mutex, 15015 * so we won't race with perf_event_{en, dis}able_family. 15016 */ 15017 if (parent_state >= PERF_EVENT_STATE_INACTIVE) 15018 child_event->state = PERF_EVENT_STATE_INACTIVE; 15019 else 15020 child_event->state = PERF_EVENT_STATE_OFF; 15021 15022 if (parent_event->attr.freq) { 15023 u64 sample_period = parent_event->hw.sample_period; 15024 struct hw_perf_event *hwc = &child_event->hw; 15025 15026 hwc->sample_period = sample_period; 15027 hwc->last_period = sample_period; 15028 15029 local64_set(&hwc->period_left, sample_period); 15030 } 15031 15032 child_event->overflow_handler = parent_event->overflow_handler; 15033 child_event->overflow_handler_context 15034 = parent_event->overflow_handler_context; 15035 15036 /* 15037 * Precalculate sample_data sizes 15038 */ 15039 perf_event__header_size(child_event); 15040 perf_event__id_header_size(child_event); 15041 15042 /* 15043 * Link it up in the child's context: 15044 */ 15045 raw_spin_lock_irqsave(&child_ctx->lock, flags); 15046 add_event_to_ctx(child_event, child_ctx); 15047 child_event->attach_state |= PERF_ATTACH_CHILD; 15048 raw_spin_unlock_irqrestore(&child_ctx->lock, flags); 15049 15050 /* 15051 * Link this into the parent event's child list 15052 */ 15053 list_add_tail(&child_event->child_list, &parent_event->child_list); 15054 mutex_unlock(&parent_event->child_mutex); 15055 15056 return child_event; 15057 } 15058 15059 /* 15060 * Inherits an event group. 15061 * 15062 * This will quietly suppress orphaned events; !inherit_event() is not an error. 15063 * This matches with perf_event_release_kernel() removing all child events. 15064 * 15065 * Returns: 15066 * - 0 on success 15067 * - <0 on error 15068 */ 15069 static int inherit_group(struct perf_event *parent_event, 15070 struct task_struct *parent, 15071 struct perf_event_context *parent_ctx, 15072 struct task_struct *child, 15073 struct perf_event_context *child_ctx) 15074 { 15075 struct perf_event *leader; 15076 struct perf_event *sub; 15077 struct perf_event *child_ctr; 15078 15079 leader = inherit_event(parent_event, parent, parent_ctx, 15080 child, NULL, child_ctx); 15081 if (IS_ERR(leader)) 15082 return PTR_ERR(leader); 15083 /* 15084 * @leader can be NULL here because of is_orphaned_event(). In this 15085 * case inherit_event() will create individual events, similar to what 15086 * perf_group_detach() would do anyway. 15087 */ 15088 for_each_sibling_event(sub, parent_event) { 15089 child_ctr = inherit_event(sub, parent, parent_ctx, 15090 child, leader, child_ctx); 15091 if (IS_ERR(child_ctr)) 15092 return PTR_ERR(child_ctr); 15093 15094 if (sub->aux_event == parent_event && child_ctr && 15095 !perf_get_aux_event(child_ctr, leader)) 15096 return -EINVAL; 15097 } 15098 if (leader) 15099 leader->group_generation = parent_event->group_generation; 15100 return 0; 15101 } 15102 15103 /* 15104 * Creates the child task context and tries to inherit the event-group. 15105 * 15106 * Clears @inherited_all on !attr.inherited or error. Note that we'll leave 15107 * inherited_all set when we 'fail' to inherit an orphaned event; this is 15108 * consistent with perf_event_release_kernel() removing all child events. 15109 * 15110 * Returns: 15111 * - 0 on success 15112 * - <0 on error 15113 */ 15114 static int 15115 inherit_task_group(struct perf_event *event, struct task_struct *parent, 15116 struct perf_event_context *parent_ctx, 15117 struct task_struct *child, 15118 u64 clone_flags, int *inherited_all) 15119 { 15120 struct perf_event_context *child_ctx; 15121 int ret; 15122 15123 if (!event->attr.inherit || 15124 (event->attr.inherit_thread && !(clone_flags & CLONE_THREAD)) || 15125 /* Do not inherit if sigtrap and signal handlers were cleared. */ 15126 (event->attr.sigtrap && (clone_flags & CLONE_CLEAR_SIGHAND))) { 15127 *inherited_all = 0; 15128 return 0; 15129 } 15130 15131 child_ctx = child->perf_event_ctxp; 15132 if (!child_ctx) { 15133 /* 15134 * This is executed from the parent task context, so 15135 * inherit events that have been marked for cloning. 15136 * First allocate and initialize a context for the 15137 * child. 15138 */ 15139 child_ctx = alloc_perf_context(child); 15140 if (!child_ctx) 15141 return -ENOMEM; 15142 15143 child->perf_event_ctxp = child_ctx; 15144 } 15145 15146 ret = inherit_group(event, parent, parent_ctx, child, child_ctx); 15147 if (ret) 15148 *inherited_all = 0; 15149 15150 return ret; 15151 } 15152 15153 /* 15154 * Initialize the perf_event context in task_struct 15155 */ 15156 static int perf_event_init_context(struct task_struct *child, u64 clone_flags) 15157 { 15158 struct perf_event_context *child_ctx, *parent_ctx; 15159 struct perf_event_context *cloned_ctx; 15160 struct perf_event *event; 15161 struct task_struct *parent = current; 15162 int inherited_all = 1; 15163 unsigned long flags; 15164 int ret = 0; 15165 15166 if (likely(!parent->perf_event_ctxp)) 15167 return 0; 15168 15169 /* 15170 * If the parent's context is a clone, pin it so it won't get 15171 * swapped under us. 15172 */ 15173 parent_ctx = perf_pin_task_context(parent); 15174 if (!parent_ctx) 15175 return 0; 15176 15177 /* 15178 * No need to check if parent_ctx != NULL here; since we saw 15179 * it non-NULL earlier, the only reason for it to become NULL 15180 * is if we exit, and since we're currently in the middle of 15181 * a fork we can't be exiting at the same time. 15182 */ 15183 15184 /* 15185 * Lock the parent list. No need to lock the child - not PID 15186 * hashed yet and not running, so nobody can access it. 15187 */ 15188 mutex_lock(&parent_ctx->mutex); 15189 15190 /* 15191 * We dont have to disable NMIs - we are only looking at 15192 * the list, not manipulating it: 15193 */ 15194 perf_event_groups_for_each(event, &parent_ctx->pinned_groups) { 15195 ret = inherit_task_group(event, parent, parent_ctx, 15196 child, clone_flags, &inherited_all); 15197 if (ret) 15198 goto out_unlock; 15199 } 15200 15201 /* 15202 * We can't hold ctx->lock when iterating the ->flexible_group list due 15203 * to allocations, but we need to prevent rotation because 15204 * rotate_ctx() will change the list from interrupt context. 15205 */ 15206 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 15207 parent_ctx->rotate_disable = 1; 15208 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 15209 15210 perf_event_groups_for_each(event, &parent_ctx->flexible_groups) { 15211 ret = inherit_task_group(event, parent, parent_ctx, 15212 child, clone_flags, &inherited_all); 15213 if (ret) 15214 goto out_unlock; 15215 } 15216 15217 raw_spin_lock_irqsave(&parent_ctx->lock, flags); 15218 parent_ctx->rotate_disable = 0; 15219 15220 child_ctx = child->perf_event_ctxp; 15221 15222 if (child_ctx && inherited_all) { 15223 /* 15224 * Mark the child context as a clone of the parent 15225 * context, or of whatever the parent is a clone of. 15226 * 15227 * Note that if the parent is a clone, the holding of 15228 * parent_ctx->lock avoids it from being uncloned. 15229 */ 15230 cloned_ctx = parent_ctx->parent_ctx; 15231 if (cloned_ctx) { 15232 child_ctx->parent_ctx = cloned_ctx; 15233 child_ctx->parent_gen = parent_ctx->parent_gen; 15234 } else { 15235 child_ctx->parent_ctx = parent_ctx; 15236 child_ctx->parent_gen = parent_ctx->generation; 15237 } 15238 get_ctx(child_ctx->parent_ctx); 15239 } 15240 15241 raw_spin_unlock_irqrestore(&parent_ctx->lock, flags); 15242 out_unlock: 15243 mutex_unlock(&parent_ctx->mutex); 15244 15245 perf_unpin_context(parent_ctx); 15246 put_ctx(parent_ctx); 15247 15248 return ret; 15249 } 15250 15251 /* 15252 * Initialize the perf_event context in task_struct 15253 */ 15254 int perf_event_init_task(struct task_struct *child, u64 clone_flags) 15255 { 15256 int ret; 15257 15258 memset(child->perf_recursion, 0, sizeof(child->perf_recursion)); 15259 child->perf_event_ctxp = NULL; 15260 mutex_init(&child->perf_event_mutex); 15261 INIT_LIST_HEAD(&child->perf_event_list); 15262 child->perf_ctx_data = NULL; 15263 15264 ret = perf_event_init_context(child, clone_flags); 15265 if (ret) { 15266 perf_event_free_task(child); 15267 return ret; 15268 } 15269 15270 return 0; 15271 } 15272 15273 static void __init perf_event_init_all_cpus(void) 15274 { 15275 struct swevent_htable *swhash; 15276 struct perf_cpu_context *cpuctx; 15277 int cpu; 15278 15279 zalloc_cpumask_var(&perf_online_mask, GFP_KERNEL); 15280 zalloc_cpumask_var(&perf_online_core_mask, GFP_KERNEL); 15281 zalloc_cpumask_var(&perf_online_die_mask, GFP_KERNEL); 15282 zalloc_cpumask_var(&perf_online_cluster_mask, GFP_KERNEL); 15283 zalloc_cpumask_var(&perf_online_pkg_mask, GFP_KERNEL); 15284 zalloc_cpumask_var(&perf_online_sys_mask, GFP_KERNEL); 15285 15286 15287 for_each_possible_cpu(cpu) { 15288 swhash = &per_cpu(swevent_htable, cpu); 15289 mutex_init(&swhash->hlist_mutex); 15290 15291 INIT_LIST_HEAD(&per_cpu(pmu_sb_events.list, cpu)); 15292 raw_spin_lock_init(&per_cpu(pmu_sb_events.lock, cpu)); 15293 15294 INIT_LIST_HEAD(&per_cpu(sched_cb_list, cpu)); 15295 15296 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15297 __perf_event_init_context(&cpuctx->ctx); 15298 lockdep_set_class(&cpuctx->ctx.mutex, &cpuctx_mutex); 15299 lockdep_set_class(&cpuctx->ctx.lock, &cpuctx_lock); 15300 cpuctx->online = cpumask_test_cpu(cpu, perf_online_mask); 15301 cpuctx->heap_size = ARRAY_SIZE(cpuctx->heap_default); 15302 cpuctx->heap = cpuctx->heap_default; 15303 } 15304 } 15305 15306 static void perf_swevent_init_cpu(unsigned int cpu) 15307 { 15308 struct swevent_htable *swhash = &per_cpu(swevent_htable, cpu); 15309 15310 mutex_lock(&swhash->hlist_mutex); 15311 if (swhash->hlist_refcount > 0 && !swevent_hlist_deref(swhash)) { 15312 struct swevent_hlist *hlist; 15313 15314 hlist = kzalloc_node(sizeof(*hlist), GFP_KERNEL, cpu_to_node(cpu)); 15315 WARN_ON(!hlist); 15316 rcu_assign_pointer(swhash->swevent_hlist, hlist); 15317 } 15318 mutex_unlock(&swhash->hlist_mutex); 15319 } 15320 15321 #if defined CONFIG_HOTPLUG_CPU || defined CONFIG_KEXEC_CORE 15322 static void __perf_event_exit_context(void *__info) 15323 { 15324 struct perf_cpu_context *cpuctx = this_cpu_ptr(&perf_cpu_context); 15325 struct perf_event_context *ctx = __info; 15326 struct perf_event *event; 15327 15328 raw_spin_lock(&ctx->lock); 15329 ctx_sched_out(ctx, NULL, EVENT_TIME); 15330 list_for_each_entry(event, &ctx->event_list, event_entry) 15331 __perf_remove_from_context(event, cpuctx, ctx, (void *)DETACH_GROUP); 15332 raw_spin_unlock(&ctx->lock); 15333 } 15334 15335 static void perf_event_clear_cpumask(unsigned int cpu) 15336 { 15337 int target[PERF_PMU_MAX_SCOPE]; 15338 unsigned int scope; 15339 struct pmu *pmu; 15340 15341 cpumask_clear_cpu(cpu, perf_online_mask); 15342 15343 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15344 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 15345 struct cpumask *pmu_cpumask = perf_scope_cpumask(scope); 15346 15347 target[scope] = -1; 15348 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 15349 continue; 15350 15351 if (!cpumask_test_and_clear_cpu(cpu, pmu_cpumask)) 15352 continue; 15353 target[scope] = cpumask_any_but(cpumask, cpu); 15354 if (target[scope] < nr_cpu_ids) 15355 cpumask_set_cpu(target[scope], pmu_cpumask); 15356 } 15357 15358 /* migrate */ 15359 list_for_each_entry(pmu, &pmus, entry) { 15360 if (pmu->scope == PERF_PMU_SCOPE_NONE || 15361 WARN_ON_ONCE(pmu->scope >= PERF_PMU_MAX_SCOPE)) 15362 continue; 15363 15364 if (target[pmu->scope] >= 0 && target[pmu->scope] < nr_cpu_ids) 15365 perf_pmu_migrate_context(pmu, cpu, target[pmu->scope]); 15366 } 15367 } 15368 15369 static void perf_event_exit_cpu_context(int cpu) 15370 { 15371 struct perf_cpu_context *cpuctx; 15372 struct perf_event_context *ctx; 15373 15374 // XXX simplify cpuctx->online 15375 mutex_lock(&pmus_lock); 15376 /* 15377 * Clear the cpumasks, and migrate to other CPUs if possible. 15378 * Must be invoked before the __perf_event_exit_context. 15379 */ 15380 perf_event_clear_cpumask(cpu); 15381 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15382 ctx = &cpuctx->ctx; 15383 15384 mutex_lock(&ctx->mutex); 15385 if (ctx->nr_events) 15386 smp_call_function_single(cpu, __perf_event_exit_context, ctx, 1); 15387 cpuctx->online = 0; 15388 mutex_unlock(&ctx->mutex); 15389 mutex_unlock(&pmus_lock); 15390 } 15391 #else 15392 15393 static void perf_event_exit_cpu_context(int cpu) { } 15394 15395 #endif 15396 15397 static void perf_event_setup_cpumask(unsigned int cpu) 15398 { 15399 struct cpumask *pmu_cpumask; 15400 unsigned int scope; 15401 15402 /* 15403 * Early boot stage, the cpumask hasn't been set yet. 15404 * The perf_online_<domain>_masks includes the first CPU of each domain. 15405 * Always unconditionally set the boot CPU for the perf_online_<domain>_masks. 15406 */ 15407 if (cpumask_empty(perf_online_mask)) { 15408 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15409 pmu_cpumask = perf_scope_cpumask(scope); 15410 if (WARN_ON_ONCE(!pmu_cpumask)) 15411 continue; 15412 cpumask_set_cpu(cpu, pmu_cpumask); 15413 } 15414 goto end; 15415 } 15416 15417 for (scope = PERF_PMU_SCOPE_NONE + 1; scope < PERF_PMU_MAX_SCOPE; scope++) { 15418 const struct cpumask *cpumask = perf_scope_cpu_topology_cpumask(scope, cpu); 15419 15420 pmu_cpumask = perf_scope_cpumask(scope); 15421 15422 if (WARN_ON_ONCE(!pmu_cpumask || !cpumask)) 15423 continue; 15424 15425 if (!cpumask_empty(cpumask) && 15426 cpumask_any_and(pmu_cpumask, cpumask) >= nr_cpu_ids) 15427 cpumask_set_cpu(cpu, pmu_cpumask); 15428 } 15429 end: 15430 cpumask_set_cpu(cpu, perf_online_mask); 15431 } 15432 15433 int perf_event_init_cpu(unsigned int cpu) 15434 { 15435 struct perf_cpu_context *cpuctx; 15436 struct perf_event_context *ctx; 15437 15438 perf_swevent_init_cpu(cpu); 15439 15440 mutex_lock(&pmus_lock); 15441 perf_event_setup_cpumask(cpu); 15442 cpuctx = per_cpu_ptr(&perf_cpu_context, cpu); 15443 ctx = &cpuctx->ctx; 15444 15445 mutex_lock(&ctx->mutex); 15446 cpuctx->online = 1; 15447 mutex_unlock(&ctx->mutex); 15448 mutex_unlock(&pmus_lock); 15449 15450 return 0; 15451 } 15452 15453 int perf_event_exit_cpu(unsigned int cpu) 15454 { 15455 perf_event_exit_cpu_context(cpu); 15456 return 0; 15457 } 15458 15459 static int 15460 perf_reboot(struct notifier_block *notifier, unsigned long val, void *v) 15461 { 15462 int cpu; 15463 15464 for_each_online_cpu(cpu) 15465 perf_event_exit_cpu(cpu); 15466 15467 return NOTIFY_OK; 15468 } 15469 15470 /* 15471 * Run the perf reboot notifier at the very last possible moment so that 15472 * the generic watchdog code runs as long as possible. 15473 */ 15474 static struct notifier_block perf_reboot_notifier = { 15475 .notifier_call = perf_reboot, 15476 .priority = INT_MIN, 15477 }; 15478 15479 void __init perf_event_init(void) 15480 { 15481 int ret; 15482 15483 idr_init(&pmu_idr); 15484 15485 unwind_deferred_init(&perf_unwind_work, 15486 perf_unwind_deferred_callback); 15487 15488 perf_event_init_all_cpus(); 15489 init_srcu_struct(&pmus_srcu); 15490 perf_pmu_register(&perf_swevent, "software", PERF_TYPE_SOFTWARE); 15491 perf_pmu_register(&perf_cpu_clock, "cpu_clock", -1); 15492 perf_pmu_register(&perf_task_clock, "task_clock", -1); 15493 perf_tp_register(); 15494 perf_event_init_cpu(smp_processor_id()); 15495 register_reboot_notifier(&perf_reboot_notifier); 15496 15497 ret = init_hw_breakpoint(); 15498 WARN(ret, "hw_breakpoint initialization failed with: %d", ret); 15499 15500 perf_event_cache = KMEM_CACHE(perf_event, SLAB_PANIC); 15501 15502 /* 15503 * Build time assertion that we keep the data_head at the intended 15504 * location. IOW, validation we got the __reserved[] size right. 15505 */ 15506 BUILD_BUG_ON((offsetof(struct perf_event_mmap_page, data_head)) 15507 != 1024); 15508 } 15509 15510 ssize_t perf_event_sysfs_show(struct device *dev, struct device_attribute *attr, 15511 char *page) 15512 { 15513 struct perf_pmu_events_attr *pmu_attr = 15514 container_of(attr, struct perf_pmu_events_attr, attr); 15515 15516 if (pmu_attr->event_str) 15517 return sprintf(page, "%s\n", pmu_attr->event_str); 15518 15519 return 0; 15520 } 15521 EXPORT_SYMBOL_GPL(perf_event_sysfs_show); 15522 15523 static int __init perf_event_sysfs_init(void) 15524 { 15525 struct pmu *pmu; 15526 int ret; 15527 15528 mutex_lock(&pmus_lock); 15529 15530 ret = bus_register(&pmu_bus); 15531 if (ret) 15532 goto unlock; 15533 15534 list_for_each_entry(pmu, &pmus, entry) { 15535 if (pmu->dev) 15536 continue; 15537 15538 ret = pmu_dev_alloc(pmu); 15539 WARN(ret, "Failed to register pmu: %s, reason %d\n", pmu->name, ret); 15540 } 15541 pmu_bus_running = 1; 15542 ret = 0; 15543 15544 unlock: 15545 mutex_unlock(&pmus_lock); 15546 15547 return ret; 15548 } 15549 device_initcall(perf_event_sysfs_init); 15550 15551 #ifdef CONFIG_CGROUP_PERF 15552 static struct cgroup_subsys_state * 15553 perf_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 15554 { 15555 struct perf_cgroup *jc; 15556 15557 jc = kzalloc_obj(*jc); 15558 if (!jc) 15559 return ERR_PTR(-ENOMEM); 15560 15561 jc->info = alloc_percpu(struct perf_cgroup_info); 15562 if (!jc->info) { 15563 kfree(jc); 15564 return ERR_PTR(-ENOMEM); 15565 } 15566 15567 return &jc->css; 15568 } 15569 15570 static void perf_cgroup_css_free(struct cgroup_subsys_state *css) 15571 { 15572 struct perf_cgroup *jc = container_of(css, struct perf_cgroup, css); 15573 15574 free_percpu(jc->info); 15575 kfree(jc); 15576 } 15577 15578 static int perf_cgroup_css_online(struct cgroup_subsys_state *css) 15579 { 15580 perf_event_cgroup(css->cgroup); 15581 return 0; 15582 } 15583 15584 static int __perf_cgroup_move(void *info) 15585 { 15586 struct task_struct *task = info; 15587 15588 preempt_disable(); 15589 perf_cgroup_switch(task); 15590 preempt_enable(); 15591 15592 return 0; 15593 } 15594 15595 static void perf_cgroup_attach(struct cgroup_taskset *tset) 15596 { 15597 struct task_struct *task; 15598 struct cgroup_subsys_state *css; 15599 15600 cgroup_taskset_for_each(task, css, tset) 15601 task_function_call(task, __perf_cgroup_move, task); 15602 } 15603 15604 struct cgroup_subsys perf_event_cgrp_subsys = { 15605 .css_alloc = perf_cgroup_css_alloc, 15606 .css_free = perf_cgroup_css_free, 15607 .css_online = perf_cgroup_css_online, 15608 .attach = perf_cgroup_attach, 15609 /* 15610 * Implicitly enable on dfl hierarchy so that perf events can 15611 * always be filtered by cgroup2 path as long as perf_event 15612 * controller is not mounted on a legacy hierarchy. 15613 */ 15614 .implicit_on_dfl = true, 15615 .threaded = true, 15616 }; 15617 #endif /* CONFIG_CGROUP_PERF */ 15618 15619 DEFINE_STATIC_CALL_RET0(perf_snapshot_branch_stack, perf_snapshot_branch_stack_t); 15620