linux/kernel/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/kallsyms.h>
  41#include <linux/interrupt.h>
  42#include <linux/tick.h>
  43#include <linux/seq_file.h>
  44#include <linux/err.h>
  45#include <linux/debugobjects.h>
  46#include <linux/sched.h>
  47#include <linux/sched/sysctl.h>
  48#include <linux/sched/rt.h>
  49#include <linux/timer.h>
  50
  51#include <asm/uaccess.h>
  52
  53#include <trace/events/timer.h>
  54
  55/*
  56 * The timer bases:
  57 *
  58 * There are more clockids then hrtimer bases. Thus, we index
  59 * into the timer bases by the hrtimer_base_type enum. When trying
  60 * to reach a base using a clockid, hrtimer_clockid_to_base()
  61 * is used to convert from clockid to the proper hrtimer_base_type.
  62 */
  63DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
  64{
  65
  66        .lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),
  67        .clock_base =
  68        {
  69                {
  70                        .index = HRTIMER_BASE_MONOTONIC,
  71                        .clockid = CLOCK_MONOTONIC,
  72                        .get_time = &ktime_get,
  73                        .resolution = KTIME_LOW_RES,
  74                },
  75                {
  76                        .index = HRTIMER_BASE_REALTIME,
  77                        .clockid = CLOCK_REALTIME,
  78                        .get_time = &ktime_get_real,
  79                        .resolution = KTIME_LOW_RES,
  80                },
  81                {
  82                        .index = HRTIMER_BASE_BOOTTIME,
  83                        .clockid = CLOCK_BOOTTIME,
  84                        .get_time = &ktime_get_boottime,
  85                        .resolution = KTIME_LOW_RES,
  86                },
  87        }
  88};
  89
  90static const int hrtimer_clock_to_base_table[MAX_CLOCKS] = {
  91        [CLOCK_REALTIME]        = HRTIMER_BASE_REALTIME,
  92        [CLOCK_MONOTONIC]       = HRTIMER_BASE_MONOTONIC,
  93        [CLOCK_BOOTTIME]        = HRTIMER_BASE_BOOTTIME,
  94};
  95
  96static inline int hrtimer_clockid_to_base(clockid_t clock_id)
  97{
  98        return hrtimer_clock_to_base_table[clock_id];
  99}
 100
 101
 102/*
 103 * Get the coarse grained time at the softirq based on xtime and
 104 * wall_to_monotonic.
 105 */
 106static void hrtimer_get_softirq_time(struct hrtimer_cpu_base *base)
 107{
 108        ktime_t xtim, mono, boot;
 109        struct timespec xts, tom, slp;
 110
 111        get_xtime_and_monotonic_and_sleep_offset(&xts, &tom, &slp);
 112
 113        xtim = timespec_to_ktime(xts);
 114        mono = ktime_add(xtim, timespec_to_ktime(tom));
 115        boot = ktime_add(mono, timespec_to_ktime(slp));
 116        base->clock_base[HRTIMER_BASE_REALTIME].softirq_time = xtim;
 117        base->clock_base[HRTIMER_BASE_MONOTONIC].softirq_time = mono;
 118        base->clock_base[HRTIMER_BASE_BOOTTIME].softirq_time = boot;
 119}
 120
 121/*
 122 * Functions and macros which are different for UP/SMP systems are kept in a
 123 * single place
 124 */
 125#ifdef CONFIG_SMP
 126
 127/*
 128 * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
 129 * means that all timers which are tied to this base via timer->base are
 130 * locked, and the base itself is locked too.
 131 *
 132 * So __run_timers/migrate_timers can safely modify all timers which could
 133 * be found on the lists/queues.
 134 *
 135 * When the timer's base is locked, and the timer removed from list, it is
 136 * possible to set timer->base = NULL and drop the lock: the timer remains
 137 * locked.
 138 */
 139static
 140struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
 141                                             unsigned long *flags)
 142{
 143        struct hrtimer_clock_base *base;
 144
 145        for (;;) {
 146                base = timer->base;
 147                if (likely(base != NULL)) {
 148                        raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
 149                        if (likely(base == timer->base))
 150                                return base;
 151                        /* The timer has migrated to another CPU: */
 152                        raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
 153                }
 154                cpu_relax();
 155        }
 156}
 157
 158
 159/*
 160 * Get the preferred target CPU for NOHZ
 161 */
 162static int hrtimer_get_target(int this_cpu, int pinned)
 163{
 164#ifdef CONFIG_NO_HZ
 165        if (!pinned && get_sysctl_timer_migration() && idle_cpu(this_cpu))
 166                return get_nohz_timer_target();
 167#endif
 168        return this_cpu;
 169}
 170
 171/*
 172 * With HIGHRES=y we do not migrate the timer when it is expiring
 173 * before the next event on the target cpu because we cannot reprogram
 174 * the target cpu hardware and we would cause it to fire late.
 175 *
 176 * Called with cpu_base->lock of target cpu held.
 177 */
 178static int
 179hrtimer_check_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base)
 180{
 181#ifdef CONFIG_HIGH_RES_TIMERS
 182        ktime_t expires;
 183
 184        if (!new_base->cpu_base->hres_active)
 185                return 0;
 186
 187        expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset);
 188        return expires.tv64 <= new_base->cpu_base->expires_next.tv64;
 189#else
 190        return 0;
 191#endif
 192}
 193
 194/*
 195 * Switch the timer base to the current CPU when possible.
 196 */
 197static inline struct hrtimer_clock_base *
 198switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
 199                    int pinned)
 200{
 201        struct hrtimer_clock_base *new_base;
 202        struct hrtimer_cpu_base *new_cpu_base;
 203        int this_cpu = smp_processor_id();
 204        int cpu = hrtimer_get_target(this_cpu, pinned);
 205        int basenum = base->index;
 206
 207again:
 208        new_cpu_base = &per_cpu(hrtimer_bases, cpu);
 209        new_base = &new_cpu_base->clock_base[basenum];
 210
 211        if (base != new_base) {
 212                /*
 213                 * We are trying to move timer to new_base.
 214                 * However we can't change timer's base while it is running,
 215                 * so we keep it on the same CPU. No hassle vs. reprogramming
 216                 * the event source in the high resolution case. The softirq
 217                 * code will take care of this when the timer function has
 218                 * completed. There is no conflict as we hold the lock until
 219                 * the timer is enqueued.
 220                 */
 221                if (unlikely(hrtimer_callback_running(timer)))
 222                        return base;
 223
 224                /* See the comment in lock_timer_base() */
 225                timer->base = NULL;
 226                raw_spin_unlock(&base->cpu_base->lock);
 227                raw_spin_lock(&new_base->cpu_base->lock);
 228
 229                if (cpu != this_cpu && hrtimer_check_target(timer, new_base)) {
 230                        cpu = this_cpu;
 231                        raw_spin_unlock(&new_base->cpu_base->lock);
 232                        raw_spin_lock(&base->cpu_base->lock);
 233                        timer->base = base;
 234                        goto again;
 235                }
 236                timer->base = new_base;
 237        }
 238        return new_base;
 239}
 240
 241#else /* CONFIG_SMP */
 242
 243static inline struct hrtimer_clock_base *
 244lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
 245{
 246        struct hrtimer_clock_base *base = timer->base;
 247
 248        raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
 249
 250        return base;
 251}
 252
 253# define switch_hrtimer_base(t, b, p)   (b)
 254
 255#endif  /* !CONFIG_SMP */
 256
 257/*
 258 * Functions for the union type storage format of ktime_t which are
 259 * too large for inlining:
 260 */
 261#if BITS_PER_LONG < 64
 262# ifndef CONFIG_KTIME_SCALAR
 263/**
 264 * ktime_add_ns - Add a scalar nanoseconds value to a ktime_t variable
 265 * @kt:         addend
 266 * @nsec:       the scalar nsec value to add
 267 *
 268 * Returns the sum of kt and nsec in ktime_t format
 269 */
 270ktime_t ktime_add_ns(const ktime_t kt, u64 nsec)
 271{
 272        ktime_t tmp;
 273
 274        if (likely(nsec < NSEC_PER_SEC)) {
 275                tmp.tv64 = nsec;
 276        } else {
 277                unsigned long rem = do_div(nsec, NSEC_PER_SEC);
 278
 279                /* Make sure nsec fits into long */
 280                if (unlikely(nsec > KTIME_SEC_MAX))
 281                        return (ktime_t){ .tv64 = KTIME_MAX };
 282
 283                tmp = ktime_set((long)nsec, rem);
 284        }
 285
 286        return ktime_add(kt, tmp);
 287}
 288
 289EXPORT_SYMBOL_GPL(ktime_add_ns);
 290
 291/**
 292 * ktime_sub_ns - Subtract a scalar nanoseconds value from a ktime_t variable
 293 * @kt:         minuend
 294 * @nsec:       the scalar nsec value to subtract
 295 *
 296 * Returns the subtraction of @nsec from @kt in ktime_t format
 297 */
 298ktime_t ktime_sub_ns(const ktime_t kt, u64 nsec)
 299{
 300        ktime_t tmp;
 301
 302        if (likely(nsec < NSEC_PER_SEC)) {
 303                tmp.tv64 = nsec;
 304        } else {
 305                unsigned long rem = do_div(nsec, NSEC_PER_SEC);
 306
 307                tmp = ktime_set((long)nsec, rem);
 308        }
 309
 310        return ktime_sub(kt, tmp);
 311}
 312
 313EXPORT_SYMBOL_GPL(ktime_sub_ns);
 314# endif /* !CONFIG_KTIME_SCALAR */
 315
 316/*
 317 * Divide a ktime value by a nanosecond value
 318 */
 319u64 ktime_divns(const ktime_t kt, s64 div)
 320{
 321        u64 dclc;
 322        int sft = 0;
 323
 324        dclc = ktime_to_ns(kt);
 325        /* Make sure the divisor is less than 2^32: */
 326        while (div >> 32) {
 327                sft++;
 328                div >>= 1;
 329        }
 330        dclc >>= sft;
 331        do_div(dclc, (unsigned long) div);
 332
 333        return dclc;
 334}
 335#endif /* BITS_PER_LONG >= 64 */
 336
 337/*
 338 * Add two ktime values and do a safety check for overflow:
 339 */
 340ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
 341{
 342        ktime_t res = ktime_add(lhs, rhs);
 343
 344        /*
 345         * We use KTIME_SEC_MAX here, the maximum timeout which we can
 346         * return to user space in a timespec:
 347         */
 348        if (res.tv64 < 0 || res.tv64 < lhs.tv64 || res.tv64 < rhs.tv64)
 349                res = ktime_set(KTIME_SEC_MAX, 0);
 350
 351        return res;
 352}
 353
 354EXPORT_SYMBOL_GPL(ktime_add_safe);
 355
 356#ifdef CONFIG_DEBUG_OBJECTS_TIMERS
 357
 358static struct debug_obj_descr hrtimer_debug_descr;
 359
 360static void *hrtimer_debug_hint(void *addr)
 361{
 362        return ((struct hrtimer *) addr)->function;
 363}
 364
 365/*
 366 * fixup_init is called when:
 367 * - an active object is initialized
 368 */
 369static int hrtimer_fixup_init(void *addr, enum debug_obj_state state)
 370{
 371        struct hrtimer *timer = addr;
 372
 373        switch (state) {
 374        case ODEBUG_STATE_ACTIVE:
 375                hrtimer_cancel(timer);
 376                debug_object_init(timer, &hrtimer_debug_descr);
 377                return 1;
 378        default:
 379                return 0;
 380        }
 381}
 382
 383/*
 384 * fixup_activate is called when:
 385 * - an active object is activated
 386 * - an unknown object is activated (might be a statically initialized object)
 387 */
 388static int hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
 389{
 390        switch (state) {
 391
 392        case ODEBUG_STATE_NOTAVAILABLE:
 393                WARN_ON_ONCE(1);
 394                return 0;
 395
 396        case ODEBUG_STATE_ACTIVE:
 397                WARN_ON(1);
 398
 399        default:
 400                return 0;
 401        }
 402}
 403
 404/*
 405 * fixup_free is called when:
 406 * - an active object is freed
 407 */
 408static int hrtimer_fixup_free(void *addr, enum debug_obj_state state)
 409{
 410        struct hrtimer *timer = addr;
 411
 412        switch (state) {
 413        case ODEBUG_STATE_ACTIVE:
 414                hrtimer_cancel(timer);
 415                debug_object_free(timer, &hrtimer_debug_descr);
 416                return 1;
 417        default:
 418                return 0;
 419        }
 420}
 421
 422static struct debug_obj_descr hrtimer_debug_descr = {
 423        .name           = "hrtimer",
 424        .debug_hint     = hrtimer_debug_hint,
 425        .fixup_init     = hrtimer_fixup_init,
 426        .fixup_activate = hrtimer_fixup_activate,
 427        .fixup_free     = hrtimer_fixup_free,
 428};
 429
 430static inline void debug_hrtimer_init(struct hrtimer *timer)
 431{
 432        debug_object_init(timer, &hrtimer_debug_descr);
 433}
 434
 435static inline void debug_hrtimer_activate(struct hrtimer *timer)
 436{
 437        debug_object_activate(timer, &hrtimer_debug_descr);
 438}
 439
 440static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
 441{
 442        debug_object_deactivate(timer, &hrtimer_debug_descr);
 443}
 444
 445static inline void debug_hrtimer_free(struct hrtimer *timer)
 446{
 447        debug_object_free(timer, &hrtimer_debug_descr);
 448}
 449
 450static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
 451                           enum hrtimer_mode mode);
 452
 453void hrtimer_init_on_stack(struct hrtimer *timer, clockid_t clock_id,
 454                           enum hrtimer_mode mode)
 455{
 456        debug_object_init_on_stack(timer, &hrtimer_debug_descr);
 457        __hrtimer_init(timer, clock_id, mode);
 458}
 459EXPORT_SYMBOL_GPL(hrtimer_init_on_stack);
 460
 461void destroy_hrtimer_on_stack(struct hrtimer *timer)
 462{
 463        debug_object_free(timer, &hrtimer_debug_descr);
 464}
 465
 466#else
 467static inline void debug_hrtimer_init(struct hrtimer *timer) { }
 468static inline void debug_hrtimer_activate(struct hrtimer *timer) { }
 469static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
 470#endif
 471
 472static inline void
 473debug_init(struct hrtimer *timer, clockid_t clockid,
 474           enum hrtimer_mode mode)
 475{
 476        debug_hrtimer_init(timer);
 477        trace_hrtimer_init(timer, clockid, mode);
 478}
 479
 480static inline void debug_activate(struct hrtimer *timer)
 481{
 482        debug_hrtimer_activate(timer);
 483        trace_hrtimer_start(timer);
 484}
 485
 486static inline void debug_deactivate(struct hrtimer *timer)
 487{
 488        debug_hrtimer_deactivate(timer);
 489        trace_hrtimer_cancel(timer);
 490}
 491
 492/* High resolution timer related functions */
 493#ifdef CONFIG_HIGH_RES_TIMERS
 494
 495/*
 496 * High resolution timer enabled ?
 497 */
 498static int hrtimer_hres_enabled __read_mostly  = 1;
 499
 500/*
 501 * Enable / Disable high resolution mode
 502 */
 503static int __init setup_hrtimer_hres(char *str)
 504{
 505        if (!strcmp(str, "off"))
 506                hrtimer_hres_enabled = 0;
 507        else if (!strcmp(str, "on"))
 508                hrtimer_hres_enabled = 1;
 509        else
 510                return 0;
 511        return 1;
 512}
 513
 514__setup("highres=", setup_hrtimer_hres);
 515
 516/*
 517 * hrtimer_high_res_enabled - query, if the highres mode is enabled
 518 */
 519static inline int hrtimer_is_hres_enabled(void)
 520{
 521        return hrtimer_hres_enabled;
 522}
 523
 524/*
 525 * Is the high resolution mode active ?
 526 */
 527static inline int hrtimer_hres_active(void)
 528{
 529        return __this_cpu_read(hrtimer_bases.hres_active);
 530}
 531
 532/*
 533 * Reprogram the event source with checking both queues for the
 534 * next event
 535 * Called with interrupts disabled and base->lock held
 536 */
 537static void
 538hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, int skip_equal)
 539{
 540        int i;
 541        struct hrtimer_clock_base *base = cpu_base->clock_base;
 542        ktime_t expires, expires_next;
 543
 544        expires_next.tv64 = KTIME_MAX;
 545
 546        for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
 547                struct hrtimer *timer;
 548                struct timerqueue_node *next;
 549
 550                next = timerqueue_getnext(&base->active);
 551                if (!next)
 552                        continue;
 553                timer = container_of(next, struct hrtimer, node);
 554
 555                expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
 556                /*
 557                 * clock_was_set() has changed base->offset so the
 558                 * result might be negative. Fix it up to prevent a
 559                 * false positive in clockevents_program_event()
 560                 */
 561                if (expires.tv64 < 0)
 562                        expires.tv64 = 0;
 563                if (expires.tv64 < expires_next.tv64)
 564                        expires_next = expires;
 565        }
 566
 567        if (skip_equal && expires_next.tv64 == cpu_base->expires_next.tv64)
 568                return;
 569
 570        cpu_base->expires_next.tv64 = expires_next.tv64;
 571
 572        if (cpu_base->expires_next.tv64 != KTIME_MAX)
 573                tick_program_event(cpu_base->expires_next, 1);
 574}
 575
 576/*
 577 * Shared reprogramming for clock_realtime and clock_monotonic
 578 *
 579 * When a timer is enqueued and expires earlier than the already enqueued
 580 * timers, we have to check, whether it expires earlier than the timer for
 581 * which the clock event device was armed.
 582 *
 583 * Called with interrupts disabled and base->cpu_base.lock held
 584 */
 585static int hrtimer_reprogram(struct hrtimer *timer,
 586                             struct hrtimer_clock_base *base)
 587{
 588        struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
 589        ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
 590        int res;
 591
 592        WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
 593
 594        /*
 595         * When the callback is running, we do not reprogram the clock event
 596         * device. The timer callback is either running on a different CPU or
 597         * the callback is executed in the hrtimer_interrupt context. The
 598         * reprogramming is handled either by the softirq, which called the
 599         * callback or at the end of the hrtimer_interrupt.
 600         */
 601        if (hrtimer_callback_running(timer))
 602                return 0;
 603
 604        /*
 605         * CLOCK_REALTIME timer might be requested with an absolute
 606         * expiry time which is less than base->offset. Nothing wrong
 607         * about that, just avoid to call into the tick code, which
 608         * has now objections against negative expiry values.
 609         */
 610        if (expires.tv64 < 0)
 611                return -ETIME;
 612
 613        if (expires.tv64 >= cpu_base->expires_next.tv64)
 614                return 0;
 615
 616        /*
 617         * If a hang was detected in the last timer interrupt then we
 618         * do not schedule a timer which is earlier than the expiry
 619         * which we enforced in the hang detection. We want the system
 620         * to make progress.
 621         */
 622        if (cpu_base->hang_detected)
 623                return 0;
 624
 625        /*
 626         * Clockevents returns -ETIME, when the event was in the past.
 627         */
 628        res = tick_program_event(expires, 0);
 629        if (!IS_ERR_VALUE(res))
 630                cpu_base->expires_next = expires;
 631        return res;
 632}
 633
 634/*
 635 * Initialize the high resolution related parts of cpu_base
 636 */
 637static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base)
 638{
 639        base->expires_next.tv64 = KTIME_MAX;
 640        base->hres_active = 0;
 641}
 642
 643/*
 644 * When High resolution timers are active, try to reprogram. Note, that in case
 645 * the state has HRTIMER_STATE_CALLBACK set, no reprogramming and no expiry
 646 * check happens. The timer gets enqueued into the rbtree. The reprogramming
 647 * and expiry check is done in the hrtimer_interrupt or in the softirq.
 648 */
 649static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
 650                                            struct hrtimer_clock_base *base)
 651{
 652        return base->cpu_base->hres_active && hrtimer_reprogram(timer, base);
 653}
 654
 655static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
 656{
 657        ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
 658        ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
 659
 660        return ktime_get_update_offsets(offs_real, offs_boot);
 661}
 662
 663/*
 664 * Retrigger next event is called after clock was set
 665 *
 666 * Called with interrupts disabled via on_each_cpu()
 667 */
 668static void retrigger_next_event(void *arg)
 669{
 670        struct hrtimer_cpu_base *base = &__get_cpu_var(hrtimer_bases);
 671
 672        if (!hrtimer_hres_active())
 673                return;
 674
 675        raw_spin_lock(&base->lock);
 676        hrtimer_update_base(base);
 677        hrtimer_force_reprogram(base, 0);
 678        raw_spin_unlock(&base->lock);
 679}
 680
 681/*
 682 * Switch to high resolution mode
 683 */
 684static int hrtimer_switch_to_hres(void)
 685{
 686        int i, cpu = smp_processor_id();
 687        struct hrtimer_cpu_base *base = &per_cpu(hrtimer_bases, cpu);
 688        unsigned long flags;
 689
 690        if (base->hres_active)
 691                return 1;
 692
 693        local_irq_save(flags);
 694
 695        if (tick_init_highres()) {
 696                local_irq_restore(flags);
 697                printk(KERN_WARNING "Could not switch to high resolution "
 698                                    "mode on CPU %d\n", cpu);
 699                return 0;
 700        }
 701        base->hres_active = 1;
 702        for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++)
 703                base->clock_base[i].resolution = KTIME_HIGH_RES;
 704
 705        tick_setup_sched_timer();
 706        /* "Retrigger" the interrupt to get things going */
 707        retrigger_next_event(NULL);
 708        local_irq_restore(flags);
 709        return 1;
 710}
 711
 712/*
 713 * Called from timekeeping code to reprogramm the hrtimer interrupt
 714 * device. If called from the timer interrupt context we defer it to
 715 * softirq context.
 716 */
 717void clock_was_set_delayed(void)
 718{
 719        struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
 720
 721        cpu_base->clock_was_set = 1;
 722        __raise_softirq_irqoff(HRTIMER_SOFTIRQ);
 723}
 724
 725#else
 726
 727static inline int hrtimer_hres_active(void) { return 0; }
 728static inline int hrtimer_is_hres_enabled(void) { return 0; }
 729static inline int hrtimer_switch_to_hres(void) { return 0; }
 730static inline void
 731hrtimer_force_reprogram(struct hrtimer_cpu_base *base, int skip_equal) { }
 732static inline int hrtimer_enqueue_reprogram(struct hrtimer *timer,
 733                                            struct hrtimer_clock_base *base)
 734{
 735        return 0;
 736}
 737static inline void hrtimer_init_hres(struct hrtimer_cpu_base *base) { }
 738static inline void retrigger_next_event(void *arg) { }
 739
 740#endif /* CONFIG_HIGH_RES_TIMERS */
 741
 742/*
 743 * Clock realtime was set
 744 *
 745 * Change the offset of the realtime clock vs. the monotonic
 746 * clock.
 747 *
 748 * We might have to reprogram the high resolution timer interrupt. On
 749 * SMP we call the architecture specific code to retrigger _all_ high
 750 * resolution timer interrupts. On UP we just disable interrupts and
 751 * call the high resolution interrupt code.
 752 */
 753void clock_was_set(void)
 754{
 755#ifdef CONFIG_HIGH_RES_TIMERS
 756        /* Retrigger the CPU local events everywhere */
 757        on_each_cpu(retrigger_next_event, NULL, 1);
 758#endif
 759        timerfd_clock_was_set();
 760}
 761
 762/*
 763 * During resume we might have to reprogram the high resolution timer
 764 * interrupt (on the local CPU):
 765 */
 766void hrtimers_resume(void)
 767{
 768        WARN_ONCE(!irqs_disabled(),
 769                  KERN_INFO "hrtimers_resume() called with IRQs enabled!");
 770
 771        retrigger_next_event(NULL);
 772        timerfd_clock_was_set();
 773}
 774
 775static inline void timer_stats_hrtimer_set_start_info(struct hrtimer *timer)
 776{
 777#ifdef CONFIG_TIMER_STATS
 778        if (timer->start_site)
 779                return;
 780        timer->start_site = __builtin_return_address(0);
 781        memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
 782        timer->start_pid = current->pid;
 783#endif
 784}
 785
 786static inline void timer_stats_hrtimer_clear_start_info(struct hrtimer *timer)
 787{
 788#ifdef CONFIG_TIMER_STATS
 789        timer->start_site = NULL;
 790#endif
 791}
 792
 793static inline void timer_stats_account_hrtimer(struct hrtimer *timer)
 794{
 795#ifdef CONFIG_TIMER_STATS
 796        if (likely(!timer_stats_active))
 797                return;
 798        timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
 799                                 timer->function, timer->start_comm, 0);
 800#endif
 801}
 802
 803/*
 804 * Counterpart to lock_hrtimer_base above:
 805 */
 806static inline
 807void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
 808{
 809        raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
 810}
 811
 812/**
 813 * hrtimer_forward - forward the timer expiry
 814 * @timer:      hrtimer to forward
 815 * @now:        forward past this time
 816 * @interval:   the interval to forward
 817 *
 818 * Forward the timer expiry so it will expire in the future.
 819 * Returns the number of overruns.
 820 */
 821u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
 822{
 823        u64 orun = 1;
 824        ktime_t delta;
 825
 826        delta = ktime_sub(now, hrtimer_get_expires(timer));
 827
 828        if (delta.tv64 < 0)
 829                return 0;
 830
 831        if (interval.tv64 < timer->base->resolution.tv64)
 832                interval.tv64 = timer->base->resolution.tv64;
 833
 834        if (unlikely(delta.tv64 >= interval.tv64)) {
 835                s64 incr = ktime_to_ns(interval);
 836
 837                orun = ktime_divns(delta, incr);
 838                hrtimer_add_expires_ns(timer, incr * orun);
 839                if (hrtimer_get_expires_tv64(timer) > now.tv64)
 840                        return orun;
 841                /*
 842                 * This (and the ktime_add() below) is the
 843                 * correction for exact:
 844                 */
 845                orun++;
 846        }
 847        hrtimer_add_expires(timer, interval);
 848
 849        return orun;
 850}
 851EXPORT_SYMBOL_GPL(hrtimer_forward);
 852
 853/*
 854 * enqueue_hrtimer - internal function to (re)start a timer
 855 *
 856 * The timer is inserted in expiry order. Insertion into the
 857 * red black tree is O(log(n)). Must hold the base lock.
 858 *
 859 * Returns 1 when the new timer is the leftmost timer in the tree.
 860 */
 861static int enqueue_hrtimer(struct hrtimer *timer,
 862                           struct hrtimer_clock_base *base)
 863{
 864        debug_activate(timer);
 865
 866        timerqueue_add(&base->active, &timer->node);
 867        base->cpu_base->active_bases |= 1 << base->index;
 868
 869        /*
 870         * HRTIMER_STATE_ENQUEUED is or'ed to the current state to preserve the
 871         * state of a possibly running callback.
 872         */
 873        timer->state |= HRTIMER_STATE_ENQUEUED;
 874
 875        return (&timer->node == base->active.next);
 876}
 877
 878/*
 879 * __remove_hrtimer - internal function to remove a timer
 880 *
 881 * Caller must hold the base lock.
 882 *
 883 * High resolution timer mode reprograms the clock event device when the
 884 * timer is the one which expires next. The caller can disable this by setting
 885 * reprogram to zero. This is useful, when the context does a reprogramming
 886 * anyway (e.g. timer interrupt)
 887 */
 888static void __remove_hrtimer(struct hrtimer *timer,
 889                             struct hrtimer_clock_base *base,
 890                             unsigned long newstate, int reprogram)
 891{
 892        struct timerqueue_node *next_timer;
 893        if (!(timer->state & HRTIMER_STATE_ENQUEUED))
 894                goto out;
 895
 896        next_timer = timerqueue_getnext(&base->active);
 897        timerqueue_del(&base->active, &timer->node);
 898        if (&timer->node == next_timer) {
 899#ifdef CONFIG_HIGH_RES_TIMERS
 900                /* Reprogram the clock event device. if enabled */
 901                if (reprogram && hrtimer_hres_active()) {
 902                        ktime_t expires;
 903
 904                        expires = ktime_sub(hrtimer_get_expires(timer),
 905                                            base->offset);
 906                        if (base->cpu_base->expires_next.tv64 == expires.tv64)
 907                                hrtimer_force_reprogram(base->cpu_base, 1);
 908                }
 909#endif
 910        }
 911        if (!timerqueue_getnext(&base->active))
 912                base->cpu_base->active_bases &= ~(1 << base->index);
 913out:
 914        timer->state = newstate;
 915}
 916
 917/*
 918 * remove hrtimer, called with base lock held
 919 */
 920static inline int
 921remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base)
 922{
 923        if (hrtimer_is_queued(timer)) {
 924                unsigned long state;
 925                int reprogram;
 926
 927                /*
 928                 * Remove the timer and force reprogramming when high
 929                 * resolution mode is active and the timer is on the current
 930                 * CPU. If we remove a timer on another CPU, reprogramming is
 931                 * skipped. The interrupt event on this CPU is fired and
 932                 * reprogramming happens in the interrupt handler. This is a
 933                 * rare case and less expensive than a smp call.
 934                 */
 935                debug_deactivate(timer);
 936                timer_stats_hrtimer_clear_start_info(timer);
 937                reprogram = base->cpu_base == &__get_cpu_var(hrtimer_bases);
 938                /*
 939                 * We must preserve the CALLBACK state flag here,
 940                 * otherwise we could move the timer base in
 941                 * switch_hrtimer_base.
 942                 */
 943                state = timer->state & HRTIMER_STATE_CALLBACK;
 944                __remove_hrtimer(timer, base, state, reprogram);
 945                return 1;
 946        }
 947        return 0;
 948}
 949
 950int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
 951                unsigned long delta_ns, const enum hrtimer_mode mode,
 952                int wakeup)
 953{
 954        struct hrtimer_clock_base *base, *new_base;
 955        unsigned long flags;
 956        int ret, leftmost;
 957
 958        base = lock_hrtimer_base(timer, &flags);
 959
 960        /* Remove an active timer from the queue: */
 961        ret = remove_hrtimer(timer, base);
 962
 963        /* Switch the timer base, if necessary: */
 964        new_base = switch_hrtimer_base(timer, base, mode & HRTIMER_MODE_PINNED);
 965
 966        if (mode & HRTIMER_MODE_REL) {
 967                tim = ktime_add_safe(tim, new_base->get_time());
 968                /*
 969                 * CONFIG_TIME_LOW_RES is a temporary way for architectures
 970                 * to signal that they simply return xtime in
 971                 * do_gettimeoffset(). In this case we want to round up by
 972                 * resolution when starting a relative timer, to avoid short
 973                 * timeouts. This will go away with the GTOD framework.
 974                 */
 975#ifdef CONFIG_TIME_LOW_RES
 976                tim = ktime_add_safe(tim, base->resolution);
 977#endif
 978        }
 979
 980        hrtimer_set_expires_range_ns(timer, tim, delta_ns);
 981
 982        timer_stats_hrtimer_set_start_info(timer);
 983
 984        leftmost = enqueue_hrtimer(timer, new_base);
 985
 986        /*
 987         * Only allow reprogramming if the new base is on this CPU.
 988         * (it might still be on another CPU if the timer was pending)
 989         *
 990         * XXX send_remote_softirq() ?
 991         */
 992        if (leftmost && new_base->cpu_base == &__get_cpu_var(hrtimer_bases)
 993                && hrtimer_enqueue_reprogram(timer, new_base)) {
 994                if (wakeup) {
 995                        /*
 996                         * We need to drop cpu_base->lock to avoid a
 997                         * lock ordering issue vs. rq->lock.
 998                         */
 999                        raw_spin_unlock(&new_base->cpu_base->lock);
1000                        raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1001                        local_irq_restore(flags);
1002                        return ret;
1003                } else {
1004                        __raise_softirq_irqoff(HRTIMER_SOFTIRQ);
1005                }
1006        }
1007
1008        unlock_hrtimer_base(timer, &flags);
1009
1010        return ret;
1011}
1012
1013/**
1014 * hrtimer_start_range_ns - (re)start an hrtimer on the current CPU
1015 * @timer:      the timer to be added
1016 * @tim:        expiry time
1017 * @delta_ns:   "slack" range for the timer
1018 * @mode:       expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
1019 *
1020 * Returns:
1021 *  0 on success
1022 *  1 when the timer was active
1023 */
1024int hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1025                unsigned long delta_ns, const enum hrtimer_mode mode)
1026{
1027        return __hrtimer_start_range_ns(timer, tim, delta_ns, mode, 1);
1028}
1029EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1030
1031/**
1032 * hrtimer_start - (re)start an hrtimer on the current CPU
1033 * @timer:      the timer to be added
1034 * @tim:        expiry time
1035 * @mode:       expiry mode: absolute (HRTIMER_ABS) or relative (HRTIMER_REL)
1036 *
1037 * Returns:
1038 *  0 on success
1039 *  1 when the timer was active
1040 */
1041int
1042hrtimer_start(struct hrtimer *timer, ktime_t tim, const enum hrtimer_mode mode)
1043{
1044        return __hrtimer_start_range_ns(timer, tim, 0, mode, 1);
1045}
1046EXPORT_SYMBOL_GPL(hrtimer_start);
1047
1048
1049/**
1050 * hrtimer_try_to_cancel - try to deactivate a timer
1051 * @timer:      hrtimer to stop
1052 *
1053 * Returns:
1054 *  0 when the timer was not active
1055 *  1 when the timer was active
1056 * -1 when the timer is currently excuting the callback function and
1057 *    cannot be stopped
1058 */
1059int hrtimer_try_to_cancel(struct hrtimer *timer)
1060{
1061        struct hrtimer_clock_base *base;
1062        unsigned long flags;
1063        int ret = -1;
1064
1065        base = lock_hrtimer_base(timer, &flags);
1066
1067        if (!hrtimer_callback_running(timer))
1068                ret = remove_hrtimer(timer, base);
1069
1070        unlock_hrtimer_base(timer, &flags);
1071
1072        return ret;
1073
1074}
1075EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1076
1077/**
1078 * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1079 * @timer:      the timer to be cancelled
1080 *
1081 * Returns:
1082 *  0 when the timer was not active
1083 *  1 when the timer was active
1084 */
1085int hrtimer_cancel(struct hrtimer *timer)
1086{
1087        for (;;) {
1088                int ret = hrtimer_try_to_cancel(timer);
1089
1090                if (ret >= 0)
1091                        return ret;
1092                cpu_relax();
1093        }
1094}
1095EXPORT_SYMBOL_GPL(hrtimer_cancel);
1096
1097/**
1098 * hrtimer_get_remaining - get remaining time for the timer
1099 * @timer:      the timer to read
1100 */
1101ktime_t hrtimer_get_remaining(const struct hrtimer *timer)
1102{
1103        unsigned long flags;
1104        ktime_t rem;
1105
1106        lock_hrtimer_base(timer, &flags);
1107        rem = hrtimer_expires_remaining(timer);
1108        unlock_hrtimer_base(timer, &flags);
1109
1110        return rem;
1111}
1112EXPORT_SYMBOL_GPL(hrtimer_get_remaining);
1113
1114#ifdef CONFIG_NO_HZ
1115/**
1116 * hrtimer_get_next_event - get the time until next expiry event
1117 *
1118 * Returns the delta to the next expiry event or KTIME_MAX if no timer
1119 * is pending.
1120 */
1121ktime_t hrtimer_get_next_event(void)
1122{
1123        struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1124        struct hrtimer_clock_base *base = cpu_base->clock_base;
1125        ktime_t delta, mindelta = { .tv64 = KTIME_MAX };
1126        unsigned long flags;
1127        int i;
1128
1129        raw_spin_lock_irqsave(&cpu_base->lock, flags);
1130
1131        if (!hrtimer_hres_active()) {
1132                for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++, base++) {
1133                        struct hrtimer *timer;
1134                        struct timerqueue_node *next;
1135
1136                        next = timerqueue_getnext(&base->active);
1137                        if (!next)
1138                                continue;
1139
1140                        timer = container_of(next, struct hrtimer, node);
1141                        delta.tv64 = hrtimer_get_expires_tv64(timer);
1142                        delta = ktime_sub(delta, base->get_time());
1143                        if (delta.tv64 < mindelta.tv64)
1144                                mindelta.tv64 = delta.tv64;
1145                }
1146        }
1147
1148        raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1149
1150        if (mindelta.tv64 < 0)
1151                mindelta.tv64 = 0;
1152        return mindelta;
1153}
1154#endif
1155
1156static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1157                           enum hrtimer_mode mode)
1158{
1159        struct hrtimer_cpu_base *cpu_base;
1160        int base;
1161
1162        memset(timer, 0, sizeof(struct hrtimer));
1163
1164        cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1165
1166        if (clock_id == CLOCK_REALTIME && mode != HRTIMER_MODE_ABS)
1167                clock_id = CLOCK_MONOTONIC;
1168
1169        base = hrtimer_clockid_to_base(clock_id);
1170        timer->base = &cpu_base->clock_base[base];
1171        timerqueue_init(&timer->node);
1172
1173#ifdef CONFIG_TIMER_STATS
1174        timer->start_site = NULL;
1175        timer->start_pid = -1;
1176        memset(timer->start_comm, 0, TASK_COMM_LEN);
1177#endif
1178}
1179
1180/**
1181 * hrtimer_init - initialize a timer to the given clock
1182 * @timer:      the timer to be initialized
1183 * @clock_id:   the clock to be used
1184 * @mode:       timer mode abs/rel
1185 */
1186void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1187                  enum hrtimer_mode mode)
1188{
1189        debug_init(timer, clock_id, mode);
1190        __hrtimer_init(timer, clock_id, mode);
1191}
1192EXPORT_SYMBOL_GPL(hrtimer_init);
1193
1194/**
1195 * hrtimer_get_res - get the timer resolution for a clock
1196 * @which_clock: which clock to query
1197 * @tp:          pointer to timespec variable to store the resolution
1198 *
1199 * Store the resolution of the clock selected by @which_clock in the
1200 * variable pointed to by @tp.
1201 */
1202int hrtimer_get_res(const clockid_t which_clock, struct timespec *tp)
1203{
1204        struct hrtimer_cpu_base *cpu_base;
1205        int base = hrtimer_clockid_to_base(which_clock);
1206
1207        cpu_base = &__raw_get_cpu_var(hrtimer_bases);
1208        *tp = ktime_to_timespec(cpu_base->clock_base[base].resolution);
1209
1210        return 0;
1211}
1212EXPORT_SYMBOL_GPL(hrtimer_get_res);
1213
1214static void __run_hrtimer(struct hrtimer *timer, ktime_t *now)
1215{
1216        struct hrtimer_clock_base *base = timer->base;
1217        struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1218        enum hrtimer_restart (*fn)(struct hrtimer *);
1219        int restart;
1220
1221        WARN_ON(!irqs_disabled());
1222
1223        debug_deactivate(timer);
1224        __remove_hrtimer(timer, base, HRTIMER_STATE_CALLBACK, 0);
1225        timer_stats_account_hrtimer(timer);
1226        fn = timer->function;
1227
1228        /*
1229         * Because we run timers from hardirq context, there is no chance
1230         * they get migrated to another cpu, therefore its safe to unlock
1231         * the timer base.
1232         */
1233        raw_spin_unlock(&cpu_base->lock);
1234        trace_hrtimer_expire_entry(timer, now);
1235        restart = fn(timer);
1236        trace_hrtimer_expire_exit(timer);
1237        raw_spin_lock(&cpu_base->lock);
1238
1239        /*
1240         * Note: We clear the CALLBACK bit after enqueue_hrtimer and
1241         * we do not reprogramm the event hardware. Happens either in
1242         * hrtimer_start_range_ns() or in hrtimer_interrupt()
1243         */
1244        if (restart != HRTIMER_NORESTART) {
1245                BUG_ON(timer->state != HRTIMER_STATE_CALLBACK);
1246                enqueue_hrtimer(timer, base);
1247        }
1248
1249        WARN_ON_ONCE(!(timer->state & HRTIMER_STATE_CALLBACK));
1250
1251        timer->state &= ~HRTIMER_STATE_CALLBACK;
1252}
1253
1254#ifdef CONFIG_HIGH_RES_TIMERS
1255
1256/*
1257 * High resolution timer interrupt
1258 * Called with interrupts disabled
1259 */
1260void hrtimer_interrupt(struct clock_event_device *dev)
1261{
1262        struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1263        ktime_t expires_next, now, entry_time, delta;
1264        int i, retries = 0;
1265
1266        BUG_ON(!cpu_base->hres_active);
1267        cpu_base->nr_events++;
1268        dev->next_event.tv64 = KTIME_MAX;
1269
1270        raw_spin_lock(&cpu_base->lock);
1271        entry_time = now = hrtimer_update_base(cpu_base);
1272retry:
1273        expires_next.tv64 = KTIME_MAX;
1274        /*
1275         * We set expires_next to KTIME_MAX here with cpu_base->lock
1276         * held to prevent that a timer is enqueued in our queue via
1277         * the migration code. This does not affect enqueueing of
1278         * timers which run their callback and need to be requeued on
1279         * this CPU.
1280         */
1281        cpu_base->expires_next.tv64 = KTIME_MAX;
1282
1283        for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1284                struct hrtimer_clock_base *base;
1285                struct timerqueue_node *node;
1286                ktime_t basenow;
1287
1288                if (!(cpu_base->active_bases & (1 << i)))
1289                        continue;
1290
1291                base = cpu_base->clock_base + i;
1292                basenow = ktime_add(now, base->offset);
1293
1294                while ((node = timerqueue_getnext(&base->active))) {
1295                        struct hrtimer *timer;
1296
1297                        timer = container_of(node, struct hrtimer, node);
1298
1299                        /*
1300                         * The immediate goal for using the softexpires is
1301                         * minimizing wakeups, not running timers at the
1302                         * earliest interrupt after their soft expiration.
1303                         * This allows us to avoid using a Priority Search
1304                         * Tree, which can answer a stabbing querry for
1305                         * overlapping intervals and instead use the simple
1306                         * BST we already have.
1307                         * We don't add extra wakeups by delaying timers that
1308                         * are right-of a not yet expired timer, because that
1309                         * timer will have to trigger a wakeup anyway.
1310                         */
1311
1312                        if (basenow.tv64 < hrtimer_get_softexpires_tv64(timer)) {
1313                                ktime_t expires;
1314
1315                                expires = ktime_sub(hrtimer_get_expires(timer),
1316                                                    base->offset);
1317                                if (expires.tv64 < 0)
1318                                        expires.tv64 = KTIME_MAX;
1319                                if (expires.tv64 < expires_next.tv64)
1320                                        expires_next = expires;
1321                                break;
1322                        }
1323
1324                        __run_hrtimer(timer, &basenow);
1325                }
1326        }
1327
1328        /*
1329         * Store the new expiry value so the migration code can verify
1330         * against it.
1331         */
1332        cpu_base->expires_next = expires_next;
1333        raw_spin_unlock(&cpu_base->lock);
1334
1335        /* Reprogramming necessary ? */
1336        if (expires_next.tv64 == KTIME_MAX ||
1337            !tick_program_event(expires_next, 0)) {
1338                cpu_base->hang_detected = 0;
1339                return;
1340        }
1341
1342        /*
1343         * The next timer was already expired due to:
1344         * - tracing
1345         * - long lasting callbacks
1346         * - being scheduled away when running in a VM
1347         *
1348         * We need to prevent that we loop forever in the hrtimer
1349         * interrupt routine. We give it 3 attempts to avoid
1350         * overreacting on some spurious event.
1351         *
1352         * Acquire base lock for updating the offsets and retrieving
1353         * the current time.
1354         */
1355        raw_spin_lock(&cpu_base->lock);
1356        now = hrtimer_update_base(cpu_base);
1357        cpu_base->nr_retries++;
1358        if (++retries < 3)
1359                goto retry;
1360        /*
1361         * Give the system a chance to do something else than looping
1362         * here. We stored the entry time, so we know exactly how long
1363         * we spent here. We schedule the next event this amount of
1364         * time away.
1365         */
1366        cpu_base->nr_hangs++;
1367        cpu_base->hang_detected = 1;
1368        raw_spin_unlock(&cpu_base->lock);
1369        delta = ktime_sub(now, entry_time);
1370        if (delta.tv64 > cpu_base->max_hang_time.tv64)
1371                cpu_base->max_hang_time = delta;
1372        /*
1373         * Limit it to a sensible value as we enforce a longer
1374         * delay. Give the CPU at least 100ms to catch up.
1375         */
1376        if (delta.tv64 > 100 * NSEC_PER_MSEC)
1377                expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1378        else
1379                expires_next = ktime_add(now, delta);
1380        tick_program_event(expires_next, 1);
1381        printk_once(KERN_WARNING "hrtimer: interrupt took %llu ns\n",
1382                    ktime_to_ns(delta));
1383}
1384
1385/*
1386 * local version of hrtimer_peek_ahead_timers() called with interrupts
1387 * disabled.
1388 */
1389static void __hrtimer_peek_ahead_timers(void)
1390{
1391        struct tick_device *td;
1392
1393        if (!hrtimer_hres_active())
1394                return;
1395
1396        td = &__get_cpu_var(tick_cpu_device);
1397        if (td && td->evtdev)
1398                hrtimer_interrupt(td->evtdev);
1399}
1400
1401/**
1402 * hrtimer_peek_ahead_timers -- run soft-expired timers now
1403 *
1404 * hrtimer_peek_ahead_timers will peek at the timer queue of
1405 * the current cpu and check if there are any timers for which
1406 * the soft expires time has passed. If any such timers exist,
1407 * they are run immediately and then removed from the timer queue.
1408 *
1409 */
1410void hrtimer_peek_ahead_timers(void)
1411{
1412        unsigned long flags;
1413
1414        local_irq_save(flags);
1415        __hrtimer_peek_ahead_timers();
1416        local_irq_restore(flags);
1417}
1418
1419static void run_hrtimer_softirq(struct softirq_action *h)
1420{
1421        struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1422
1423        if (cpu_base->clock_was_set) {
1424                cpu_base->clock_was_set = 0;
1425                clock_was_set();
1426        }
1427
1428        hrtimer_peek_ahead_timers();
1429}
1430
1431#else /* CONFIG_HIGH_RES_TIMERS */
1432
1433static inline void __hrtimer_peek_ahead_timers(void) { }
1434
1435#endif  /* !CONFIG_HIGH_RES_TIMERS */
1436
1437/*
1438 * Called from timer softirq every jiffy, expire hrtimers:
1439 *
1440 * For HRT its the fall back code to run the softirq in the timer
1441 * softirq context in case the hrtimer initialization failed or has
1442 * not been done yet.
1443 */
1444void hrtimer_run_pending(void)
1445{
1446        if (hrtimer_hres_active())
1447                return;
1448
1449        /*
1450         * This _is_ ugly: We have to check in the softirq context,
1451         * whether we can switch to highres and / or nohz mode. The
1452         * clocksource switch happens in the timer interrupt with
1453         * xtime_lock held. Notification from there only sets the
1454         * check bit in the tick_oneshot code, otherwise we might
1455         * deadlock vs. xtime_lock.
1456         */
1457        if (tick_check_oneshot_change(!hrtimer_is_hres_enabled()))
1458                hrtimer_switch_to_hres();
1459}
1460
1461/*
1462 * Called from hardirq context every jiffy
1463 */
1464void hrtimer_run_queues(void)
1465{
1466        struct timerqueue_node *node;
1467        struct hrtimer_cpu_base *cpu_base = &__get_cpu_var(hrtimer_bases);
1468        struct hrtimer_clock_base *base;
1469        int index, gettime = 1;
1470
1471        if (hrtimer_hres_active())
1472                return;
1473
1474        for (index = 0; index < HRTIMER_MAX_CLOCK_BASES; index++) {
1475                base = &cpu_base->clock_base[index];
1476                if (!timerqueue_getnext(&base->active))
1477                        continue;
1478
1479                if (gettime) {
1480                        hrtimer_get_softirq_time(cpu_base);
1481                        gettime = 0;
1482                }
1483
1484                raw_spin_lock(&cpu_base->lock);
1485
1486                while ((node = timerqueue_getnext(&base->active))) {
1487                        struct hrtimer *timer;
1488
1489                        timer = container_of(node, struct hrtimer, node);
1490                        if (base->softirq_time.tv64 <=
1491                                        hrtimer_get_expires_tv64(timer))
1492                                break;
1493
1494                        __run_hrtimer(timer, &base->softirq_time);
1495                }
1496                raw_spin_unlock(&cpu_base->lock);
1497        }
1498}
1499
1500/*
1501 * Sleep related functions:
1502 */
1503static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1504{
1505        struct hrtimer_sleeper *t =
1506                container_of(timer, struct hrtimer_sleeper, timer);
1507        struct task_struct *task = t->task;
1508
1509        t->task = NULL;
1510        if (task)
1511                wake_up_process(task);
1512
1513        return HRTIMER_NORESTART;
1514}
1515
1516void hrtimer_init_sleeper(struct hrtimer_sleeper *sl, struct task_struct *task)
1517{
1518        sl->timer.function = hrtimer_wakeup;
1519        sl->task = task;
1520}
1521EXPORT_SYMBOL_GPL(hrtimer_init_sleeper);
1522
1523static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
1524{
1525        hrtimer_init_sleeper(t, current);
1526
1527        do {
1528                set_current_state(TASK_INTERRUPTIBLE);
1529                hrtimer_start_expires(&t->timer, mode);
1530                if (!hrtimer_active(&t->timer))
1531                        t->task = NULL;
1532
1533                if (likely(t->task))
1534                        schedule();
1535
1536                hrtimer_cancel(&t->timer);
1537                mode = HRTIMER_MODE_ABS;
1538
1539        } while (t->task && !signal_pending(current));
1540
1541        __set_current_state(TASK_RUNNING);
1542
1543        return t->task == NULL;
1544}
1545
1546static int update_rmtp(struct hrtimer *timer, struct timespec __user *rmtp)
1547{
1548        struct timespec rmt;
1549        ktime_t rem;
1550
1551        rem = hrtimer_expires_remaining(timer);
1552        if (rem.tv64 <= 0)
1553                return 0;
1554        rmt = ktime_to_timespec(rem);
1555
1556        if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
1557                return -EFAULT;
1558
1559        return 1;
1560}
1561
1562long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
1563{
1564        struct hrtimer_sleeper t;
1565        struct timespec __user  *rmtp;
1566        int ret = 0;
1567
1568        hrtimer_init_on_stack(&t.timer, restart->nanosleep.clockid,
1569                                HRTIMER_MODE_ABS);
1570        hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
1571
1572        if (do_nanosleep(&t, HRTIMER_MODE_ABS))
1573                goto out;
1574
1575        rmtp = restart->nanosleep.rmtp;
1576        if (rmtp) {
1577                ret = update_rmtp(&t.timer, rmtp);
1578                if (ret <= 0)
1579                        goto out;
1580        }
1581
1582        /* The other values in restart are already filled in */
1583        ret = -ERESTART_RESTARTBLOCK;
1584out:
1585        destroy_hrtimer_on_stack(&t.timer);
1586        return ret;
1587}
1588
1589long hrtimer_nanosleep(struct timespec *rqtp, struct timespec __user *rmtp,
1590                       const enum hrtimer_mode mode, const clockid_t clockid)
1591{
1592        struct restart_block *restart;
1593        struct hrtimer_sleeper t;
1594        int ret = 0;
1595        unsigned long slack;
1596
1597        slack = current->timer_slack_ns;
1598        if (rt_task(current))
1599                slack = 0;
1600
1601        hrtimer_init_on_stack(&t.timer, clockid, mode);
1602        hrtimer_set_expires_range_ns(&t.timer, timespec_to_ktime(*rqtp), slack);
1603        if (do_nanosleep(&t, mode))
1604                goto out;
1605
1606        /* Absolute timers do not update the rmtp value and restart: */
1607        if (mode == HRTIMER_MODE_ABS) {
1608                ret = -ERESTARTNOHAND;
1609                goto out;
1610        }
1611
1612        if (rmtp) {
1613                ret = update_rmtp(&t.timer, rmtp);
1614                if (ret <= 0)
1615                        goto out;
1616        }
1617
1618        restart = &current_thread_info()->restart_block;
1619        restart->fn = hrtimer_nanosleep_restart;
1620        restart->nanosleep.clockid = t.timer.base->clockid;
1621        restart->nanosleep.rmtp = rmtp;
1622        restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
1623
1624        ret = -ERESTART_RESTARTBLOCK;
1625out:
1626        destroy_hrtimer_on_stack(&t.timer);
1627        return ret;
1628}
1629
1630SYSCALL_DEFINE2(nanosleep, struct timespec __user *, rqtp,
1631                struct timespec __user *, rmtp)
1632{
1633        struct timespec tu;
1634
1635        if (copy_from_user(&tu, rqtp, sizeof(tu)))
1636                return -EFAULT;
1637
1638        if (!timespec_valid(&tu))
1639                return -EINVAL;
1640
1641        return hrtimer_nanosleep(&tu, rmtp, HRTIMER_MODE_REL, CLOCK_MONOTONIC);
1642}
1643
1644/*
1645 * Functions related to boot-time initialization:
1646 */
1647static void __cpuinit init_hrtimers_cpu(int cpu)
1648{
1649        struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
1650        int i;
1651
1652        for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1653                cpu_base->clock_base[i].cpu_base = cpu_base;
1654                timerqueue_init_head(&cpu_base->clock_base[i].active);
1655        }
1656
1657        hrtimer_init_hres(cpu_base);
1658}
1659
1660#ifdef CONFIG_HOTPLUG_CPU
1661
1662static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
1663                                struct hrtimer_clock_base *new_base)
1664{
1665        struct hrtimer *timer;
1666        struct timerqueue_node *node;
1667
1668        while ((node = timerqueue_getnext(&old_base->active))) {
1669                timer = container_of(node, struct hrtimer, node);
1670                BUG_ON(hrtimer_callback_running(timer));
1671                debug_deactivate(timer);
1672
1673                /*
1674                 * Mark it as STATE_MIGRATE not INACTIVE otherwise the
1675                 * timer could be seen as !active and just vanish away
1676                 * under us on another CPU
1677                 */
1678                __remove_hrtimer(timer, old_base, HRTIMER_STATE_MIGRATE, 0);
1679                timer->base = new_base;
1680                /*
1681                 * Enqueue the timers on the new cpu. This does not
1682                 * reprogram the event device in case the timer
1683                 * expires before the earliest on this CPU, but we run
1684                 * hrtimer_interrupt after we migrated everything to
1685                 * sort out already expired timers and reprogram the
1686                 * event device.
1687                 */
1688                enqueue_hrtimer(timer, new_base);
1689
1690                /* Clear the migration state bit */
1691                timer->state &= ~HRTIMER_STATE_MIGRATE;
1692        }
1693}
1694
1695static void migrate_hrtimers(int scpu)
1696{
1697        struct hrtimer_cpu_base *old_base, *new_base;
1698        int i;
1699
1700        BUG_ON(cpu_online(scpu));
1701        tick_cancel_sched_timer(scpu);
1702
1703        local_irq_disable();
1704        old_base = &per_cpu(hrtimer_bases, scpu);
1705        new_base = &__get_cpu_var(hrtimer_bases);
1706        /*
1707         * The caller is globally serialized and nobody else
1708         * takes two locks at once, deadlock is not possible.
1709         */
1710        raw_spin_lock(&new_base->lock);
1711        raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1712
1713        for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
1714                migrate_hrtimer_list(&old_base->clock_base[i],
1715                                     &new_base->clock_base[i]);
1716        }
1717
1718        raw_spin_unlock(&old_base->lock);
1719        raw_spin_unlock(&new_base->lock);
1720
1721        /* Check, if we got expired work to do */
1722        __hrtimer_peek_ahead_timers();
1723        local_irq_enable();
1724}
1725
1726#endif /* CONFIG_HOTPLUG_CPU */
1727
1728static int __cpuinit hrtimer_cpu_notify(struct notifier_block *self,
1729                                        unsigned long action, void *hcpu)
1730{
1731        int scpu = (long)hcpu;
1732
1733        switch (action) {
1734
1735        case CPU_UP_PREPARE:
1736        case CPU_UP_PREPARE_FROZEN:
1737                init_hrtimers_cpu(scpu);
1738                break;
1739
1740#ifdef CONFIG_HOTPLUG_CPU
1741        case CPU_DYING:
1742        case CPU_DYING_FROZEN:
1743                clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DYING, &scpu);
1744                break;
1745        case CPU_DEAD:
1746        case CPU_DEAD_FROZEN:
1747        {
1748                clockevents_notify(CLOCK_EVT_NOTIFY_CPU_DEAD, &scpu);
1749                migrate_hrtimers(scpu);
1750                break;
1751        }
1752#endif
1753
1754        default:
1755                break;
1756        }
1757
1758        return NOTIFY_OK;
1759}
1760
1761static struct notifier_block __cpuinitdata hrtimers_nb = {
1762        .notifier_call = hrtimer_cpu_notify,
1763};
1764
1765void __init hrtimers_init(void)
1766{
1767        hrtimer_cpu_notify(&hrtimers_nb, (unsigned long)CPU_UP_PREPARE,
1768                          (void *)(long)smp_processor_id());
1769        register_cpu_notifier(&hrtimers_nb);
1770#ifdef CONFIG_HIGH_RES_TIMERS
1771        open_softirq(HRTIMER_SOFTIRQ, run_hrtimer_softirq);
1772#endif
1773}
1774
1775/**
1776 * schedule_hrtimeout_range_clock - sleep until timeout
1777 * @expires:    timeout value (ktime_t)
1778 * @delta:      slack in expires timeout (ktime_t)
1779 * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1780 * @clock:      timer clock, CLOCK_MONOTONIC or CLOCK_REALTIME
1781 */
1782int __sched
1783schedule_hrtimeout_range_clock(ktime_t *expires, unsigned long delta,
1784                               const enum hrtimer_mode mode, int clock)
1785{
1786        struct hrtimer_sleeper t;
1787
1788        /*
1789         * Optimize when a zero timeout value is given. It does not
1790         * matter whether this is an absolute or a relative time.
1791         */
1792        if (expires && !expires->tv64) {
1793                __set_current_state(TASK_RUNNING);
1794                return 0;
1795        }
1796
1797        /*
1798         * A NULL parameter means "infinite"
1799         */
1800        if (!expires) {
1801                schedule();
1802                __set_current_state(TASK_RUNNING);
1803                return -EINTR;
1804        }
1805
1806        hrtimer_init_on_stack(&t.timer, clock, mode);
1807        hrtimer_set_expires_range_ns(&t.timer, *expires, delta);
1808
1809        hrtimer_init_sleeper(&t, current);
1810
1811        hrtimer_start_expires(&t.timer, mode);
1812        if (!hrtimer_active(&t.timer))
1813                t.task = NULL;
1814
1815        if (likely(t.task))
1816                schedule();
1817
1818        hrtimer_cancel(&t.timer);
1819        destroy_hrtimer_on_stack(&t.timer);
1820
1821        __set_current_state(TASK_RUNNING);
1822
1823        return !t.task ? 0 : -EINTR;
1824}
1825
1826/**
1827 * schedule_hrtimeout_range - sleep until timeout
1828 * @expires:    timeout value (ktime_t)
1829 * @delta:      slack in expires timeout (ktime_t)
1830 * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1831 *
1832 * Make the current task sleep until the given expiry time has
1833 * elapsed. The routine will return immediately unless
1834 * the current task state has been set (see set_current_state()).
1835 *
1836 * The @delta argument gives the kernel the freedom to schedule the
1837 * actual wakeup to a time that is both power and performance friendly.
1838 * The kernel give the normal best effort behavior for "@expires+@delta",
1839 * but may decide to fire the timer earlier, but no earlier than @expires.
1840 *
1841 * You can set the task state as follows -
1842 *
1843 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1844 * pass before the routine returns.
1845 *
1846 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1847 * delivered to the current task.
1848 *
1849 * The current task state is guaranteed to be TASK_RUNNING when this
1850 * routine returns.
1851 *
1852 * Returns 0 when the timer has expired otherwise -EINTR
1853 */
1854int __sched schedule_hrtimeout_range(ktime_t *expires, unsigned long delta,
1855                                     const enum hrtimer_mode mode)
1856{
1857        return schedule_hrtimeout_range_clock(expires, delta, mode,
1858                                              CLOCK_MONOTONIC);
1859}
1860EXPORT_SYMBOL_GPL(schedule_hrtimeout_range);
1861
1862/**
1863 * schedule_hrtimeout - sleep until timeout
1864 * @expires:    timeout value (ktime_t)
1865 * @mode:       timer mode, HRTIMER_MODE_ABS or HRTIMER_MODE_REL
1866 *
1867 * Make the current task sleep until the given expiry time has
1868 * elapsed. The routine will return immediately unless
1869 * the current task state has been set (see set_current_state()).
1870 *
1871 * You can set the task state as follows -
1872 *
1873 * %TASK_UNINTERRUPTIBLE - at least @timeout time is guaranteed to
1874 * pass before the routine returns.
1875 *
1876 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1877 * delivered to the current task.
1878 *
1879 * The current task state is guaranteed to be TASK_RUNNING when this
1880 * routine returns.
1881 *
1882 * Returns 0 when the timer has expired otherwise -EINTR
1883 */
1884int __sched schedule_hrtimeout(ktime_t *expires,
1885                               const enum hrtimer_mode mode)
1886{
1887        return schedule_hrtimeout_range(expires, 0, mode);
1888}
1889EXPORT_SYMBOL_GPL(schedule_hrtimeout);
1890
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.