1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Copyright(C) 2005-2006, Linutronix GmbH, Thomas Gleixner <tglx@kernel.org> 4 * Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar 5 * Copyright(C) 2006-2007 Timesys Corp., Thomas Gleixner 6 * 7 * High-resolution kernel timers 8 * 9 * In contrast to the low-resolution timeout API, aka timer wheel, 10 * hrtimers provide finer resolution and accuracy depending on system 11 * configuration and capabilities. 12 * 13 * Started by: Thomas Gleixner and Ingo Molnar 14 * 15 * Credits: 16 * Based on the original timer wheel code 17 * 18 * Help, testing, suggestions, bugfixes, improvements were 19 * provided by: 20 * 21 * George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel 22 * et. al. 23 */ 24 25 #include <linux/cpu.h> 26 #include <linux/export.h> 27 #include <linux/percpu.h> 28 #include <linux/hrtimer.h> 29 #include <linux/hrtimer_bases.h> 30 #include <linux/notifier.h> 31 #include <linux/syscalls.h> 32 #include <linux/interrupt.h> 33 #include <linux/tick.h> 34 #include <linux/err.h> 35 #include <linux/debugobjects.h> 36 #include <linux/sched/signal.h> 37 #include <linux/sched/sysctl.h> 38 #include <linux/sched/rt.h> 39 #include <linux/sched/deadline.h> 40 #include <linux/sched/nohz.h> 41 #include <linux/sched/debug.h> 42 #include <linux/sched/isolation.h> 43 #include <linux/timer.h> 44 #include <linux/freezer.h> 45 #include <linux/compat.h> 46 47 #include <linux/uaccess.h> 48 49 #include <trace/events/timer.h> 50 51 #include "tick-internal.h" 52 53 /* 54 * Constants to set the queued state of the timer (INACTIVE, ENQUEUED) 55 * 56 * The callback state is kept separate in the CPU base because having it in 57 * the timer would required touching the timer after the callback, which 58 * makes it impossible to free the timer from the callback function. 59 * 60 * Therefore we track the callback state in: 61 * 62 * timer->base->cpu_base->running == timer 63 * 64 * On SMP it is possible to have a "callback function running and enqueued" 65 * status. It happens for example when a posix timer expired and the callback 66 * queued a signal. Between dropping the lock which protects the posix timer 67 * and reacquiring the base lock of the hrtimer, another CPU can deliver the 68 * signal and rearm the timer. 69 * 70 * All state transitions are protected by cpu_base->lock. 71 */ 72 #define HRTIMER_STATE_INACTIVE false 73 #define HRTIMER_STATE_ENQUEUED true 74 75 /* 76 * The resolution of the clocks. The resolution value is returned in 77 * the clock_getres() system call to give application programmers an 78 * idea of the (in)accuracy of timers. Timer values are rounded up to 79 * this resolution values. 80 */ 81 #define HIGH_RES_NSEC 1 82 83 /* 84 * Masks for selecting the soft and hard context timers from 85 * cpu_base->active 86 */ 87 #define MASK_SHIFT (HRTIMER_BASE_MONOTONIC_SOFT) 88 #define HRTIMER_ACTIVE_HARD ((1U << MASK_SHIFT) - 1) 89 #define HRTIMER_ACTIVE_SOFT (HRTIMER_ACTIVE_HARD << MASK_SHIFT) 90 #define HRTIMER_ACTIVE_ALL (HRTIMER_ACTIVE_SOFT | HRTIMER_ACTIVE_HARD) 91 92 static void retrigger_next_event(void *arg); 93 static ktime_t __hrtimer_cb_get_time(clockid_t clock_id); 94 95 /* 96 * The timer bases: 97 * 98 * There are more clockids than hrtimer bases. Thus, we index 99 * into the timer bases by the hrtimer_base_type enum. When trying 100 * to reach a base using a clockid, hrtimer_clockid_to_base() 101 * is used to convert from clockid to the proper hrtimer_base_type. 102 */ 103 104 #define BASE_INIT(idx, cid) \ 105 [idx] = { .index = idx, .clockid = cid } 106 107 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) = 108 { 109 .lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock), 110 .clock_base = { 111 BASE_INIT(HRTIMER_BASE_MONOTONIC, CLOCK_MONOTONIC), 112 BASE_INIT(HRTIMER_BASE_REALTIME, CLOCK_REALTIME), 113 BASE_INIT(HRTIMER_BASE_BOOTTIME, CLOCK_BOOTTIME), 114 BASE_INIT(HRTIMER_BASE_TAI, CLOCK_TAI), 115 BASE_INIT(HRTIMER_BASE_MONOTONIC_SOFT, CLOCK_MONOTONIC), 116 BASE_INIT(HRTIMER_BASE_REALTIME_SOFT, CLOCK_REALTIME), 117 BASE_INIT(HRTIMER_BASE_BOOTTIME_SOFT, CLOCK_BOOTTIME), 118 BASE_INIT(HRTIMER_BASE_TAI_SOFT, CLOCK_TAI), 119 }, 120 .csd = CSD_INIT(retrigger_next_event, NULL) 121 }; 122 123 static inline bool hrtimer_base_is_online(struct hrtimer_cpu_base *base) 124 { 125 if (!IS_ENABLED(CONFIG_HOTPLUG_CPU)) 126 return true; 127 else 128 return likely(base->online); 129 } 130 131 #ifdef CONFIG_HIGH_RES_TIMERS 132 DEFINE_STATIC_KEY_FALSE(hrtimer_highres_enabled_key); 133 134 static void hrtimer_hres_workfn(struct work_struct *work) 135 { 136 static_branch_enable(&hrtimer_highres_enabled_key); 137 } 138 139 static DECLARE_WORK(hrtimer_hres_work, hrtimer_hres_workfn); 140 141 static inline void hrtimer_schedule_hres_work(void) 142 { 143 if (!hrtimer_highres_enabled()) 144 schedule_work(&hrtimer_hres_work); 145 } 146 #else 147 static inline void hrtimer_schedule_hres_work(void) { } 148 #endif 149 150 /* 151 * Functions and macros which are different for UP/SMP systems are kept in a 152 * single place 153 */ 154 #ifdef CONFIG_SMP 155 /* 156 * We require the migration_base for lock_hrtimer_base()/switch_hrtimer_base() 157 * such that hrtimer_callback_running() can unconditionally dereference 158 * timer->base->cpu_base 159 */ 160 static struct hrtimer_cpu_base migration_cpu_base = { 161 .clock_base = { 162 [0] = { 163 .cpu_base = &migration_cpu_base, 164 .seq = SEQCNT_RAW_SPINLOCK_ZERO(migration_cpu_base.seq, 165 &migration_cpu_base.lock), 166 }, 167 }, 168 }; 169 170 #define migration_base migration_cpu_base.clock_base[0] 171 172 /* 173 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock 174 * means that all timers which are tied to this base via timer->base are 175 * locked, and the base itself is locked too. 176 * 177 * So __run_timers/migrate_timers can safely modify all timers which could 178 * be found on the lists/queues. 179 * 180 * When the timer's base is locked, and the timer removed from list, it is 181 * possible to set timer->base = &migration_base and drop the lock: the timer 182 * remains locked. 183 */ 184 static struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer, 185 unsigned long *flags) 186 __acquires(&timer->base->lock) 187 { 188 for (;;) { 189 struct hrtimer_clock_base *base = READ_ONCE(timer->base); 190 191 if (likely(base != &migration_base)) { 192 raw_spin_lock_irqsave(&base->cpu_base->lock, *flags); 193 if (likely(base == timer->base)) 194 return base; 195 /* The timer has migrated to another CPU: */ 196 raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags); 197 } 198 cpu_relax(); 199 } 200 } 201 202 /* 203 * Check if the elected target is suitable considering its next 204 * event and the hotplug state of the current CPU. 205 * 206 * If the elected target is remote and its next event is after the timer 207 * to queue, then a remote reprogram is necessary. However there is no 208 * guarantee the IPI handling the operation would arrive in time to meet 209 * the high resolution deadline. In this case the local CPU becomes a 210 * preferred target, unless it is offline. 211 * 212 * High and low resolution modes are handled the same way for simplicity. 213 * 214 * Called with cpu_base->lock of target cpu held. 215 */ 216 static bool hrtimer_suitable_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base, 217 struct hrtimer_cpu_base *new_cpu_base, 218 struct hrtimer_cpu_base *this_cpu_base) 219 { 220 ktime_t expires; 221 222 /* 223 * The local CPU clockevent can be reprogrammed. Also get_target_base() 224 * guarantees it is online. 225 */ 226 if (new_cpu_base == this_cpu_base) 227 return true; 228 229 /* 230 * The offline local CPU can't be the default target if the 231 * next remote target event is after this timer. Keep the 232 * elected new base. An IPI will be issued to reprogram 233 * it as a last resort. 234 */ 235 if (!hrtimer_base_is_online(this_cpu_base)) 236 return true; 237 238 expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset); 239 240 return expires >= new_base->cpu_base->expires_next; 241 } 242 243 static inline struct hrtimer_cpu_base *get_target_base(struct hrtimer_cpu_base *base, bool pinned) 244 { 245 if (!hrtimer_base_is_online(base)) { 246 int cpu = cpumask_any_and(cpu_online_mask, housekeeping_cpumask(HK_TYPE_TIMER)); 247 248 return &per_cpu(hrtimer_bases, cpu); 249 } 250 251 #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON) 252 if (static_branch_likely(&timers_migration_enabled) && !pinned) 253 return &per_cpu(hrtimer_bases, get_nohz_timer_target()); 254 #endif 255 return base; 256 } 257 258 /* 259 * We switch the timer base to a power-optimized selected CPU target, 260 * if: 261 * - NO_HZ_COMMON is enabled 262 * - timer migration is enabled 263 * - the timer callback is not running 264 * - the timer is not the first expiring timer on the new target 265 * 266 * If one of the above requirements is not fulfilled we move the timer 267 * to the current CPU or leave it on the previously assigned CPU if 268 * the timer callback is currently running. 269 */ 270 static inline struct hrtimer_clock_base * 271 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base, bool pinned) 272 { 273 struct hrtimer_cpu_base *new_cpu_base, *this_cpu_base; 274 struct hrtimer_clock_base *new_base; 275 int basenum = base->index; 276 277 this_cpu_base = this_cpu_ptr(&hrtimer_bases); 278 new_cpu_base = get_target_base(this_cpu_base, pinned); 279 again: 280 new_base = &new_cpu_base->clock_base[basenum]; 281 282 if (base != new_base) { 283 /* 284 * We are trying to move timer to new_base. However we can't 285 * change timer's base while it is running, so we keep it on 286 * the same CPU. No hassle vs. reprogramming the event source 287 * in the high resolution case. The remote CPU will take care 288 * of this when the timer function has completed. There is no 289 * conflict as we hold the lock until the timer is enqueued. 290 */ 291 if (unlikely(hrtimer_callback_running(timer))) 292 return base; 293 294 /* See the comment in lock_hrtimer_base() */ 295 WRITE_ONCE(timer->base, &migration_base); 296 raw_spin_unlock(&base->cpu_base->lock); 297 raw_spin_lock(&new_base->cpu_base->lock); 298 299 if (!hrtimer_suitable_target(timer, new_base, new_cpu_base, this_cpu_base)) { 300 raw_spin_unlock(&new_base->cpu_base->lock); 301 raw_spin_lock(&base->cpu_base->lock); 302 new_cpu_base = this_cpu_base; 303 WRITE_ONCE(timer->base, base); 304 goto again; 305 } 306 WRITE_ONCE(timer->base, new_base); 307 } else { 308 if (!hrtimer_suitable_target(timer, new_base, new_cpu_base, this_cpu_base)) { 309 new_cpu_base = this_cpu_base; 310 goto again; 311 } 312 } 313 return new_base; 314 } 315 316 #else /* CONFIG_SMP */ 317 318 static inline struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer, 319 unsigned long *flags) 320 __acquires(&timer->base->cpu_base->lock) 321 { 322 struct hrtimer_clock_base *base = timer->base; 323 324 raw_spin_lock_irqsave(&base->cpu_base->lock, *flags); 325 return base; 326 } 327 328 # define switch_hrtimer_base(t, b, p) (b) 329 330 #endif /* !CONFIG_SMP */ 331 332 /* 333 * Functions for the union type storage format of ktime_t which are 334 * too large for inlining: 335 */ 336 #if BITS_PER_LONG < 64 337 /* 338 * Divide a ktime value by a nanosecond value 339 */ 340 s64 __ktime_divns(const ktime_t kt, s64 div) 341 { 342 int sft = 0; 343 s64 dclc; 344 u64 tmp; 345 346 dclc = ktime_to_ns(kt); 347 tmp = dclc < 0 ? -dclc : dclc; 348 349 /* Make sure the divisor is less than 2^32: */ 350 while (div >> 32) { 351 sft++; 352 div >>= 1; 353 } 354 tmp >>= sft; 355 do_div(tmp, (u32) div); 356 return dclc < 0 ? -tmp : tmp; 357 } 358 EXPORT_SYMBOL_GPL(__ktime_divns); 359 #endif /* BITS_PER_LONG < 64 */ 360 361 /* 362 * Add two ktime values and do a safety check for overflow: 363 */ 364 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs) 365 { 366 ktime_t res = ktime_add_unsafe(lhs, rhs); 367 368 /* 369 * We use KTIME_SEC_MAX here, the maximum timeout which we can 370 * return to user space in a timespec: 371 */ 372 if (res < 0 || res < lhs || res < rhs) 373 res = ktime_set(KTIME_SEC_MAX, 0); 374 375 return res; 376 } 377 378 EXPORT_SYMBOL_GPL(ktime_add_safe); 379 380 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS 381 382 static const struct debug_obj_descr hrtimer_debug_descr; 383 384 static void *hrtimer_debug_hint(void *addr) 385 { 386 return ACCESS_PRIVATE((struct hrtimer *)addr, function); 387 } 388 389 /* 390 * fixup_init is called when: 391 * - an active object is initialized 392 */ 393 static bool hrtimer_fixup_init(void *addr, enum debug_obj_state state) 394 { 395 struct hrtimer *timer = addr; 396 397 switch (state) { 398 case ODEBUG_STATE_ACTIVE: 399 hrtimer_cancel(timer); 400 debug_object_init(timer, &hrtimer_debug_descr); 401 return true; 402 default: 403 return false; 404 } 405 } 406 407 /* 408 * fixup_activate is called when: 409 * - an active object is activated 410 * - an unknown non-static object is activated 411 */ 412 static bool hrtimer_fixup_activate(void *addr, enum debug_obj_state state) 413 { 414 switch (state) { 415 case ODEBUG_STATE_ACTIVE: 416 WARN_ON(1); 417 fallthrough; 418 default: 419 return false; 420 } 421 } 422 423 /* 424 * fixup_free is called when: 425 * - an active object is freed 426 */ 427 static bool hrtimer_fixup_free(void *addr, enum debug_obj_state state) 428 { 429 struct hrtimer *timer = addr; 430 431 switch (state) { 432 case ODEBUG_STATE_ACTIVE: 433 hrtimer_cancel(timer); 434 debug_object_free(timer, &hrtimer_debug_descr); 435 return true; 436 default: 437 return false; 438 } 439 } 440 441 /* Stub timer callback for improperly used timers. */ 442 static enum hrtimer_restart stub_timer(struct hrtimer *unused) 443 { 444 WARN_ON_ONCE(1); 445 return HRTIMER_NORESTART; 446 } 447 448 /* 449 * hrtimer_fixup_assert_init is called when: 450 * - an untracked/uninit-ed object is found 451 */ 452 static bool hrtimer_fixup_assert_init(void *addr, enum debug_obj_state state) 453 { 454 struct hrtimer *timer = addr; 455 456 switch (state) { 457 case ODEBUG_STATE_NOTAVAILABLE: 458 hrtimer_setup(timer, stub_timer, CLOCK_MONOTONIC, 0); 459 return true; 460 default: 461 return false; 462 } 463 } 464 465 static const struct debug_obj_descr hrtimer_debug_descr = { 466 .name = "hrtimer", 467 .debug_hint = hrtimer_debug_hint, 468 .fixup_init = hrtimer_fixup_init, 469 .fixup_activate = hrtimer_fixup_activate, 470 .fixup_free = hrtimer_fixup_free, 471 .fixup_assert_init = hrtimer_fixup_assert_init, 472 }; 473 474 static inline void debug_hrtimer_init(struct hrtimer *timer) 475 { 476 debug_object_init(timer, &hrtimer_debug_descr); 477 } 478 479 static inline void debug_hrtimer_init_on_stack(struct hrtimer *timer) 480 { 481 debug_object_init_on_stack(timer, &hrtimer_debug_descr); 482 } 483 484 static inline void debug_hrtimer_activate(struct hrtimer *timer, enum hrtimer_mode mode) 485 { 486 debug_object_activate(timer, &hrtimer_debug_descr); 487 } 488 489 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) 490 { 491 debug_object_deactivate(timer, &hrtimer_debug_descr); 492 } 493 494 static inline void debug_hrtimer_assert_init(struct hrtimer *timer) 495 { 496 debug_object_assert_init(timer, &hrtimer_debug_descr); 497 } 498 499 void destroy_hrtimer_on_stack(struct hrtimer *timer) 500 { 501 debug_object_free(timer, &hrtimer_debug_descr); 502 } 503 EXPORT_SYMBOL_GPL(destroy_hrtimer_on_stack); 504 505 #else 506 507 static inline void debug_hrtimer_init(struct hrtimer *timer) { } 508 static inline void debug_hrtimer_init_on_stack(struct hrtimer *timer) { } 509 static inline void debug_hrtimer_activate(struct hrtimer *timer, enum hrtimer_mode mode) { } 510 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { } 511 static inline void debug_hrtimer_assert_init(struct hrtimer *timer) { } 512 #endif 513 514 static inline void debug_setup(struct hrtimer *timer, clockid_t clockid, enum hrtimer_mode mode) 515 { 516 debug_hrtimer_init(timer); 517 trace_hrtimer_setup(timer, clockid, mode); 518 } 519 520 static inline void debug_setup_on_stack(struct hrtimer *timer, clockid_t clockid, 521 enum hrtimer_mode mode) 522 { 523 debug_hrtimer_init_on_stack(timer); 524 trace_hrtimer_setup(timer, clockid, mode); 525 } 526 527 static inline void debug_activate(struct hrtimer *timer, enum hrtimer_mode mode, bool was_armed) 528 { 529 debug_hrtimer_activate(timer, mode); 530 trace_hrtimer_start(timer, mode, was_armed); 531 } 532 533 #define for_each_active_base(base, cpu_base, active) \ 534 for (unsigned int idx = ffs(active); idx--; idx = ffs((active))) \ 535 for (bool done = false; !done; active &= ~(1U << idx)) \ 536 for (base = &cpu_base->clock_base[idx]; !done; done = true) 537 538 #define hrtimer_from_timerqueue_node(_n) container_of_const(_n, struct hrtimer, node) 539 540 #if defined(CONFIG_NO_HZ_COMMON) 541 /* 542 * Same as hrtimer_bases_next_event() below, but skips the excluded timer and 543 * does not update cpu_base->next_timer/expires. 544 */ 545 static ktime_t hrtimer_bases_next_event_without(struct hrtimer_cpu_base *cpu_base, 546 const struct hrtimer *exclude, 547 unsigned int active, ktime_t expires_next) 548 { 549 struct hrtimer_clock_base *base; 550 ktime_t expires; 551 552 lockdep_assert_held(&cpu_base->lock); 553 554 for_each_active_base(base, cpu_base, active) { 555 expires = ktime_sub(base->expires_next, base->offset); 556 if (expires >= expires_next) 557 continue; 558 559 /* 560 * If the excluded timer is the first on this base evaluate the 561 * next timer. 562 */ 563 struct timerqueue_linked_node *node = timerqueue_linked_first(&base->active); 564 565 if (unlikely(&exclude->node == node)) { 566 node = timerqueue_linked_next(node); 567 if (!node) 568 continue; 569 expires = ktime_sub(node->expires, base->offset); 570 if (expires >= expires_next) 571 continue; 572 } 573 expires_next = expires; 574 } 575 /* If base->offset changed, the result might be negative */ 576 return max(expires_next, 0); 577 } 578 #endif 579 580 static __always_inline struct hrtimer *clock_base_next_timer(struct hrtimer_clock_base *base) 581 { 582 struct timerqueue_linked_node *next = timerqueue_linked_first(&base->active); 583 584 return hrtimer_from_timerqueue_node(next); 585 } 586 587 /* Find the base with the earliest expiry */ 588 static void hrtimer_bases_first(struct hrtimer_cpu_base *cpu_base,unsigned int active, 589 ktime_t *expires_next, struct hrtimer **next_timer) 590 { 591 struct hrtimer_clock_base *base; 592 ktime_t expires; 593 594 for_each_active_base(base, cpu_base, active) { 595 expires = ktime_sub(base->expires_next, base->offset); 596 if (expires < *expires_next) { 597 *expires_next = expires; 598 *next_timer = clock_base_next_timer(base); 599 } 600 } 601 } 602 603 /* 604 * Recomputes cpu_base::*next_timer and returns the earliest expires_next 605 * but does not set cpu_base::*expires_next, that is done by 606 * hrtimer[_force]_reprogram and hrtimer_interrupt only. When updating 607 * cpu_base::*expires_next right away, reprogramming logic would no longer 608 * work. 609 * 610 * When a softirq is pending, we can ignore the HRTIMER_ACTIVE_SOFT bases, 611 * those timers will get run whenever the softirq gets handled, at the end of 612 * hrtimer_run_softirq(), hrtimer_update_softirq_timer() will re-add these bases. 613 * 614 * Therefore softirq values are those from the HRTIMER_ACTIVE_SOFT clock bases. 615 * The !softirq values are the minima across HRTIMER_ACTIVE_ALL, unless an actual 616 * softirq is pending, in which case they're the minima of HRTIMER_ACTIVE_HARD. 617 * 618 * @active_mask must be one of: 619 * - HRTIMER_ACTIVE_ALL, 620 * - HRTIMER_ACTIVE_SOFT, or 621 * - HRTIMER_ACTIVE_HARD. 622 */ 623 static ktime_t __hrtimer_get_next_event(struct hrtimer_cpu_base *cpu_base, unsigned int active_mask) 624 { 625 struct hrtimer *next_timer = NULL; 626 ktime_t expires_next = KTIME_MAX; 627 unsigned int active; 628 629 lockdep_assert_held(&cpu_base->lock); 630 631 if (!cpu_base->softirq_activated && (active_mask & HRTIMER_ACTIVE_SOFT)) { 632 active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT; 633 if (active) 634 hrtimer_bases_first(cpu_base, active, &expires_next, &next_timer); 635 cpu_base->softirq_next_timer = next_timer; 636 } 637 638 if (active_mask & HRTIMER_ACTIVE_HARD) { 639 active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD; 640 if (active) 641 hrtimer_bases_first(cpu_base, active, &expires_next, &next_timer); 642 cpu_base->next_timer = next_timer; 643 } 644 return max(expires_next, 0); 645 } 646 647 static ktime_t hrtimer_update_next_event(struct hrtimer_cpu_base *cpu_base) 648 { 649 ktime_t expires_next, soft = KTIME_MAX; 650 651 /* 652 * If the soft interrupt has already been activated, ignore the 653 * soft bases. They will be handled in the already raised soft 654 * interrupt. 655 */ 656 if (!cpu_base->softirq_activated) { 657 soft = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_SOFT); 658 /* 659 * Update the soft expiry time. clock_settime() might have 660 * affected it. 661 */ 662 cpu_base->softirq_expires_next = soft; 663 } 664 665 expires_next = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_HARD); 666 /* 667 * If a softirq timer is expiring first, update cpu_base->next_timer 668 * and program the hardware with the soft expiry time. 669 */ 670 if (expires_next > soft) { 671 cpu_base->next_timer = cpu_base->softirq_next_timer; 672 expires_next = soft; 673 } 674 675 return expires_next; 676 } 677 678 static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base) 679 { 680 lockdep_assert_held(&base->lock); 681 682 ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset; 683 ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset; 684 ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset; 685 686 ktime_t now = ktime_get_update_offsets_now(&base->clock_was_set_seq, offs_real, 687 offs_boot, offs_tai); 688 689 base->clock_base[HRTIMER_BASE_REALTIME_SOFT].offset = *offs_real; 690 base->clock_base[HRTIMER_BASE_BOOTTIME_SOFT].offset = *offs_boot; 691 base->clock_base[HRTIMER_BASE_TAI_SOFT].offset = *offs_tai; 692 693 return now; 694 } 695 696 /* 697 * Is the high resolution mode active in the CPU base. This cannot use the 698 * static key as the CPUs are switched to high resolution mode 699 * asynchronously. 700 */ 701 static inline int hrtimer_hres_active(struct hrtimer_cpu_base *cpu_base) 702 { 703 return IS_ENABLED(CONFIG_HIGH_RES_TIMERS) ? 704 cpu_base->hres_active : 0; 705 } 706 707 static inline void hrtimer_rearm_event(ktime_t expires_next, bool deferred) 708 { 709 trace_hrtimer_rearm(expires_next, deferred); 710 tick_program_event(expires_next, 1); 711 } 712 713 static void __hrtimer_reprogram(struct hrtimer_cpu_base *cpu_base, 714 ktime_t expires_next) 715 { 716 cpu_base->expires_next = expires_next; 717 718 /* 719 * If hres is not active, hardware does not have to be 720 * reprogrammed yet. 721 * 722 * If a hang was detected in the last timer interrupt then we 723 * leave the hang delay active in the hardware. We want the 724 * system to make progress. That also prevents the following 725 * scenario: 726 * T1 expires 50ms from now 727 * T2 expires 5s from now 728 * 729 * T1 is removed, so this code is called and would reprogram 730 * the hardware to 5s from now. Any hrtimer_start after that 731 * will not reprogram the hardware due to hang_detected being 732 * set. So we'd effectively block all timers until the T2 event 733 * fires. 734 */ 735 if (!hrtimer_hres_active(cpu_base) || cpu_base->hang_detected) 736 return; 737 738 hrtimer_rearm_event(expires_next, false); 739 } 740 741 /* Reprogram the event source with a evaluation of all clock bases */ 742 static void hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, bool skip_equal) 743 { 744 ktime_t expires_next = hrtimer_update_next_event(cpu_base); 745 746 if (skip_equal && expires_next == cpu_base->expires_next) 747 return; 748 749 __hrtimer_reprogram(cpu_base, expires_next); 750 } 751 752 /* High resolution timer related functions */ 753 #ifdef CONFIG_HIGH_RES_TIMERS 754 755 /* High resolution timer enabled ? */ 756 static bool hrtimer_hres_enabled __read_mostly = true; 757 unsigned int hrtimer_resolution __read_mostly = LOW_RES_NSEC; 758 EXPORT_SYMBOL_GPL(hrtimer_resolution); 759 760 /* Enable / Disable high resolution mode */ 761 static int __init setup_hrtimer_hres(char *str) 762 { 763 return (kstrtobool(str, &hrtimer_hres_enabled) == 0); 764 } 765 __setup("highres=", setup_hrtimer_hres); 766 767 /* hrtimer_high_res_enabled - query, if the highres mode is enabled */ 768 static inline bool hrtimer_is_hres_enabled(void) 769 { 770 return hrtimer_hres_enabled; 771 } 772 773 /* Switch to high resolution mode */ 774 static void hrtimer_switch_to_hres(void) 775 { 776 struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases); 777 778 if (tick_init_highres()) { 779 pr_warn("Could not switch to high resolution mode on CPU %u\n", base->cpu); 780 return; 781 } 782 base->hres_active = true; 783 if (hrtimer_resolution != HIGH_RES_NSEC) 784 hrtimer_resolution = HIGH_RES_NSEC; 785 786 tick_setup_sched_timer(true); 787 /* "Retrigger" the interrupt to get things going */ 788 retrigger_next_event(NULL); 789 hrtimer_schedule_hres_work(); 790 } 791 792 #else 793 794 static inline bool hrtimer_is_hres_enabled(void) { return 0; } 795 static inline void hrtimer_switch_to_hres(void) { } 796 797 #endif /* CONFIG_HIGH_RES_TIMERS */ 798 799 /* 800 * Retrigger next event is called after clock was set with interrupts 801 * disabled through an SMP function call or directly from low level 802 * resume code. 803 * 804 * This is only invoked when: 805 * - CONFIG_HIGH_RES_TIMERS is enabled. 806 * - CONFIG_NO_HZ_COMMON is enabled 807 * 808 * For the other cases this function is empty and because the call sites 809 * are optimized out it vanishes as well, i.e. no need for lots of 810 * #ifdeffery. 811 */ 812 static void retrigger_next_event(void *arg) 813 { 814 struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases); 815 816 /* 817 * When high resolution mode or nohz is active, then the offsets of 818 * CLOCK_REALTIME/TAI/BOOTTIME have to be updated. Otherwise the 819 * next tick will take care of that. 820 * 821 * If high resolution mode is active then the next expiring timer 822 * must be reevaluated and the clock event device reprogrammed if 823 * necessary. 824 * 825 * In the NOHZ case the update of the offset and the reevaluation 826 * of the next expiring timer is enough. The return from the SMP 827 * function call will take care of the reprogramming in case the 828 * CPU was in a NOHZ idle sleep. 829 * 830 * In periodic low resolution mode, the next softirq expiration 831 * must also be updated. 832 */ 833 guard(raw_spinlock)(&base->lock); 834 hrtimer_update_base(base); 835 if (hrtimer_hres_active(base)) 836 hrtimer_force_reprogram(base, /* skip_equal */ false); 837 else 838 hrtimer_update_next_event(base); 839 } 840 841 /* 842 * When a timer is enqueued and expires earlier than the already enqueued 843 * timers, we have to check, whether it expires earlier than the timer for 844 * which the clock event device was armed. 845 * 846 * Called with interrupts disabled and base->cpu_base.lock held 847 */ 848 static void hrtimer_reprogram(struct hrtimer *timer, bool reprogram) 849 { 850 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases); 851 struct hrtimer_clock_base *base = timer->base; 852 ktime_t expires = hrtimer_get_expires(timer); 853 854 WARN_ON_ONCE(expires < 0); 855 856 expires = ktime_sub(expires, base->offset); 857 /* 858 * CLOCK_REALTIME timer might be requested with an absolute 859 * expiry time which is less than base->offset. Set it to 0. 860 */ 861 if (expires < 0) 862 expires = 0; 863 864 if (timer->is_soft) { 865 /* 866 * soft hrtimer could be started on a remote CPU. In this 867 * case softirq_expires_next needs to be updated on the 868 * remote CPU. The soft hrtimer will not expire before the 869 * first hard hrtimer on the remote CPU - 870 * hrtimer_check_target() prevents this case. 871 */ 872 struct hrtimer_cpu_base *timer_cpu_base = base->cpu_base; 873 874 if (timer_cpu_base->softirq_activated) 875 return; 876 877 if (!ktime_before(expires, timer_cpu_base->softirq_expires_next)) 878 return; 879 880 timer_cpu_base->softirq_next_timer = timer; 881 timer_cpu_base->softirq_expires_next = expires; 882 883 if (!ktime_before(expires, timer_cpu_base->expires_next) || !reprogram) 884 return; 885 } 886 887 /* 888 * If the timer is not on the current cpu, we cannot reprogram 889 * the other cpus clock event device. 890 */ 891 if (base->cpu_base != cpu_base) 892 return; 893 894 if (expires >= cpu_base->expires_next) 895 return; 896 897 /* If a deferred rearm is pending skip reprogramming the device */ 898 if (cpu_base->deferred_rearm) 899 return; 900 901 cpu_base->next_timer = timer; 902 903 __hrtimer_reprogram(cpu_base, expires); 904 } 905 906 static bool update_needs_ipi(struct hrtimer_cpu_base *cpu_base, unsigned int active) 907 { 908 struct hrtimer_clock_base *base; 909 ktime_t expires; 910 u32 seq; 911 912 /* 913 * Update the base offsets unconditionally so the following 914 * checks whether the SMP function call is required works. 915 * 916 * The update is safe even when the remote CPU is in the hrtimer 917 * interrupt or the hrtimer soft interrupt and expiring affected 918 * bases. Either it will see the update before handling a base or 919 * it will see it when it finishes the processing and reevaluates 920 * the next expiring timer. 921 */ 922 seq = cpu_base->clock_was_set_seq; 923 hrtimer_update_base(cpu_base); 924 925 /* 926 * If the sequence did not change over the update then the 927 * remote CPU already handled it. 928 */ 929 if (seq == cpu_base->clock_was_set_seq) 930 return false; 931 932 /* If a deferred rearm is pending the remote CPU will take care of it */ 933 if (cpu_base->deferred_rearm) { 934 cpu_base->deferred_needs_update = true; 935 return false; 936 } 937 938 /* 939 * Walk the affected clock bases and check whether the first expiring 940 * timer in a clock base is moving ahead of the first expiring timer of 941 * @cpu_base. If so, the IPI must be invoked because per CPU clock 942 * event devices cannot be remotely reprogrammed. 943 */ 944 active &= cpu_base->active_bases; 945 946 for_each_active_base(base, cpu_base, active) { 947 struct timerqueue_linked_node *next; 948 949 next = timerqueue_linked_first(&base->active); 950 expires = ktime_sub(next->expires, base->offset); 951 if (expires < cpu_base->expires_next) 952 return true; 953 954 /* Extra check for softirq clock bases */ 955 if (base->index < HRTIMER_BASE_MONOTONIC_SOFT) 956 continue; 957 if (cpu_base->softirq_activated) 958 continue; 959 if (expires < cpu_base->softirq_expires_next) 960 return true; 961 } 962 return false; 963 } 964 965 /* 966 * Clock was set. This might affect CLOCK_REALTIME, CLOCK_TAI and 967 * CLOCK_BOOTTIME (for late sleep time injection). 968 * 969 * This requires to update the offsets for these clocks 970 * vs. CLOCK_MONOTONIC. When high resolution timers are enabled, then this 971 * also requires to eventually reprogram the per CPU clock event devices 972 * when the change moves an affected timer ahead of the first expiring 973 * timer on that CPU. Obviously remote per CPU clock event devices cannot 974 * be reprogrammed. The other reason why an IPI has to be sent is when the 975 * system is in !HIGH_RES and NOHZ mode. The NOHZ mode updates the offsets 976 * in the tick, which obviously might be stopped, so this has to bring out 977 * the remote CPU which might sleep in idle to get this sorted. 978 */ 979 void clock_was_set(unsigned int bases) 980 { 981 cpumask_var_t mask; 982 983 if (!hrtimer_highres_enabled() && !tick_nohz_is_active()) 984 goto out_timerfd; 985 986 if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) { 987 on_each_cpu(retrigger_next_event, NULL, 1); 988 goto out_timerfd; 989 } 990 991 /* Avoid interrupting CPUs if possible */ 992 scoped_guard(cpus_read_lock) { 993 int cpu; 994 995 for_each_online_cpu(cpu) { 996 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu); 997 998 guard(raw_spinlock_irqsave)(&cpu_base->lock); 999 if (update_needs_ipi(cpu_base, bases)) 1000 cpumask_set_cpu(cpu, mask); 1001 } 1002 scoped_guard(preempt) 1003 smp_call_function_many(mask, retrigger_next_event, NULL, 1); 1004 } 1005 free_cpumask_var(mask); 1006 1007 out_timerfd: 1008 timerfd_clock_was_set(); 1009 } 1010 1011 static void clock_was_set_work(struct work_struct *work) 1012 { 1013 clock_was_set(CLOCK_SET_WALL); 1014 } 1015 1016 static DECLARE_WORK(hrtimer_work, clock_was_set_work); 1017 1018 /* 1019 * Called from timekeeping code to reprogram the hrtimer interrupt device 1020 * on all cpus and to notify timerfd. 1021 */ 1022 void clock_was_set_delayed(void) 1023 { 1024 schedule_work(&hrtimer_work); 1025 } 1026 1027 /* 1028 * Called during resume either directly from via timekeeping_resume() 1029 * or in the case of s2idle from tick_unfreeze() to ensure that the 1030 * hrtimers are up to date. 1031 */ 1032 void hrtimers_resume_local(void) 1033 { 1034 lockdep_assert_irqs_disabled(); 1035 /* Retrigger on the local CPU */ 1036 retrigger_next_event(NULL); 1037 } 1038 1039 /* Counterpart to lock_hrtimer_base above */ 1040 static inline void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags) 1041 __releases(&timer->base->cpu_base->lock) 1042 { 1043 raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags); 1044 } 1045 1046 /** 1047 * hrtimer_update_function - Update the timer's callback function 1048 * @timer: Timer to update 1049 * @function: New callback function 1050 * 1051 * Only safe to call if the timer is not enqueued. Can be called in the callback function if the 1052 * timer is not enqueued at the same time (see the comments above HRTIMER_STATE_ENQUEUED). 1053 */ 1054 void hrtimer_update_function(struct hrtimer *timer, 1055 enum hrtimer_restart (*function)(struct hrtimer *)) 1056 { 1057 #ifdef CONFIG_PROVE_LOCKING 1058 guard(raw_spinlock_irqsave)(&timer->base->cpu_base->lock); 1059 1060 if (WARN_ON_ONCE(hrtimer_is_queued(timer))) 1061 return; 1062 1063 if (WARN_ON_ONCE(!function)) 1064 return; 1065 #endif 1066 ACCESS_PRIVATE(timer, function) = function; 1067 } 1068 EXPORT_SYMBOL_GPL(hrtimer_update_function); 1069 1070 /** 1071 * hrtimer_forward() - forward the timer expiry 1072 * @timer: hrtimer to forward 1073 * @now: forward past this time 1074 * @interval: the interval to forward 1075 * 1076 * Forward the timer expiry so it will expire in the future. 1077 * 1078 * .. note:: 1079 * This only updates the timer expiry value and does not requeue the timer. 1080 * 1081 * There is also a variant of this function: hrtimer_forward_now(). 1082 * 1083 * Context: Can be safely called from the callback function of @timer. If called 1084 * from other contexts @timer must neither be enqueued nor running the 1085 * callback and the caller needs to take care of serialization. 1086 * 1087 * Return: The number of overruns are returned. 1088 */ 1089 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval) 1090 { 1091 ktime_t delta; 1092 u64 orun = 1; 1093 1094 delta = ktime_sub(now, hrtimer_get_expires(timer)); 1095 1096 if (delta < 0) 1097 return 0; 1098 1099 if (WARN_ON(timer->is_queued)) 1100 return 0; 1101 1102 if (interval < hrtimer_resolution) 1103 interval = hrtimer_resolution; 1104 1105 if (unlikely(delta >= interval)) { 1106 s64 incr = ktime_to_ns(interval); 1107 1108 orun = ktime_divns(delta, incr); 1109 hrtimer_add_expires_ns(timer, incr * orun); 1110 if (hrtimer_get_expires(timer) > now) 1111 return orun; 1112 /* 1113 * This (and the ktime_add() below) is the 1114 * correction for exact: 1115 */ 1116 orun++; 1117 } 1118 hrtimer_add_expires(timer, interval); 1119 1120 return orun; 1121 } 1122 EXPORT_SYMBOL_GPL(hrtimer_forward); 1123 1124 /* 1125 * enqueue_hrtimer - internal function to (re)start a timer 1126 * 1127 * The timer is inserted in expiry order. Insertion into the 1128 * red black tree is O(log(n)). 1129 * 1130 * Returns true when the new timer is the leftmost timer in the tree. 1131 */ 1132 static bool enqueue_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base, 1133 enum hrtimer_mode mode, bool was_armed) 1134 { 1135 lockdep_assert_held(&base->cpu_base->lock); 1136 1137 debug_activate(timer, mode, was_armed); 1138 WARN_ON_ONCE(!base->cpu_base->online); 1139 1140 base->cpu_base->active_bases |= 1 << base->index; 1141 1142 /* Pairs with the lockless read in hrtimer_is_queued() */ 1143 WRITE_ONCE(timer->is_queued, HRTIMER_STATE_ENQUEUED); 1144 1145 if (!timerqueue_linked_add(&base->active, &timer->node)) 1146 return false; 1147 1148 base->expires_next = hrtimer_get_expires(timer); 1149 return true; 1150 } 1151 1152 static inline void base_update_next_timer(struct hrtimer_clock_base *base) 1153 { 1154 struct timerqueue_linked_node *next = timerqueue_linked_first(&base->active); 1155 1156 base->expires_next = next ? next->expires : KTIME_MAX; 1157 } 1158 1159 /* 1160 * __remove_hrtimer - internal function to remove a timer 1161 * 1162 * High resolution timer mode reprograms the clock event device when the 1163 * timer is the one which expires next. The caller can disable this by setting 1164 * reprogram to zero. This is useful, when the context does a reprogramming 1165 * anyway (e.g. timer interrupt) 1166 */ 1167 static void __remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base, 1168 bool newstate, bool reprogram) 1169 { 1170 struct hrtimer_cpu_base *cpu_base = base->cpu_base; 1171 bool was_first; 1172 1173 lockdep_assert_held(&cpu_base->lock); 1174 1175 if (!timer->is_queued) 1176 return; 1177 1178 /* Pairs with the lockless read in hrtimer_is_queued() */ 1179 WRITE_ONCE(timer->is_queued, newstate); 1180 1181 was_first = !timerqueue_linked_prev(&timer->node); 1182 1183 if (!timerqueue_linked_del(&base->active, &timer->node)) 1184 cpu_base->active_bases &= ~(1 << base->index); 1185 1186 /* Nothing to update if this was not the first timer in the base */ 1187 if (!was_first) 1188 return; 1189 1190 base_update_next_timer(base); 1191 1192 /* 1193 * If reprogram is false don't update cpu_base->next_timer and do not 1194 * touch the clock event device. 1195 * 1196 * This happens when removing the first timer on a remote CPU, which 1197 * will be handled by the remote CPU's interrupt. It also happens when 1198 * a local timer is removed to be immediately restarted. That's handled 1199 * at the call site. 1200 */ 1201 if (!reprogram || timer != cpu_base->next_timer || timer->is_lazy) 1202 return; 1203 1204 if (cpu_base->deferred_rearm) 1205 cpu_base->deferred_needs_update = true; 1206 else 1207 hrtimer_force_reprogram(cpu_base, /* skip_equal */ true); 1208 } 1209 1210 static inline bool remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base, 1211 bool newstate) 1212 { 1213 lockdep_assert_held(&base->cpu_base->lock); 1214 1215 if (timer->is_queued) { 1216 bool reprogram; 1217 1218 debug_hrtimer_deactivate(timer); 1219 1220 /* 1221 * Remove the timer and force reprogramming when high 1222 * resolution mode is active and the timer is on the current 1223 * CPU. If we remove a timer on another CPU, reprogramming is 1224 * skipped. The interrupt event on this CPU is fired and 1225 * reprogramming happens in the interrupt handler. This is a 1226 * rare case and less expensive than a smp call. 1227 */ 1228 reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases); 1229 1230 __remove_hrtimer(timer, base, newstate, reprogram); 1231 return true; 1232 } 1233 return false; 1234 } 1235 1236 /* 1237 * Update in place has to retrieve the expiry times of the neighbour nodes 1238 * if they exist. That is cache line neutral because the dequeue/enqueue 1239 * operation is going to need the same cache lines. But there is a big win 1240 * when the dequeue/enqueue can be avoided because the RB tree does not 1241 * have to be rebalanced twice. 1242 */ 1243 static inline bool 1244 hrtimer_can_update_in_place(struct hrtimer *timer, struct hrtimer_clock_base *base, ktime_t expires) 1245 { 1246 struct timerqueue_linked_node *next = timerqueue_linked_next(&timer->node); 1247 struct timerqueue_linked_node *prev = timerqueue_linked_prev(&timer->node); 1248 1249 /* If the new expiry goes behind the next timer, requeue is required */ 1250 if (next && expires > next->expires) 1251 return false; 1252 1253 /* If this is the first timer, update in place */ 1254 if (!prev) 1255 return true; 1256 1257 /* Update in place when it does not go ahead of the previous one */ 1258 return expires >= prev->expires; 1259 } 1260 1261 static inline bool 1262 remove_and_enqueue_same_base(struct hrtimer *timer, struct hrtimer_clock_base *base, 1263 const enum hrtimer_mode mode, ktime_t expires, u64 delta_ns) 1264 { 1265 bool was_first = false; 1266 1267 /* 1268 * Updating the sort key while @timer is queued can temporarily 1269 * make the tree inconsistent. This is safe under cpu_base->lock: 1270 * no other queue operation can observe that state. 1271 * hrtimer_can_update_in_place() either confirms that the new expiry 1272 * fits between the neighbours or timerqueue_linked_del() removes the 1273 * timer without consulting the expiry. 1274 */ 1275 hrtimer_set_expires_range_ns(timer, expires, delta_ns); 1276 expires = hrtimer_get_expires(timer); 1277 1278 /* Remove it from the timer queue if active */ 1279 if (timer->is_queued) { 1280 was_first = !timerqueue_linked_prev(&timer->node); 1281 1282 /* Try to update in place to avoid the de/enqueue dance */ 1283 if (hrtimer_can_update_in_place(timer, base, expires)) { 1284 trace_hrtimer_start(timer, mode, true); 1285 if (was_first) 1286 base->expires_next = expires; 1287 return was_first; 1288 } 1289 1290 debug_hrtimer_deactivate(timer); 1291 timerqueue_linked_del(&base->active, &timer->node); 1292 } 1293 1294 debug_activate(timer, mode, timer->is_queued); 1295 base->cpu_base->active_bases |= 1 << base->index; 1296 1297 /* Pairs with the lockless read in hrtimer_is_queued() */ 1298 WRITE_ONCE(timer->is_queued, HRTIMER_STATE_ENQUEUED); 1299 1300 /* If it's the first expiring timer now or again, update base */ 1301 if (timerqueue_linked_add(&base->active, &timer->node)) { 1302 base->expires_next = expires; 1303 return true; 1304 } 1305 1306 if (was_first) 1307 base_update_next_timer(base); 1308 1309 return false; 1310 } 1311 1312 static inline ktime_t hrtimer_update_lowres(struct hrtimer *timer, ktime_t tim, 1313 const enum hrtimer_mode mode) 1314 { 1315 #ifdef CONFIG_TIME_LOW_RES 1316 /* 1317 * CONFIG_TIME_LOW_RES indicates that the system has no way to return 1318 * granular time values. For relative timers we add hrtimer_resolution 1319 * (i.e. one jiffy) to prevent short timeouts. 1320 */ 1321 timer->is_rel = mode & HRTIMER_MODE_REL; 1322 if (timer->is_rel) 1323 tim = ktime_add_safe(tim, hrtimer_resolution); 1324 #endif 1325 return tim; 1326 } 1327 1328 static void hrtimer_update_softirq_timer(struct hrtimer_cpu_base *cpu_base, bool reprogram) 1329 { 1330 ktime_t expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_SOFT); 1331 1332 /* 1333 * Reprogramming needs to be triggered, even if the next soft 1334 * hrtimer expires at the same time as the next hard 1335 * hrtimer. cpu_base->softirq_expires_next needs to be updated! 1336 */ 1337 if (expires == KTIME_MAX) 1338 return; 1339 1340 /* 1341 * cpu_base->next_timer is recomputed by __hrtimer_get_next_event() 1342 * cpu_base->expires_next is only set by hrtimer_reprogram() 1343 */ 1344 hrtimer_reprogram(cpu_base->softirq_next_timer, reprogram); 1345 } 1346 1347 #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON) 1348 static __always_inline bool hrtimer_prefer_local(bool is_local, bool is_first, bool is_pinned) 1349 { 1350 if (static_branch_likely(&timers_migration_enabled)) { 1351 /* 1352 * If it is local and the first expiring timer keep it on the local 1353 * CPU to optimize reprogramming of the clockevent device. Also 1354 * avoid switch_hrtimer_base() overhead when local and pinned. 1355 */ 1356 if (!is_local) 1357 return false; 1358 if (is_first || is_pinned) 1359 return true; 1360 1361 /* Honour the NOHZ full restrictions */ 1362 if (!housekeeping_cpu(smp_processor_id(), HK_TYPE_KERNEL_NOISE)) 1363 return false; 1364 1365 /* 1366 * If the tick is not stopped or need_resched() is set, then 1367 * there is no point in moving the timer somewhere else. 1368 */ 1369 return !tick_nohz_tick_stopped() || need_resched(); 1370 } 1371 return is_local; 1372 } 1373 #else 1374 static __always_inline bool hrtimer_prefer_local(bool is_local, bool is_first, bool is_pinned) 1375 { 1376 return is_local; 1377 } 1378 #endif 1379 1380 static inline bool hrtimer_keep_base(struct hrtimer *timer, bool is_local, bool is_first, 1381 bool is_pinned) 1382 { 1383 /* If the timer is running the callback it has to stay on its CPU base. */ 1384 if (unlikely(timer->base->running == timer)) 1385 return true; 1386 1387 return hrtimer_prefer_local(is_local, is_first, is_pinned); 1388 } 1389 1390 enum { 1391 HRTIMER_REPROGRAM_NONE, 1392 HRTIMER_REPROGRAM, 1393 HRTIMER_REPROGRAM_FORCE, 1394 }; 1395 1396 static int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim, u64 delta_ns, 1397 const enum hrtimer_mode mode, struct hrtimer_clock_base *base) 1398 { 1399 struct hrtimer_cpu_base *this_cpu_base = this_cpu_ptr(&hrtimer_bases); 1400 bool is_pinned, first, was_first, keep_base = false; 1401 struct hrtimer_cpu_base *cpu_base = base->cpu_base; 1402 1403 was_first = cpu_base->next_timer == timer; 1404 is_pinned = !!(mode & HRTIMER_MODE_PINNED); 1405 1406 /* 1407 * Don't keep it local if this enqueue happens on a unplugged CPU 1408 * after hrtimer_cpu_dying() has been invoked. 1409 */ 1410 if (likely(this_cpu_base->online)) { 1411 bool is_local = cpu_base == this_cpu_base; 1412 1413 keep_base = hrtimer_keep_base(timer, is_local, was_first, is_pinned); 1414 } 1415 1416 /* Calculate absolute expiry time for relative timers */ 1417 if (mode & HRTIMER_MODE_REL) 1418 tim = ktime_add_safe(tim, __hrtimer_cb_get_time(base->clockid)); 1419 /* Compensate for low resolution granularity */ 1420 tim = hrtimer_update_lowres(timer, tim, mode); 1421 1422 /* 1423 * Remove an active timer from the queue. In case it is not queued 1424 * on the current CPU, make sure that remove_hrtimer() updates the 1425 * remote data correctly. 1426 * 1427 * If it's on the current CPU and the first expiring timer, then 1428 * skip reprogramming, keep the timer local and enforce 1429 * reprogramming later if it was the first expiring timer. This 1430 * avoids programming the underlying clock event twice (once at 1431 * removal and once after enqueue). 1432 * 1433 * @keep_base is also true if the timer callback is running on a 1434 * remote CPU and for local pinned timers. 1435 */ 1436 if (likely(keep_base)) { 1437 first = remove_and_enqueue_same_base(timer, base, mode, tim, delta_ns); 1438 } else { 1439 /* Keep the ENQUEUED state in case it is queued */ 1440 bool was_armed = remove_hrtimer(timer, base, HRTIMER_STATE_ENQUEUED); 1441 1442 hrtimer_set_expires_range_ns(timer, tim, delta_ns); 1443 1444 /* Switch the timer base, if necessary: */ 1445 base = switch_hrtimer_base(timer, base, is_pinned); 1446 cpu_base = base->cpu_base; 1447 1448 first = enqueue_hrtimer(timer, base, mode, was_armed); 1449 } 1450 1451 /* If a deferred rearm is pending skip reprogramming the device */ 1452 if (cpu_base->deferred_rearm) { 1453 cpu_base->deferred_needs_update = true; 1454 return HRTIMER_REPROGRAM_NONE; 1455 } 1456 1457 if (!was_first || cpu_base != this_cpu_base) { 1458 /* 1459 * If the current CPU base is online, then the timer is never 1460 * queued on a remote CPU if it would be the first expiring 1461 * timer there unless the timer callback is currently executed 1462 * on the remote CPU. In the latter case the remote CPU will 1463 * re-evaluate the first expiring timer after completing the 1464 * callbacks. 1465 */ 1466 if (likely(hrtimer_base_is_online(this_cpu_base))) 1467 return first ? HRTIMER_REPROGRAM : HRTIMER_REPROGRAM_NONE; 1468 1469 /* 1470 * Timer was enqueued remote because the current base is 1471 * already offline. If the timer is the first to expire, 1472 * kick the remote CPU to reprogram the clock event. 1473 */ 1474 if (first) 1475 smp_call_function_single_async(cpu_base->cpu, &cpu_base->csd); 1476 return HRTIMER_REPROGRAM_NONE; 1477 } 1478 1479 /* 1480 * Special case for the HRTICK timer. It is frequently rearmed and most 1481 * of the time moves the expiry into the future. That's expensive in 1482 * virtual machines and it's better to take the pointless already armed 1483 * interrupt than reprogramming the hardware on every context switch. 1484 * 1485 * If the new expiry is before the armed time, then reprogramming is 1486 * required. 1487 */ 1488 if (timer->is_lazy) { 1489 if (cpu_base->expires_next <= hrtimer_get_expires(timer)) 1490 return HRTIMER_REPROGRAM_NONE; 1491 } 1492 1493 /* 1494 * Timer was the first expiring timer and forced to stay on the 1495 * current CPU to avoid reprogramming on removal and enqueue. Force 1496 * reprogram the hardware by evaluating the new first expiring 1497 * timer. 1498 */ 1499 return HRTIMER_REPROGRAM_FORCE; 1500 } 1501 1502 static int hrtimer_start_range_ns_common(struct hrtimer *timer, ktime_t tim, 1503 u64 delta_ns, const enum hrtimer_mode mode, 1504 struct hrtimer_clock_base *base) 1505 { 1506 /* 1507 * Check whether the HRTIMER_MODE_SOFT bit and hrtimer.is_soft 1508 * match on CONFIG_PREEMPT_RT = n. With PREEMPT_RT check the hard 1509 * expiry mode because unmarked timers are moved to softirq expiry. 1510 */ 1511 if (!IS_ENABLED(CONFIG_PREEMPT_RT)) 1512 WARN_ON_ONCE(!(mode & HRTIMER_MODE_SOFT) ^ !timer->is_soft); 1513 else 1514 WARN_ON_ONCE(!(mode & HRTIMER_MODE_HARD) ^ !timer->is_hard); 1515 1516 return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, base); 1517 } 1518 1519 /** 1520 * hrtimer_start_range_ns - (re)start an hrtimer 1521 * @timer: the timer to be added 1522 * @tim: expiry time 1523 * @delta_ns: "slack" range for the timer 1524 * @mode: timer mode: absolute (HRTIMER_MODE_ABS) or 1525 * relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED); 1526 * softirq based mode is considered for debug purpose only! 1527 */ 1528 void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim, u64 delta_ns, 1529 const enum hrtimer_mode mode) 1530 { 1531 struct hrtimer_clock_base *base; 1532 unsigned long flags; 1533 1534 debug_hrtimer_assert_init(timer); 1535 1536 base = lock_hrtimer_base(timer, &flags); 1537 1538 switch (hrtimer_start_range_ns_common(timer, tim, delta_ns, mode, base)) { 1539 case HRTIMER_REPROGRAM: 1540 hrtimer_reprogram(timer, true); 1541 break; 1542 case HRTIMER_REPROGRAM_FORCE: 1543 hrtimer_force_reprogram(timer->base->cpu_base, 1); 1544 break; 1545 case HRTIMER_REPROGRAM_NONE: 1546 break; 1547 } 1548 1549 unlock_hrtimer_base(timer, &flags); 1550 } 1551 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns); 1552 1553 static inline bool hrtimer_check_user_timer(struct hrtimer *timer) 1554 { 1555 struct hrtimer_cpu_base *cpu_base = timer->base->cpu_base; 1556 ktime_t expires; 1557 1558 /* 1559 * This uses soft expires because that's the user provided 1560 * expiry time, while expires can be further in the past 1561 * due to a slack value added to the user expiry time. 1562 */ 1563 expires = hrtimer_get_softexpires(timer); 1564 1565 /* Convert to monotonic */ 1566 expires = ktime_sub(expires, timer->base->offset); 1567 1568 /* 1569 * Check whether this timer will end up as the first expiring timer in 1570 * the CPU base. If not, no further checks required as it's then 1571 * guaranteed to expire in the future. 1572 */ 1573 if (expires >= cpu_base->expires_next) 1574 return true; 1575 1576 /* Validate that the expiry time is in the future. */ 1577 if (expires > ktime_get()) 1578 return true; 1579 1580 debug_hrtimer_deactivate(timer); 1581 __remove_hrtimer(timer, timer->base, HRTIMER_STATE_INACTIVE, false); 1582 trace_hrtimer_start_expired(timer); 1583 return false; 1584 } 1585 1586 /** 1587 * hrtimer_start_range_ns_user - (re)start an user controlled hrtimer 1588 * @timer: the timer to be added 1589 * @tim: expiry time 1590 * @delta_ns: "slack" range for the timer 1591 * @mode: timer mode: absolute (HRTIMER_MODE_ABS) or 1592 * relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED); 1593 * softirq based mode is considered for debug purpose only! 1594 * 1595 * Returns: True when the timer was queued, false if it was already expired 1596 * 1597 * This function cannot invoke the timer callback for expired timers as it might 1598 * be called under a lock which the timer callback needs to acquire. So the 1599 * caller has to handle that case. 1600 */ 1601 bool hrtimer_start_range_ns_user(struct hrtimer *timer, ktime_t tim, 1602 u64 delta_ns, const enum hrtimer_mode mode) 1603 { 1604 struct hrtimer_clock_base *base; 1605 unsigned long flags; 1606 bool ret = true; 1607 1608 debug_hrtimer_assert_init(timer); 1609 1610 base = lock_hrtimer_base(timer, &flags); 1611 1612 switch (hrtimer_start_range_ns_common(timer, tim, delta_ns, mode, base)) { 1613 case HRTIMER_REPROGRAM: 1614 ret = hrtimer_check_user_timer(timer); 1615 if (ret) 1616 hrtimer_reprogram(timer, true); 1617 break; 1618 case HRTIMER_REPROGRAM_FORCE: 1619 ret = hrtimer_check_user_timer(timer); 1620 /* 1621 * The base must always be reevaluated, independent of the 1622 * result above because the timer was the first pending timer. 1623 */ 1624 hrtimer_force_reprogram(timer->base->cpu_base, 1); 1625 break; 1626 case HRTIMER_REPROGRAM_NONE: 1627 break; 1628 } 1629 1630 unlock_hrtimer_base(timer, &flags); 1631 return ret; 1632 } 1633 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns_user); 1634 1635 /** 1636 * hrtimer_try_to_cancel - try to deactivate a timer 1637 * @timer: hrtimer to stop 1638 * 1639 * Returns: 1640 * 1641 * * 0 when the timer was not active 1642 * * 1 when the timer was active 1643 * * -1 when the timer is currently executing the callback function and 1644 * cannot be stopped 1645 */ 1646 int hrtimer_try_to_cancel(struct hrtimer *timer) 1647 { 1648 struct hrtimer_clock_base *base; 1649 unsigned long flags; 1650 int ret = -1; 1651 1652 /* 1653 * Check lockless first. If the timer is not active (neither 1654 * enqueued nor running the callback, nothing to do here. The 1655 * base lock does not serialize against a concurrent enqueue, 1656 * so we can avoid taking it. 1657 */ 1658 if (!hrtimer_active(timer)) 1659 return 0; 1660 1661 base = lock_hrtimer_base(timer, &flags); 1662 1663 if (!hrtimer_callback_running(timer)) { 1664 ret = remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE); 1665 if (ret) 1666 trace_hrtimer_cancel(timer); 1667 } 1668 1669 unlock_hrtimer_base(timer, &flags); 1670 1671 return ret; 1672 1673 } 1674 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel); 1675 1676 #ifdef CONFIG_PREEMPT_RT 1677 static void hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base) 1678 { 1679 spin_lock_init(&base->softirq_expiry_lock); 1680 } 1681 1682 static void hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base) 1683 __acquires(&base->softirq_expiry_lock) 1684 { 1685 spin_lock(&base->softirq_expiry_lock); 1686 } 1687 1688 static void hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base) 1689 __releases(&base->softirq_expiry_lock) 1690 { 1691 spin_unlock(&base->softirq_expiry_lock); 1692 } 1693 1694 /* 1695 * The counterpart to hrtimer_cancel_wait_running(). 1696 * 1697 * If there is a waiter for cpu_base->expiry_lock, then it was waiting for 1698 * the timer callback to finish. Drop expiry_lock and reacquire it. That 1699 * allows the waiter to acquire the lock and make progress. 1700 */ 1701 static void hrtimer_sync_wait_running(struct hrtimer_cpu_base *cpu_base, unsigned long flags) 1702 { 1703 if (atomic_read(&cpu_base->timer_waiters)) { 1704 raw_spin_unlock_irqrestore(&cpu_base->lock, flags); 1705 spin_unlock(&cpu_base->softirq_expiry_lock); 1706 spin_lock(&cpu_base->softirq_expiry_lock); 1707 raw_spin_lock_irq(&cpu_base->lock); 1708 } 1709 } 1710 1711 #ifdef CONFIG_SMP 1712 static __always_inline bool is_migration_base(struct hrtimer_clock_base *base) 1713 { 1714 return base == &migration_base; 1715 } 1716 #else 1717 static __always_inline bool is_migration_base(struct hrtimer_clock_base *base) 1718 { 1719 return false; 1720 } 1721 #endif 1722 1723 /* 1724 * This function is called on PREEMPT_RT kernels when the fast path 1725 * deletion of a timer failed because the timer callback function was 1726 * running. 1727 * 1728 * This prevents priority inversion: if the soft irq thread is preempted 1729 * in the middle of a timer callback, then calling hrtimer_cancel() can 1730 * lead to two issues: 1731 * 1732 * - If the caller is on a remote CPU then it has to spin wait for the timer 1733 * handler to complete. This can result in unbound priority inversion. 1734 * 1735 * - If the caller originates from the task which preempted the timer 1736 * handler on the same CPU, then spin waiting for the timer handler to 1737 * complete is never going to end. 1738 */ 1739 void hrtimer_cancel_wait_running(const struct hrtimer *timer) 1740 { 1741 /* Lockless read. Prevent the compiler from reloading it below */ 1742 struct hrtimer_clock_base *base = READ_ONCE(timer->base); 1743 1744 /* 1745 * Just relax if the timer expires in hard interrupt context or if 1746 * it is currently on the migration base. 1747 */ 1748 if (!timer->is_soft || is_migration_base(base)) { 1749 cpu_relax(); 1750 return; 1751 } 1752 1753 /* 1754 * Mark the base as contended and grab the expiry lock, which is 1755 * held by the softirq across the timer callback. Drop the lock 1756 * immediately so the softirq can expire the next timer. In theory 1757 * the timer could already be running again, but that's more than 1758 * unlikely and just causes another wait loop. 1759 */ 1760 atomic_inc(&base->cpu_base->timer_waiters); 1761 spin_lock_bh(&base->cpu_base->softirq_expiry_lock); 1762 atomic_dec(&base->cpu_base->timer_waiters); 1763 spin_unlock_bh(&base->cpu_base->softirq_expiry_lock); 1764 } 1765 #else 1766 static inline void hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base) { } 1767 static inline void hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base) { } 1768 static inline void hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base) { } 1769 static inline void hrtimer_sync_wait_running(struct hrtimer_cpu_base *base, unsigned long fl) { } 1770 #endif 1771 1772 /** 1773 * hrtimer_cancel - cancel a timer and wait for the handler to finish. 1774 * @timer: the timer to be cancelled 1775 * 1776 * Returns: 1777 * 0 when the timer was not active 1778 * 1 when the timer was active 1779 */ 1780 int hrtimer_cancel(struct hrtimer *timer) 1781 { 1782 int ret; 1783 1784 do { 1785 ret = hrtimer_try_to_cancel(timer); 1786 1787 if (ret < 0) 1788 hrtimer_cancel_wait_running(timer); 1789 } while (ret < 0); 1790 return ret; 1791 } 1792 EXPORT_SYMBOL_GPL(hrtimer_cancel); 1793 1794 /** 1795 * __hrtimer_get_remaining - get remaining time for the timer 1796 * @timer: the timer to read 1797 * @adjust: adjust relative timers when CONFIG_TIME_LOW_RES=y 1798 */ 1799 ktime_t __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust) 1800 { 1801 unsigned long flags; 1802 ktime_t rem; 1803 1804 lock_hrtimer_base(timer, &flags); 1805 if (IS_ENABLED(CONFIG_TIME_LOW_RES) && adjust) 1806 rem = hrtimer_expires_remaining_adjusted(timer); 1807 else 1808 rem = hrtimer_expires_remaining(timer); 1809 unlock_hrtimer_base(timer, &flags); 1810 1811 return rem; 1812 } 1813 EXPORT_SYMBOL_GPL(__hrtimer_get_remaining); 1814 1815 #ifdef CONFIG_NO_HZ_COMMON 1816 /** 1817 * hrtimer_get_next_event - get the time until next expiry event 1818 * 1819 * Returns the next expiry time or KTIME_MAX if no timer is pending. 1820 */ 1821 ktime_t hrtimer_get_next_event(void) 1822 { 1823 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases); 1824 1825 /* 1826 * When HRES is active cmp_next_hrtimer_event() expects KTIME_MAX. 1827 * 1828 * cpu_base->hres_active is written only by the local CPU in 1829 * hrtimer_switch_to_hres() from hard interrupt context and in 1830 * hrtimers_cpu_starting() during CPU bring-up, and all callers reach 1831 * this with interrupts disabled on the same CPU, so an unlocked read is 1832 * stable without holding the lock. 1833 */ 1834 if (hrtimer_hres_active(cpu_base)) 1835 return KTIME_MAX; 1836 1837 guard(raw_spinlock_irqsave)(&cpu_base->lock); 1838 return __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_ALL); 1839 } 1840 1841 /** 1842 * hrtimer_next_event_without - time until next expiry event w/o one timer 1843 * @exclude: timer to exclude 1844 * 1845 * Returns the next expiry time over all timers except for the @exclude one or 1846 * KTIME_MAX if none of them is pending. 1847 */ 1848 ktime_t hrtimer_next_event_without(const struct hrtimer *exclude) 1849 { 1850 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases); 1851 ktime_t expires = KTIME_MAX; 1852 unsigned int active; 1853 1854 guard(raw_spinlock_irqsave)(&cpu_base->lock); 1855 if (!hrtimer_hres_active(cpu_base)) 1856 return expires; 1857 1858 active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT; 1859 if (active && !cpu_base->softirq_activated) 1860 expires = hrtimer_bases_next_event_without(cpu_base, exclude, active, KTIME_MAX); 1861 1862 active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD; 1863 if (!active) 1864 return expires; 1865 return hrtimer_bases_next_event_without(cpu_base, exclude, active, expires); 1866 } 1867 #endif 1868 1869 static inline int hrtimer_clockid_to_base(clockid_t clock_id) 1870 { 1871 switch (clock_id) { 1872 case CLOCK_MONOTONIC: 1873 return HRTIMER_BASE_MONOTONIC; 1874 case CLOCK_REALTIME: 1875 return HRTIMER_BASE_REALTIME; 1876 case CLOCK_BOOTTIME: 1877 return HRTIMER_BASE_BOOTTIME; 1878 case CLOCK_TAI: 1879 return HRTIMER_BASE_TAI; 1880 default: 1881 WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id); 1882 return HRTIMER_BASE_MONOTONIC; 1883 } 1884 } 1885 1886 static ktime_t __hrtimer_cb_get_time(clockid_t clock_id) 1887 { 1888 switch (clock_id) { 1889 case CLOCK_MONOTONIC: 1890 return ktime_get(); 1891 case CLOCK_REALTIME: 1892 return ktime_get_real(); 1893 case CLOCK_BOOTTIME: 1894 return ktime_get_boottime(); 1895 case CLOCK_TAI: 1896 return ktime_get_clocktai(); 1897 default: 1898 WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id); 1899 return ktime_get(); 1900 } 1901 } 1902 1903 ktime_t hrtimer_cb_get_time(const struct hrtimer *timer) 1904 { 1905 return __hrtimer_cb_get_time(timer->base->clockid); 1906 } 1907 EXPORT_SYMBOL_GPL(hrtimer_cb_get_time); 1908 1909 static void __hrtimer_setup(struct hrtimer *timer, enum hrtimer_restart (*fn)(struct hrtimer *), 1910 clockid_t clock_id, enum hrtimer_mode mode) 1911 { 1912 bool softtimer = !!(mode & HRTIMER_MODE_SOFT); 1913 struct hrtimer_cpu_base *cpu_base; 1914 int base; 1915 1916 /* 1917 * On PREEMPT_RT enabled kernels hrtimers which are not explicitly 1918 * marked for hard interrupt expiry mode are moved into soft 1919 * interrupt context for latency reasons and because the callbacks 1920 * can invoke functions which might sleep on RT, e.g. spin_lock(). 1921 */ 1922 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(mode & HRTIMER_MODE_HARD)) 1923 softtimer = true; 1924 1925 memset(timer, 0, sizeof(struct hrtimer)); 1926 1927 cpu_base = raw_cpu_ptr(&hrtimer_bases); 1928 1929 /* 1930 * POSIX magic: Relative CLOCK_REALTIME timers are not affected by 1931 * clock modifications, so they needs to become CLOCK_MONOTONIC to 1932 * ensure POSIX compliance. 1933 */ 1934 if (clock_id == CLOCK_REALTIME && mode & HRTIMER_MODE_REL) 1935 clock_id = CLOCK_MONOTONIC; 1936 1937 base = softtimer ? HRTIMER_MAX_CLOCK_BASES / 2 : 0; 1938 base += hrtimer_clockid_to_base(clock_id); 1939 timer->is_soft = softtimer; 1940 timer->is_hard = !!(mode & HRTIMER_MODE_HARD); 1941 timer->is_lazy = !!(mode & HRTIMER_MODE_LAZY_REARM); 1942 timer->base = &cpu_base->clock_base[base]; 1943 timerqueue_linked_init(&timer->node); 1944 1945 if (WARN_ON_ONCE(!fn)) 1946 ACCESS_PRIVATE(timer, function) = hrtimer_dummy_timeout; 1947 else 1948 ACCESS_PRIVATE(timer, function) = fn; 1949 } 1950 1951 /** 1952 * hrtimer_setup - initialize a timer to the given clock 1953 * @timer: the timer to be initialized 1954 * @function: the callback function 1955 * @clock_id: the clock to be used 1956 * @mode: The modes which are relevant for initialization: 1957 * HRTIMER_MODE_ABS, HRTIMER_MODE_REL, HRTIMER_MODE_ABS_SOFT, 1958 * HRTIMER_MODE_REL_SOFT 1959 * 1960 * The PINNED variants of the above can be handed in, 1961 * but the PINNED bit is ignored as pinning happens 1962 * when the hrtimer is started 1963 */ 1964 void hrtimer_setup(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *), 1965 clockid_t clock_id, enum hrtimer_mode mode) 1966 { 1967 debug_setup(timer, clock_id, mode); 1968 __hrtimer_setup(timer, function, clock_id, mode); 1969 } 1970 EXPORT_SYMBOL_GPL(hrtimer_setup); 1971 1972 /** 1973 * hrtimer_setup_on_stack - initialize a timer on stack memory 1974 * @timer: The timer to be initialized 1975 * @function: the callback function 1976 * @clock_id: The clock to be used 1977 * @mode: The timer mode 1978 * 1979 * Similar to hrtimer_setup(), except that this one must be used if struct 1980 * hrtimer is in stack memory. 1981 * 1982 * Callers that do not use the hrtimer_on_stack cleanup class must call 1983 * destroy_hrtimer_on_stack() before the stack storage goes out of scope. The 1984 * cleanup class pairs setup and destruction automatically. 1985 */ 1986 void hrtimer_setup_on_stack(struct hrtimer *timer, 1987 enum hrtimer_restart (*function)(struct hrtimer *), 1988 clockid_t clock_id, enum hrtimer_mode mode) 1989 { 1990 debug_setup_on_stack(timer, clock_id, mode); 1991 __hrtimer_setup(timer, function, clock_id, mode); 1992 } 1993 EXPORT_SYMBOL_GPL(hrtimer_setup_on_stack); 1994 1995 /* 1996 * A timer is active, when it is enqueued into the rbtree or the 1997 * callback function is running or it's in the state of being migrated 1998 * to another cpu. 1999 * 2000 * It is important for this function to not return a false negative. 2001 */ 2002 bool hrtimer_active(const struct hrtimer *timer) 2003 { 2004 struct hrtimer_clock_base *base; 2005 unsigned int seq; 2006 2007 do { 2008 base = READ_ONCE(timer->base); 2009 seq = raw_read_seqcount_begin(&base->seq); 2010 2011 if (timer->is_queued || READ_ONCE(base->running) == timer) 2012 return true; 2013 2014 } while (read_seqcount_retry(&base->seq, seq) || base != READ_ONCE(timer->base)); 2015 2016 return false; 2017 } 2018 EXPORT_SYMBOL_GPL(hrtimer_active); 2019 2020 /* 2021 * The write_seqcount_barrier()s in __run_hrtimer() split the thing into 3 2022 * distinct sections: 2023 * 2024 * - queued: the timer is queued 2025 * - callback: the timer is being ran 2026 * - post: the timer is inactive or (re)queued 2027 * 2028 * On the read side we ensure we observe timer->is_queued and cpu_base->running 2029 * from the same section, if anything changed while we looked at it, we retry. 2030 * This includes timer->base changing because sequence numbers alone are 2031 * insufficient for that. 2032 * 2033 * The sequence numbers are required because otherwise we could still observe 2034 * a false negative if the read side got smeared over multiple consecutive 2035 * __run_hrtimer() invocations. 2036 */ 2037 static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base, struct hrtimer_clock_base *base, 2038 struct hrtimer *timer, ktime_t now, unsigned long flags) 2039 __must_hold(&cpu_base->lock) 2040 { 2041 enum hrtimer_restart (*fn)(struct hrtimer *); 2042 bool expires_in_hardirq; 2043 int restart; 2044 2045 lockdep_assert_held(&cpu_base->lock); 2046 2047 debug_hrtimer_deactivate(timer); 2048 WRITE_ONCE(base->running, timer); 2049 2050 /* 2051 * Separate the ->running assignment from the ->is_queued assignment. 2052 * 2053 * As with a regular write barrier, this ensures the read side in 2054 * hrtimer_active() cannot observe base->running == NULL && 2055 * timer->is_queued == INACTIVE. 2056 */ 2057 raw_write_seqcount_barrier(&base->seq); 2058 2059 __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE, false); 2060 fn = ACCESS_PRIVATE(timer, function); 2061 2062 /* 2063 * Clear the 'is relative' flag for the TIME_LOW_RES case. If the 2064 * timer is restarted with a period then it becomes an absolute 2065 * timer. If its not restarted it does not matter. 2066 */ 2067 if (IS_ENABLED(CONFIG_TIME_LOW_RES)) 2068 timer->is_rel = false; 2069 2070 /* 2071 * The timer is marked as running in the CPU base, so it is 2072 * protected against migration to a different CPU even if the lock 2073 * is dropped. 2074 */ 2075 raw_spin_unlock_irqrestore(&cpu_base->lock, flags); 2076 trace_hrtimer_expire_entry(timer, now); 2077 expires_in_hardirq = lockdep_hrtimer_enter(timer); 2078 2079 restart = fn(timer); 2080 2081 lockdep_hrtimer_exit(expires_in_hardirq); 2082 trace_hrtimer_expire_exit(timer); 2083 raw_spin_lock_irq(&cpu_base->lock); 2084 2085 /* 2086 * Note: We clear the running state after enqueue_hrtimer and 2087 * we do not reprogram the event hardware. Happens either in 2088 * hrtimer_start_range_ns() or in hrtimer_interrupt() 2089 * 2090 * Note: Because we dropped the cpu_base->lock above, 2091 * hrtimer_start_range_ns() can have popped in and enqueued the timer 2092 * for us already. 2093 */ 2094 if (restart == HRTIMER_RESTART && !timer->is_queued) 2095 enqueue_hrtimer(timer, base, HRTIMER_MODE_ABS, false); 2096 2097 /* 2098 * Separate the ->running assignment from the ->is_queued assignment. 2099 * 2100 * As with a regular write barrier, this ensures the read side in 2101 * hrtimer_active() cannot observe base->running.timer == NULL && 2102 * timer->is_queued == INACTIVE. 2103 */ 2104 raw_write_seqcount_barrier(&base->seq); 2105 2106 WARN_ON_ONCE(base->running != timer); 2107 WRITE_ONCE(base->running, NULL); 2108 } 2109 2110 static void __hrtimer_run_queues(struct hrtimer_cpu_base *cpu_base, ktime_t now, 2111 unsigned long flags, unsigned int active_mask) 2112 { 2113 unsigned int active = cpu_base->active_bases & active_mask; 2114 struct hrtimer_clock_base *base; 2115 2116 for_each_active_base(base, cpu_base, active) { 2117 ktime_t basenow = ktime_add(now, base->offset); 2118 struct hrtimer *timer; 2119 2120 while ((timer = clock_base_next_timer(base))) { 2121 /* 2122 * The immediate goal for using the softexpires is 2123 * minimizing wakeups, not running timers at the 2124 * earliest interrupt after their soft expiration. 2125 * This allows us to avoid using a Priority Search 2126 * Tree, which can answer a stabbing query for 2127 * overlapping intervals and instead use the simple 2128 * BST we already have. 2129 * We don't add extra wakeups by delaying timers that 2130 * are right-of a not yet expired timer, because that 2131 * timer will have to trigger a wakeup anyway. 2132 */ 2133 if (basenow < hrtimer_get_softexpires(timer)) 2134 break; 2135 2136 __run_hrtimer(cpu_base, base, timer, basenow, flags); 2137 if (active_mask == HRTIMER_ACTIVE_SOFT) 2138 hrtimer_sync_wait_running(cpu_base, flags); 2139 } 2140 } 2141 } 2142 2143 static __latent_entropy void hrtimer_run_softirq(void) 2144 { 2145 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases); 2146 unsigned long flags; 2147 ktime_t now; 2148 2149 hrtimer_cpu_base_lock_expiry(cpu_base); 2150 raw_spin_lock_irqsave(&cpu_base->lock, flags); 2151 2152 now = hrtimer_update_base(cpu_base); 2153 __hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_SOFT); 2154 2155 cpu_base->softirq_activated = false; 2156 hrtimer_update_softirq_timer(cpu_base, true); 2157 2158 raw_spin_unlock_irqrestore(&cpu_base->lock, flags); 2159 hrtimer_cpu_base_unlock_expiry(cpu_base); 2160 } 2161 2162 #ifdef CONFIG_HIGH_RES_TIMERS 2163 2164 /* 2165 * Very similar to hrtimer_force_reprogram(), except it deals with 2166 * deferred_rearm and hang_detected. 2167 */ 2168 static void hrtimer_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next, bool deferred) 2169 { 2170 cpu_base->expires_next = expires_next; 2171 cpu_base->deferred_rearm = false; 2172 2173 if (unlikely(cpu_base->hang_detected)) { 2174 /* 2175 * Give the system a chance to do something else than looping 2176 * on hrtimer interrupts. 2177 */ 2178 expires_next = ktime_add_ns(ktime_get(), 2179 min(100 * NSEC_PER_MSEC, cpu_base->max_hang_time)); 2180 } 2181 hrtimer_rearm_event(expires_next, deferred); 2182 } 2183 2184 #ifdef CONFIG_HRTIMER_REARM_DEFERRED 2185 void __hrtimer_rearm_deferred(void) 2186 { 2187 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases); 2188 ktime_t expires_next; 2189 2190 if (!cpu_base->deferred_rearm) 2191 return; 2192 2193 guard(raw_spinlock)(&cpu_base->lock); 2194 if (cpu_base->deferred_needs_update) { 2195 hrtimer_update_base(cpu_base); 2196 expires_next = hrtimer_update_next_event(cpu_base); 2197 } else { 2198 /* No timer added/removed. Use the cached value */ 2199 expires_next = cpu_base->deferred_expires_next; 2200 } 2201 hrtimer_rearm(cpu_base, expires_next, true); 2202 } 2203 2204 static __always_inline void 2205 hrtimer_interrupt_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next) 2206 { 2207 /* hrtimer_interrupt() just re-evaluated the first expiring timer */ 2208 cpu_base->deferred_needs_update = false; 2209 /* Cache the expiry time */ 2210 cpu_base->deferred_expires_next = expires_next; 2211 set_thread_flag(TIF_HRTIMER_REARM); 2212 } 2213 #else /* CONFIG_HRTIMER_REARM_DEFERRED */ 2214 static __always_inline void 2215 hrtimer_interrupt_rearm(struct hrtimer_cpu_base *cpu_base, ktime_t expires_next) 2216 { 2217 hrtimer_rearm(cpu_base, expires_next, false); 2218 } 2219 #endif /* !CONFIG_HRTIMER_REARM_DEFERRED */ 2220 2221 /* 2222 * High resolution timer interrupt 2223 * Called with interrupts disabled 2224 */ 2225 void hrtimer_interrupt(struct clock_event_device *dev) 2226 { 2227 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases); 2228 ktime_t expires_next, now, entry_time, delta; 2229 unsigned long flags; 2230 int retries = 0; 2231 2232 BUG_ON(!cpu_base->hres_active); 2233 cpu_base->nr_events++; 2234 dev->next_event = KTIME_MAX; 2235 dev->next_event_forced = 0; 2236 2237 raw_spin_lock_irqsave(&cpu_base->lock, flags); 2238 entry_time = now = hrtimer_update_base(cpu_base); 2239 retry: 2240 cpu_base->deferred_rearm = true; 2241 /* 2242 * Set expires_next to KTIME_MAX, which prevents that remote CPUs queue 2243 * timers while __hrtimer_run_queues() is expiring the clock bases. 2244 * Timers which are re/enqueued on the local CPU are not affected by 2245 * this. 2246 */ 2247 cpu_base->expires_next = KTIME_MAX; 2248 2249 if (!ktime_before(now, cpu_base->softirq_expires_next)) { 2250 cpu_base->softirq_expires_next = KTIME_MAX; 2251 cpu_base->softirq_activated = true; 2252 raise_timer_softirq(HRTIMER_SOFTIRQ); 2253 } 2254 2255 __hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD); 2256 2257 /* 2258 * The next timer was already expired due to: 2259 * - tracing 2260 * - long lasting callbacks 2261 * - being scheduled away when running in a VM 2262 * 2263 * We need to prevent that we loop forever in the hrtiner interrupt 2264 * routine. We give it 3 attempts to avoid overreacting on some 2265 * spurious event. 2266 */ 2267 now = hrtimer_update_base(cpu_base); 2268 expires_next = hrtimer_update_next_event(cpu_base); 2269 cpu_base->hang_detected = false; 2270 if (expires_next < now) { 2271 if (++retries < 3) { 2272 cpu_base->nr_retries++; 2273 goto retry; 2274 } 2275 2276 delta = ktime_sub(now, entry_time); 2277 cpu_base->max_hang_time = max_t(unsigned int, cpu_base->max_hang_time, delta); 2278 cpu_base->nr_hangs++; 2279 cpu_base->hang_detected = true; 2280 } 2281 2282 hrtimer_interrupt_rearm(cpu_base, expires_next); 2283 raw_spin_unlock_irqrestore(&cpu_base->lock, flags); 2284 } 2285 2286 #endif /* !CONFIG_HIGH_RES_TIMERS */ 2287 2288 /* 2289 * Called from run_local_timers in hardirq context every jiffy 2290 */ 2291 void hrtimer_run_queues(void) 2292 { 2293 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases); 2294 unsigned long flags; 2295 ktime_t now; 2296 2297 if (hrtimer_hres_active(cpu_base)) 2298 return; 2299 2300 /* 2301 * This _is_ ugly: We have to check periodically, whether we 2302 * can switch to highres and / or nohz mode. The clocksource 2303 * switch happens with xtime_lock held. Notification from 2304 * there only sets the check bit in the tick_oneshot code, 2305 * otherwise we might deadlock vs. xtime_lock. 2306 */ 2307 if (tick_check_oneshot_change(!hrtimer_is_hres_enabled())) { 2308 hrtimer_switch_to_hres(); 2309 return; 2310 } 2311 2312 raw_spin_lock_irqsave(&cpu_base->lock, flags); 2313 now = hrtimer_update_base(cpu_base); 2314 2315 if (!ktime_before(now, cpu_base->softirq_expires_next)) { 2316 cpu_base->softirq_expires_next = KTIME_MAX; 2317 cpu_base->softirq_activated = true; 2318 raise_timer_softirq(HRTIMER_SOFTIRQ); 2319 } 2320 2321 __hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD); 2322 raw_spin_unlock_irqrestore(&cpu_base->lock, flags); 2323 } 2324 2325 /* 2326 * Sleep related functions: 2327 */ 2328 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer) 2329 { 2330 struct hrtimer_sleeper *t = container_of(timer, struct hrtimer_sleeper, timer); 2331 struct task_struct *task = hrtimer_sleeper_task_get(t); 2332 2333 hrtimer_sleeper_task_set(t, NULL); 2334 if (task) 2335 wake_up_process(task); 2336 2337 return HRTIMER_NORESTART; 2338 } 2339 2340 /** 2341 * hrtimer_sleeper_start_expires - Start a hrtimer sleeper timer 2342 * @sl: sleeper to be started 2343 * @mode: timer mode abs/rel 2344 * 2345 * Wrapper around hrtimer_start_expires() for hrtimer_sleeper based timers 2346 * to allow PREEMPT_RT to tweak the delivery mode (soft/hardirq context) 2347 */ 2348 void hrtimer_sleeper_start_expires(struct hrtimer_sleeper *sl, enum hrtimer_mode mode) 2349 { 2350 /* 2351 * Make the enqueue delivery mode check work on RT. If the sleeper 2352 * was initialized for hard interrupt delivery, force the mode bit. 2353 * This is a special case for hrtimer_sleepers because 2354 * __hrtimer_setup_sleeper() determines the delivery mode on RT so the 2355 * fiddling with this decision is avoided at the call sites. 2356 */ 2357 if (IS_ENABLED(CONFIG_PREEMPT_RT) && sl->timer.is_hard) 2358 mode |= HRTIMER_MODE_HARD; 2359 2360 /* If already expired, clear the task pointer and set current state to running */ 2361 if (!hrtimer_start_expires_user(&sl->timer, mode)) { 2362 hrtimer_sleeper_task_set(sl, NULL); 2363 __set_current_state(TASK_RUNNING); 2364 } 2365 } 2366 EXPORT_SYMBOL_GPL(hrtimer_sleeper_start_expires); 2367 2368 static void __hrtimer_setup_sleeper(struct hrtimer_sleeper *sl, clockid_t clock_id, 2369 enum hrtimer_mode mode) 2370 { 2371 /* 2372 * On PREEMPT_RT enabled kernels hrtimers which are not explicitly 2373 * marked for hard interrupt expiry mode are moved into soft 2374 * interrupt context either for latency reasons or because the 2375 * hrtimer callback takes regular spinlocks or invokes other 2376 * functions which are not suitable for hard interrupt context on 2377 * PREEMPT_RT. 2378 * 2379 * The hrtimer_sleeper callback is RT compatible in hard interrupt 2380 * context, but there is a latency concern: Untrusted userspace can 2381 * spawn many threads which arm timers for the same expiry time on 2382 * the same CPU. That causes a latency spike due to the wakeup of 2383 * a gazillion threads. 2384 * 2385 * OTOH, privileged real-time user space applications rely on the 2386 * low latency of hard interrupt wakeups. If the current task is in 2387 * a real-time scheduling class, mark the mode for hard interrupt 2388 * expiry. 2389 */ 2390 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 2391 if (rt_or_dl_task_policy(current) && !(mode & HRTIMER_MODE_SOFT)) 2392 mode |= HRTIMER_MODE_HARD; 2393 } 2394 2395 __hrtimer_setup(&sl->timer, hrtimer_wakeup, clock_id, mode); 2396 hrtimer_sleeper_task_set(sl, current); 2397 } 2398 2399 /** 2400 * hrtimer_setup_sleeper_on_stack - initialize a sleeper in stack memory 2401 * @sl: sleeper to be initialized 2402 * @clock_id: the clock to be used 2403 * @mode: timer mode abs/rel 2404 */ 2405 void hrtimer_setup_sleeper_on_stack(struct hrtimer_sleeper *sl, clockid_t clock_id, 2406 enum hrtimer_mode mode) 2407 { 2408 debug_setup_on_stack(&sl->timer, clock_id, mode); 2409 __hrtimer_setup_sleeper(sl, clock_id, mode); 2410 } 2411 EXPORT_SYMBOL_GPL(hrtimer_setup_sleeper_on_stack); 2412 2413 int nanosleep_copyout(struct restart_block *restart, struct timespec64 *ts) 2414 { 2415 switch(restart->nanosleep.type) { 2416 #ifdef CONFIG_COMPAT_32BIT_TIME 2417 case TT_COMPAT: 2418 if (put_old_timespec32(ts, restart->nanosleep.compat_rmtp)) 2419 return -EFAULT; 2420 break; 2421 #endif 2422 case TT_NATIVE: 2423 if (put_timespec64(ts, restart->nanosleep.rmtp)) 2424 return -EFAULT; 2425 break; 2426 default: 2427 BUG(); 2428 } 2429 return -ERESTART_RESTARTBLOCK; 2430 } 2431 2432 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode) 2433 { 2434 struct restart_block *restart; 2435 2436 do { 2437 set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE); 2438 hrtimer_sleeper_start_expires(t, mode); 2439 2440 if (likely(hrtimer_sleeper_task_get(t))) 2441 schedule(); 2442 2443 hrtimer_cancel(&t->timer); 2444 mode = HRTIMER_MODE_ABS; 2445 2446 } while (hrtimer_sleeper_task_get(t) && !signal_pending(current)); 2447 2448 __set_current_state(TASK_RUNNING); 2449 2450 if (!hrtimer_sleeper_task_get(t)) 2451 return 0; 2452 2453 restart = ¤t->restart_block; 2454 if (restart->nanosleep.type != TT_NONE) { 2455 ktime_t rem = hrtimer_expires_remaining(&t->timer); 2456 struct timespec64 rmt; 2457 2458 if (rem <= 0) 2459 return 0; 2460 rmt = ktime_to_timespec64(rem); 2461 2462 return nanosleep_copyout(restart, &rmt); 2463 } 2464 return -ERESTART_RESTARTBLOCK; 2465 } 2466 2467 static long __sched hrtimer_nanosleep_restart(struct restart_block *restart) 2468 { 2469 struct hrtimer_sleeper t; 2470 int ret; 2471 2472 hrtimer_setup_sleeper_on_stack(&t, restart->nanosleep.clockid, HRTIMER_MODE_ABS); 2473 hrtimer_set_expires(&t.timer, restart->nanosleep.expires); 2474 ret = do_nanosleep(&t, HRTIMER_MODE_ABS); 2475 destroy_hrtimer_on_stack(&t.timer); 2476 return ret; 2477 } 2478 2479 long hrtimer_nanosleep(ktime_t rqtp, const enum hrtimer_mode mode, const clockid_t clockid) 2480 { 2481 struct restart_block *restart; 2482 struct hrtimer_sleeper t; 2483 int ret; 2484 2485 hrtimer_setup_sleeper_on_stack(&t, clockid, mode); 2486 hrtimer_set_expires_range_ns(&t.timer, rqtp, current->timer_slack_ns); 2487 ret = do_nanosleep(&t, mode); 2488 if (ret != -ERESTART_RESTARTBLOCK) 2489 goto out; 2490 2491 /* Absolute timers do not update the rmtp value and restart: */ 2492 if (mode == HRTIMER_MODE_ABS) { 2493 ret = -ERESTARTNOHAND; 2494 goto out; 2495 } 2496 2497 restart = ¤t->restart_block; 2498 restart->nanosleep.clockid = t.timer.base->clockid; 2499 restart->nanosleep.expires = hrtimer_get_expires(&t.timer); 2500 set_restart_fn(restart, hrtimer_nanosleep_restart); 2501 out: 2502 destroy_hrtimer_on_stack(&t.timer); 2503 return ret; 2504 } 2505 2506 #ifdef CONFIG_64BIT 2507 2508 SYSCALL_DEFINE2(nanosleep, struct __kernel_timespec __user *, rqtp, 2509 struct __kernel_timespec __user *, rmtp) 2510 { 2511 struct timespec64 tu; 2512 2513 if (get_timespec64(&tu, rqtp)) 2514 return -EFAULT; 2515 2516 if (!timespec64_valid(&tu)) 2517 return -EINVAL; 2518 2519 current->restart_block.fn = do_no_restart_syscall; 2520 current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE; 2521 current->restart_block.nanosleep.rmtp = rmtp; 2522 return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL, CLOCK_MONOTONIC); 2523 } 2524 2525 #endif 2526 2527 #ifdef CONFIG_COMPAT_32BIT_TIME 2528 2529 SYSCALL_DEFINE2(nanosleep_time32, struct old_timespec32 __user *, rqtp, 2530 struct old_timespec32 __user *, rmtp) 2531 { 2532 struct timespec64 tu; 2533 2534 if (get_old_timespec32(&tu, rqtp)) 2535 return -EFAULT; 2536 2537 if (!timespec64_valid(&tu)) 2538 return -EINVAL; 2539 2540 current->restart_block.fn = do_no_restart_syscall; 2541 current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE; 2542 current->restart_block.nanosleep.compat_rmtp = rmtp; 2543 return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL, CLOCK_MONOTONIC); 2544 } 2545 #endif 2546 2547 /* 2548 * Functions related to boot-time initialization: 2549 */ 2550 int hrtimers_prepare_cpu(unsigned int cpu) 2551 { 2552 struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu); 2553 2554 for (int i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) { 2555 struct hrtimer_clock_base *clock_b = &cpu_base->clock_base[i]; 2556 2557 clock_b->cpu_base = cpu_base; 2558 seqcount_raw_spinlock_init(&clock_b->seq, &cpu_base->lock); 2559 timerqueue_linked_init_head(&clock_b->active); 2560 } 2561 2562 cpu_base->cpu = cpu; 2563 hrtimer_cpu_base_init_expiry_lock(cpu_base); 2564 return 0; 2565 } 2566 2567 int hrtimers_cpu_starting(unsigned int cpu) 2568 { 2569 struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases); 2570 2571 /* Clear out any left over state from a CPU down operation */ 2572 cpu_base->active_bases = 0; 2573 cpu_base->hres_active = false; 2574 cpu_base->hang_detected = false; 2575 cpu_base->next_timer = NULL; 2576 cpu_base->softirq_next_timer = NULL; 2577 cpu_base->expires_next = KTIME_MAX; 2578 cpu_base->softirq_expires_next = KTIME_MAX; 2579 cpu_base->softirq_activated = false; 2580 cpu_base->online = true; 2581 return 0; 2582 } 2583 2584 #ifdef CONFIG_HOTPLUG_CPU 2585 2586 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base, 2587 struct hrtimer_clock_base *new_base) 2588 { 2589 struct timerqueue_linked_node *node; 2590 struct hrtimer *timer; 2591 2592 while ((node = timerqueue_linked_first(&old_base->active))) { 2593 timer = hrtimer_from_timerqueue_node(node); 2594 BUG_ON(hrtimer_callback_running(timer)); 2595 debug_hrtimer_deactivate(timer); 2596 2597 /* 2598 * Mark it as ENQUEUED not INACTIVE otherwise the 2599 * timer could be seen as !active and just vanish away 2600 * under us on another CPU 2601 */ 2602 __remove_hrtimer(timer, old_base, HRTIMER_STATE_ENQUEUED, false); 2603 timer->base = new_base; 2604 /* 2605 * Enqueue the timers on the new cpu. This does not 2606 * reprogram the event device in case the timer 2607 * expires before the earliest on this CPU, but we run 2608 * hrtimer_interrupt after we migrated everything to 2609 * sort out already expired timers and reprogram the 2610 * event device. 2611 */ 2612 enqueue_hrtimer(timer, new_base, HRTIMER_MODE_ABS, true); 2613 } 2614 } 2615 2616 int hrtimers_cpu_dying(unsigned int dying_cpu) 2617 { 2618 int ncpu = cpumask_any_and(cpu_active_mask, housekeeping_cpumask(HK_TYPE_TIMER)); 2619 struct hrtimer_cpu_base *old_base, *new_base; 2620 2621 old_base = this_cpu_ptr(&hrtimer_bases); 2622 new_base = &per_cpu(hrtimer_bases, ncpu); 2623 2624 /* 2625 * The caller is globally serialized and nobody else 2626 * takes two locks at once, deadlock is not possible. 2627 */ 2628 raw_spin_lock(&old_base->lock); 2629 raw_spin_lock_nested(&new_base->lock, SINGLE_DEPTH_NESTING); 2630 2631 for (int i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) 2632 migrate_hrtimer_list(&old_base->clock_base[i], &new_base->clock_base[i]); 2633 2634 /* Tell the other CPU to retrigger the next event */ 2635 smp_call_function_single(ncpu, retrigger_next_event, NULL, 0); 2636 2637 raw_spin_unlock(&new_base->lock); 2638 old_base->online = false; 2639 raw_spin_unlock(&old_base->lock); 2640 2641 return 0; 2642 } 2643 2644 #endif /* CONFIG_HOTPLUG_CPU */ 2645 2646 void __init hrtimers_init(void) 2647 { 2648 hrtimers_prepare_cpu(smp_processor_id()); 2649 hrtimers_cpu_starting(smp_processor_id()); 2650 open_softirq(HRTIMER_SOFTIRQ, hrtimer_run_softirq); 2651 } 2652