linux/kernel/time/hrtimer.c
<<
>>
Prefs
   1/*
   2 *  linux/kernel/hrtimer.c
   3 *
   4 *  Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
   5 *  Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
   6 *  Copyright(C) 2006-2007  Timesys Corp., Thomas Gleixner
   7 *
   8 *  High-resolution kernel timers
   9 *
  10 *  In contrast to the low-resolution timeout API implemented in
  11 *  kernel/timer.c, hrtimers provide finer resolution and accuracy
  12 *  depending on system configuration and capabilities.
  13 *
  14 *  These timers are currently used for:
  15 *   - itimers
  16 *   - POSIX timers
  17 *   - nanosleep
  18 *   - precise in-kernel timing
  19 *
  20 *  Started by: Thomas Gleixner and Ingo Molnar
  21 *
  22 *  Credits:
  23 *      based on kernel/timer.c
  24 *
  25 *      Help, testing, suggestions, bugfixes, improvements were
  26 *      provided by:
  27 *
  28 *      George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
  29 *      et. al.
  30 *
  31 *  For licencing details see kernel-base/COPYING
  32 */
  33
  34#include <linux/cpu.h>
  35#include <linux/export.h>
  36#include <linux/percpu.h>
  37#include <linux/hrtimer.h>
  38#include <linux/notifier.h>
  39#include <linux/syscalls.h>
  40#include <linux/interrupt.h>
  41#include <linux/tick.h>
  42#include <linux/seq_file.h>
  43#include <linux/err.h>
  44#include <linux/debugobjects.h>
  45#include <linux/sched/signal.h>
  46#include <linux/sched/sysctl.h>
  47#include <linux/sched/rt.h>
  48#include <linux/sched/deadline.h>
  49#include <linux/sched/nohz.h>
  50#include <linux/sched/debug.h>
  51#include <linux/timer.h>
  52#include <linux/freezer.h>
  53#include <linux/compat.h>
  54
  55#include <linux/uaccess.h>
  56
  57#include <trace/events/timer.h>
  58
  59#include "tick-internal.h"
  60
  61/*
  62 * Masks for selecting the soft and hard context timers from
  63 * cpu_base->active
  64 */
  65#define MASK_SHIFT              (HRTIMER_BASE_MONOTONIC_SOFT)
  66#define HRTIMER_ACTIVE_HARD     ((1U << MASK_SHIFT) - 1)
  67#define HRTIMER_ACTIVE_SOFT     (HRTIMER_ACTIVE_HARD << MASK_SHIFT)
  68#define HRTIMER_ACTIVE_ALL      (HRTIMER_ACTIVE_SOFT | HRTIMER_ACTIVE_HARD)
  69
  70/*
  71 * The timer bases:
  72 *
  73 * There are more clockids than hrtimer bases. Thus, we index
  74 * into the timer bases by the hrtimer_base_type enum. When trying
  75 * to reach a base using a clockid, hrtimer_clockid_to_base()
  76 * is used to convert from clockid to the proper hrtimer_base_type.
  77 */
  78DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
  79{
  80        .lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),
  81        .clock_base =
  82        {
  83                {
  84                        .index = HRTIMER_BASE_MONOTONIC,
  85                        .clockid = CLOCK_MONOTONIC,
  86                        .get_time = &ktime_get,
  87                },
  88                {
  89                        .index = HRTIMER_BASE_REALTIME,
  90                        .clockid = CLOCK_REALTIME,
  91                        .get_time = &ktime_get_real,
  92                },
  93                {
  94                        .index = HRTIMER_BASE_BOOTTIME,
  95                        .clockid = CLOCK_BOOTTIME,
  96                        .get_time = &ktime_get_boottime,
  97                },
  98                {
  99                        .index = HRTIMER_BASE_TAI,
 100                        .clockid = CLOCK_TAI,
 101                        .get_time = &ktime_get_clocktai,
 102                },
 103                {
 104                        .index = HRTIMER_BASE_MONOTONIC_SOFT,
 105                        .clockid = CLOCK_MONOTONIC,
 106                        .get_time = &ktime_get,
 107                },
 108                {
 109                        .index = HRTIMER_BASE_REALTIME_SOFT,
 110                        .clockid = CLOCK_REALTIME,
 111                        .get_time = &ktime_get_real,
 112                },
 113                {
 114                        .index = HRTIMER_BASE_BOOTTIME_SOFT,
 115                        .clockid = CLOCK_BOOTTIME,
 116                        .get_time = &ktime_get_boottime,
 117                },
 118                {
 119                        .index = HRTIMER_BASE_TAI_SOFT,
 120                        .clockid = CLOCK_TAI,
 121                        .get_time = &ktime_get_clocktai,
 122                },
 123        }
 124};
 125
 126static const int hrtimer_clock_to_base_table[MAX_CLOCKS] = {
 127        /* Make sure we catch unsupported clockids */
 128        [0 ... MAX_CLOCKS - 1]  = HRTIMER_MAX_CLOCK_BASES,
 129
 130        [CLOCK_REALTIME]        = HRTIMER_BASE_REALTIME,
 131        [CLOCK_MONOTONIC]       = HRTIMER_BASE_MONOTONIC,
 132        [CLOCK_BOOTTIME]        = HRTIMER_BASE_BOOTTIME,
 133        [CLOCK_TAI]             = HRTIMER_BASE_TAI,
 134};
 135
 136/*
 137 * Functions and macros which are different for UP/SMP systems are kept in a
 138 * single place
 139 */
 140#ifdef CONFIG_SMP
 141
 142/*
 143 * We require the migration_base for lock_hrtimer_base()/switch_hrtimer_base()
 144 * such that hrtimer_callback_running() can unconditionally dereference
 145 * timer->base->cpu_base
 146 */
 147static struct hrtimer_cpu_base migration_cpu_base = {
 148        .clock_base = { {
 149                .cpu_base = &migration_cpu_base,
 150                .seq      = SEQCNT_RAW_SPINLOCK_ZERO(migration_cpu_base.seq,
 151                                                     &migration_cpu_base.lock),
 152        }, },
 153};
 154
 155#define migration_base  migration_cpu_base.clock_base[0]
 156
 157static inline bool is_migration_base(struct hrtimer_clock_base *base)
 158{
 159        return base == &migration_base;
 160}
 161
 162/*
 163 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
 164 * means that all timers which are tied to this base via timer->base are
 165 * locked, and the base itself is locked too.
 166 *
 167 * So __run_timers/migrate_timers can safely modify all timers which could
 168 * be found on the lists/queues.
 169 *
 170 * When the timer's base is locked, and the timer removed from list, it is
 171 * possible to set timer->base = &migration_base and drop the lock: the timer
 172 * remains locked.
 173 */
 174static
 175struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
 176                                             unsigned long *flags)
 177{
 178        struct hrtimer_clock_base *base;
 179
 180        for (;;) {
 181                base = READ_ONCE(timer->base);
 182                if (likely(base != &migration_base)) {
 183                        raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
 184                        if (likely(base == timer->base))
 185                                return base;
 186                        /* The timer has migrated to another CPU: */
 187                        raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
 188                }
 189                cpu_relax();
 190        }
 191}
 192
 193/*
 194 * We do not migrate the timer when it is expiring before the next
 195 * event on the target cpu. When high resolution is enabled, we cannot
 196 * reprogram the target cpu hardware and we would cause it to fire
 197 * late. To keep it simple, we handle the high resolution enabled and
 198 * disabled case similar.
 199 *
 200 * Called with cpu_base->lock of target cpu held.
 201 */
 202static int
 203hrtimer_check_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base)
 204{
 205        ktime_t expires;
 206
 207        expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset);
 208        return expires < new_base->cpu_base->expires_next;
 209}
 210
 211static inline
 212struct hrtimer_cpu_base *get_target_base(struct hrtimer_cpu_base *base,
 213                                         int pinned)
 214{
 215#if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
 216        if (static_branch_likely(&timers_migration_enabled) && !pinned)
 217                return &per_cpu(hrtimer_bases, get_nohz_timer_target());
 218#endif
 219        return base;
 220}
 221
 222/*
 223 * We switch the timer base to a power-optimized selected CPU target,
 224 * if:
 225 *      - NO_HZ_COMMON is enabled
 226 *      - timer migration is enabled
 227 *      - the timer callback is not running
 228 *      - the timer is not the first expiring timer on the new target
 229 *
 230 * If one of the above requirements is not fulfilled we move the timer
 231 * to the current CPU or leave it on the previously assigned CPU if
 232 * the timer callback is currently running.
 233 */
 234static inline struct hrtimer_clock_base *
 235switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
 236                    int pinned)
 237{
 238        struct hrtimer_cpu_base *new_cpu_base, *this_cpu_base;
 239        struct hrtimer_clock_base *new_base;
 240        int basenum = base->index;
 241
 242        this_cpu_base = this_cpu_ptr(&hrtimer_bases);
 243        new_cpu_base = get_target_base(this_cpu_base, pinned);
 244again:
 245        new_base = &new_cpu_base->clock_base[basenum];
 246
 247        if (base != new_base) {
 248                /*
 249                 * We are trying to move timer to new_base.
 250                 * However we can't change timer's base while it is running,
 251                 * so we keep it on the same CPU. No hassle vs. reprogramming
 252                 * the event source in the high resolution case. The softirq
 253                 * code will take care of this when the timer function has
 254                 * completed. There is no conflict as we hold the lock until
 255                 * the timer is enqueued.
 256                 */
 257                if (unlikely(hrtimer_callback_running(timer)))
 258                        return base;
 259
 260                /* See the comment in lock_hrtimer_base() */
 261                WRITE_ONCE(timer->base, &migration_base);
 262                raw_spin_unlock(&base->cpu_base->lock);
 263                raw_spin_lock(&new_base->cpu_base->lock);
 264
 265                if (new_cpu_base != this_cpu_base &&
 266                    hrtimer_check_target(timer, new_base)) {
 267                        raw_spin_unlock(&new_base->cpu_base->lock);
 268                        raw_spin_lock(&base->cpu_base->lock);
 269                        new_cpu_base = this_cpu_base;
 270                        WRITE_ONCE(timer->base, base);
 271                        goto again;
 272                }
 273                WRITE_ONCE(timer->base, new_base);
 274        } else {
 275                if (new_cpu_base != this_cpu_base &&
 276                    hrtimer_check_target(timer, new_base)) {
 277                        new_cpu_base = this_cpu_base;
 278                        goto again;
 279                }
 280        }
 281        return new_base;
 282}
 283
 284#else /* CONFIG_SMP */
 285
 286static inline bool is_migration_base(struct hrtimer_clock_base *base)
 287{
 288        return false;
 289}
 290
 291static inline struct hrtimer_clock_base *
 292lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
 293{
 294        struct hrtimer_clock_base *base = timer->base;
 295
 296        raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
 297
 298        return base;
 299}
 300
 301# define switch_hrtimer_base(t, b, p)   (b)
 302
 303#endif  /* !CONFIG_SMP */
 304
 305/*
 306 * Functions for the union type storage format of ktime_t which are
 307 * too large for inlining:
 308 */
 309#if BITS_PER_LONG < 64
 310/*
 311 * Divide a ktime value by a nanosecond value
 312 */
 313s64 __ktime_divns(const ktime_t kt, s64 div)
 314{
 315        int sft = 0;
 316        s64 dclc;
 317        u64 tmp;
 318
 319        dclc = ktime_to_ns(kt);
 320        tmp = dclc < 0 ? -dclc : dclc;
 321
 322        /* Make sure the divisor is less than 2^32: */
 323        while (div >> 32) {
 324                sft++;
 325                div >>= 1;
 326        }
 327        tmp >>= sft;
 328        do_div(tmp, (unsigned long) div);
 329        return dclc < 0 ? -tmp : tmp;
 330}
 331EXPORT_SYMBOL_GPL(__ktime_divns);
 332#endif /* BITS_PER_LONG >= 64 */
 333
 334/*
 335 * Add two ktime values and do a safety check for overflow:
 336 */
 337ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
 338{
 339        ktime_t res = ktime_add_unsafe(lhs, rhs);
 340
 341        /*
 342         * We use KTIME_SEC_MAX here, the maximum timeout which we can
 343         * return to user space in a timespec:
 344         */
 345        if (res < 0 || res < lhs || res < rhs)
 346                res = ktime_set(KTIME_SEC_MAX, 0);
 347
 348        return res;
 349}
 350
 351EXPORT_SYMBOL_GPL(ktime_add_safe);
 352
 353#ifdef CONFIG_DEBUG_OBJECTS_TIMERS
 354
 355static struct debug_obj_descr hrtimer_debug_descr;
 356
 357static void *hrtimer_debug_hint(void *addr)
 358{
 359        return ((struct hrtimer *) addr)->function;
 360}
 361
 362/*
 363 * fixup_init is called when:
 364 * - an active object is initialized
 365 */
 366static bool hrtimer_fixup_init(void *addr, enum debug_obj_state state)
 367{
 368        struct hrtimer *timer = addr;
 369
 370        switch (state) {
 371        case ODEBUG_STATE_ACTIVE:
 372                hrtimer_cancel(timer);
 373                debug_object_init(timer, &hrtimer_debug_descr);
 374                return true;
 375        default:
 376                return false;
 377        }
 378}
 379
 380/*
 381 * fixup_activate is called when:
 382 * - an active object is activated
 383 * - an unknown non-static object is activated
 384 */
 385static bool hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
 386{
 387        switch (state) {
 388        case ODEBUG_STATE_ACTIVE:
 389                WARN_ON(1);
 390
 391        default:
 392                return false;
 393        }
 394}
 395
 396/*
 397 * fixup_free is called when:
 398 * - an active object is freed
 399 */
 400static bool hrtimer_fixup_free(void *addr, enum debug_obj_state state)
 401{
 402        struct hrtimer *timer = addr;
 403
 404        switch (state) {
 405        case ODEBUG_STATE_ACTIVE:
 406                hrtimer_cancel(timer);
 407                debug_object_free(timer, &hrtimer_debug_descr);
 408                return true;
 409        default:
 410                return false;
 411        }
 412}
 413
 414static struct debug_obj_descr hrtimer_debug_descr = {
 415        .name           = "hrtimer",
 416        .debug_hint     = hrtimer_debug_hint,
 417        .fixup_init     = hrtimer_fixup_init,
 418        .fixup_activate = hrtimer_fixup_activate,
 419        .fixup_free     = hrtimer_fixup_free,
 420};
 421
 422static inline void debug_hrtimer_init(struct hrtimer *timer)
 423{
 424        debug_object_init(timer, &hrtimer_debug_descr);
 425}
 426
 427static inline void debug_hrtimer_activate(struct hrtimer *timer,
 428                                          enum hrtimer_mode mode)
 429{
 430        debug_object_activate(timer, &hrtimer_debug_descr);
 431}
 432
 433static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
 434{
 435        debug_object_deactivate(timer, &hrtimer_debug_descr);
 436}
 437
 438static inline void debug_hrtimer_free(struct hrtimer *timer)
 439{
 440        debug_object_free(timer, &hrtimer_debug_descr);
 441}
 442
 443static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
 444                           enum hrtimer_mode mode);
 445
 446void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
 447                           enum hrtimer_mode mode)
 448{
 449        debug_object_init_on_stack(timer, &hrtimer_debug_descr);
 450        __hrtimer_init(timer, clock_id, mode);
 451}
 452EXPORT_SYMBOL_GPL(hrtimer_init_on_stack);
 453
 454static void __hrtimer_init_sleeper(struct hrtimer_sleeper *sl,
 455                                   clockid_t clock_id, enum hrtimer_mode mode);
 456
 457void hrtimer_init_sleeper_on_stack(struct hrtimer_sleeper *sl,
 458                                   clockid_t clock_id, enum hrtimer_mode mode)
 459{
 460        debug_object_init_on_stack(&sl->timer, &hrtimer_debug_descr);
 461        __hrtimer_init_sleeper(sl, clock_id, mode);
 462}
 463EXPORT_SYMBOL_GPL(hrtimer_init_sleeper_on_stack);
 464
 465void destroy_hrtimer_on_stack(struct hrtimer *timer)
 466{
 467        debug_object_free(timer, &hrtimer_debug_descr);
 468}
 469EXPORT_SYMBOL_GPL(destroy_hrtimer_on_stack);
 470
 471#else
 472
 473static inline void debug_hrtimer_init(struct hrtimer *timer) { }
 474static inline void debug_hrtimer_activate(struct hrtimer *timer,
 475                                          enum hrtimer_mode mode) { }
 476static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
 477#endif
 478
 479static inline void
 480debug_init(struct hrtimer *timer, clockid_t clockid,
 481           enum hrtimer_mode mode)
 482{
 483        debug_hrtimer_init(timer);
 484        trace_hrtimer_init(timer, clockid, mode);
 485}
 486
 487static inline void debug_activate(struct hrtimer *timer,
 488                                  enum hrtimer_mode mode)
 489{
 490        debug_hrtimer_activate(timer, mode);
 491        trace_hrtimer_start(timer, mode);
 492}
 493
 494static inline void debug_deactivate(struct hrtimer *timer)
 495{
 496        debug_hrtimer_deactivate(timer);
 497        trace_hrtimer_cancel(timer);
 498}
 499
 500static struct hrtimer_clock_base *
 501__next_base(struct hrtimer_cpu_base *cpu_base, unsigned int *active)
 502{
 503        unsigned int idx;
 504
 505        if (!*active)
 506                return NULL;
 507
 508        idx = __ffs(*active);
 509        *active &= ~(1U << idx);
 510
 511        return &cpu_base->clock_base[idx];
 512}
 513
 514#define for_each_active_base(base, cpu_base, active)    \
 515        while ((base = __next_base((cpu_base), &(active))))
 516
 517static ktime_t __hrtimer_next_event_base(struct hrtimer_cpu_base *cpu_base,
 518                                         const struct hrtimer *exclude,
 519                                         unsigned int active,
 520                                         ktime_t expires_next)
 521{
 522        struct hrtimer_clock_base *base;
 523        ktime_t expires;
 524
 525        for_each_active_base(base, cpu_base, active) {
 526                struct timerqueue_node *next;
 527                struct hrtimer *timer;
 528
 529                next = timerqueue_getnext(&base->active);
 530                timer = container_of(next, struct hrtimer, node);
 531                if (timer == exclude) {
 532                        /* Get to the next timer in the queue. */
 533                        next = timerqueue_iterate_next(next);
 534                        if (!next)
 535                                continue;
 536
 537                        timer = container_of(next, struct hrtimer, node);
 538                }
 539                expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
 540                if (expires < expires_next) {
 541                        expires_next = expires;
 542
 543                        /* Skip cpu_base update if a timer is being excluded. */
 544                        if (exclude)
 545                                continue;
 546
 547                        if (timer->is_soft)
 548                                cpu_base->softirq_next_timer = timer;
 549                        else
 550                                cpu_base->next_timer = timer;
 551                }
 552        }
 553        /*
 554         * clock_was_set() might have changed base->offset of any of
 555         * the clock bases so the result might be negative. Fix it up
 556         * to prevent a false positive in clockevents_program_event().
 557         */
 558        if (expires_next < 0)
 559                expires_next = 0;
 560        return expires_next;
 561}
 562
 563/*
 564 * Recomputes cpu_base::*next_timer and returns the earliest expires_next but
 565 * does not set cpu_base::*expires_next, that is done by hrtimer_reprogram.
 566 *
 567 * When a softirq is pending, we can ignore the HRTIMER_ACTIVE_SOFT bases,
 568 * those timers will get run whenever the softirq gets handled, at the end of
 569 * hrtimer_run_softirq(), hrtimer_update_softirq_timer() will re-add these bases.
 570 *
 571 * Therefore softirq values are those from the HRTIMER_ACTIVE_SOFT clock bases.
 572 * The !softirq values are the minima across HRTIMER_ACTIVE_ALL, unless an actual
 573 * softirq is pending, in which case they're the minima of HRTIMER_ACTIVE_HARD.
 574 *
 575 * @active_mask must be one of:
 576 *  - HRTIMER_ACTIVE_ALL,
 577 *  - HRTIMER_ACTIVE_SOFT, or
 578 *  - HRTIMER_ACTIVE_HARD.
 579 */
 580static ktime_t
 581__hrtimer_get_next_event(struct hrtimer_cpu_base *cpu_base, unsigned int active_mask)
 582{
 583        unsigned int active;
 584        struct hrtimer *next_timer = NULL;
 585        ktime_t expires_next = KTIME_MAX;
 586
 587        if (!cpu_base->softirq_activated && (active_mask & HRTIMER_ACTIVE_SOFT)) {
 588                active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT;
 589                cpu_base->softirq_next_timer = NULL;
 590                expires_next = __hrtimer_next_event_base(cpu_base, NULL,
 591                                                         active, KTIME_MAX);
 592
 593                next_timer = cpu_base->softirq_next_timer;
 594        }
 595
 596        if (active_mask & HRTIMER_ACTIVE_HARD) {
 597                active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD;
 598                cpu_base->next_timer = next_timer;
 599                expires_next = __hrtimer_next_event_base(cpu_base, NULL, active,
 600                                                         expires_next);
 601        }
 602
 603        return expires_next;
 604}
 605
 606static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
 607{
 608        ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
 609        ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
 610        ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset;
 611
 612        ktime_t now = ktime_get_update_offsets_now(&base->clock_was_set_seq,
 613                                            offs_real, offs_boot, offs_tai);
 614
 615        base->clock_base[HRTIMER_BASE_REALTIME_SOFT].offset = *offs_real;
 616        base->clock_base[HRTIMER_BASE_BOOTTIME_SOFT].offset = *offs_boot;
 617        base->clock_base[HRTIMER_BASE_TAI_SOFT].offset = *offs_tai;
 618
 619        return now;
 620}
 621
 622/*
 623 * Is the high resolution mode active ?
 624 */
 625static inline int __hrtimer_hres_active(struct hrtimer_cpu_base *cpu_base)
 626{
 627        return IS_ENABLED(CONFIG_HIGH_RES_TIMERS) ?
 628                cpu_base->hres_active : 0;
 629}
 630
 631static inline int hrtimer_hres_active(void)
 632{
 633        return __hrtimer_hres_active(this_cpu_ptr(&hrtimer_bases));
 634}
 635
 636/*
 637 * Reprogram the event source with checking both queues for the
 638 * next event
 639 * Called with interrupts disabled and base->lock held
 640 */
 641static void
 642hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, int skip_equal)
 643{
 644        ktime_t expires_next;
 645
 646        /*
 647         * Find the current next expiration time.
 648         */
 649        expires_next = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_ALL);
 650
 651        if (cpu_base->next_timer && cpu_base->next_timer->is_soft) {
 652                /*
 653                 * When the softirq is activated, hrtimer has to be
 654                 * programmed with the first hard hrtimer because soft
 655                 * timer interrupt could occur too late.
 656                 */
 657                if (cpu_base->softirq_activated)
 658                        expires_next = __hrtimer_get_next_event(cpu_base,
 659                                                                HRTIMER_ACTIVE_HARD);
 660                else
 661                        cpu_base->softirq_expires_next = expires_next;
 662        }
 663
 664        if (skip_equal && expires_next == cpu_base->expires_next)
 665                return;
 666
 667        cpu_base->expires_next = expires_next;
 668
 669        /*
 670         * If hres is not active, hardware does not have to be
 671         * reprogrammed yet.
 672         *
 673         * If a hang was detected in the last timer interrupt then we
 674         * leave the hang delay active in the hardware. We want the
 675         * system to make progress. That also prevents the following
 676         * scenario:
 677         * T1 expires 50ms from now
 678         * T2 expires 5s from now
 679         *
 680         * T1 is removed, so this code is called and would reprogram
 681         * the hardware to 5s from now. Any hrtimer_start after that
 682         * will not reprogram the hardware due to hang_detected being
 683         * set. So we'd effectivly block all timers until the T2 event
 684         * fires.
 685         */
 686        if (!__hrtimer_hres_active(cpu_base) || cpu_base->hang_detected)
 687                return;
 688
 689        tick_program_event(cpu_base->expires_next, 1);
 690}
 691
 692/* High resolution timer related functions */
 693#ifdef CONFIG_HIGH_RES_TIMERS
 694
 695/*
 696 * High resolution timer enabled ?
 697 */
 698static bool hrtimer_hres_enabled __read_mostly  = true;
 699unsigned int hrtimer_resolution __read_mostly = LOW_RES_NSEC;
 700EXPORT_SYMBOL_GPL(hrtimer_resolution);
 701
 702/*
 703 * Enable / Disable high resolution mode
 704 */
 705static int __init setup_hrtimer_hres(char *str)
 706{
 707        return (kstrtobool(str, &hrtimer_hres_enabled) == 0);
 708}
 709
 710__setup("highres=", setup_hrtimer_hres);
 711
 712/*
 713 * hrtimer_high_res_enabled - query, if the highres mode is enabled
 714 */
 715static inline int hrtimer_is_hres_enabled(void)
 716{
 717        return hrtimer_hres_enabled;
 718}
 719
 720/*
 721 * Retrigger next event is called after clock was set
 722 *
 723 * Called with interrupts disabled via on_each_cpu()
 724 */
 725static void retrigger_next_event(void *arg)
 726{
 727        struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
 728
 729        if (!__hrtimer_hres_active(base))
 730                return;
 731
 732        raw_spin_lock(&base->lock);
 733        hrtimer_update_base(base);
 734        hrtimer_force_reprogram(base, 0);
 735        raw_spin_unlock(&base->lock);
 736}
 737
 738/*
 739 * Switch to high resolution mode
 740 */
 741static void hrtimer_switch_to_hres(void)
 742{
 743        struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
 744
 745        if (tick_init_highres()) {
 746                printk(KERN_WARNING "Could not switch to high resolution "
 747                                    "mode on CPU %d\n", base->cpu);
 748                return;
 749        }
 750        base->hres_active = 1;
 751        hrtimer_resolution = HIGH_RES_NSEC;
 752
 753        tick_setup_sched_timer();
 754        /* "Retrigger" the interrupt to get things going */
 755        retrigger_next_event(NULL);
 756}
 757
 758static void clock_was_set_work(struct work_struct *work)
 759{
 760        clock_was_set();
 761}
 762
 763static DECLARE_WORK(hrtimer_work, clock_was_set_work);
 764
 765/*
 766 * Called from timekeeping and resume code to reprogram the hrtimer
 767 * interrupt device on all cpus.
 768 */
 769void clock_was_set_delayed(void)
 770{
 771        schedule_work(&hrtimer_work);
 772}
 773
 774#else
 775
 776static inline int hrtimer_is_hres_enabled(void) { return 0; }
 777static inline void hrtimer_switch_to_hres(void) { }
 778static inline void retrigger_next_event(void *arg) { }
 779
 780#endif /* CONFIG_HIGH_RES_TIMERS */
 781
 782/*
 783 * When a timer is enqueued and expires earlier than the already enqueued
 784 * timers, we have to check, whether it expires earlier than the timer for
 785 * which the clock event device was armed.
 786 *
 787 * Called with interrupts disabled and base->cpu_base.lock held
 788 */
 789static void hrtimer_reprogram(struct hrtimer *timer, bool reprogram)
 790{
 791        struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
 792        struct hrtimer_clock_base *base = timer->base;
 793        ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
 794
 795        WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
 796
 797        /*
 798         * CLOCK_REALTIME timer might be requested with an absolute
 799         * expiry time which is less than base->offset. Set it to 0.
 800         */
 801        if (expires < 0)
 802                expires = 0;
 803
 804        if (timer->is_soft) {
 805                /*
 806                 * soft hrtimer could be started on a remote CPU. In this
 807                 * case softirq_expires_next needs to be updated on the
 808                 * remote CPU. The soft hrtimer will not expire before the
 809                 * first hard hrtimer on the remote CPU -
 810                 * hrtimer_check_target() prevents this case.
 811                 */
 812                struct hrtimer_cpu_base *timer_cpu_base = base->cpu_base;
 813
 814                if (timer_cpu_base->softirq_activated)
 815                        return;
 816
 817                if (!ktime_before(expires, timer_cpu_base->softirq_expires_next))
 818                        return;
 819
 820                timer_cpu_base->softirq_next_timer = timer;
 821                timer_cpu_base->softirq_expires_next = expires;
 822
 823                if (!ktime_before(expires, timer_cpu_base->expires_next) ||
 824                    !reprogram)
 825                        return;
 826        }
 827
 828        /*
 829         * If the timer is not on the current cpu, we cannot reprogram
 830         * the other cpus clock event device.
 831         */
 832        if (base->cpu_base != cpu_base)
 833                return;
 834
 835        /*
 836         * If the hrtimer interrupt is running, then it will
 837         * reevaluate the clock bases and reprogram the clock event
 838         * device. The callbacks are always executed in hard interrupt
 839         * context so we don't need an extra check for a running
 840         * callback.
 841         */
 842        if (cpu_base->in_hrtirq)
 843                return;
 844
 845        if (expires >= cpu_base->expires_next)
 846                return;
 847
 848        /* Update the pointer to the next expiring timer */
 849        cpu_base->next_timer = timer;
 850        cpu_base->expires_next = expires;
 851
 852        /*
 853         * If hres is not active, hardware does not have to be
 854         * programmed yet.
 855         *
 856         * If a hang was detected in the last timer interrupt then we
 857         * do not schedule a timer which is earlier than the expiry
 858         * which we enforced in the hang detection. We want the system
 859         * to make progress.
 860         */
 861        if (!__hrtimer_hres_active(cpu_base) || cpu_base->hang_detected)
 862                return;
 863
 864        /*
 865         * Program the timer hardware. We enforce the expiry for
 866         * events which are already in the past.
 867         */
 868        tick_program_event(expires, 1);
 869}
 870
 871/*
 872 * Clock realtime was set
 873 *
 874 * Change the offset of the realtime clock vs. the monotonic
 875 * clock.
 876 *
 877 * We might have to reprogram the high resolution timer interrupt. On
 878 * SMP we call the architecture specific code to retrigger _all_ high
 879 * resolution timer interrupts. On UP we just disable interrupts and
 880 * call the high resolution interrupt code.
 881 */
 882void clock_was_set(void)
 883{
 884#ifdef CONFIG_HIGH_RES_TIMERS
 885        /* Retrigger the CPU local events everywhere */
 886        on_each_cpu(retrigger_next_event, NULL, 1);
 887#endif
 888        timerfd_clock_was_set();
 889}
 890
 891/*
 892 * During resume we might have to reprogram the high resolution timer
 893 * interrupt on all online CPUs.  However, all other CPUs will be
 894 * stopped with IRQs interrupts disabled so the clock_was_set() call
 895 * must be deferred.
 896 */
 897void hrtimers_resume(void)
 898{
 899        lockdep_assert_irqs_disabled();
 900        /* Retrigger on the local CPU */
 901        retrigger_next_event(NULL);
 902        /* And schedule a retrigger for all others */
 903        clock_was_set_delayed();
 904}
 905
 906/*
 907 * Counterpart to lock_hrtimer_base above:
 908 */
 909static inline
 910void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
 911{
 912        raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
 913}
 914
 915/**
 916 * hrtimer_forward - forward the timer expiry
 917 * @timer:      hrtimer to forward
 918 * @now:        forward past this time
 919 * @interval:   the interval to forward
 920 *
 921 * Forward the timer expiry so it will expire in the future.
 922 * Returns the number of overruns.
 923 *
 924 * Can be safely called from the callback function of @timer. If
 925 * called from other contexts @timer must neither be enqueued nor
 926 * running the callback and the caller needs to take care of
 927 * serialization.
 928 *
 929 * Note: This only updates the timer expiry value and does not requeue
 930 * the timer.
 931 */
 932u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
 933{
 934        u64 orun = 1;
 935        ktime_t delta;
 936
 937        delta = ktime_sub(now, hrtimer_get_expires(timer));
 938
 939        if (delta < 0)
 940                return 0;
 941
 942        if (WARN_ON(timer->state & HRTIMER_STATE_ENQUEUED))
 943                return 0;
 944
 945        if (interval < hrtimer_resolution)
 946                interval = hrtimer_resolution;
 947
 948        if (unlikely(delta >= interval)) {
 949                s64 incr = ktime_to_ns(interval);
 950
 951                orun = ktime_divns(delta, incr);
 952                hrtimer_add_expires_ns(timer, incr * orun);
 953                if (hrtimer_get_expires_tv64(timer) > now)
 954                        return orun;
 955                /*
 956                 * This (and the ktime_add() below) is the
 957                 * correction for exact:
 958                 */
 959                orun++;
 960        }
 961        hrtimer_add_expires(timer, interval);
 962
 963        return orun;
 964}
 965EXPORT_SYMBOL_GPL(hrtimer_forward);
 966
 967/*
 968 * enqueue_hrtimer - internal function to (re)start a timer
 969 *
 970 * The timer is inserted in expiry order. Insertion into the
 971 * red black tree is O(log(n)). Must hold the base lock.
 972 *
 973 * Returns 1 when the new timer is the leftmost timer in the tree.
 974 */
 975static int enqueue_hrtimer(struct hrtimer *timer,
 976                           struct hrtimer_clock_base *base,
 977                           enum hrtimer_mode mode)
 978{
 979        debug_activate(timer, mode);
 980
 981        base->cpu_base->active_bases |= 1 << base->index;
 982
 983        timer->state = HRTIMER_STATE_ENQUEUED;
 984
 985        return timerqueue_add(&base->active, &timer->node);
 986}
 987
 988/*
 989 * __remove_hrtimer - internal function to remove a timer
 990 *
 991 * Caller must hold the base lock.
 992 *
 993 * High resolution timer mode reprograms the clock event device when the
 994 * timer is the one which expires next. The caller can disable this by setting
 995 * reprogram to zero. This is useful, when the context does a reprogramming
 996 * anyway (e.g. timer interrupt)
 997 */
 998static void __remove_hrtimer(struct hrtimer *timer,
 999                             struct hrtimer_clock_base *base,
1000                             u8 newstate, int reprogram)
1001{
1002        struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1003        u8 state = timer->state;
1004
1005        timer->state = newstate;
1006        if (!(state & HRTIMER_STATE_ENQUEUED))
1007                return;
1008
1009        if (!timerqueue_del(&base->active, &timer->node))
1010                cpu_base->active_bases &= ~(1 << base->index);
1011
1012        /*
1013         * Note: If reprogram is false we do not update
1014         * cpu_base->next_timer. This happens when we remove the first
1015         * timer on a remote cpu. No harm as we never dereference
1016         * cpu_base->next_timer. So the worst thing what can happen is
1017         * an superflous call to hrtimer_force_reprogram() on the
1018         * remote cpu later on if the same timer gets enqueued again.
1019         */
1020        if (reprogram && timer == cpu_base->next_timer)
1021                hrtimer_force_reprogram(cpu_base, 1);
1022}
1023
1024/*
1025 * remove hrtimer, called with base lock held
1026 */
1027static inline int
1028remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base, bool restart)
1029{
1030        if (hrtimer_is_queued(timer)) {
1031                u8 state = timer->state;
1032                int reprogram;
1033
1034                /*
1035                 * Remove the timer and force reprogramming when high
1036                 * resolution mode is active and the timer is on the current
1037                 * CPU. If we remove a timer on another CPU, reprogramming is
1038                 * skipped. The interrupt event on this CPU is fired and
1039                 * reprogramming happens in the interrupt handler. This is a
1040                 * rare case and less expensive than a smp call.
1041                 */
1042                debug_deactivate(timer);
1043                reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
1044
1045                if (!restart)
1046                        state = HRTIMER_STATE_INACTIVE;
1047
1048                __remove_hrtimer(timer, base, state, reprogram);
1049                return 1;
1050        }
1051        return 0;
1052}
1053
1054static inline ktime_t hrtimer_update_lowres(struct hrtimer *timer, ktime_t tim,
1055                                            const enum hrtimer_mode mode)
1056{
1057#ifdef CONFIG_TIME_LOW_RES
1058        /*
1059         * CONFIG_TIME_LOW_RES indicates that the system has no way to return
1060         * granular time values. For relative timers we add hrtimer_resolution
1061         * (i.e. one jiffie) to prevent short timeouts.
1062         */
1063        timer->is_rel = mode & HRTIMER_MODE_REL;
1064        if (timer->is_rel)
1065                tim = ktime_add_safe(tim, hrtimer_resolution);
1066#endif
1067        return tim;
1068}
1069
1070static void
1071hrtimer_update_softirq_timer(struct hrtimer_cpu_base *cpu_base, bool reprogram)
1072{
1073        ktime_t expires;
1074
1075        /*
1076         * Find the next SOFT expiration.
1077         */
1078        expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_SOFT);
1079
1080        /*
1081         * reprogramming needs to be triggered, even if the next soft
1082         * hrtimer expires at the same time than the next hard
1083         * hrtimer. cpu_base->softirq_expires_next needs to be updated!
1084         */
1085        if (expires == KTIME_MAX)
1086                return;
1087
1088        /*
1089         * cpu_base->*next_timer is recomputed by __hrtimer_get_next_event()
1090         * cpu_base->*expires_next is only set by hrtimer_reprogram()
1091         */
1092        hrtimer_reprogram(cpu_base->softirq_next_timer, reprogram);
1093}
1094
1095static int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1096                                    u64 delta_ns, const enum hrtimer_mode mode,
1097                                    struct hrtimer_clock_base *base)
1098{
1099        struct hrtimer_clock_base *new_base;
1100
1101        /* Remove an active timer from the queue: */
1102        remove_hrtimer(timer, base, true);
1103
1104        if (mode & HRTIMER_MODE_REL)
1105                tim = ktime_add_safe(tim, base->get_time());
1106
1107        tim = hrtimer_update_lowres(timer, tim, mode);
1108
1109        hrtimer_set_expires_range_ns(timer, tim, delta_ns);
1110
1111        /* Switch the timer base, if necessary: */
1112        new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
1113
1114        return enqueue_hrtimer(timer, new_base, mode);
1115}
1116
1117/**
1118 * hrtimer_start_range_ns - (re)start an hrtimer
1119 * @timer:      the timer to be added
1120 * @tim:        expiry time
1121 * @delta_ns:   "slack" range for the timer
1122 * @mode:       timer mode: absolute (HRTIMER_MODE_ABS) or
1123 *              relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED);
1124 *              softirq based mode is considered for debug purpose only!
1125 */
1126void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1127                            u64 delta_ns, const enum hrtimer_mode mode)
1128{
1129        struct hrtimer_clock_base *base;
1130        unsigned long flags;
1131
1132        /*
1133         * Check whether the HRTIMER_MODE_SOFT bit and hrtimer.is_soft
1134         * match on CONFIG_PREEMPT_RT = n. With PREEMPT_RT check the hard
1135         * expiry mode because unmarked timers are moved to softirq expiry.
1136         */
1137        if (!IS_ENABLED(CONFIG_PREEMPT_RT))
1138                WARN_ON_ONCE(!(mode & HRTIMER_MODE_SOFT) ^ !timer->is_soft);
1139        else
1140                WARN_ON_ONCE(!(mode & HRTIMER_MODE_HARD) ^ !timer->is_hard);
1141
1142        base = lock_hrtimer_base(timer, &flags);
1143
1144        if (__hrtimer_start_range_ns(timer, tim, delta_ns, mode, base))
1145                hrtimer_reprogram(timer, true);
1146
1147        unlock_hrtimer_base(timer, &flags);
1148}
1149EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1150
1151/**
1152 * hrtimer_try_to_cancel - try to deactivate a timer
1153 * @timer:      hrtimer to stop
1154 *
1155 * Returns:
1156 *  0 when the timer was not active
1157 *  1 when the timer was active
1158 * -1 when the timer is currently executing the callback function and
1159 *    cannot be stopped
1160 */
1161int hrtimer_try_to_cancel(struct hrtimer *timer)
1162{
1163        struct hrtimer_clock_base *base;
1164        unsigned long flags;
1165        int ret = -1;
1166
1167        /*
1168         * Check lockless first. If the timer is not active (neither
1169         * enqueued nor running the callback, nothing to do here.  The
1170         * base lock does not serialize against a concurrent enqueue,
1171         * so we can avoid taking it.
1172         */
1173        if (!hrtimer_active(timer))
1174                return 0;
1175
1176        base = lock_hrtimer_base(timer, &flags);
1177
1178        if (!hrtimer_callback_running(timer))
1179                ret = remove_hrtimer(timer, base, false);
1180
1181        unlock_hrtimer_base(timer, &flags);
1182
1183        return ret;
1184
1185}
1186EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1187
1188#ifdef CONFIG_PREEMPT_RT
1189static void hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base)
1190{
1191        spin_lock_init(&base->softirq_expiry_lock);
1192}
1193
1194static void hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base)
1195{
1196        spin_lock(&base->softirq_expiry_lock);
1197}
1198
1199static void hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base)
1200{
1201        spin_unlock(&base->softirq_expiry_lock);
1202}
1203
1204/*
1205 * The counterpart to hrtimer_cancel_wait_running().
1206 *
1207 * If there is a waiter for cpu_base->expiry_lock, then it was waiting for
1208 * the timer callback to finish. Drop expiry_lock and reaquire it. That
1209 * allows the waiter to acquire the lock and make progress.
1210 */
1211static void hrtimer_sync_wait_running(struct hrtimer_cpu_base *cpu_base,
1212                                      unsigned long flags)
1213{
1214        if (atomic_read(&cpu_base->timer_waiters)) {
1215                raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1216                spin_unlock(&cpu_base->softirq_expiry_lock);
1217                spin_lock(&cpu_base->softirq_expiry_lock);
1218                raw_spin_lock_irq(&cpu_base->lock);
1219        }
1220}
1221
1222/*
1223 * This function is called on PREEMPT_RT kernels when the fast path
1224 * deletion of a timer failed because the timer callback function was
1225 * running.
1226 *
1227 * This prevents priority inversion: if the soft irq thread is preempted
1228 * in the middle of a timer callback, then calling del_timer_sync() can
1229 * lead to two issues:
1230 *
1231 *  - If the caller is on a remote CPU then it has to spin wait for the timer
1232 *    handler to complete. This can result in unbound priority inversion.
1233 *
1234 *  - If the caller originates from the task which preempted the timer
1235 *    handler on the same CPU, then spin waiting for the timer handler to
1236 *    complete is never going to end.
1237 */
1238void hrtimer_cancel_wait_running(const struct hrtimer *timer)
1239{
1240        /* Lockless read. Prevent the compiler from reloading it below */
1241        struct hrtimer_clock_base *base = READ_ONCE(timer->base);
1242
1243        /*
1244         * Just relax if the timer expires in hard interrupt context or if
1245         * it is currently on the migration base.
1246         */
1247        if (!timer->is_soft || is_migration_base(base)) {
1248                cpu_relax();
1249                return;
1250        }
1251
1252        /*
1253         * Mark the base as contended and grab the expiry lock, which is
1254         * held by the softirq across the timer callback. Drop the lock
1255         * immediately so the softirq can expire the next timer. In theory
1256         * the timer could already be running again, but that's more than
1257         * unlikely and just causes another wait loop.
1258         */
1259        atomic_inc(&base->cpu_base->timer_waiters);
1260        spin_lock_bh(&base->cpu_base->softirq_expiry_lock);
1261        atomic_dec(&base->cpu_base->timer_waiters);
1262        spin_unlock_bh(&base->cpu_base->softirq_expiry_lock);
1263}
1264#else
1265static inline void
1266hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base) { }
1267static inline void
1268hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base) { }
1269static inline void
1270hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base) { }
1271static inline void hrtimer_sync_wait_running(struct hrtimer_cpu_base *base,
1272                                             unsigned long flags) { }
1273#endif
1274
1275/**
1276 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1277 * @timer:      the timer to be cancelled
1278 *
1279 * Returns:
1280 *  0 when the timer was not active
1281 *  1 when the timer was active
1282 */
1283int hrtimer_cancel(struct hrtimer *timer)
1284{
1285        int ret;
1286
1287        do {
1288                ret = hrtimer_try_to_cancel(timer);
1289
1290                if (ret < 0)
1291                        hrtimer_cancel_wait_running(timer);
1292        } while (ret < 0);
1293        return ret;
1294}
1295EXPORT_SYMBOL_GPL(hrtimer_cancel);
1296
1297/**
1298 * hrtimer_get_remaining - get remaining time for the timer
1299 * @timer:      the timer to read
1300 * @adjust:     adjust relative timers when CONFIG_TIME_LOW_RES=y
1301 */
1302ktime_t __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust)
1303{
1304        unsigned long flags;
1305        ktime_t rem;
1306
1307        lock_hrtimer_base(timer, &flags);
1308        if (IS_ENABLED(CONFIG_TIME_LOW_RES) && adjust)
1309                rem = hrtimer_expires_remaining_adjusted(timer);
1310        else
1311                rem = hrtimer_expires_remaining(timer);
1312        unlock_hrtimer_base(timer, &flags);
1313
1314        return rem;
1315}
1316EXPORT_SYMBOL_GPL(__hrtimer_get_remaining);
1317
1318#ifdef CONFIG_NO_HZ_COMMON
1319/**
1320 * hrtimer_get_next_event - get the time until next expiry event
1321 *
1322 * Returns the next expiry time or KTIME_MAX if no timer is pending.
1323 */
1324u64 hrtimer_get_next_event(void)
1325{
1326        struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1327        u64 expires = KTIME_MAX;
1328        unsigned long flags;
1329
1330        raw_spin_lock_irqsave(&cpu_base->lock, flags);
1331
1332        if (!__hrtimer_hres_active(cpu_base))
1333                expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_ALL);
1334
1335        raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1336
1337        return expires;
1338}
1339
1340/**
1341 * hrtimer_next_event_without - time until next expiry event w/o one timer
1342 * @exclude:    timer to exclude
1343 *
1344 * Returns the next expiry time over all timers except for the @exclude one or
1345 * KTIME_MAX if none of them is pending.
1346 */
1347u64 hrtimer_next_event_without(const struct hrtimer *exclude)
1348{
1349        struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1350        u64 expires = KTIME_MAX;
1351        unsigned long flags;
1352
1353        raw_spin_lock_irqsave(&cpu_base->lock, flags);
1354
1355        if (__hrtimer_hres_active(cpu_base)) {
1356                unsigned int active;
1357
1358                if (!cpu_base->softirq_activated) {
1359                        active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT;
1360                        expires = __hrtimer_next_event_base(cpu_base, exclude,
1361                                                            active, KTIME_MAX);
1362                }
1363                active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD;
1364                expires = __hrtimer_next_event_base(cpu_base, exclude, active,
1365                                                    expires);
1366        }
1367
1368        raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1369
1370        return expires;
1371}
1372#endif
1373
1374static inline int hrtimer_clockid_to_base(clockid_t clock_id)
1375{
1376        if (likely(clock_id < MAX_CLOCKS)) {
1377                int base = hrtimer_clock_to_base_table[clock_id];
1378
1379                if (likely(base != HRTIMER_MAX_CLOCK_BASES))
1380                        return base;
1381        }
1382        WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id);
1383        return HRTIMER_BASE_MONOTONIC;
1384}
1385
1386static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1387                           enum hrtimer_mode mode)
1388{
1389        bool softtimer = !!(mode & HRTIMER_MODE_SOFT);
1390        struct hrtimer_cpu_base *cpu_base;
1391        int base;
1392
1393        /*
1394         * On PREEMPT_RT enabled kernels hrtimers which are not explicitely
1395         * marked for hard interrupt expiry mode are moved into soft
1396         * interrupt context for latency reasons and because the callbacks
1397         * can invoke functions which might sleep on RT, e.g. spin_lock().
1398         */
1399        if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(mode & HRTIMER_MODE_HARD))
1400                softtimer = true;
1401
1402        memset(timer, 0, sizeof(struct hrtimer));
1403
1404        cpu_base = raw_cpu_ptr(&hrtimer_bases);
1405
1406        /*
1407         * POSIX magic: Relative CLOCK_REALTIME timers are not affected by
1408         * clock modifications, so they needs to become CLOCK_MONOTONIC to
1409         * ensure POSIX compliance.
1410         */
1411        if (clock_id == CLOCK_REALTIME && mode & HRTIMER_MODE_REL)
1412                clock_id = CLOCK_MONOTONIC;
1413
1414        base = softtimer ? HRTIMER_MAX_CLOCK_BASES / 2 : 0;
1415        base += hrtimer_clockid_to_base(clock_id);
1416        timer->is_soft = softtimer;
1417        timer->is_hard = !!(mode & HRTIMER_MODE_HARD);
1418        timer->base = &cpu_base->clock_base[base];
1419        timerqueue_init(&timer->node);
1420}
1421
1422/**
1423 * hrtimer_init - initialize a timer to the given clock
1424 * @timer:      the timer to be initialized
1425 * @clock_id:   the clock to be used
1426 * @mode:       The modes which are relevant for intitialization:
1427 *              HRTIMER_MODE_ABS, HRTIMER_MODE_REL, HRTIMER_MODE_ABS_SOFT,
1428 *              HRTIMER_MODE_REL_SOFT
1429 *
1430 *              The PINNED variants of the above can be handed in,
1431 *              but the PINNED bit is ignored as pinning happens
1432 *              when the hrtimer is started
1433 */
1434void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1435                  enum hrtimer_mode mode)
1436{
1437        debug_init(timer, clock_id, mode);
1438        __hrtimer_init(timer, clock_id, mode);
1439}
1440EXPORT_SYMBOL_GPL(hrtimer_init);
1441
1442/*
1443 * A timer is active, when it is enqueued into the rbtree or the
1444 * callback function is running or it's in the state of being migrated
1445 * to another cpu.
1446 *
1447 * It is important for this function to not return a false negative.
1448 */
1449bool hrtimer_active(const struct hrtimer *timer)
1450{
1451        struct hrtimer_clock_base *base;
1452        unsigned int seq;
1453
1454        do {
1455                base = READ_ONCE(timer->base);
1456                seq = raw_read_seqcount_begin(&base->seq);
1457
1458                if (timer->state != HRTIMER_STATE_INACTIVE ||
1459                    base->running == timer)
1460                        return true;
1461
1462        } while (read_seqcount_retry(&base->seq, seq) ||
1463                 base != READ_ONCE(timer->base));
1464
1465        return false;
1466}
1467EXPORT_SYMBOL_GPL(hrtimer_active);
1468
1469/*
1470 * The write_seqcount_barrier()s in __run_hrtimer() split the thing into 3
1471 * distinct sections:
1472 *
1473 *  - queued:   the timer is queued
1474 *  - callback: the timer is being ran
1475 *  - post:     the timer is inactive or (re)queued
1476 *
1477 * On the read side we ensure we observe timer->state and cpu_base->running
1478 * from the same section, if anything changed while we looked at it, we retry.
1479 * This includes timer->base changing because sequence numbers alone are
1480 * insufficient for that.
1481 *
1482 * The sequence numbers are required because otherwise we could still observe
1483 * a false negative if the read side got smeared over multiple consequtive
1484 * __run_hrtimer() invocations.
1485 */
1486
1487static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base,
1488                          struct hrtimer_clock_base *base,
1489                          struct hrtimer *timer, ktime_t *now,
1490                          unsigned long flags) __must_hold(&cpu_base->lock)
1491{
1492        enum hrtimer_restart (*fn)(struct hrtimer *);
1493        bool expires_in_hardirq;
1494        int restart;
1495
1496        lockdep_assert_held(&cpu_base->lock);
1497
1498        debug_deactivate(timer);
1499        base->running = timer;
1500
1501        /*
1502         * Separate the ->running assignment from the ->state assignment.
1503         *
1504         * As with a regular write barrier, this ensures the read side in
1505         * hrtimer_active() cannot observe base->running == NULL &&
1506         * timer->state == INACTIVE.
1507         */
1508        raw_write_seqcount_barrier(&base->seq);
1509
1510        __remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE, 0);
1511        fn = timer->function;
1512
1513        /*
1514         * Clear the 'is relative' flag for the TIME_LOW_RES case. If the
1515         * timer is restarted with a period then it becomes an absolute
1516         * timer. If its not restarted it does not matter.
1517         */
1518        if (IS_ENABLED(CONFIG_TIME_LOW_RES))
1519                timer->is_rel = false;
1520
1521        /*
1522         * The timer is marked as running in the CPU base, so it is
1523         * protected against migration to a different CPU even if the lock
1524         * is dropped.
1525         */
1526        raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1527        trace_hrtimer_expire_entry(timer, now);
1528        expires_in_hardirq = lockdep_hrtimer_enter(timer);
1529
1530        restart = fn(timer);
1531
1532        lockdep_hrtimer_exit(expires_in_hardirq);
1533        trace_hrtimer_expire_exit(timer);
1534        raw_spin_lock_irq(&cpu_base->lock);
1535
1536        /*
1537         * Note: We clear the running state after enqueue_hrtimer and
1538         * we do not reprogram the event hardware. Happens either in
1539         * hrtimer_start_range_ns() or in hrtimer_interrupt()
1540         *
1541         * Note: Because we dropped the cpu_base->lock above,
1542         * hrtimer_start_range_ns() can have popped in and enqueued the timer
1543         * for us already.
1544         */
1545        if (restart != HRTIMER_NORESTART &&
1546            !(timer->state & HRTIMER_STATE_ENQUEUED))
1547                enqueue_hrtimer(timer, base, HRTIMER_MODE_ABS);
1548
1549        /*
1550         * Separate the ->running assignment from the ->state assignment.
1551         *
1552         * As with a regular write barrier, this ensures the read side in
1553         * hrtimer_active() cannot observe base->running.timer == NULL &&
1554         * timer->state == INACTIVE.
1555         */
1556        raw_write_seqcount_barrier(&base->seq);
1557
1558        WARN_ON_ONCE(base->running != timer);
1559        base->running = NULL;
1560}
1561
1562static void __hrtimer_run_queues(struct hrtimer_cpu_base *cpu_base, ktime_t now,
1563                                 unsigned long flags, unsigned int active_mask)
1564{
1565        struct hrtimer_clock_base *base;
1566        unsigned int active = cpu_base->active_bases & active_mask;
1567
1568        for_each_active_base(base, cpu_base, active) {
1569                struct timerqueue_node *node;
1570                ktime_t basenow;
1571
1572                basenow = ktime_add(now, base->offset);
1573
1574                while ((node = timerqueue_getnext(&base->active))) {
1575                        struct hrtimer *timer;
1576
1577                        timer = container_of(node, struct hrtimer, node);
1578
1579                        /*
1580                         * The immediate goal for using the softexpires is
1581                         * minimizing wakeups, not running timers at the
1582                         * earliest interrupt after their soft expiration.
1583                         * This allows us to avoid using a Priority Search
1584                         * Tree, which can answer a stabbing querry for
1585                         * overlapping intervals and instead use the simple
1586                         * BST we already have.
1587                         * We don't add extra wakeups by delaying timers that
1588                         * are right-of a not yet expired timer, because that
1589                         * timer will have to trigger a wakeup anyway.
1590                         */
1591                        if (basenow < hrtimer_get_softexpires_tv64(timer))
1592                                break;
1593
1594                        __run_hrtimer(cpu_base, base, timer, &basenow, flags);
1595                        if (active_mask == HRTIMER_ACTIVE_SOFT)
1596                                hrtimer_sync_wait_running(cpu_base, flags);
1597                }
1598        }
1599}
1600
1601static __latent_entropy void hrtimer_run_softirq(struct softirq_action *h)
1602{
1603        struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1604        unsigned long flags;
1605        ktime_t now;
1606
1607        hrtimer_cpu_base_lock_expiry(cpu_base);
1608        raw_spin_lock_irqsave(&cpu_base->lock, flags);
1609
1610        now = hrtimer_update_base(cpu_base);
1611        __hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_SOFT);
1612
1613        cpu_base->softirq_activated = 0;
1614        hrtimer_update_softirq_timer(cpu_base, true);
1615
1616        raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1617        hrtimer_cpu_base_unlock_expiry(cpu_base);
1618}
1619
1620#ifdef CONFIG_HIGH_RES_TIMERS
1621
1622/*
1623 * High resolution timer interrupt
1624 * Called with interrupts disabled
1625 */
1626void hrtimer_interrupt(struct clock_event_device *dev)
1627{
1628        struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1629        ktime_t expires_next, now, entry_time, delta;
1630        unsigned long flags;
1631        int retries = 0;
1632
1633        BUG_ON(!cpu_base->hres_active);
1634        cpu_base->nr_events++;
1635        dev->next_event = KTIME_MAX;
1636
1637        raw_spin_lock_irqsave(&cpu_base->lock, flags);
1638        entry_time = now = hrtimer_update_base(cpu_base);
1639retry:
1640        cpu_base->in_hrtirq = 1;
1641        /*
1642         * We set expires_next to KTIME_MAX here with cpu_base->lock
1643         * held to prevent that a timer is enqueued in our queue via
1644         * the migration code. This does not affect enqueueing of
1645         * timers which run their callback and need to be requeued on
1646         * this CPU.
1647         */
1648        cpu_base->expires_next = KTIME_MAX;
1649
1650        if (!ktime_before(now, cpu_base->softirq_expires_next)) {
1651                cpu_base->softirq_expires_next = KTIME_MAX;
1652                cpu_base->softirq_activated = 1;
1653                raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1654        }
1655
1656        __hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
1657
1658        /* Reevaluate the clock bases for the next expiry */
1659        expires_next = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_ALL);
1660        /*
1661         * Store the new expiry value so the migration code can verify
1662         * against it.
1663         */
1664        cpu_base->expires_next = expires_next;
1665        cpu_base->in_hrtirq = 0;
1666        raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1667
1668        /* Reprogramming necessary ? */
1669        if (!tick_program_event(expires_next, 0)) {
1670                cpu_base->hang_detected = 0;
1671                return;
1672        }
1673
1674        /*
1675         * The next timer was already expired due to:
1676         * - tracing
1677         * - long lasting callbacks
1678         * - being scheduled away when running in a VM
1679         *
1680         * We need to prevent that we loop forever in the hrtimer
1681         * interrupt routine. We give it 3 attempts to avoid
1682         * overreacting on some spurious event.
1683         *
1684         * Acquire base lock for updating the offsets and retrieving
1685         * the current time.
1686         */
1687        raw_spin_lock_irqsave(&cpu_base->lock, flags);
1688        now = hrtimer_update_base(cpu_base);
1689        cpu_base->nr_retries++;
1690        if (++retries < 3)
1691                goto retry;
1692        /*
1693         * Give the system a chance to do something else than looping
1694         * here. We stored the entry time, so we know exactly how long
1695         * we spent here. We schedule the next event this amount of
1696         * time away.
1697         */
1698        cpu_base->nr_hangs++;
1699        cpu_base->hang_detected = 1;
1700        raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1701
1702        delta = ktime_sub(now, entry_time);
1703        if ((unsigned int)delta > cpu_base->max_hang_time)
1704                cpu_base->max_hang_time = (unsigned int) delta;
1705        /*
1706         * Limit it to a sensible value as we enforce a longer
1707         * delay. Give the CPU at least 100ms to catch up.
1708         */
1709        if (delta > 100 * NSEC_PER_MSEC)
1710                expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1711        else
1712                expires_next = ktime_add(now, delta);
1713        tick_program_event(expires_next, 1);
1714        printk_once(KERN_WARNING "hrtimer: interrupt took %llu ns\n",
1715                    ktime_to_ns(delta));
1716}
1717
1718/* called with interrupts disabled */
1719static inline void __hrtimer_peek_ahead_timers(void)
1720{
1721        struct tick_device *td;
1722
1723        if (!hrtimer_hres_active())
1724                return;
1725
1726        td = this_cpu_ptr(&tick_cpu_device);
1727        if (td && td->evtdev)
1728                hrtimer_interrupt(td->evtdev);
1729}
1730
1731#else /* CONFIG_HIGH_RES_TIMERS */
1732
1733static inline void __hrtimer_peek_ahead_timers(void) { }
1734
1735#endif  /* !CONFIG_HIGH_RES_TIMERS */
1736
1737/*
1738 * Called from run_local_timers in hardirq context every jiffy
1739 */
1740void hrtimer_run_queues(void)
1741{
1742        struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1743        unsigned long flags;
1744        ktime_t now;
1745
1746        if (__hrtimer_hres_active(cpu_base))
1747                return;
1748
1749        /*
1750         * This _is_ ugly: We have to check periodically, whether we
1751         * can switch to highres and / or nohz mode. The clocksource
1752         * switch happens with xtime_lock held. Notification from
1753         * there only sets the check bit in the tick_oneshot code,
1754         * otherwise we might deadlock vs. xtime_lock.
1755         */
1756        if (tick_check_oneshot_change(!hrtimer_is_hres_enabled())) {
1757                hrtimer_switch_to_hres();
1758                return;
1759        }
1760
1761        raw_spin_lock_irqsave(&cpu_base->lock, flags);
1762        now = hrtimer_update_base(cpu_base);
1763
1764        if (!ktime_before(now, cpu_base->softirq_expires_next)) {
1765                cpu_base->softirq_expires_next = KTIME_MAX;
1766                cpu_base->softirq_activated = 1;
1767                raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1768        }
1769
1770        __hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
1771        raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1772}
1773
1774/*
1775 * Sleep related functions:
1776 */
1777static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1778{
1779        struct hrtimer_sleeper *t =
1780                container_of(timer, struct hrtimer_sleeper, timer);
1781        struct task_struct *task = t->task;
1782
1783        t->task = NULL;
1784        if (task)
1785                wake_up_process(task);
1786
1787        return HRTIMER_NORESTART;
1788}
1789
1790/**
1791 * hrtimer_sleeper_start_expires - Start a hrtimer sleeper timer
1792 * @sl:         sleeper to be started
1793 * @mode:       timer mode abs/rel
1794 *
1795 * Wrapper around hrtimer_start_expires() for hrtimer_sleeper based timers
1796 * to allow PREEMPT_RT to tweak the delivery mode (soft/hardirq context)
1797 */
1798void hrtimer_sleeper_start_expires(struct hrtimer_sleeper *sl,
1799                                   enum hrtimer_mode mode)
1800{
1801        /*
1802         * Make the enqueue delivery mode check work on RT. If the sleeper
1803         * was initialized for hard interrupt delivery, force the mode bit.
1804         * This is a special case for hrtimer_sleepers because
1805         * hrtimer_init_sleeper() determines the delivery mode on RT so the
1806         * fiddling with this decision is avoided at the call sites.
1807         */
1808        if (IS_ENABLED(CONFIG_PREEMPT_RT) && sl->timer.is_hard)
1809                mode |= HRTIMER_MODE_HARD;
1810
1811        hrtimer_start_expires(&sl->timer, mode);
1812}
1813EXPORT_SYMBOL_GPL(hrtimer_sleeper_start_expires);
1814
1815static void __hrtimer_init_sleeper(struct hrtimer_sleeper *sl,
1816                                   clockid_t clock_id, enum hrtimer_mode mode)
1817{
1818        /*
1819         * On PREEMPT_RT enabled kernels hrtimers which are not explicitely
1820         * marked for hard interrupt expiry mode are moved into soft
1821         * interrupt context either for latency reasons or because the
1822         * hrtimer callback takes regular spinlocks or invokes other
1823         * functions which are not suitable for hard interrupt context on
1824         * PREEMPT_RT.
1825         *
1826         * The hrtimer_sleeper callback is RT compatible in hard interrupt
1827         * context, but there is a latency concern: Untrusted userspace can
1828         * spawn many threads which arm timers for the same expiry time on
1829         * the same CPU. That causes a latency spike due to the wakeup of
1830         * a gazillion threads.
1831         *
1832         * OTOH, priviledged real-time user space applications rely on the
1833         * low latency of hard interrupt wakeups. If the current task is in
1834         * a real-time scheduling class, mark the mode for hard interrupt
1835         * expiry.
1836         */
1837        if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
1838                if (task_is_realtime(current) && !(mode & HRTIMER_MODE_SOFT))
1839                        mode |= HRTIMER_MODE_HARD;
1840        }
1841
1842        __hrtimer_init(&sl->timer, clock_id, mode);
1843        sl->timer.function = hrtimer_wakeup;
1844        sl->task = current;
1845}
1846
1847/**
1848 * hrtimer_init_sleeper - initialize sleeper to the given clock
1849 * @sl:         sleeper to be initialized
1850 * @clock_id:   the clock to be used
1851 * @mode:       timer mode abs/rel
1852 */
1853void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, clockid_t clock_id,
1854                          enum hrtimer_mode mode)
1855{
1856        debug_init(&sl->timer, clock_id, mode);
1857        __hrtimer_init_sleeper(sl, clock_id, mode);
1858
1859}
1860EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
1861
1862int nanosleep_copyout(struct restart_block *restart, struct timespec64 *ts)
1863{
1864        switch(restart->nanosleep.type) {
1865#ifdef CONFIG_COMPAT_32BIT_TIME
1866        case TT_COMPAT:
1867                if (compat_put_timespec64(ts, restart->nanosleep.compat_rmtp))
1868                        return -EFAULT;
1869                break;
1870#endif
1871        case TT_NATIVE:
1872                if (put_timespec64(ts, restart->nanosleep.rmtp))
1873                        return -EFAULT;
1874                break;
1875        default:
1876                BUG();
1877        }
1878        return -ERESTART_RESTARTBLOCK;
1879}
1880
1881static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1882{
1883        struct restart_block *restart;
1884
1885        do {
1886                set_current_state(TASK_INTERRUPTIBLE);
1887                hrtimer_sleeper_start_expires(t, mode);
1888
1889                if (likely(t->task))
1890                        freezable_schedule();
1891
1892                hrtimer_cancel(&t->timer);
1893                mode = HRTIMER_MODE_ABS;
1894
1895        } while (t->task && !signal_pending(current));
1896
1897        __set_current_state(TASK_RUNNING);
1898
1899        if (!t->task)
1900                return 0;
1901
1902        restart = &current->restart_block;
1903        if (restart->nanosleep.type != TT_NONE) {
1904                ktime_t rem = hrtimer_expires_remaining(&t->timer);
1905                struct timespec64 rmt;
1906
1907                if (rem <= 0)
1908                        return 0;
1909                rmt = ktime_to_timespec64(rem);
1910
1911                return nanosleep_copyout(restart, &rmt);
1912        }
1913        return -ERESTART_RESTARTBLOCK;
1914}
1915
1916static long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1917{
1918        struct hrtimer_sleeper t;
1919        int ret;
1920
1921        hrtimer_init_sleeper_on_stack(&t, restart->nanosleep.clockid,
1922                                      HRTIMER_MODE_ABS);
1923        hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1924        ret = do_nanosleep(&t, HRTIMER_MODE_ABS);
1925        destroy_hrtimer_on_stack(&t.timer);
1926        return ret;
1927}
1928
1929long hrtimer_nanosleep(ktime_t rqtp, const enum hrtimer_mode mode,
1930                       const clockid_t clockid)
1931{
1932        struct restart_block *restart;
1933        struct hrtimer_sleeper t;
1934        int ret = 0;
1935        u64 slack;
1936
1937        slack = current->timer_slack_ns;
1938        if (dl_task(current) || rt_task(current))
1939                slack = 0;
1940
1941        hrtimer_init_sleeper_on_stack(&t, clockid, mode);
1942        hrtimer_set_expires_range_ns(&t.timer, rqtp, slack);
1943        ret = do_nanosleep(&t, mode);
1944        if (ret != -ERESTART_RESTARTBLOCK)
1945                goto out;
1946
1947        /* Absolute timers do not update the rmtp value and restart: */
1948        if (mode == HRTIMER_MODE_ABS) {
1949                ret = -ERESTARTNOHAND;
1950                goto out;
1951        }
1952
1953        restart = &current->restart_block;
1954        restart->fn = hrtimer_nanosleep_restart;
1955        restart->nanosleep.clockid = t.timer.base->clockid;
1956        restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1957out:
1958        destroy_hrtimer_on_stack(&t.timer);
1959        return ret;
1960}
1961
1962#if !defined(CONFIG_64BIT_TIME) || defined(CONFIG_64BIT)
1963
1964SYSCALL_DEFINE2(nanosleep, struct __kernel_timespec __user *, rqtp,
1965                struct __kernel_timespec __user *, rmtp)
1966{
1967        struct timespec64 tu;
1968
1969        if (get_timespec64(&tu, rqtp))
1970                return -EFAULT;
1971
1972        if (!timespec64_valid(&tu))
1973                return -EINVAL;
1974
1975        current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE;
1976        current->restart_block.nanosleep.rmtp = rmtp;
1977        return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL,
1978                                 CLOCK_MONOTONIC);
1979}
1980
1981#endif
1982
1983#ifdef CONFIG_COMPAT_32BIT_TIME
1984
1985COMPAT_SYSCALL_DEFINE2(nanosleep, struct compat_timespec __user *, rqtp,
1986                       struct compat_timespec __user *, rmtp)
1987{
1988        struct timespec64 tu;
1989
1990        if (compat_get_timespec64(&tu, rqtp))
1991                return -EFAULT;
1992
1993        if (!timespec64_valid(&tu))
1994                return -EINVAL;
1995
1996        current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE;
1997        current->restart_block.nanosleep.compat_rmtp = rmtp;
1998        return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL,
1999                                 CLOCK_MONOTONIC);
2000}
2001#endif
2002
2003/*
2004 * Functions related to boot-time initialization:
2005 */
2006int hrtimers_prepare_cpu(unsigned int cpu)
2007{
2008        struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
2009        int i;
2010
2011        for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
2012                struct hrtimer_clock_base *clock_b = &cpu_base->clock_base[i];
2013
2014                clock_b->cpu_base = cpu_base;
2015                seqcount_raw_spinlock_init(&clock_b->seq, &cpu_base->lock);
2016                timerqueue_init_head(&clock_b->active);
2017        }
2018
2019        cpu_base->cpu = cpu;
2020        cpu_base->active_bases = 0;
2021        cpu_base->hres_active = 0;
2022        cpu_base->hang_detected = 0;
2023        cpu_base->next_timer = NULL;
2024        cpu_base->softirq_next_timer = NULL;
2025        cpu_base->expires_next = KTIME_MAX;
2026        cpu_base->softirq_expires_next = KTIME_MAX;
2027        hrtimer_cpu_base_init_expiry_lock(cpu_base);
2028        return 0;
2029}
2030
2031#ifdef CONFIG_HOTPLUG_CPU
2032
2033static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
2034                                struct hrtimer_clock_base *new_base)
2035{
2036        struct hrtimer *timer;
2037        struct timerqueue_node *node;
2038
2039        while ((node = timerqueue_getnext(&old_base->active))) {
2040                timer = container_of(node, struct hrtimer, node);
2041                BUG_ON(hrtimer_callback_running(timer));
2042                debug_deactivate(timer);
2043
2044                /*
2045                 * Mark it as ENQUEUED not INACTIVE otherwise the
2046                 * timer could be seen as !active and just vanish away
2047                 * under us on another CPU
2048                 */
2049                __remove_hrtimer(timer, old_base, HRTIMER_STATE_ENQUEUED, 0);
2050                timer->base = new_base;
2051                /*
2052                 * Enqueue the timers on the new cpu. This does not
2053                 * reprogram the event device in case the timer
2054                 * expires before the earliest on this CPU, but we run
2055                 * hrtimer_interrupt after we migrated everything to
2056                 * sort out already expired timers and reprogram the
2057                 * event device.
2058                 */
2059                enqueue_hrtimer(timer, new_base, HRTIMER_MODE_ABS);
2060        }
2061}
2062
2063int hrtimers_dead_cpu(unsigned int scpu)
2064{
2065        struct hrtimer_cpu_base *old_base, *new_base;
2066        int i;
2067
2068        BUG_ON(cpu_online(scpu));
2069        tick_cancel_sched_timer(scpu);
2070
2071        /*
2072         * this BH disable ensures that raise_softirq_irqoff() does
2073         * not wakeup ksoftirqd (and acquire the pi-lock) while
2074         * holding the cpu_base lock
2075         */
2076        local_bh_disable();
2077        local_irq_disable();
2078        old_base = &per_cpu(hrtimer_bases, scpu);
2079        new_base = this_cpu_ptr(&hrtimer_bases);
2080        /*
2081         * The caller is globally serialized and nobody else
2082         * takes two locks at once, deadlock is not possible.
2083         */
2084        raw_spin_lock(&new_base->lock);
2085        raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
2086
2087        for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
2088                migrate_hrtimer_list(&old_base->clock_base[i],
2089                                     &new_base->clock_base[i]);
2090        }
2091
2092        /*
2093         * The migration might have changed the first expiring softirq
2094         * timer on this CPU. Update it.
2095         */
2096        hrtimer_update_softirq_timer(new_base, false);
2097
2098        raw_spin_unlock(&old_base->lock);
2099        raw_spin_unlock(&new_base->lock);
2100
2101        /* Check, if we got expired work to do */
2102        __hrtimer_peek_ahead_timers();
2103        local_irq_enable();
2104        local_bh_enable();
2105        return 0;
2106}
2107
2108#endif /* CONFIG_HOTPLUG_CPU */
2109
2110void __init hrtimers_init(void)
2111{
2112        hrtimers_prepare_cpu(smp_processor_id());
2113        open_softirq(HRTIMER_SOFTIRQ, hrtimer_run_softirq);
2114}
2115
2116/**
2117 * schedule_hrtimeout_range_clock - sleep until timeout
2118 * @expires:    timeout value (ktime_t)
2119 * @delta:      slack in expires timeout (ktime_t)
2120 * @mode:       timer mode
2121 * @clock_id:   timer clock to be used
2122 */
2123int __sched
2124schedule_hrtimeout_range_clock(ktime_t *expires, u64 delta,
2125                               const enum hrtimer_mode mode, clockid_t clock_id)
2126{
2127        struct hrtimer_sleeper t;
2128
2129        /*
2130         * Optimize when a zero timeout value is given. It does not
2131         * matter whether this is an absolute or a relative time.
2132         */
2133        if (expires && *expires == 0) {
2134                __set_current_state(TASK_RUNNING);
2135                return 0;
2136        }
2137
2138        /*
2139         * A NULL parameter means "infinite"
2140         */
2141        if (!expires) {
2142                schedule();
2143                return -EINTR;
2144        }
2145
2146        hrtimer_init_sleeper_on_stack(&t, clock_id, mode);
2147        hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
2148        hrtimer_sleeper_start_expires(&t, mode);
2149
2150        if (likely(t.task))
2151                schedule();
2152
2153        hrtimer_cancel(&t.timer);
2154        destroy_hrtimer_on_stack(&t.timer);
2155
2156        __set_current_state(TASK_RUNNING);
2157
2158        return !t.task ? 0 : -EINTR;
2159}
2160
2161/**
2162 * schedule_hrtimeout_range - sleep until timeout
2163 * @expires:    timeout value (ktime_t)
2164 * @delta:      slack in expires timeout (ktime_t)
2165 * @mode:       timer mode
2166 *
2167 * Make the current task sleep until the given expiry time has
2168 * elapsed. The routine will return immediately unless
2169 * the current task state has been set (see set_current_state()).
2170 *
2171 * The @delta argument gives the kernel the freedom to schedule the
2172 * actual wakeup to a time that is both power and performance friendly.
2173 * The kernel give the normal best effort behavior for "@expires+@delta",
2174 * but may decide to fire the timer earlier, but no earlier than @expires.
2175 *
2176 * You can set the task state as follows -
2177 *
2178 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2179 * pass before the routine returns unless the current task is explicitly
2180 * woken up, (e.g. by wake_up_process()).
2181 *
2182 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2183 * delivered to the current task or the current task is explicitly woken
2184 * up.
2185 *
2186 * The current task state is guaranteed to be TASK_RUNNING when this
2187 * routine returns.
2188 *
2189 * Returns 0 when the timer has expired. If the task was woken before the
2190 * timer expired by a signal (only possible in state TASK_INTERRUPTIBLE) or
2191 * by an explicit wakeup, it returns -EINTR.
2192 */
2193int __sched schedule_hrtimeout_range(ktime_t *expires, u64 delta,
2194                                     const enum hrtimer_mode mode)
2195{
2196        return schedule_hrtimeout_range_clock(expires, delta, mode,
2197                                              CLOCK_MONOTONIC);
2198}
2199EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
2200
2201/**
2202 * schedule_hrtimeout - sleep until timeout
2203 * @expires:    timeout value (ktime_t)
2204 * @mode:       timer mode
2205 *
2206 * Make the current task sleep until the given expiry time has
2207 * elapsed. The routine will return immediately unless
2208 * the current task state has been set (see set_current_state()).
2209 *
2210 * You can set the task state as follows -
2211 *
2212 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
2213 * pass before the routine returns unless the current task is explicitly
2214 * woken up, (e.g. by wake_up_process()).
2215 *
2216 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2217 * delivered to the current task or the current task is explicitly woken
2218 * up.
2219 *
2220 * The current task state is guaranteed to be TASK_RUNNING when this
2221 * routine returns.
2222 *
2223 * Returns 0 when the timer has expired. If the task was woken before the
2224 * timer expired by a signal (only possible in state TASK_INTERRUPTIBLE) or
2225 * by an explicit wakeup, it returns -EINTR.
2226 */
2227int __sched schedule_hrtimeout(ktime_t *expires,
2228                               const enum hrtimer_mode mode)
2229{
2230        return schedule_hrtimeout_range(expires, 0, mode);
2231}
2232EXPORT_SYMBOL_GPL(schedule_hrtimeout);
2233