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