1 // SPDX-License-Identifier: GPL-2.0
3 * Kernel internal timers
5 * Copyright (C) 1991, 1992 Linus Torvalds
7 * 1997-01-28 Modified by Finn Arne Gangstad to make timers scale better.
9 * 1997-09-10 Updated NTP code according to technical memorandum Jan '96
10 * "A Kernel Model for Precision Timekeeping" by Dave Mills
11 * 1998-12-24 Fixed a xtime SMP race (we need the xtime_lock rw spinlock to
12 * serialize accesses to xtime/lost_ticks).
13 * Copyright (C) 1998 Andrea Arcangeli
14 * 1999-03-10 Improved NTP compatibility by Ulrich Windl
15 * 2002-05-31 Move sys_sysinfo here and make its locking sane, Robert Love
16 * 2000-10-05 Implemented scalable SMP per-CPU timer handling.
17 * Copyright (C) 2000, 2001, 2002 Ingo Molnar
18 * Designed by David S. Miller, Alexey Kuznetsov and Ingo Molnar
21 #include <linux/kernel_stat.h>
22 #include <linux/export.h>
23 #include <linux/interrupt.h>
24 #include <linux/percpu.h>
25 #include <linux/init.h>
27 #include <linux/swap.h>
28 #include <linux/pid_namespace.h>
29 #include <linux/notifier.h>
30 #include <linux/thread_info.h>
31 #include <linux/time.h>
32 #include <linux/jiffies.h>
33 #include <linux/posix-timers.h>
34 #include <linux/cpu.h>
35 #include <linux/syscalls.h>
36 #include <linux/delay.h>
37 #include <linux/tick.h>
38 #include <linux/kallsyms.h>
39 #include <linux/irq_work.h>
40 #include <linux/sched/signal.h>
41 #include <linux/sched/sysctl.h>
42 #include <linux/sched/nohz.h>
43 #include <linux/sched/debug.h>
44 #include <linux/slab.h>
45 #include <linux/compat.h>
46 #include <linux/random.h>
47 #include <linux/sysctl.h>
49 #include <linux/uaccess.h>
50 #include <asm/unistd.h>
51 #include <asm/div64.h>
52 #include <asm/timex.h>
55 #include "tick-internal.h"
57 #define CREATE_TRACE_POINTS
58 #include <trace/events/timer.h>
60 __visible u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
62 EXPORT_SYMBOL(jiffies_64);
65 * The timer wheel has LVL_DEPTH array levels. Each level provides an array of
66 * LVL_SIZE buckets. Each level is driven by its own clock and therefor each
67 * level has a different granularity.
69 * The level granularity is: LVL_CLK_DIV ^ lvl
70 * The level clock frequency is: HZ / (LVL_CLK_DIV ^ level)
72 * The array level of a newly armed timer depends on the relative expiry
73 * time. The farther the expiry time is away the higher the array level and
74 * therefor the granularity becomes.
76 * Contrary to the original timer wheel implementation, which aims for 'exact'
77 * expiry of the timers, this implementation removes the need for recascading
78 * the timers into the lower array levels. The previous 'classic' timer wheel
79 * implementation of the kernel already violated the 'exact' expiry by adding
80 * slack to the expiry time to provide batched expiration. The granularity
81 * levels provide implicit batching.
83 * This is an optimization of the original timer wheel implementation for the
84 * majority of the timer wheel use cases: timeouts. The vast majority of
85 * timeout timers (networking, disk I/O ...) are canceled before expiry. If
86 * the timeout expires it indicates that normal operation is disturbed, so it
87 * does not matter much whether the timeout comes with a slight delay.
89 * The only exception to this are networking timers with a small expiry
90 * time. They rely on the granularity. Those fit into the first wheel level,
91 * which has HZ granularity.
93 * We don't have cascading anymore. timers with a expiry time above the
94 * capacity of the last wheel level are force expired at the maximum timeout
95 * value of the last wheel level. From data sampling we know that the maximum
96 * value observed is 5 days (network connection tracking), so this should not
99 * The currently chosen array constants values are a good compromise between
100 * array size and granularity.
102 * This results in the following granularity and range levels:
105 * Level Offset Granularity Range
106 * 0 0 1 ms 0 ms - 63 ms
107 * 1 64 8 ms 64 ms - 511 ms
108 * 2 128 64 ms 512 ms - 4095 ms (512ms - ~4s)
109 * 3 192 512 ms 4096 ms - 32767 ms (~4s - ~32s)
110 * 4 256 4096 ms (~4s) 32768 ms - 262143 ms (~32s - ~4m)
111 * 5 320 32768 ms (~32s) 262144 ms - 2097151 ms (~4m - ~34m)
112 * 6 384 262144 ms (~4m) 2097152 ms - 16777215 ms (~34m - ~4h)
113 * 7 448 2097152 ms (~34m) 16777216 ms - 134217727 ms (~4h - ~1d)
114 * 8 512 16777216 ms (~4h) 134217728 ms - 1073741822 ms (~1d - ~12d)
117 * Level Offset Granularity Range
118 * 0 0 3 ms 0 ms - 210 ms
119 * 1 64 26 ms 213 ms - 1703 ms (213ms - ~1s)
120 * 2 128 213 ms 1706 ms - 13650 ms (~1s - ~13s)
121 * 3 192 1706 ms (~1s) 13653 ms - 109223 ms (~13s - ~1m)
122 * 4 256 13653 ms (~13s) 109226 ms - 873810 ms (~1m - ~14m)
123 * 5 320 109226 ms (~1m) 873813 ms - 6990503 ms (~14m - ~1h)
124 * 6 384 873813 ms (~14m) 6990506 ms - 55924050 ms (~1h - ~15h)
125 * 7 448 6990506 ms (~1h) 55924053 ms - 447392423 ms (~15h - ~5d)
126 * 8 512 55924053 ms (~15h) 447392426 ms - 3579139406 ms (~5d - ~41d)
129 * Level Offset Granularity Range
130 * 0 0 4 ms 0 ms - 255 ms
131 * 1 64 32 ms 256 ms - 2047 ms (256ms - ~2s)
132 * 2 128 256 ms 2048 ms - 16383 ms (~2s - ~16s)
133 * 3 192 2048 ms (~2s) 16384 ms - 131071 ms (~16s - ~2m)
134 * 4 256 16384 ms (~16s) 131072 ms - 1048575 ms (~2m - ~17m)
135 * 5 320 131072 ms (~2m) 1048576 ms - 8388607 ms (~17m - ~2h)
136 * 6 384 1048576 ms (~17m) 8388608 ms - 67108863 ms (~2h - ~18h)
137 * 7 448 8388608 ms (~2h) 67108864 ms - 536870911 ms (~18h - ~6d)
138 * 8 512 67108864 ms (~18h) 536870912 ms - 4294967288 ms (~6d - ~49d)
141 * Level Offset Granularity Range
142 * 0 0 10 ms 0 ms - 630 ms
143 * 1 64 80 ms 640 ms - 5110 ms (640ms - ~5s)
144 * 2 128 640 ms 5120 ms - 40950 ms (~5s - ~40s)
145 * 3 192 5120 ms (~5s) 40960 ms - 327670 ms (~40s - ~5m)
146 * 4 256 40960 ms (~40s) 327680 ms - 2621430 ms (~5m - ~43m)
147 * 5 320 327680 ms (~5m) 2621440 ms - 20971510 ms (~43m - ~5h)
148 * 6 384 2621440 ms (~43m) 20971520 ms - 167772150 ms (~5h - ~1d)
149 * 7 448 20971520 ms (~5h) 167772160 ms - 1342177270 ms (~1d - ~15d)
152 /* Clock divisor for the next level */
153 #define LVL_CLK_SHIFT 3
154 #define LVL_CLK_DIV (1UL << LVL_CLK_SHIFT)
155 #define LVL_CLK_MASK (LVL_CLK_DIV - 1)
156 #define LVL_SHIFT(n) ((n) * LVL_CLK_SHIFT)
157 #define LVL_GRAN(n) (1UL << LVL_SHIFT(n))
160 * The time start value for each level to select the bucket at enqueue
161 * time. We start from the last possible delta of the previous level
162 * so that we can later add an extra LVL_GRAN(n) to n (see calc_index()).
164 #define LVL_START(n) ((LVL_SIZE - 1) << (((n) - 1) * LVL_CLK_SHIFT))
166 /* Size of each clock level */
168 #define LVL_SIZE (1UL << LVL_BITS)
169 #define LVL_MASK (LVL_SIZE - 1)
170 #define LVL_OFFS(n) ((n) * LVL_SIZE)
179 /* The cutoff (max. capacity of the wheel) */
180 #define WHEEL_TIMEOUT_CUTOFF (LVL_START(LVL_DEPTH))
181 #define WHEEL_TIMEOUT_MAX (WHEEL_TIMEOUT_CUTOFF - LVL_GRAN(LVL_DEPTH - 1))
184 * The resulting wheel size. If NOHZ is configured we allocate two
185 * wheels so we have a separate storage for the deferrable timers.
187 #define WHEEL_SIZE (LVL_SIZE * LVL_DEPTH)
189 #ifdef CONFIG_NO_HZ_COMMON
200 * struct timer_base - Per CPU timer base (number of base depends on config)
201 * @lock: Lock protecting the timer_base
202 * @running_timer: When expiring timers, the lock is dropped. To make
203 * sure not to race agains deleting/modifying a
204 * currently running timer, the pointer is set to the
205 * timer, which expires at the moment. If no timer is
206 * running, the pointer is NULL.
207 * @expiry_lock: PREEMPT_RT only: Lock is taken in softirq around
208 * timer expiry callback execution and when trying to
209 * delete a running timer and it wasn't successful in
210 * the first glance. It prevents priority inversion
211 * when callback was preempted on a remote CPU and a
212 * caller tries to delete the running timer. It also
213 * prevents a life lock, when the task which tries to
214 * delete a timer preempted the softirq thread which
215 * is running the timer callback function.
216 * @timer_waiters: PREEMPT_RT only: Tells, if there is a waiter
217 * waiting for the end of the timer callback function
219 * @clk: clock of the timer base; is updated before enqueue
220 * of a timer; during expiry, it is 1 offset ahead of
221 * jiffies to avoid endless requeuing to current
223 * @next_expiry: expiry value of the first timer; it is updated when
224 * finding the next timer and during enqueue; the
225 * value is not valid, when next_expiry_recalc is set
226 * @cpu: Number of CPU the timer base belongs to
227 * @next_expiry_recalc: States, whether a recalculation of next_expiry is
228 * required. Value is set true, when a timer was
230 * @is_idle: Is set, when timer_base is idle. It is triggered by NOHZ
231 * code. This state is only used in standard
232 * base. Deferrable timers, which are enqueued remotely
233 * never wake up an idle CPU. So no matter of supporting it
235 * @timers_pending: Is set, when a timer is pending in the base. It is only
236 * reliable when next_expiry_recalc is not set.
237 * @pending_map: bitmap of the timer wheel; each bit reflects a
238 * bucket of the wheel. When a bit is set, at least a
239 * single timer is enqueued in the related bucket.
240 * @vectors: Array of lists; Each array member reflects a bucket
241 * of the timer wheel. The list contains all timers
242 * which are enqueued into a specific bucket.
246 struct timer_list *running_timer;
247 #ifdef CONFIG_PREEMPT_RT
248 spinlock_t expiry_lock;
249 atomic_t timer_waiters;
252 unsigned long next_expiry;
254 bool next_expiry_recalc;
257 DECLARE_BITMAP(pending_map, WHEEL_SIZE);
258 struct hlist_head vectors[WHEEL_SIZE];
259 } ____cacheline_aligned;
261 static DEFINE_PER_CPU(struct timer_base, timer_bases[NR_BASES]);
263 #ifdef CONFIG_NO_HZ_COMMON
265 static DEFINE_STATIC_KEY_FALSE(timers_nohz_active);
266 static DEFINE_MUTEX(timer_keys_mutex);
268 static void timer_update_keys(struct work_struct *work);
269 static DECLARE_WORK(timer_update_work, timer_update_keys);
272 static unsigned int sysctl_timer_migration = 1;
274 DEFINE_STATIC_KEY_FALSE(timers_migration_enabled);
276 static void timers_update_migration(void)
278 if (sysctl_timer_migration && tick_nohz_active)
279 static_branch_enable(&timers_migration_enabled);
281 static_branch_disable(&timers_migration_enabled);
285 static int timer_migration_handler(struct ctl_table *table, int write,
286 void *buffer, size_t *lenp, loff_t *ppos)
290 mutex_lock(&timer_keys_mutex);
291 ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
293 timers_update_migration();
294 mutex_unlock(&timer_keys_mutex);
298 static struct ctl_table timer_sysctl[] = {
300 .procname = "timer_migration",
301 .data = &sysctl_timer_migration,
302 .maxlen = sizeof(unsigned int),
304 .proc_handler = timer_migration_handler,
305 .extra1 = SYSCTL_ZERO,
306 .extra2 = SYSCTL_ONE,
311 static int __init timer_sysctl_init(void)
313 register_sysctl("kernel", timer_sysctl);
316 device_initcall(timer_sysctl_init);
317 #endif /* CONFIG_SYSCTL */
318 #else /* CONFIG_SMP */
319 static inline void timers_update_migration(void) { }
320 #endif /* !CONFIG_SMP */
322 static void timer_update_keys(struct work_struct *work)
324 mutex_lock(&timer_keys_mutex);
325 timers_update_migration();
326 static_branch_enable(&timers_nohz_active);
327 mutex_unlock(&timer_keys_mutex);
330 void timers_update_nohz(void)
332 schedule_work(&timer_update_work);
335 static inline bool is_timers_nohz_active(void)
337 return static_branch_unlikely(&timers_nohz_active);
340 static inline bool is_timers_nohz_active(void) { return false; }
341 #endif /* NO_HZ_COMMON */
343 static unsigned long round_jiffies_common(unsigned long j, int cpu,
347 unsigned long original = j;
350 * We don't want all cpus firing their timers at once hitting the
351 * same lock or cachelines, so we skew each extra cpu with an extra
352 * 3 jiffies. This 3 jiffies came originally from the mm/ code which
354 * The skew is done by adding 3*cpunr, then round, then subtract this
355 * extra offset again.
362 * If the target jiffie is just after a whole second (which can happen
363 * due to delays of the timer irq, long irq off times etc etc) then
364 * we should round down to the whole second, not up. Use 1/4th second
365 * as cutoff for this rounding as an extreme upper bound for this.
366 * But never round down if @force_up is set.
368 if (rem < HZ/4 && !force_up) /* round down */
373 /* now that we have rounded, subtract the extra skew again */
377 * Make sure j is still in the future. Otherwise return the
380 return time_is_after_jiffies(j) ? j : original;
384 * __round_jiffies - function to round jiffies to a full second
385 * @j: the time in (absolute) jiffies that should be rounded
386 * @cpu: the processor number on which the timeout will happen
388 * __round_jiffies() rounds an absolute time in the future (in jiffies)
389 * up or down to (approximately) full seconds. This is useful for timers
390 * for which the exact time they fire does not matter too much, as long as
391 * they fire approximately every X seconds.
393 * By rounding these timers to whole seconds, all such timers will fire
394 * at the same time, rather than at various times spread out. The goal
395 * of this is to have the CPU wake up less, which saves power.
397 * The exact rounding is skewed for each processor to avoid all
398 * processors firing at the exact same time, which could lead
399 * to lock contention or spurious cache line bouncing.
401 * The return value is the rounded version of the @j parameter.
403 unsigned long __round_jiffies(unsigned long j, int cpu)
405 return round_jiffies_common(j, cpu, false);
407 EXPORT_SYMBOL_GPL(__round_jiffies);
410 * __round_jiffies_relative - function to round jiffies to a full second
411 * @j: the time in (relative) jiffies that should be rounded
412 * @cpu: the processor number on which the timeout will happen
414 * __round_jiffies_relative() rounds a time delta in the future (in jiffies)
415 * up or down to (approximately) full seconds. This is useful for timers
416 * for which the exact time they fire does not matter too much, as long as
417 * they fire approximately every X seconds.
419 * By rounding these timers to whole seconds, all such timers will fire
420 * at the same time, rather than at various times spread out. The goal
421 * of this is to have the CPU wake up less, which saves power.
423 * The exact rounding is skewed for each processor to avoid all
424 * processors firing at the exact same time, which could lead
425 * to lock contention or spurious cache line bouncing.
427 * The return value is the rounded version of the @j parameter.
429 unsigned long __round_jiffies_relative(unsigned long j, int cpu)
431 unsigned long j0 = jiffies;
433 /* Use j0 because jiffies might change while we run */
434 return round_jiffies_common(j + j0, cpu, false) - j0;
436 EXPORT_SYMBOL_GPL(__round_jiffies_relative);
439 * round_jiffies - function to round jiffies to a full second
440 * @j: the time in (absolute) jiffies that should be rounded
442 * round_jiffies() rounds an absolute time in the future (in jiffies)
443 * up or down to (approximately) full seconds. This is useful for timers
444 * for which the exact time they fire does not matter too much, as long as
445 * they fire approximately every X seconds.
447 * By rounding these timers to whole seconds, all such timers will fire
448 * at the same time, rather than at various times spread out. The goal
449 * of this is to have the CPU wake up less, which saves power.
451 * The return value is the rounded version of the @j parameter.
453 unsigned long round_jiffies(unsigned long j)
455 return round_jiffies_common(j, raw_smp_processor_id(), false);
457 EXPORT_SYMBOL_GPL(round_jiffies);
460 * round_jiffies_relative - function to round jiffies to a full second
461 * @j: the time in (relative) jiffies that should be rounded
463 * round_jiffies_relative() rounds a time delta in the future (in jiffies)
464 * up or down to (approximately) full seconds. This is useful for timers
465 * for which the exact time they fire does not matter too much, as long as
466 * they fire approximately every X seconds.
468 * By rounding these timers to whole seconds, all such timers will fire
469 * at the same time, rather than at various times spread out. The goal
470 * of this is to have the CPU wake up less, which saves power.
472 * The return value is the rounded version of the @j parameter.
474 unsigned long round_jiffies_relative(unsigned long j)
476 return __round_jiffies_relative(j, raw_smp_processor_id());
478 EXPORT_SYMBOL_GPL(round_jiffies_relative);
481 * __round_jiffies_up - function to round jiffies up to a full second
482 * @j: the time in (absolute) jiffies that should be rounded
483 * @cpu: the processor number on which the timeout will happen
485 * This is the same as __round_jiffies() except that it will never
486 * round down. This is useful for timeouts for which the exact time
487 * of firing does not matter too much, as long as they don't fire too
490 unsigned long __round_jiffies_up(unsigned long j, int cpu)
492 return round_jiffies_common(j, cpu, true);
494 EXPORT_SYMBOL_GPL(__round_jiffies_up);
497 * __round_jiffies_up_relative - function to round jiffies up to a full second
498 * @j: the time in (relative) jiffies that should be rounded
499 * @cpu: the processor number on which the timeout will happen
501 * This is the same as __round_jiffies_relative() except that it will never
502 * round down. This is useful for timeouts for which the exact time
503 * of firing does not matter too much, as long as they don't fire too
506 unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
508 unsigned long j0 = jiffies;
510 /* Use j0 because jiffies might change while we run */
511 return round_jiffies_common(j + j0, cpu, true) - j0;
513 EXPORT_SYMBOL_GPL(__round_jiffies_up_relative);
516 * round_jiffies_up - function to round jiffies up to a full second
517 * @j: the time in (absolute) jiffies that should be rounded
519 * This is the same as round_jiffies() except that it will never
520 * round down. This is useful for timeouts for which the exact time
521 * of firing does not matter too much, as long as they don't fire too
524 unsigned long round_jiffies_up(unsigned long j)
526 return round_jiffies_common(j, raw_smp_processor_id(), true);
528 EXPORT_SYMBOL_GPL(round_jiffies_up);
531 * round_jiffies_up_relative - function to round jiffies up to a full second
532 * @j: the time in (relative) jiffies that should be rounded
534 * This is the same as round_jiffies_relative() except that it will never
535 * round down. This is useful for timeouts for which the exact time
536 * of firing does not matter too much, as long as they don't fire too
539 unsigned long round_jiffies_up_relative(unsigned long j)
541 return __round_jiffies_up_relative(j, raw_smp_processor_id());
543 EXPORT_SYMBOL_GPL(round_jiffies_up_relative);
546 static inline unsigned int timer_get_idx(struct timer_list *timer)
548 return (timer->flags & TIMER_ARRAYMASK) >> TIMER_ARRAYSHIFT;
551 static inline void timer_set_idx(struct timer_list *timer, unsigned int idx)
553 timer->flags = (timer->flags & ~TIMER_ARRAYMASK) |
554 idx << TIMER_ARRAYSHIFT;
558 * Helper function to calculate the array index for a given expiry
561 static inline unsigned calc_index(unsigned long expires, unsigned lvl,
562 unsigned long *bucket_expiry)
566 * The timer wheel has to guarantee that a timer does not fire
567 * early. Early expiry can happen due to:
568 * - Timer is armed at the edge of a tick
569 * - Truncation of the expiry time in the outer wheel levels
571 * Round up with level granularity to prevent this.
573 expires = (expires >> LVL_SHIFT(lvl)) + 1;
574 *bucket_expiry = expires << LVL_SHIFT(lvl);
575 return LVL_OFFS(lvl) + (expires & LVL_MASK);
578 static int calc_wheel_index(unsigned long expires, unsigned long clk,
579 unsigned long *bucket_expiry)
581 unsigned long delta = expires - clk;
584 if (delta < LVL_START(1)) {
585 idx = calc_index(expires, 0, bucket_expiry);
586 } else if (delta < LVL_START(2)) {
587 idx = calc_index(expires, 1, bucket_expiry);
588 } else if (delta < LVL_START(3)) {
589 idx = calc_index(expires, 2, bucket_expiry);
590 } else if (delta < LVL_START(4)) {
591 idx = calc_index(expires, 3, bucket_expiry);
592 } else if (delta < LVL_START(5)) {
593 idx = calc_index(expires, 4, bucket_expiry);
594 } else if (delta < LVL_START(6)) {
595 idx = calc_index(expires, 5, bucket_expiry);
596 } else if (delta < LVL_START(7)) {
597 idx = calc_index(expires, 6, bucket_expiry);
598 } else if (LVL_DEPTH > 8 && delta < LVL_START(8)) {
599 idx = calc_index(expires, 7, bucket_expiry);
600 } else if ((long) delta < 0) {
601 idx = clk & LVL_MASK;
602 *bucket_expiry = clk;
605 * Force expire obscene large timeouts to expire at the
606 * capacity limit of the wheel.
608 if (delta >= WHEEL_TIMEOUT_CUTOFF)
609 expires = clk + WHEEL_TIMEOUT_MAX;
611 idx = calc_index(expires, LVL_DEPTH - 1, bucket_expiry);
617 trigger_dyntick_cpu(struct timer_base *base, struct timer_list *timer)
620 * Deferrable timers do not prevent the CPU from entering dynticks and
621 * are not taken into account on the idle/nohz_full path. An IPI when a
622 * new deferrable timer is enqueued will wake up the remote CPU but
623 * nothing will be done with the deferrable timer base. Therefore skip
624 * the remote IPI for deferrable timers completely.
626 if (!is_timers_nohz_active() || timer->flags & TIMER_DEFERRABLE)
630 * We might have to IPI the remote CPU if the base is idle and the
631 * timer is not deferrable. If the other CPU is on the way to idle
632 * then it can't set base->is_idle as we hold the base lock:
635 wake_up_nohz_cpu(base->cpu);
639 * Enqueue the timer into the hash bucket, mark it pending in
640 * the bitmap, store the index in the timer flags then wake up
641 * the target CPU if needed.
643 static void enqueue_timer(struct timer_base *base, struct timer_list *timer,
644 unsigned int idx, unsigned long bucket_expiry)
647 hlist_add_head(&timer->entry, base->vectors + idx);
648 __set_bit(idx, base->pending_map);
649 timer_set_idx(timer, idx);
651 trace_timer_start(timer, bucket_expiry);
654 * Check whether this is the new first expiring timer. The
655 * effective expiry time of the timer is required here
656 * (bucket_expiry) instead of timer->expires.
658 if (time_before(bucket_expiry, base->next_expiry)) {
660 * Set the next expiry time and kick the CPU so it
661 * can reevaluate the wheel:
663 base->next_expiry = bucket_expiry;
664 base->timers_pending = true;
665 base->next_expiry_recalc = false;
666 trigger_dyntick_cpu(base, timer);
670 static void internal_add_timer(struct timer_base *base, struct timer_list *timer)
672 unsigned long bucket_expiry;
675 idx = calc_wheel_index(timer->expires, base->clk, &bucket_expiry);
676 enqueue_timer(base, timer, idx, bucket_expiry);
679 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
681 static const struct debug_obj_descr timer_debug_descr;
684 void (*function)(struct timer_list *t);
688 #define TIMER_HINT(fn, container, timr, hintfn) \
691 .offset = offsetof(container, hintfn) - \
692 offsetof(container, timr) \
695 static const struct timer_hint timer_hints[] = {
696 TIMER_HINT(delayed_work_timer_fn,
697 struct delayed_work, timer, work.func),
698 TIMER_HINT(kthread_delayed_work_timer_fn,
699 struct kthread_delayed_work, timer, work.func),
702 static void *timer_debug_hint(void *addr)
704 struct timer_list *timer = addr;
707 for (i = 0; i < ARRAY_SIZE(timer_hints); i++) {
708 if (timer_hints[i].function == timer->function) {
709 void (**fn)(void) = addr + timer_hints[i].offset;
715 return timer->function;
718 static bool timer_is_static_object(void *addr)
720 struct timer_list *timer = addr;
722 return (timer->entry.pprev == NULL &&
723 timer->entry.next == TIMER_ENTRY_STATIC);
727 * fixup_init is called when:
728 * - an active object is initialized
730 static bool timer_fixup_init(void *addr, enum debug_obj_state state)
732 struct timer_list *timer = addr;
735 case ODEBUG_STATE_ACTIVE:
736 del_timer_sync(timer);
737 debug_object_init(timer, &timer_debug_descr);
744 /* Stub timer callback for improperly used timers. */
745 static void stub_timer(struct timer_list *unused)
751 * fixup_activate is called when:
752 * - an active object is activated
753 * - an unknown non-static object is activated
755 static bool timer_fixup_activate(void *addr, enum debug_obj_state state)
757 struct timer_list *timer = addr;
760 case ODEBUG_STATE_NOTAVAILABLE:
761 timer_setup(timer, stub_timer, 0);
764 case ODEBUG_STATE_ACTIVE:
773 * fixup_free is called when:
774 * - an active object is freed
776 static bool timer_fixup_free(void *addr, enum debug_obj_state state)
778 struct timer_list *timer = addr;
781 case ODEBUG_STATE_ACTIVE:
782 del_timer_sync(timer);
783 debug_object_free(timer, &timer_debug_descr);
791 * fixup_assert_init is called when:
792 * - an untracked/uninit-ed object is found
794 static bool timer_fixup_assert_init(void *addr, enum debug_obj_state state)
796 struct timer_list *timer = addr;
799 case ODEBUG_STATE_NOTAVAILABLE:
800 timer_setup(timer, stub_timer, 0);
807 static const struct debug_obj_descr timer_debug_descr = {
808 .name = "timer_list",
809 .debug_hint = timer_debug_hint,
810 .is_static_object = timer_is_static_object,
811 .fixup_init = timer_fixup_init,
812 .fixup_activate = timer_fixup_activate,
813 .fixup_free = timer_fixup_free,
814 .fixup_assert_init = timer_fixup_assert_init,
817 static inline void debug_timer_init(struct timer_list *timer)
819 debug_object_init(timer, &timer_debug_descr);
822 static inline void debug_timer_activate(struct timer_list *timer)
824 debug_object_activate(timer, &timer_debug_descr);
827 static inline void debug_timer_deactivate(struct timer_list *timer)
829 debug_object_deactivate(timer, &timer_debug_descr);
832 static inline void debug_timer_assert_init(struct timer_list *timer)
834 debug_object_assert_init(timer, &timer_debug_descr);
837 static void do_init_timer(struct timer_list *timer,
838 void (*func)(struct timer_list *),
840 const char *name, struct lock_class_key *key);
842 void init_timer_on_stack_key(struct timer_list *timer,
843 void (*func)(struct timer_list *),
845 const char *name, struct lock_class_key *key)
847 debug_object_init_on_stack(timer, &timer_debug_descr);
848 do_init_timer(timer, func, flags, name, key);
850 EXPORT_SYMBOL_GPL(init_timer_on_stack_key);
852 void destroy_timer_on_stack(struct timer_list *timer)
854 debug_object_free(timer, &timer_debug_descr);
856 EXPORT_SYMBOL_GPL(destroy_timer_on_stack);
859 static inline void debug_timer_init(struct timer_list *timer) { }
860 static inline void debug_timer_activate(struct timer_list *timer) { }
861 static inline void debug_timer_deactivate(struct timer_list *timer) { }
862 static inline void debug_timer_assert_init(struct timer_list *timer) { }
865 static inline void debug_init(struct timer_list *timer)
867 debug_timer_init(timer);
868 trace_timer_init(timer);
871 static inline void debug_deactivate(struct timer_list *timer)
873 debug_timer_deactivate(timer);
874 trace_timer_cancel(timer);
877 static inline void debug_assert_init(struct timer_list *timer)
879 debug_timer_assert_init(timer);
882 static void do_init_timer(struct timer_list *timer,
883 void (*func)(struct timer_list *),
885 const char *name, struct lock_class_key *key)
887 timer->entry.pprev = NULL;
888 timer->function = func;
889 if (WARN_ON_ONCE(flags & ~TIMER_INIT_FLAGS))
890 flags &= TIMER_INIT_FLAGS;
891 timer->flags = flags | raw_smp_processor_id();
892 lockdep_init_map(&timer->lockdep_map, name, key, 0);
896 * init_timer_key - initialize a timer
897 * @timer: the timer to be initialized
898 * @func: timer callback function
899 * @flags: timer flags
900 * @name: name of the timer
901 * @key: lockdep class key of the fake lock used for tracking timer
902 * sync lock dependencies
904 * init_timer_key() must be done to a timer prior calling *any* of the
905 * other timer functions.
907 void init_timer_key(struct timer_list *timer,
908 void (*func)(struct timer_list *), unsigned int flags,
909 const char *name, struct lock_class_key *key)
912 do_init_timer(timer, func, flags, name, key);
914 EXPORT_SYMBOL(init_timer_key);
916 static inline void detach_timer(struct timer_list *timer, bool clear_pending)
918 struct hlist_node *entry = &timer->entry;
920 debug_deactivate(timer);
925 entry->next = LIST_POISON2;
928 static int detach_if_pending(struct timer_list *timer, struct timer_base *base,
931 unsigned idx = timer_get_idx(timer);
933 if (!timer_pending(timer))
936 if (hlist_is_singular_node(&timer->entry, base->vectors + idx)) {
937 __clear_bit(idx, base->pending_map);
938 base->next_expiry_recalc = true;
941 detach_timer(timer, clear_pending);
945 static inline struct timer_base *get_timer_cpu_base(u32 tflags, u32 cpu)
947 struct timer_base *base = per_cpu_ptr(&timer_bases[BASE_STD], cpu);
950 * If the timer is deferrable and NO_HZ_COMMON is set then we need
951 * to use the deferrable base.
953 if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
954 base = per_cpu_ptr(&timer_bases[BASE_DEF], cpu);
958 static inline struct timer_base *get_timer_this_cpu_base(u32 tflags)
960 struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
963 * If the timer is deferrable and NO_HZ_COMMON is set then we need
964 * to use the deferrable base.
966 if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
967 base = this_cpu_ptr(&timer_bases[BASE_DEF]);
971 static inline struct timer_base *get_timer_base(u32 tflags)
973 return get_timer_cpu_base(tflags, tflags & TIMER_CPUMASK);
976 static inline struct timer_base *
977 get_target_base(struct timer_base *base, unsigned tflags)
979 #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
980 if (static_branch_likely(&timers_migration_enabled) &&
981 !(tflags & TIMER_PINNED))
982 return get_timer_cpu_base(tflags, get_nohz_timer_target());
984 return get_timer_this_cpu_base(tflags);
987 static inline void __forward_timer_base(struct timer_base *base,
991 * Check whether we can forward the base. We can only do that when
992 * @basej is past base->clk otherwise we might rewind base->clk.
994 if (time_before_eq(basej, base->clk))
998 * If the next expiry value is > jiffies, then we fast forward to
999 * jiffies otherwise we forward to the next expiry value.
1001 if (time_after(base->next_expiry, basej)) {
1004 if (WARN_ON_ONCE(time_before(base->next_expiry, base->clk)))
1006 base->clk = base->next_expiry;
1011 static inline void forward_timer_base(struct timer_base *base)
1013 __forward_timer_base(base, READ_ONCE(jiffies));
1017 * We are using hashed locking: Holding per_cpu(timer_bases[x]).lock means
1018 * that all timers which are tied to this base are locked, and the base itself
1021 * So __run_timers/migrate_timers can safely modify all timers which could
1022 * be found in the base->vectors array.
1024 * When a timer is migrating then the TIMER_MIGRATING flag is set and we need
1025 * to wait until the migration is done.
1027 static struct timer_base *lock_timer_base(struct timer_list *timer,
1028 unsigned long *flags)
1029 __acquires(timer->base->lock)
1032 struct timer_base *base;
1036 * We need to use READ_ONCE() here, otherwise the compiler
1037 * might re-read @tf between the check for TIMER_MIGRATING
1040 tf = READ_ONCE(timer->flags);
1042 if (!(tf & TIMER_MIGRATING)) {
1043 base = get_timer_base(tf);
1044 raw_spin_lock_irqsave(&base->lock, *flags);
1045 if (timer->flags == tf)
1047 raw_spin_unlock_irqrestore(&base->lock, *flags);
1053 #define MOD_TIMER_PENDING_ONLY 0x01
1054 #define MOD_TIMER_REDUCE 0x02
1055 #define MOD_TIMER_NOTPENDING 0x04
1058 __mod_timer(struct timer_list *timer, unsigned long expires, unsigned int options)
1060 unsigned long clk = 0, flags, bucket_expiry;
1061 struct timer_base *base, *new_base;
1062 unsigned int idx = UINT_MAX;
1065 debug_assert_init(timer);
1068 * This is a common optimization triggered by the networking code - if
1069 * the timer is re-modified to have the same timeout or ends up in the
1070 * same array bucket then just return:
1072 if (!(options & MOD_TIMER_NOTPENDING) && timer_pending(timer)) {
1074 * The downside of this optimization is that it can result in
1075 * larger granularity than you would get from adding a new
1076 * timer with this expiry.
1078 long diff = timer->expires - expires;
1082 if (options & MOD_TIMER_REDUCE && diff <= 0)
1086 * We lock timer base and calculate the bucket index right
1087 * here. If the timer ends up in the same bucket, then we
1088 * just update the expiry time and avoid the whole
1089 * dequeue/enqueue dance.
1091 base = lock_timer_base(timer, &flags);
1093 * Has @timer been shutdown? This needs to be evaluated
1094 * while holding base lock to prevent a race against the
1097 if (!timer->function)
1100 forward_timer_base(base);
1102 if (timer_pending(timer) && (options & MOD_TIMER_REDUCE) &&
1103 time_before_eq(timer->expires, expires)) {
1109 idx = calc_wheel_index(expires, clk, &bucket_expiry);
1112 * Retrieve and compare the array index of the pending
1113 * timer. If it matches set the expiry to the new value so a
1114 * subsequent call will exit in the expires check above.
1116 if (idx == timer_get_idx(timer)) {
1117 if (!(options & MOD_TIMER_REDUCE))
1118 timer->expires = expires;
1119 else if (time_after(timer->expires, expires))
1120 timer->expires = expires;
1125 base = lock_timer_base(timer, &flags);
1127 * Has @timer been shutdown? This needs to be evaluated
1128 * while holding base lock to prevent a race against the
1131 if (!timer->function)
1134 forward_timer_base(base);
1137 ret = detach_if_pending(timer, base, false);
1138 if (!ret && (options & MOD_TIMER_PENDING_ONLY))
1141 new_base = get_target_base(base, timer->flags);
1143 if (base != new_base) {
1145 * We are trying to schedule the timer on the new base.
1146 * However we can't change timer's base while it is running,
1147 * otherwise timer_delete_sync() can't detect that the timer's
1148 * handler yet has not finished. This also guarantees that the
1149 * timer is serialized wrt itself.
1151 if (likely(base->running_timer != timer)) {
1152 /* See the comment in lock_timer_base() */
1153 timer->flags |= TIMER_MIGRATING;
1155 raw_spin_unlock(&base->lock);
1157 raw_spin_lock(&base->lock);
1158 WRITE_ONCE(timer->flags,
1159 (timer->flags & ~TIMER_BASEMASK) | base->cpu);
1160 forward_timer_base(base);
1164 debug_timer_activate(timer);
1166 timer->expires = expires;
1168 * If 'idx' was calculated above and the base time did not advance
1169 * between calculating 'idx' and possibly switching the base, only
1170 * enqueue_timer() is required. Otherwise we need to (re)calculate
1171 * the wheel index via internal_add_timer().
1173 if (idx != UINT_MAX && clk == base->clk)
1174 enqueue_timer(base, timer, idx, bucket_expiry);
1176 internal_add_timer(base, timer);
1179 raw_spin_unlock_irqrestore(&base->lock, flags);
1185 * mod_timer_pending - Modify a pending timer's timeout
1186 * @timer: The pending timer to be modified
1187 * @expires: New absolute timeout in jiffies
1189 * mod_timer_pending() is the same for pending timers as mod_timer(), but
1190 * will not activate inactive timers.
1192 * If @timer->function == NULL then the start operation is silently
1196 * * %0 - The timer was inactive and not modified or was in
1197 * shutdown state and the operation was discarded
1198 * * %1 - The timer was active and requeued to expire at @expires
1200 int mod_timer_pending(struct timer_list *timer, unsigned long expires)
1202 return __mod_timer(timer, expires, MOD_TIMER_PENDING_ONLY);
1204 EXPORT_SYMBOL(mod_timer_pending);
1207 * mod_timer - Modify a timer's timeout
1208 * @timer: The timer to be modified
1209 * @expires: New absolute timeout in jiffies
1211 * mod_timer(timer, expires) is equivalent to:
1213 * del_timer(timer); timer->expires = expires; add_timer(timer);
1215 * mod_timer() is more efficient than the above open coded sequence. In
1216 * case that the timer is inactive, the del_timer() part is a NOP. The
1217 * timer is in any case activated with the new expiry time @expires.
1219 * Note that if there are multiple unserialized concurrent users of the
1220 * same timer, then mod_timer() is the only safe way to modify the timeout,
1221 * since add_timer() cannot modify an already running timer.
1223 * If @timer->function == NULL then the start operation is silently
1224 * discarded. In this case the return value is 0 and meaningless.
1227 * * %0 - The timer was inactive and started or was in shutdown
1228 * state and the operation was discarded
1229 * * %1 - The timer was active and requeued to expire at @expires or
1230 * the timer was active and not modified because @expires did
1231 * not change the effective expiry time
1233 int mod_timer(struct timer_list *timer, unsigned long expires)
1235 return __mod_timer(timer, expires, 0);
1237 EXPORT_SYMBOL(mod_timer);
1240 * timer_reduce - Modify a timer's timeout if it would reduce the timeout
1241 * @timer: The timer to be modified
1242 * @expires: New absolute timeout in jiffies
1244 * timer_reduce() is very similar to mod_timer(), except that it will only
1245 * modify an enqueued timer if that would reduce the expiration time. If
1246 * @timer is not enqueued it starts the timer.
1248 * If @timer->function == NULL then the start operation is silently
1252 * * %0 - The timer was inactive and started or was in shutdown
1253 * state and the operation was discarded
1254 * * %1 - The timer was active and requeued to expire at @expires or
1255 * the timer was active and not modified because @expires
1256 * did not change the effective expiry time such that the
1257 * timer would expire earlier than already scheduled
1259 int timer_reduce(struct timer_list *timer, unsigned long expires)
1261 return __mod_timer(timer, expires, MOD_TIMER_REDUCE);
1263 EXPORT_SYMBOL(timer_reduce);
1266 * add_timer - Start a timer
1267 * @timer: The timer to be started
1269 * Start @timer to expire at @timer->expires in the future. @timer->expires
1270 * is the absolute expiry time measured in 'jiffies'. When the timer expires
1271 * timer->function(timer) will be invoked from soft interrupt context.
1273 * The @timer->expires and @timer->function fields must be set prior
1274 * to calling this function.
1276 * If @timer->function == NULL then the start operation is silently
1279 * If @timer->expires is already in the past @timer will be queued to
1280 * expire at the next timer tick.
1282 * This can only operate on an inactive timer. Attempts to invoke this on
1283 * an active timer are rejected with a warning.
1285 void add_timer(struct timer_list *timer)
1287 if (WARN_ON_ONCE(timer_pending(timer)))
1289 __mod_timer(timer, timer->expires, MOD_TIMER_NOTPENDING);
1291 EXPORT_SYMBOL(add_timer);
1294 * add_timer_on - Start a timer on a particular CPU
1295 * @timer: The timer to be started
1296 * @cpu: The CPU to start it on
1298 * Same as add_timer() except that it starts the timer on the given CPU.
1300 * See add_timer() for further details.
1302 void add_timer_on(struct timer_list *timer, int cpu)
1304 struct timer_base *new_base, *base;
1305 unsigned long flags;
1307 debug_assert_init(timer);
1309 if (WARN_ON_ONCE(timer_pending(timer)))
1312 new_base = get_timer_cpu_base(timer->flags, cpu);
1315 * If @timer was on a different CPU, it should be migrated with the
1316 * old base locked to prevent other operations proceeding with the
1317 * wrong base locked. See lock_timer_base().
1319 base = lock_timer_base(timer, &flags);
1321 * Has @timer been shutdown? This needs to be evaluated while
1322 * holding base lock to prevent a race against the shutdown code.
1324 if (!timer->function)
1327 if (base != new_base) {
1328 timer->flags |= TIMER_MIGRATING;
1330 raw_spin_unlock(&base->lock);
1332 raw_spin_lock(&base->lock);
1333 WRITE_ONCE(timer->flags,
1334 (timer->flags & ~TIMER_BASEMASK) | cpu);
1336 forward_timer_base(base);
1338 debug_timer_activate(timer);
1339 internal_add_timer(base, timer);
1341 raw_spin_unlock_irqrestore(&base->lock, flags);
1343 EXPORT_SYMBOL_GPL(add_timer_on);
1346 * __timer_delete - Internal function: Deactivate a timer
1347 * @timer: The timer to be deactivated
1348 * @shutdown: If true, this indicates that the timer is about to be
1349 * shutdown permanently.
1351 * If @shutdown is true then @timer->function is set to NULL under the
1352 * timer base lock which prevents further rearming of the time. In that
1353 * case any attempt to rearm @timer after this function returns will be
1357 * * %0 - The timer was not pending
1358 * * %1 - The timer was pending and deactivated
1360 static int __timer_delete(struct timer_list *timer, bool shutdown)
1362 struct timer_base *base;
1363 unsigned long flags;
1366 debug_assert_init(timer);
1369 * If @shutdown is set then the lock has to be taken whether the
1370 * timer is pending or not to protect against a concurrent rearm
1371 * which might hit between the lockless pending check and the lock
1372 * aquisition. By taking the lock it is ensured that such a newly
1373 * enqueued timer is dequeued and cannot end up with
1374 * timer->function == NULL in the expiry code.
1376 * If timer->function is currently executed, then this makes sure
1377 * that the callback cannot requeue the timer.
1379 if (timer_pending(timer) || shutdown) {
1380 base = lock_timer_base(timer, &flags);
1381 ret = detach_if_pending(timer, base, true);
1383 timer->function = NULL;
1384 raw_spin_unlock_irqrestore(&base->lock, flags);
1391 * timer_delete - Deactivate a timer
1392 * @timer: The timer to be deactivated
1394 * The function only deactivates a pending timer, but contrary to
1395 * timer_delete_sync() it does not take into account whether the timer's
1396 * callback function is concurrently executed on a different CPU or not.
1397 * It neither prevents rearming of the timer. If @timer can be rearmed
1398 * concurrently then the return value of this function is meaningless.
1401 * * %0 - The timer was not pending
1402 * * %1 - The timer was pending and deactivated
1404 int timer_delete(struct timer_list *timer)
1406 return __timer_delete(timer, false);
1408 EXPORT_SYMBOL(timer_delete);
1411 * timer_shutdown - Deactivate a timer and prevent rearming
1412 * @timer: The timer to be deactivated
1414 * The function does not wait for an eventually running timer callback on a
1415 * different CPU but it prevents rearming of the timer. Any attempt to arm
1416 * @timer after this function returns will be silently ignored.
1418 * This function is useful for teardown code and should only be used when
1419 * timer_shutdown_sync() cannot be invoked due to locking or context constraints.
1422 * * %0 - The timer was not pending
1423 * * %1 - The timer was pending
1425 int timer_shutdown(struct timer_list *timer)
1427 return __timer_delete(timer, true);
1429 EXPORT_SYMBOL_GPL(timer_shutdown);
1432 * __try_to_del_timer_sync - Internal function: Try to deactivate a timer
1433 * @timer: Timer to deactivate
1434 * @shutdown: If true, this indicates that the timer is about to be
1435 * shutdown permanently.
1437 * If @shutdown is true then @timer->function is set to NULL under the
1438 * timer base lock which prevents further rearming of the timer. Any
1439 * attempt to rearm @timer after this function returns will be silently
1442 * This function cannot guarantee that the timer cannot be rearmed
1443 * right after dropping the base lock if @shutdown is false. That
1444 * needs to be prevented by the calling code if necessary.
1447 * * %0 - The timer was not pending
1448 * * %1 - The timer was pending and deactivated
1449 * * %-1 - The timer callback function is running on a different CPU
1451 static int __try_to_del_timer_sync(struct timer_list *timer, bool shutdown)
1453 struct timer_base *base;
1454 unsigned long flags;
1457 debug_assert_init(timer);
1459 base = lock_timer_base(timer, &flags);
1461 if (base->running_timer != timer)
1462 ret = detach_if_pending(timer, base, true);
1464 timer->function = NULL;
1466 raw_spin_unlock_irqrestore(&base->lock, flags);
1472 * try_to_del_timer_sync - Try to deactivate a timer
1473 * @timer: Timer to deactivate
1475 * This function tries to deactivate a timer. On success the timer is not
1476 * queued and the timer callback function is not running on any CPU.
1478 * This function does not guarantee that the timer cannot be rearmed right
1479 * after dropping the base lock. That needs to be prevented by the calling
1480 * code if necessary.
1483 * * %0 - The timer was not pending
1484 * * %1 - The timer was pending and deactivated
1485 * * %-1 - The timer callback function is running on a different CPU
1487 int try_to_del_timer_sync(struct timer_list *timer)
1489 return __try_to_del_timer_sync(timer, false);
1491 EXPORT_SYMBOL(try_to_del_timer_sync);
1493 #ifdef CONFIG_PREEMPT_RT
1494 static __init void timer_base_init_expiry_lock(struct timer_base *base)
1496 spin_lock_init(&base->expiry_lock);
1499 static inline void timer_base_lock_expiry(struct timer_base *base)
1501 spin_lock(&base->expiry_lock);
1504 static inline void timer_base_unlock_expiry(struct timer_base *base)
1506 spin_unlock(&base->expiry_lock);
1510 * The counterpart to del_timer_wait_running().
1512 * If there is a waiter for base->expiry_lock, then it was waiting for the
1513 * timer callback to finish. Drop expiry_lock and reacquire it. That allows
1514 * the waiter to acquire the lock and make progress.
1516 static void timer_sync_wait_running(struct timer_base *base)
1518 if (atomic_read(&base->timer_waiters)) {
1519 raw_spin_unlock_irq(&base->lock);
1520 spin_unlock(&base->expiry_lock);
1521 spin_lock(&base->expiry_lock);
1522 raw_spin_lock_irq(&base->lock);
1527 * This function is called on PREEMPT_RT kernels when the fast path
1528 * deletion of a timer failed because the timer callback function was
1531 * This prevents priority inversion, if the softirq thread on a remote CPU
1532 * got preempted, and it prevents a life lock when the task which tries to
1533 * delete a timer preempted the softirq thread running the timer callback
1536 static void del_timer_wait_running(struct timer_list *timer)
1540 tf = READ_ONCE(timer->flags);
1541 if (!(tf & (TIMER_MIGRATING | TIMER_IRQSAFE))) {
1542 struct timer_base *base = get_timer_base(tf);
1545 * Mark the base as contended and grab the expiry lock,
1546 * which is held by the softirq across the timer
1547 * callback. Drop the lock immediately so the softirq can
1548 * expire the next timer. In theory the timer could already
1549 * be running again, but that's more than unlikely and just
1550 * causes another wait loop.
1552 atomic_inc(&base->timer_waiters);
1553 spin_lock_bh(&base->expiry_lock);
1554 atomic_dec(&base->timer_waiters);
1555 spin_unlock_bh(&base->expiry_lock);
1559 static inline void timer_base_init_expiry_lock(struct timer_base *base) { }
1560 static inline void timer_base_lock_expiry(struct timer_base *base) { }
1561 static inline void timer_base_unlock_expiry(struct timer_base *base) { }
1562 static inline void timer_sync_wait_running(struct timer_base *base) { }
1563 static inline void del_timer_wait_running(struct timer_list *timer) { }
1567 * __timer_delete_sync - Internal function: Deactivate a timer and wait
1568 * for the handler to finish.
1569 * @timer: The timer to be deactivated
1570 * @shutdown: If true, @timer->function will be set to NULL under the
1571 * timer base lock which prevents rearming of @timer
1573 * If @shutdown is not set the timer can be rearmed later. If the timer can
1574 * be rearmed concurrently, i.e. after dropping the base lock then the
1575 * return value is meaningless.
1577 * If @shutdown is set then @timer->function is set to NULL under timer
1578 * base lock which prevents rearming of the timer. Any attempt to rearm
1579 * a shutdown timer is silently ignored.
1581 * If the timer should be reused after shutdown it has to be initialized
1585 * * %0 - The timer was not pending
1586 * * %1 - The timer was pending and deactivated
1588 static int __timer_delete_sync(struct timer_list *timer, bool shutdown)
1592 #ifdef CONFIG_LOCKDEP
1593 unsigned long flags;
1596 * If lockdep gives a backtrace here, please reference
1597 * the synchronization rules above.
1599 local_irq_save(flags);
1600 lock_map_acquire(&timer->lockdep_map);
1601 lock_map_release(&timer->lockdep_map);
1602 local_irq_restore(flags);
1605 * don't use it in hardirq context, because it
1606 * could lead to deadlock.
1608 WARN_ON(in_hardirq() && !(timer->flags & TIMER_IRQSAFE));
1611 * Must be able to sleep on PREEMPT_RT because of the slowpath in
1612 * del_timer_wait_running().
1614 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(timer->flags & TIMER_IRQSAFE))
1615 lockdep_assert_preemption_enabled();
1618 ret = __try_to_del_timer_sync(timer, shutdown);
1620 if (unlikely(ret < 0)) {
1621 del_timer_wait_running(timer);
1630 * timer_delete_sync - Deactivate a timer and wait for the handler to finish.
1631 * @timer: The timer to be deactivated
1633 * Synchronization rules: Callers must prevent restarting of the timer,
1634 * otherwise this function is meaningless. It must not be called from
1635 * interrupt contexts unless the timer is an irqsafe one. The caller must
1636 * not hold locks which would prevent completion of the timer's callback
1637 * function. The timer's handler must not call add_timer_on(). Upon exit
1638 * the timer is not queued and the handler is not running on any CPU.
1640 * For !irqsafe timers, the caller must not hold locks that are held in
1641 * interrupt context. Even if the lock has nothing to do with the timer in
1642 * question. Here's why::
1648 * base->running_timer = mytimer;
1649 * spin_lock_irq(somelock);
1651 * spin_lock(somelock);
1652 * timer_delete_sync(mytimer);
1653 * while (base->running_timer == mytimer);
1655 * Now timer_delete_sync() will never return and never release somelock.
1656 * The interrupt on the other CPU is waiting to grab somelock but it has
1657 * interrupted the softirq that CPU0 is waiting to finish.
1659 * This function cannot guarantee that the timer is not rearmed again by
1660 * some concurrent or preempting code, right after it dropped the base
1661 * lock. If there is the possibility of a concurrent rearm then the return
1662 * value of the function is meaningless.
1664 * If such a guarantee is needed, e.g. for teardown situations then use
1665 * timer_shutdown_sync() instead.
1668 * * %0 - The timer was not pending
1669 * * %1 - The timer was pending and deactivated
1671 int timer_delete_sync(struct timer_list *timer)
1673 return __timer_delete_sync(timer, false);
1675 EXPORT_SYMBOL(timer_delete_sync);
1678 * timer_shutdown_sync - Shutdown a timer and prevent rearming
1679 * @timer: The timer to be shutdown
1681 * When the function returns it is guaranteed that:
1682 * - @timer is not queued
1683 * - The callback function of @timer is not running
1684 * - @timer cannot be enqueued again. Any attempt to rearm
1685 * @timer is silently ignored.
1687 * See timer_delete_sync() for synchronization rules.
1689 * This function is useful for final teardown of an infrastructure where
1690 * the timer is subject to a circular dependency problem.
1692 * A common pattern for this is a timer and a workqueue where the timer can
1693 * schedule work and work can arm the timer. On shutdown the workqueue must
1694 * be destroyed and the timer must be prevented from rearming. Unless the
1695 * code has conditionals like 'if (mything->in_shutdown)' to prevent that
1696 * there is no way to get this correct with timer_delete_sync().
1698 * timer_shutdown_sync() is solving the problem. The correct ordering of
1699 * calls in this case is:
1701 * timer_shutdown_sync(&mything->timer);
1702 * workqueue_destroy(&mything->workqueue);
1704 * After this 'mything' can be safely freed.
1706 * This obviously implies that the timer is not required to be functional
1707 * for the rest of the shutdown operation.
1710 * * %0 - The timer was not pending
1711 * * %1 - The timer was pending
1713 int timer_shutdown_sync(struct timer_list *timer)
1715 return __timer_delete_sync(timer, true);
1717 EXPORT_SYMBOL_GPL(timer_shutdown_sync);
1719 static void call_timer_fn(struct timer_list *timer,
1720 void (*fn)(struct timer_list *),
1721 unsigned long baseclk)
1723 int count = preempt_count();
1725 #ifdef CONFIG_LOCKDEP
1727 * It is permissible to free the timer from inside the
1728 * function that is called from it, this we need to take into
1729 * account for lockdep too. To avoid bogus "held lock freed"
1730 * warnings as well as problems when looking into
1731 * timer->lockdep_map, make a copy and use that here.
1733 struct lockdep_map lockdep_map;
1735 lockdep_copy_map(&lockdep_map, &timer->lockdep_map);
1738 * Couple the lock chain with the lock chain at
1739 * timer_delete_sync() by acquiring the lock_map around the fn()
1740 * call here and in timer_delete_sync().
1742 lock_map_acquire(&lockdep_map);
1744 trace_timer_expire_entry(timer, baseclk);
1746 trace_timer_expire_exit(timer);
1748 lock_map_release(&lockdep_map);
1750 if (count != preempt_count()) {
1751 WARN_ONCE(1, "timer: %pS preempt leak: %08x -> %08x\n",
1752 fn, count, preempt_count());
1754 * Restore the preempt count. That gives us a decent
1755 * chance to survive and extract information. If the
1756 * callback kept a lock held, bad luck, but not worse
1757 * than the BUG() we had.
1759 preempt_count_set(count);
1763 static void expire_timers(struct timer_base *base, struct hlist_head *head)
1766 * This value is required only for tracing. base->clk was
1767 * incremented directly before expire_timers was called. But expiry
1768 * is related to the old base->clk value.
1770 unsigned long baseclk = base->clk - 1;
1772 while (!hlist_empty(head)) {
1773 struct timer_list *timer;
1774 void (*fn)(struct timer_list *);
1776 timer = hlist_entry(head->first, struct timer_list, entry);
1778 base->running_timer = timer;
1779 detach_timer(timer, true);
1781 fn = timer->function;
1783 if (WARN_ON_ONCE(!fn)) {
1784 /* Should never happen. Emphasis on should! */
1785 base->running_timer = NULL;
1789 if (timer->flags & TIMER_IRQSAFE) {
1790 raw_spin_unlock(&base->lock);
1791 call_timer_fn(timer, fn, baseclk);
1792 raw_spin_lock(&base->lock);
1793 base->running_timer = NULL;
1795 raw_spin_unlock_irq(&base->lock);
1796 call_timer_fn(timer, fn, baseclk);
1797 raw_spin_lock_irq(&base->lock);
1798 base->running_timer = NULL;
1799 timer_sync_wait_running(base);
1804 static int collect_expired_timers(struct timer_base *base,
1805 struct hlist_head *heads)
1807 unsigned long clk = base->clk = base->next_expiry;
1808 struct hlist_head *vec;
1812 for (i = 0; i < LVL_DEPTH; i++) {
1813 idx = (clk & LVL_MASK) + i * LVL_SIZE;
1815 if (__test_and_clear_bit(idx, base->pending_map)) {
1816 vec = base->vectors + idx;
1817 hlist_move_list(vec, heads++);
1820 /* Is it time to look at the next level? */
1821 if (clk & LVL_CLK_MASK)
1823 /* Shift clock for the next level granularity */
1824 clk >>= LVL_CLK_SHIFT;
1830 * Find the next pending bucket of a level. Search from level start (@offset)
1831 * + @clk upwards and if nothing there, search from start of the level
1832 * (@offset) up to @offset + clk.
1834 static int next_pending_bucket(struct timer_base *base, unsigned offset,
1837 unsigned pos, start = offset + clk;
1838 unsigned end = offset + LVL_SIZE;
1840 pos = find_next_bit(base->pending_map, end, start);
1844 pos = find_next_bit(base->pending_map, start, offset);
1845 return pos < start ? pos + LVL_SIZE - start : -1;
1849 * Search the first expiring timer in the various clock levels. Caller must
1852 * Store next expiry time in base->next_expiry.
1854 static void next_expiry_recalc(struct timer_base *base)
1856 unsigned long clk, next, adj;
1857 unsigned lvl, offset = 0;
1859 next = base->clk + NEXT_TIMER_MAX_DELTA;
1861 for (lvl = 0; lvl < LVL_DEPTH; lvl++, offset += LVL_SIZE) {
1862 int pos = next_pending_bucket(base, offset, clk & LVL_MASK);
1863 unsigned long lvl_clk = clk & LVL_CLK_MASK;
1866 unsigned long tmp = clk + (unsigned long) pos;
1868 tmp <<= LVL_SHIFT(lvl);
1869 if (time_before(tmp, next))
1873 * If the next expiration happens before we reach
1874 * the next level, no need to check further.
1876 if (pos <= ((LVL_CLK_DIV - lvl_clk) & LVL_CLK_MASK))
1880 * Clock for the next level. If the current level clock lower
1881 * bits are zero, we look at the next level as is. If not we
1882 * need to advance it by one because that's going to be the
1883 * next expiring bucket in that level. base->clk is the next
1884 * expiring jiffie. So in case of:
1886 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1889 * we have to look at all levels @index 0. With
1891 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1894 * LVL0 has the next expiring bucket @index 2. The upper
1895 * levels have the next expiring bucket @index 1.
1897 * In case that the propagation wraps the next level the same
1900 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1903 * So after looking at LVL0 we get:
1905 * LVL5 LVL4 LVL3 LVL2 LVL1
1908 * So no propagation from LVL1 to LVL2 because that happened
1909 * with the add already, but then we need to propagate further
1910 * from LVL2 to LVL3.
1912 * So the simple check whether the lower bits of the current
1913 * level are 0 or not is sufficient for all cases.
1915 adj = lvl_clk ? 1 : 0;
1916 clk >>= LVL_CLK_SHIFT;
1920 base->next_expiry = next;
1921 base->next_expiry_recalc = false;
1922 base->timers_pending = !(next == base->clk + NEXT_TIMER_MAX_DELTA);
1925 #ifdef CONFIG_NO_HZ_COMMON
1927 * Check, if the next hrtimer event is before the next timer wheel
1930 static u64 cmp_next_hrtimer_event(u64 basem, u64 expires)
1932 u64 nextevt = hrtimer_get_next_event();
1935 * If high resolution timers are enabled
1936 * hrtimer_get_next_event() returns KTIME_MAX.
1938 if (expires <= nextevt)
1942 * If the next timer is already expired, return the tick base
1943 * time so the tick is fired immediately.
1945 if (nextevt <= basem)
1949 * Round up to the next jiffie. High resolution timers are
1950 * off, so the hrtimers are expired in the tick and we need to
1951 * make sure that this tick really expires the timer to avoid
1952 * a ping pong of the nohz stop code.
1954 * Use DIV_ROUND_UP_ULL to prevent gcc calling __divdi3
1956 return DIV_ROUND_UP_ULL(nextevt, TICK_NSEC) * TICK_NSEC;
1959 static inline u64 __get_next_timer_interrupt(unsigned long basej, u64 basem,
1962 struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1963 unsigned long nextevt = basej + NEXT_TIMER_MAX_DELTA;
1964 u64 expires = KTIME_MAX;
1967 * Pretend that there is no timer pending if the cpu is offline.
1968 * Possible pending timers will be migrated later to an active cpu.
1970 if (cpu_is_offline(smp_processor_id())) {
1976 raw_spin_lock(&base->lock);
1977 if (base->next_expiry_recalc)
1978 next_expiry_recalc(base);
1980 if (base->timers_pending) {
1981 nextevt = base->next_expiry;
1983 /* If we missed a tick already, force 0 delta */
1984 if (time_before(nextevt, basej))
1986 expires = basem + (u64)(nextevt - basej) * TICK_NSEC;
1989 * Move next_expiry for the empty base into the future to
1990 * prevent a unnecessary raise of the timer softirq when the
1991 * next_expiry value will be reached even if there is no timer
1994 base->next_expiry = nextevt;
1998 * We have a fresh next event. Check whether we can forward the
2001 __forward_timer_base(base, basej);
2004 * Set base->is_idle only when caller is timer_base_try_to_set_idle()
2008 * Base is idle if the next event is more than a tick away.
2010 * If the base is marked idle then any timer add operation must
2011 * forward the base clk itself to keep granularity small. This
2012 * idle logic is only maintained for the BASE_STD base,
2013 * deferrable timers may still see large granularity skew (by
2016 if (!base->is_idle) {
2017 if (time_after(nextevt, basej + 1)) {
2018 base->is_idle = true;
2019 trace_timer_base_idle(true, base->cpu);
2022 *idle = base->is_idle;
2025 raw_spin_unlock(&base->lock);
2027 return cmp_next_hrtimer_event(basem, expires);
2031 * get_next_timer_interrupt() - return the time (clock mono) of the next timer
2032 * @basej: base time jiffies
2033 * @basem: base time clock monotonic
2035 * Returns the tick aligned clock monotonic time of the next pending
2036 * timer or KTIME_MAX if no timer is pending.
2038 u64 get_next_timer_interrupt(unsigned long basej, u64 basem)
2040 return __get_next_timer_interrupt(basej, basem, NULL);
2044 * timer_base_try_to_set_idle() - Try to set the idle state of the timer bases
2045 * @basej: base time jiffies
2046 * @basem: base time clock monotonic
2047 * @idle: pointer to store the value of timer_base->is_idle on return;
2048 * *idle contains the information whether tick was already stopped
2050 * Returns the tick aligned clock monotonic time of the next pending timer or
2051 * KTIME_MAX if no timer is pending. When tick was already stopped KTIME_MAX is
2054 u64 timer_base_try_to_set_idle(unsigned long basej, u64 basem, bool *idle)
2059 return __get_next_timer_interrupt(basej, basem, idle);
2063 * timer_clear_idle - Clear the idle state of the timer base
2065 * Called with interrupts disabled
2067 void timer_clear_idle(void)
2069 struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
2072 * We do this unlocked. The worst outcome is a remote enqueue sending
2073 * a pointless IPI, but taking the lock would just make the window for
2074 * sending the IPI a few instructions smaller for the cost of taking
2075 * the lock in the exit from idle path.
2077 base->is_idle = false;
2078 trace_timer_base_idle(false, smp_processor_id());
2083 * __run_timers - run all expired timers (if any) on this CPU.
2084 * @base: the timer vector to be processed.
2086 static inline void __run_timers(struct timer_base *base)
2088 struct hlist_head heads[LVL_DEPTH];
2091 if (time_before(jiffies, base->next_expiry))
2094 timer_base_lock_expiry(base);
2095 raw_spin_lock_irq(&base->lock);
2097 while (time_after_eq(jiffies, base->clk) &&
2098 time_after_eq(jiffies, base->next_expiry)) {
2099 levels = collect_expired_timers(base, heads);
2101 * The two possible reasons for not finding any expired
2102 * timer at this clk are that all matching timers have been
2103 * dequeued or no timer has been queued since
2104 * base::next_expiry was set to base::clk +
2105 * NEXT_TIMER_MAX_DELTA.
2107 WARN_ON_ONCE(!levels && !base->next_expiry_recalc
2108 && base->timers_pending);
2110 * While executing timers, base->clk is set 1 offset ahead of
2111 * jiffies to avoid endless requeuing to current jiffies.
2114 next_expiry_recalc(base);
2117 expire_timers(base, heads + levels);
2119 raw_spin_unlock_irq(&base->lock);
2120 timer_base_unlock_expiry(base);
2124 * This function runs timers and the timer-tq in bottom half context.
2126 static __latent_entropy void run_timer_softirq(struct softirq_action *h)
2128 struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
2131 if (IS_ENABLED(CONFIG_NO_HZ_COMMON))
2132 __run_timers(this_cpu_ptr(&timer_bases[BASE_DEF]));
2136 * Called by the local, per-CPU timer interrupt on SMP.
2138 static void run_local_timers(void)
2140 struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
2142 hrtimer_run_queues();
2143 /* Raise the softirq only if required. */
2144 if (time_before(jiffies, base->next_expiry)) {
2145 if (!IS_ENABLED(CONFIG_NO_HZ_COMMON))
2147 /* CPU is awake, so check the deferrable base. */
2149 if (time_before(jiffies, base->next_expiry))
2152 raise_softirq(TIMER_SOFTIRQ);
2156 * Called from the timer interrupt handler to charge one tick to the current
2157 * process. user_tick is 1 if the tick is user time, 0 for system.
2159 void update_process_times(int user_tick)
2161 struct task_struct *p = current;
2163 /* Note: this timer irq context must be accounted for as well. */
2164 account_process_tick(p, user_tick);
2166 rcu_sched_clock_irq(user_tick);
2167 #ifdef CONFIG_IRQ_WORK
2172 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2173 run_posix_cpu_timers();
2177 * Since schedule_timeout()'s timer is defined on the stack, it must store
2178 * the target task on the stack as well.
2180 struct process_timer {
2181 struct timer_list timer;
2182 struct task_struct *task;
2185 static void process_timeout(struct timer_list *t)
2187 struct process_timer *timeout = from_timer(timeout, t, timer);
2189 wake_up_process(timeout->task);
2193 * schedule_timeout - sleep until timeout
2194 * @timeout: timeout value in jiffies
2196 * Make the current task sleep until @timeout jiffies have elapsed.
2197 * The function behavior depends on the current task state
2198 * (see also set_current_state() description):
2200 * %TASK_RUNNING - the scheduler is called, but the task does not sleep
2201 * at all. That happens because sched_submit_work() does nothing for
2202 * tasks in %TASK_RUNNING state.
2204 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
2205 * pass before the routine returns unless the current task is explicitly
2206 * woken up, (e.g. by wake_up_process()).
2208 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2209 * delivered to the current task or the current task is explicitly woken
2212 * The current task state is guaranteed to be %TASK_RUNNING when this
2215 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
2216 * the CPU away without a bound on the timeout. In this case the return
2217 * value will be %MAX_SCHEDULE_TIMEOUT.
2219 * Returns 0 when the timer has expired otherwise the remaining time in
2220 * jiffies will be returned. In all cases the return value is guaranteed
2221 * to be non-negative.
2223 signed long __sched schedule_timeout(signed long timeout)
2225 struct process_timer timer;
2226 unsigned long expire;
2230 case MAX_SCHEDULE_TIMEOUT:
2232 * These two special cases are useful to be comfortable
2233 * in the caller. Nothing more. We could take
2234 * MAX_SCHEDULE_TIMEOUT from one of the negative value
2235 * but I' d like to return a valid offset (>=0) to allow
2236 * the caller to do everything it want with the retval.
2242 * Another bit of PARANOID. Note that the retval will be
2243 * 0 since no piece of kernel is supposed to do a check
2244 * for a negative retval of schedule_timeout() (since it
2245 * should never happens anyway). You just have the printk()
2246 * that will tell you if something is gone wrong and where.
2249 printk(KERN_ERR "schedule_timeout: wrong timeout "
2250 "value %lx\n", timeout);
2252 __set_current_state(TASK_RUNNING);
2257 expire = timeout + jiffies;
2259 timer.task = current;
2260 timer_setup_on_stack(&timer.timer, process_timeout, 0);
2261 __mod_timer(&timer.timer, expire, MOD_TIMER_NOTPENDING);
2263 del_timer_sync(&timer.timer);
2265 /* Remove the timer from the object tracker */
2266 destroy_timer_on_stack(&timer.timer);
2268 timeout = expire - jiffies;
2271 return timeout < 0 ? 0 : timeout;
2273 EXPORT_SYMBOL(schedule_timeout);
2276 * We can use __set_current_state() here because schedule_timeout() calls
2277 * schedule() unconditionally.
2279 signed long __sched schedule_timeout_interruptible(signed long timeout)
2281 __set_current_state(TASK_INTERRUPTIBLE);
2282 return schedule_timeout(timeout);
2284 EXPORT_SYMBOL(schedule_timeout_interruptible);
2286 signed long __sched schedule_timeout_killable(signed long timeout)
2288 __set_current_state(TASK_KILLABLE);
2289 return schedule_timeout(timeout);
2291 EXPORT_SYMBOL(schedule_timeout_killable);
2293 signed long __sched schedule_timeout_uninterruptible(signed long timeout)
2295 __set_current_state(TASK_UNINTERRUPTIBLE);
2296 return schedule_timeout(timeout);
2298 EXPORT_SYMBOL(schedule_timeout_uninterruptible);
2301 * Like schedule_timeout_uninterruptible(), except this task will not contribute
2304 signed long __sched schedule_timeout_idle(signed long timeout)
2306 __set_current_state(TASK_IDLE);
2307 return schedule_timeout(timeout);
2309 EXPORT_SYMBOL(schedule_timeout_idle);
2311 #ifdef CONFIG_HOTPLUG_CPU
2312 static void migrate_timer_list(struct timer_base *new_base, struct hlist_head *head)
2314 struct timer_list *timer;
2315 int cpu = new_base->cpu;
2317 while (!hlist_empty(head)) {
2318 timer = hlist_entry(head->first, struct timer_list, entry);
2319 detach_timer(timer, false);
2320 timer->flags = (timer->flags & ~TIMER_BASEMASK) | cpu;
2321 internal_add_timer(new_base, timer);
2325 int timers_prepare_cpu(unsigned int cpu)
2327 struct timer_base *base;
2330 for (b = 0; b < NR_BASES; b++) {
2331 base = per_cpu_ptr(&timer_bases[b], cpu);
2332 base->clk = jiffies;
2333 base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
2334 base->next_expiry_recalc = false;
2335 base->timers_pending = false;
2336 base->is_idle = false;
2341 int timers_dead_cpu(unsigned int cpu)
2343 struct timer_base *old_base;
2344 struct timer_base *new_base;
2347 for (b = 0; b < NR_BASES; b++) {
2348 old_base = per_cpu_ptr(&timer_bases[b], cpu);
2349 new_base = get_cpu_ptr(&timer_bases[b]);
2351 * The caller is globally serialized and nobody else
2352 * takes two locks at once, deadlock is not possible.
2354 raw_spin_lock_irq(&new_base->lock);
2355 raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
2358 * The current CPUs base clock might be stale. Update it
2359 * before moving the timers over.
2361 forward_timer_base(new_base);
2363 WARN_ON_ONCE(old_base->running_timer);
2364 old_base->running_timer = NULL;
2366 for (i = 0; i < WHEEL_SIZE; i++)
2367 migrate_timer_list(new_base, old_base->vectors + i);
2369 raw_spin_unlock(&old_base->lock);
2370 raw_spin_unlock_irq(&new_base->lock);
2371 put_cpu_ptr(&timer_bases);
2376 #endif /* CONFIG_HOTPLUG_CPU */
2378 static void __init init_timer_cpu(int cpu)
2380 struct timer_base *base;
2383 for (i = 0; i < NR_BASES; i++) {
2384 base = per_cpu_ptr(&timer_bases[i], cpu);
2386 raw_spin_lock_init(&base->lock);
2387 base->clk = jiffies;
2388 base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
2389 timer_base_init_expiry_lock(base);
2393 static void __init init_timer_cpus(void)
2397 for_each_possible_cpu(cpu)
2398 init_timer_cpu(cpu);
2401 void __init init_timers(void)
2404 posix_cputimers_init_work();
2405 open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
2409 * msleep - sleep safely even with waitqueue interruptions
2410 * @msecs: Time in milliseconds to sleep for
2412 void msleep(unsigned int msecs)
2414 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
2417 timeout = schedule_timeout_uninterruptible(timeout);
2420 EXPORT_SYMBOL(msleep);
2423 * msleep_interruptible - sleep waiting for signals
2424 * @msecs: Time in milliseconds to sleep for
2426 unsigned long msleep_interruptible(unsigned int msecs)
2428 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
2430 while (timeout && !signal_pending(current))
2431 timeout = schedule_timeout_interruptible(timeout);
2432 return jiffies_to_msecs(timeout);
2435 EXPORT_SYMBOL(msleep_interruptible);
2438 * usleep_range_state - Sleep for an approximate time in a given state
2439 * @min: Minimum time in usecs to sleep
2440 * @max: Maximum time in usecs to sleep
2441 * @state: State of the current task that will be while sleeping
2443 * In non-atomic context where the exact wakeup time is flexible, use
2444 * usleep_range_state() instead of udelay(). The sleep improves responsiveness
2445 * by avoiding the CPU-hogging busy-wait of udelay(), and the range reduces
2446 * power usage by allowing hrtimers to take advantage of an already-
2447 * scheduled interrupt instead of scheduling a new one just for this sleep.
2449 void __sched usleep_range_state(unsigned long min, unsigned long max,
2452 ktime_t exp = ktime_add_us(ktime_get(), min);
2453 u64 delta = (u64)(max - min) * NSEC_PER_USEC;
2456 __set_current_state(state);
2457 /* Do not return before the requested sleep time has elapsed */
2458 if (!schedule_hrtimeout_range(&exp, delta, HRTIMER_MODE_ABS))
2462 EXPORT_SYMBOL(usleep_range_state);