xref: /linux-6.15/kernel/time/timer.c (revision e2a71bde)
135728b82SThomas Gleixner // SPDX-License-Identifier: GPL-2.0
25cee9645SThomas Gleixner /*
35cee9645SThomas Gleixner  *  Kernel internal timers
45cee9645SThomas Gleixner  *
55cee9645SThomas Gleixner  *  Copyright (C) 1991, 1992  Linus Torvalds
65cee9645SThomas Gleixner  *
75cee9645SThomas Gleixner  *  1997-01-28  Modified by Finn Arne Gangstad to make timers scale better.
85cee9645SThomas Gleixner  *
95cee9645SThomas Gleixner  *  1997-09-10  Updated NTP code according to technical memorandum Jan '96
105cee9645SThomas Gleixner  *              "A Kernel Model for Precision Timekeeping" by Dave Mills
115cee9645SThomas Gleixner  *  1998-12-24  Fixed a xtime SMP race (we need the xtime_lock rw spinlock to
125cee9645SThomas Gleixner  *              serialize accesses to xtime/lost_ticks).
135cee9645SThomas Gleixner  *                              Copyright (C) 1998  Andrea Arcangeli
145cee9645SThomas Gleixner  *  1999-03-10  Improved NTP compatibility by Ulrich Windl
155cee9645SThomas Gleixner  *  2002-05-31	Move sys_sysinfo here and make its locking sane, Robert Love
165cee9645SThomas Gleixner  *  2000-10-05  Implemented scalable SMP per-CPU timer handling.
175cee9645SThomas Gleixner  *                              Copyright (C) 2000, 2001, 2002  Ingo Molnar
185cee9645SThomas Gleixner  *              Designed by David S. Miller, Alexey Kuznetsov and Ingo Molnar
195cee9645SThomas Gleixner  */
205cee9645SThomas Gleixner 
215cee9645SThomas Gleixner #include <linux/kernel_stat.h>
225cee9645SThomas Gleixner #include <linux/export.h>
235cee9645SThomas Gleixner #include <linux/interrupt.h>
245cee9645SThomas Gleixner #include <linux/percpu.h>
255cee9645SThomas Gleixner #include <linux/init.h>
265cee9645SThomas Gleixner #include <linux/mm.h>
275cee9645SThomas Gleixner #include <linux/swap.h>
285cee9645SThomas Gleixner #include <linux/pid_namespace.h>
295cee9645SThomas Gleixner #include <linux/notifier.h>
305cee9645SThomas Gleixner #include <linux/thread_info.h>
315cee9645SThomas Gleixner #include <linux/time.h>
325cee9645SThomas Gleixner #include <linux/jiffies.h>
335cee9645SThomas Gleixner #include <linux/posix-timers.h>
345cee9645SThomas Gleixner #include <linux/cpu.h>
355cee9645SThomas Gleixner #include <linux/syscalls.h>
365cee9645SThomas Gleixner #include <linux/delay.h>
375cee9645SThomas Gleixner #include <linux/tick.h>
385cee9645SThomas Gleixner #include <linux/kallsyms.h>
395cee9645SThomas Gleixner #include <linux/irq_work.h>
40174cd4b1SIngo Molnar #include <linux/sched/signal.h>
415cee9645SThomas Gleixner #include <linux/sched/sysctl.h>
42370c9135SIngo Molnar #include <linux/sched/nohz.h>
43b17b0153SIngo Molnar #include <linux/sched/debug.h>
445cee9645SThomas Gleixner #include <linux/slab.h>
455cee9645SThomas Gleixner #include <linux/compat.h>
465cee9645SThomas Gleixner 
477c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
485cee9645SThomas Gleixner #include <asm/unistd.h>
495cee9645SThomas Gleixner #include <asm/div64.h>
505cee9645SThomas Gleixner #include <asm/timex.h>
515cee9645SThomas Gleixner #include <asm/io.h>
525cee9645SThomas Gleixner 
53c1ad348bSThomas Gleixner #include "tick-internal.h"
54c1ad348bSThomas Gleixner 
555cee9645SThomas Gleixner #define CREATE_TRACE_POINTS
565cee9645SThomas Gleixner #include <trace/events/timer.h>
575cee9645SThomas Gleixner 
585cee9645SThomas Gleixner __visible u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
595cee9645SThomas Gleixner 
605cee9645SThomas Gleixner EXPORT_SYMBOL(jiffies_64);
615cee9645SThomas Gleixner 
625cee9645SThomas Gleixner /*
63500462a9SThomas Gleixner  * The timer wheel has LVL_DEPTH array levels. Each level provides an array of
64500462a9SThomas Gleixner  * LVL_SIZE buckets. Each level is driven by its own clock and therefor each
65500462a9SThomas Gleixner  * level has a different granularity.
66500462a9SThomas Gleixner  *
67500462a9SThomas Gleixner  * The level granularity is:		LVL_CLK_DIV ^ lvl
68500462a9SThomas Gleixner  * The level clock frequency is:	HZ / (LVL_CLK_DIV ^ level)
69500462a9SThomas Gleixner  *
70500462a9SThomas Gleixner  * The array level of a newly armed timer depends on the relative expiry
71500462a9SThomas Gleixner  * time. The farther the expiry time is away the higher the array level and
72500462a9SThomas Gleixner  * therefor the granularity becomes.
73500462a9SThomas Gleixner  *
74500462a9SThomas Gleixner  * Contrary to the original timer wheel implementation, which aims for 'exact'
75500462a9SThomas Gleixner  * expiry of the timers, this implementation removes the need for recascading
76500462a9SThomas Gleixner  * the timers into the lower array levels. The previous 'classic' timer wheel
77500462a9SThomas Gleixner  * implementation of the kernel already violated the 'exact' expiry by adding
78500462a9SThomas Gleixner  * slack to the expiry time to provide batched expiration. The granularity
79500462a9SThomas Gleixner  * levels provide implicit batching.
80500462a9SThomas Gleixner  *
81500462a9SThomas Gleixner  * This is an optimization of the original timer wheel implementation for the
82500462a9SThomas Gleixner  * majority of the timer wheel use cases: timeouts. The vast majority of
83500462a9SThomas Gleixner  * timeout timers (networking, disk I/O ...) are canceled before expiry. If
84500462a9SThomas Gleixner  * the timeout expires it indicates that normal operation is disturbed, so it
85500462a9SThomas Gleixner  * does not matter much whether the timeout comes with a slight delay.
86500462a9SThomas Gleixner  *
87500462a9SThomas Gleixner  * The only exception to this are networking timers with a small expiry
88500462a9SThomas Gleixner  * time. They rely on the granularity. Those fit into the first wheel level,
89500462a9SThomas Gleixner  * which has HZ granularity.
90500462a9SThomas Gleixner  *
91500462a9SThomas Gleixner  * We don't have cascading anymore. timers with a expiry time above the
92500462a9SThomas Gleixner  * capacity of the last wheel level are force expired at the maximum timeout
93500462a9SThomas Gleixner  * value of the last wheel level. From data sampling we know that the maximum
94500462a9SThomas Gleixner  * value observed is 5 days (network connection tracking), so this should not
95500462a9SThomas Gleixner  * be an issue.
96500462a9SThomas Gleixner  *
97500462a9SThomas Gleixner  * The currently chosen array constants values are a good compromise between
98500462a9SThomas Gleixner  * array size and granularity.
99500462a9SThomas Gleixner  *
100500462a9SThomas Gleixner  * This results in the following granularity and range levels:
101500462a9SThomas Gleixner  *
102500462a9SThomas Gleixner  * HZ 1000 steps
103500462a9SThomas Gleixner  * Level Offset  Granularity            Range
104500462a9SThomas Gleixner  *  0      0         1 ms                0 ms -         63 ms
105500462a9SThomas Gleixner  *  1     64         8 ms               64 ms -        511 ms
106500462a9SThomas Gleixner  *  2    128        64 ms              512 ms -       4095 ms (512ms - ~4s)
107500462a9SThomas Gleixner  *  3    192       512 ms             4096 ms -      32767 ms (~4s - ~32s)
108500462a9SThomas Gleixner  *  4    256      4096 ms (~4s)      32768 ms -     262143 ms (~32s - ~4m)
109500462a9SThomas Gleixner  *  5    320     32768 ms (~32s)    262144 ms -    2097151 ms (~4m - ~34m)
110500462a9SThomas Gleixner  *  6    384    262144 ms (~4m)    2097152 ms -   16777215 ms (~34m - ~4h)
111500462a9SThomas Gleixner  *  7    448   2097152 ms (~34m)  16777216 ms -  134217727 ms (~4h - ~1d)
112500462a9SThomas Gleixner  *  8    512  16777216 ms (~4h)  134217728 ms - 1073741822 ms (~1d - ~12d)
113500462a9SThomas Gleixner  *
114500462a9SThomas Gleixner  * HZ  300
115500462a9SThomas Gleixner  * Level Offset  Granularity            Range
116500462a9SThomas Gleixner  *  0	   0         3 ms                0 ms -        210 ms
117500462a9SThomas Gleixner  *  1	  64        26 ms              213 ms -       1703 ms (213ms - ~1s)
118500462a9SThomas Gleixner  *  2	 128       213 ms             1706 ms -      13650 ms (~1s - ~13s)
119500462a9SThomas Gleixner  *  3	 192      1706 ms (~1s)      13653 ms -     109223 ms (~13s - ~1m)
120500462a9SThomas Gleixner  *  4	 256     13653 ms (~13s)    109226 ms -     873810 ms (~1m - ~14m)
121500462a9SThomas Gleixner  *  5	 320    109226 ms (~1m)     873813 ms -    6990503 ms (~14m - ~1h)
122500462a9SThomas Gleixner  *  6	 384    873813 ms (~14m)   6990506 ms -   55924050 ms (~1h - ~15h)
123500462a9SThomas Gleixner  *  7	 448   6990506 ms (~1h)   55924053 ms -  447392423 ms (~15h - ~5d)
124500462a9SThomas Gleixner  *  8    512  55924053 ms (~15h) 447392426 ms - 3579139406 ms (~5d - ~41d)
125500462a9SThomas Gleixner  *
126500462a9SThomas Gleixner  * HZ  250
127500462a9SThomas Gleixner  * Level Offset  Granularity            Range
128500462a9SThomas Gleixner  *  0	   0         4 ms                0 ms -        255 ms
129500462a9SThomas Gleixner  *  1	  64        32 ms              256 ms -       2047 ms (256ms - ~2s)
130500462a9SThomas Gleixner  *  2	 128       256 ms             2048 ms -      16383 ms (~2s - ~16s)
131500462a9SThomas Gleixner  *  3	 192      2048 ms (~2s)      16384 ms -     131071 ms (~16s - ~2m)
132500462a9SThomas Gleixner  *  4	 256     16384 ms (~16s)    131072 ms -    1048575 ms (~2m - ~17m)
133500462a9SThomas Gleixner  *  5	 320    131072 ms (~2m)    1048576 ms -    8388607 ms (~17m - ~2h)
134500462a9SThomas Gleixner  *  6	 384   1048576 ms (~17m)   8388608 ms -   67108863 ms (~2h - ~18h)
135500462a9SThomas Gleixner  *  7	 448   8388608 ms (~2h)   67108864 ms -  536870911 ms (~18h - ~6d)
136500462a9SThomas Gleixner  *  8    512  67108864 ms (~18h) 536870912 ms - 4294967288 ms (~6d - ~49d)
137500462a9SThomas Gleixner  *
138500462a9SThomas Gleixner  * HZ  100
139500462a9SThomas Gleixner  * Level Offset  Granularity            Range
140500462a9SThomas Gleixner  *  0	   0         10 ms               0 ms -        630 ms
141500462a9SThomas Gleixner  *  1	  64         80 ms             640 ms -       5110 ms (640ms - ~5s)
142500462a9SThomas Gleixner  *  2	 128        640 ms            5120 ms -      40950 ms (~5s - ~40s)
143500462a9SThomas Gleixner  *  3	 192       5120 ms (~5s)     40960 ms -     327670 ms (~40s - ~5m)
144500462a9SThomas Gleixner  *  4	 256      40960 ms (~40s)   327680 ms -    2621430 ms (~5m - ~43m)
145500462a9SThomas Gleixner  *  5	 320     327680 ms (~5m)   2621440 ms -   20971510 ms (~43m - ~5h)
146500462a9SThomas Gleixner  *  6	 384    2621440 ms (~43m) 20971520 ms -  167772150 ms (~5h - ~1d)
147500462a9SThomas Gleixner  *  7	 448   20971520 ms (~5h) 167772160 ms - 1342177270 ms (~1d - ~15d)
1485cee9645SThomas Gleixner  */
1495cee9645SThomas Gleixner 
150500462a9SThomas Gleixner /* Clock divisor for the next level */
151500462a9SThomas Gleixner #define LVL_CLK_SHIFT	3
152500462a9SThomas Gleixner #define LVL_CLK_DIV	(1UL << LVL_CLK_SHIFT)
153500462a9SThomas Gleixner #define LVL_CLK_MASK	(LVL_CLK_DIV - 1)
154500462a9SThomas Gleixner #define LVL_SHIFT(n)	((n) * LVL_CLK_SHIFT)
155500462a9SThomas Gleixner #define LVL_GRAN(n)	(1UL << LVL_SHIFT(n))
1565cee9645SThomas Gleixner 
157500462a9SThomas Gleixner /*
158500462a9SThomas Gleixner  * The time start value for each level to select the bucket at enqueue
159500462a9SThomas Gleixner  * time.
160500462a9SThomas Gleixner  */
161500462a9SThomas Gleixner #define LVL_START(n)	((LVL_SIZE - 1) << (((n) - 1) * LVL_CLK_SHIFT))
1625cee9645SThomas Gleixner 
163500462a9SThomas Gleixner /* Size of each clock level */
164500462a9SThomas Gleixner #define LVL_BITS	6
165500462a9SThomas Gleixner #define LVL_SIZE	(1UL << LVL_BITS)
166500462a9SThomas Gleixner #define LVL_MASK	(LVL_SIZE - 1)
167500462a9SThomas Gleixner #define LVL_OFFS(n)	((n) * LVL_SIZE)
168500462a9SThomas Gleixner 
169500462a9SThomas Gleixner /* Level depth */
170500462a9SThomas Gleixner #if HZ > 100
171500462a9SThomas Gleixner # define LVL_DEPTH	9
172500462a9SThomas Gleixner # else
173500462a9SThomas Gleixner # define LVL_DEPTH	8
174500462a9SThomas Gleixner #endif
175500462a9SThomas Gleixner 
176500462a9SThomas Gleixner /* The cutoff (max. capacity of the wheel) */
177500462a9SThomas Gleixner #define WHEEL_TIMEOUT_CUTOFF	(LVL_START(LVL_DEPTH))
178500462a9SThomas Gleixner #define WHEEL_TIMEOUT_MAX	(WHEEL_TIMEOUT_CUTOFF - LVL_GRAN(LVL_DEPTH - 1))
179500462a9SThomas Gleixner 
180500462a9SThomas Gleixner /*
181500462a9SThomas Gleixner  * The resulting wheel size. If NOHZ is configured we allocate two
182500462a9SThomas Gleixner  * wheels so we have a separate storage for the deferrable timers.
183500462a9SThomas Gleixner  */
184500462a9SThomas Gleixner #define WHEEL_SIZE	(LVL_SIZE * LVL_DEPTH)
185500462a9SThomas Gleixner 
186500462a9SThomas Gleixner #ifdef CONFIG_NO_HZ_COMMON
187500462a9SThomas Gleixner # define NR_BASES	2
188500462a9SThomas Gleixner # define BASE_STD	0
189500462a9SThomas Gleixner # define BASE_DEF	1
190500462a9SThomas Gleixner #else
191500462a9SThomas Gleixner # define NR_BASES	1
192500462a9SThomas Gleixner # define BASE_STD	0
193500462a9SThomas Gleixner # define BASE_DEF	0
194500462a9SThomas Gleixner #endif
1955cee9645SThomas Gleixner 
196494af3edSThomas Gleixner struct timer_base {
1972287d866SSebastian Andrzej Siewior 	raw_spinlock_t		lock;
1985cee9645SThomas Gleixner 	struct timer_list	*running_timer;
199030dcdd1SAnna-Maria Gleixner #ifdef CONFIG_PREEMPT_RT
200030dcdd1SAnna-Maria Gleixner 	spinlock_t		expiry_lock;
201030dcdd1SAnna-Maria Gleixner 	atomic_t		timer_waiters;
202030dcdd1SAnna-Maria Gleixner #endif
203494af3edSThomas Gleixner 	unsigned long		clk;
204a683f390SThomas Gleixner 	unsigned long		next_expiry;
205500462a9SThomas Gleixner 	unsigned int		cpu;
206a683f390SThomas Gleixner 	bool			is_idle;
2072fe59f50SNicholas Piggin 	bool			must_forward_clk;
208500462a9SThomas Gleixner 	DECLARE_BITMAP(pending_map, WHEEL_SIZE);
209500462a9SThomas Gleixner 	struct hlist_head	vectors[WHEEL_SIZE];
2105cee9645SThomas Gleixner } ____cacheline_aligned;
2115cee9645SThomas Gleixner 
212500462a9SThomas Gleixner static DEFINE_PER_CPU(struct timer_base, timer_bases[NR_BASES]);
2135cee9645SThomas Gleixner 
214ae67badaSThomas Gleixner #ifdef CONFIG_NO_HZ_COMMON
215ae67badaSThomas Gleixner 
21614c80341SAnna-Maria Gleixner static DEFINE_STATIC_KEY_FALSE(timers_nohz_active);
217ae67badaSThomas Gleixner static DEFINE_MUTEX(timer_keys_mutex);
218ae67badaSThomas Gleixner 
219ae67badaSThomas Gleixner static void timer_update_keys(struct work_struct *work);
220ae67badaSThomas Gleixner static DECLARE_WORK(timer_update_work, timer_update_keys);
221ae67badaSThomas Gleixner 
222ae67badaSThomas Gleixner #ifdef CONFIG_SMP
223bc7a34b8SThomas Gleixner unsigned int sysctl_timer_migration = 1;
224bc7a34b8SThomas Gleixner 
225ae67badaSThomas Gleixner DEFINE_STATIC_KEY_FALSE(timers_migration_enabled);
226ae67badaSThomas Gleixner 
227ae67badaSThomas Gleixner static void timers_update_migration(void)
228bc7a34b8SThomas Gleixner {
229ae67badaSThomas Gleixner 	if (sysctl_timer_migration && tick_nohz_active)
230ae67badaSThomas Gleixner 		static_branch_enable(&timers_migration_enabled);
231ae67badaSThomas Gleixner 	else
232ae67badaSThomas Gleixner 		static_branch_disable(&timers_migration_enabled);
233bc7a34b8SThomas Gleixner }
234ae67badaSThomas Gleixner #else
235ae67badaSThomas Gleixner static inline void timers_update_migration(void) { }
236ae67badaSThomas Gleixner #endif /* !CONFIG_SMP */
237ae67badaSThomas Gleixner 
238ae67badaSThomas Gleixner static void timer_update_keys(struct work_struct *work)
239ae67badaSThomas Gleixner {
240ae67badaSThomas Gleixner 	mutex_lock(&timer_keys_mutex);
241ae67badaSThomas Gleixner 	timers_update_migration();
242ae67badaSThomas Gleixner 	static_branch_enable(&timers_nohz_active);
243ae67badaSThomas Gleixner 	mutex_unlock(&timer_keys_mutex);
244ae67badaSThomas Gleixner }
245ae67badaSThomas Gleixner 
246ae67badaSThomas Gleixner void timers_update_nohz(void)
247ae67badaSThomas Gleixner {
248ae67badaSThomas Gleixner 	schedule_work(&timer_update_work);
249bc7a34b8SThomas Gleixner }
250bc7a34b8SThomas Gleixner 
251bc7a34b8SThomas Gleixner int timer_migration_handler(struct ctl_table *table, int write,
25232927393SChristoph Hellwig 			    void *buffer, size_t *lenp, loff_t *ppos)
253bc7a34b8SThomas Gleixner {
254bc7a34b8SThomas Gleixner 	int ret;
255bc7a34b8SThomas Gleixner 
256ae67badaSThomas Gleixner 	mutex_lock(&timer_keys_mutex);
257b94bf594SMyungho Jung 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
258bc7a34b8SThomas Gleixner 	if (!ret && write)
259ae67badaSThomas Gleixner 		timers_update_migration();
260ae67badaSThomas Gleixner 	mutex_unlock(&timer_keys_mutex);
261bc7a34b8SThomas Gleixner 	return ret;
262bc7a34b8SThomas Gleixner }
26314c80341SAnna-Maria Gleixner 
26414c80341SAnna-Maria Gleixner static inline bool is_timers_nohz_active(void)
26514c80341SAnna-Maria Gleixner {
26614c80341SAnna-Maria Gleixner 	return static_branch_unlikely(&timers_nohz_active);
26714c80341SAnna-Maria Gleixner }
26814c80341SAnna-Maria Gleixner #else
26914c80341SAnna-Maria Gleixner static inline bool is_timers_nohz_active(void) { return false; }
270ae67badaSThomas Gleixner #endif /* NO_HZ_COMMON */
271bc7a34b8SThomas Gleixner 
2725cee9645SThomas Gleixner static unsigned long round_jiffies_common(unsigned long j, int cpu,
2735cee9645SThomas Gleixner 		bool force_up)
2745cee9645SThomas Gleixner {
2755cee9645SThomas Gleixner 	int rem;
2765cee9645SThomas Gleixner 	unsigned long original = j;
2775cee9645SThomas Gleixner 
2785cee9645SThomas Gleixner 	/*
2795cee9645SThomas Gleixner 	 * We don't want all cpus firing their timers at once hitting the
2805cee9645SThomas Gleixner 	 * same lock or cachelines, so we skew each extra cpu with an extra
2815cee9645SThomas Gleixner 	 * 3 jiffies. This 3 jiffies came originally from the mm/ code which
2825cee9645SThomas Gleixner 	 * already did this.
2835cee9645SThomas Gleixner 	 * The skew is done by adding 3*cpunr, then round, then subtract this
2845cee9645SThomas Gleixner 	 * extra offset again.
2855cee9645SThomas Gleixner 	 */
2865cee9645SThomas Gleixner 	j += cpu * 3;
2875cee9645SThomas Gleixner 
2885cee9645SThomas Gleixner 	rem = j % HZ;
2895cee9645SThomas Gleixner 
2905cee9645SThomas Gleixner 	/*
2915cee9645SThomas Gleixner 	 * If the target jiffie is just after a whole second (which can happen
2925cee9645SThomas Gleixner 	 * due to delays of the timer irq, long irq off times etc etc) then
2935cee9645SThomas Gleixner 	 * we should round down to the whole second, not up. Use 1/4th second
2945cee9645SThomas Gleixner 	 * as cutoff for this rounding as an extreme upper bound for this.
2955cee9645SThomas Gleixner 	 * But never round down if @force_up is set.
2965cee9645SThomas Gleixner 	 */
2975cee9645SThomas Gleixner 	if (rem < HZ/4 && !force_up) /* round down */
2985cee9645SThomas Gleixner 		j = j - rem;
2995cee9645SThomas Gleixner 	else /* round up */
3005cee9645SThomas Gleixner 		j = j - rem + HZ;
3015cee9645SThomas Gleixner 
3025cee9645SThomas Gleixner 	/* now that we have rounded, subtract the extra skew again */
3035cee9645SThomas Gleixner 	j -= cpu * 3;
3045cee9645SThomas Gleixner 
3055cee9645SThomas Gleixner 	/*
3065cee9645SThomas Gleixner 	 * Make sure j is still in the future. Otherwise return the
3075cee9645SThomas Gleixner 	 * unmodified value.
3085cee9645SThomas Gleixner 	 */
3095cee9645SThomas Gleixner 	return time_is_after_jiffies(j) ? j : original;
3105cee9645SThomas Gleixner }
3115cee9645SThomas Gleixner 
3125cee9645SThomas Gleixner /**
3135cee9645SThomas Gleixner  * __round_jiffies - function to round jiffies to a full second
3145cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
3155cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
3165cee9645SThomas Gleixner  *
3175cee9645SThomas Gleixner  * __round_jiffies() rounds an absolute time in the future (in jiffies)
3185cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
3195cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
3205cee9645SThomas Gleixner  * they fire approximately every X seconds.
3215cee9645SThomas Gleixner  *
3225cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
3235cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
3245cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
3255cee9645SThomas Gleixner  *
3265cee9645SThomas Gleixner  * The exact rounding is skewed for each processor to avoid all
3275cee9645SThomas Gleixner  * processors firing at the exact same time, which could lead
3285cee9645SThomas Gleixner  * to lock contention or spurious cache line bouncing.
3295cee9645SThomas Gleixner  *
3305cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
3315cee9645SThomas Gleixner  */
3325cee9645SThomas Gleixner unsigned long __round_jiffies(unsigned long j, int cpu)
3335cee9645SThomas Gleixner {
3345cee9645SThomas Gleixner 	return round_jiffies_common(j, cpu, false);
3355cee9645SThomas Gleixner }
3365cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies);
3375cee9645SThomas Gleixner 
3385cee9645SThomas Gleixner /**
3395cee9645SThomas Gleixner  * __round_jiffies_relative - function to round jiffies to a full second
3405cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
3415cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
3425cee9645SThomas Gleixner  *
3435cee9645SThomas Gleixner  * __round_jiffies_relative() rounds a time delta  in the future (in jiffies)
3445cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
3455cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
3465cee9645SThomas Gleixner  * they fire approximately every X seconds.
3475cee9645SThomas Gleixner  *
3485cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
3495cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
3505cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
3515cee9645SThomas Gleixner  *
3525cee9645SThomas Gleixner  * The exact rounding is skewed for each processor to avoid all
3535cee9645SThomas Gleixner  * processors firing at the exact same time, which could lead
3545cee9645SThomas Gleixner  * to lock contention or spurious cache line bouncing.
3555cee9645SThomas Gleixner  *
3565cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
3575cee9645SThomas Gleixner  */
3585cee9645SThomas Gleixner unsigned long __round_jiffies_relative(unsigned long j, int cpu)
3595cee9645SThomas Gleixner {
3605cee9645SThomas Gleixner 	unsigned long j0 = jiffies;
3615cee9645SThomas Gleixner 
3625cee9645SThomas Gleixner 	/* Use j0 because jiffies might change while we run */
3635cee9645SThomas Gleixner 	return round_jiffies_common(j + j0, cpu, false) - j0;
3645cee9645SThomas Gleixner }
3655cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies_relative);
3665cee9645SThomas Gleixner 
3675cee9645SThomas Gleixner /**
3685cee9645SThomas Gleixner  * round_jiffies - function to round jiffies to a full second
3695cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
3705cee9645SThomas Gleixner  *
3715cee9645SThomas Gleixner  * round_jiffies() rounds an absolute time in the future (in jiffies)
3725cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
3735cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
3745cee9645SThomas Gleixner  * they fire approximately every X seconds.
3755cee9645SThomas Gleixner  *
3765cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
3775cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
3785cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
3795cee9645SThomas Gleixner  *
3805cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
3815cee9645SThomas Gleixner  */
3825cee9645SThomas Gleixner unsigned long round_jiffies(unsigned long j)
3835cee9645SThomas Gleixner {
3845cee9645SThomas Gleixner 	return round_jiffies_common(j, raw_smp_processor_id(), false);
3855cee9645SThomas Gleixner }
3865cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies);
3875cee9645SThomas Gleixner 
3885cee9645SThomas Gleixner /**
3895cee9645SThomas Gleixner  * round_jiffies_relative - function to round jiffies to a full second
3905cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
3915cee9645SThomas Gleixner  *
3925cee9645SThomas Gleixner  * round_jiffies_relative() rounds a time delta  in the future (in jiffies)
3935cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
3945cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
3955cee9645SThomas Gleixner  * they fire approximately every X seconds.
3965cee9645SThomas Gleixner  *
3975cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
3985cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
3995cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
4005cee9645SThomas Gleixner  *
4015cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
4025cee9645SThomas Gleixner  */
4035cee9645SThomas Gleixner unsigned long round_jiffies_relative(unsigned long j)
4045cee9645SThomas Gleixner {
4055cee9645SThomas Gleixner 	return __round_jiffies_relative(j, raw_smp_processor_id());
4065cee9645SThomas Gleixner }
4075cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies_relative);
4085cee9645SThomas Gleixner 
4095cee9645SThomas Gleixner /**
4105cee9645SThomas Gleixner  * __round_jiffies_up - function to round jiffies up to a full second
4115cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
4125cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
4135cee9645SThomas Gleixner  *
4145cee9645SThomas Gleixner  * This is the same as __round_jiffies() except that it will never
4155cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
4165cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
4175cee9645SThomas Gleixner  * early.
4185cee9645SThomas Gleixner  */
4195cee9645SThomas Gleixner unsigned long __round_jiffies_up(unsigned long j, int cpu)
4205cee9645SThomas Gleixner {
4215cee9645SThomas Gleixner 	return round_jiffies_common(j, cpu, true);
4225cee9645SThomas Gleixner }
4235cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies_up);
4245cee9645SThomas Gleixner 
4255cee9645SThomas Gleixner /**
4265cee9645SThomas Gleixner  * __round_jiffies_up_relative - function to round jiffies up to a full second
4275cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
4285cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
4295cee9645SThomas Gleixner  *
4305cee9645SThomas Gleixner  * This is the same as __round_jiffies_relative() except that it will never
4315cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
4325cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
4335cee9645SThomas Gleixner  * early.
4345cee9645SThomas Gleixner  */
4355cee9645SThomas Gleixner unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
4365cee9645SThomas Gleixner {
4375cee9645SThomas Gleixner 	unsigned long j0 = jiffies;
4385cee9645SThomas Gleixner 
4395cee9645SThomas Gleixner 	/* Use j0 because jiffies might change while we run */
4405cee9645SThomas Gleixner 	return round_jiffies_common(j + j0, cpu, true) - j0;
4415cee9645SThomas Gleixner }
4425cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies_up_relative);
4435cee9645SThomas Gleixner 
4445cee9645SThomas Gleixner /**
4455cee9645SThomas Gleixner  * round_jiffies_up - function to round jiffies up to a full second
4465cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
4475cee9645SThomas Gleixner  *
4485cee9645SThomas Gleixner  * This is the same as round_jiffies() except that it will never
4495cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
4505cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
4515cee9645SThomas Gleixner  * early.
4525cee9645SThomas Gleixner  */
4535cee9645SThomas Gleixner unsigned long round_jiffies_up(unsigned long j)
4545cee9645SThomas Gleixner {
4555cee9645SThomas Gleixner 	return round_jiffies_common(j, raw_smp_processor_id(), true);
4565cee9645SThomas Gleixner }
4575cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies_up);
4585cee9645SThomas Gleixner 
4595cee9645SThomas Gleixner /**
4605cee9645SThomas Gleixner  * round_jiffies_up_relative - function to round jiffies up to a full second
4615cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
4625cee9645SThomas Gleixner  *
4635cee9645SThomas Gleixner  * This is the same as round_jiffies_relative() except that it will never
4645cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
4655cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
4665cee9645SThomas Gleixner  * early.
4675cee9645SThomas Gleixner  */
4685cee9645SThomas Gleixner unsigned long round_jiffies_up_relative(unsigned long j)
4695cee9645SThomas Gleixner {
4705cee9645SThomas Gleixner 	return __round_jiffies_up_relative(j, raw_smp_processor_id());
4715cee9645SThomas Gleixner }
4725cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies_up_relative);
4735cee9645SThomas Gleixner 
4745cee9645SThomas Gleixner 
475500462a9SThomas Gleixner static inline unsigned int timer_get_idx(struct timer_list *timer)
4765cee9645SThomas Gleixner {
477500462a9SThomas Gleixner 	return (timer->flags & TIMER_ARRAYMASK) >> TIMER_ARRAYSHIFT;
4785cee9645SThomas Gleixner }
479500462a9SThomas Gleixner 
480500462a9SThomas Gleixner static inline void timer_set_idx(struct timer_list *timer, unsigned int idx)
481500462a9SThomas Gleixner {
482500462a9SThomas Gleixner 	timer->flags = (timer->flags & ~TIMER_ARRAYMASK) |
483500462a9SThomas Gleixner 			idx << TIMER_ARRAYSHIFT;
484500462a9SThomas Gleixner }
485500462a9SThomas Gleixner 
486500462a9SThomas Gleixner /*
487500462a9SThomas Gleixner  * Helper function to calculate the array index for a given expiry
488500462a9SThomas Gleixner  * time.
489500462a9SThomas Gleixner  */
490500462a9SThomas Gleixner static inline unsigned calc_index(unsigned expires, unsigned lvl)
491500462a9SThomas Gleixner {
492500462a9SThomas Gleixner 	expires = (expires + LVL_GRAN(lvl)) >> LVL_SHIFT(lvl);
493500462a9SThomas Gleixner 	return LVL_OFFS(lvl) + (expires & LVL_MASK);
494500462a9SThomas Gleixner }
495500462a9SThomas Gleixner 
496ffdf0477SAnna-Maria Gleixner static int calc_wheel_index(unsigned long expires, unsigned long clk)
4975cee9645SThomas Gleixner {
498ffdf0477SAnna-Maria Gleixner 	unsigned long delta = expires - clk;
499500462a9SThomas Gleixner 	unsigned int idx;
5005cee9645SThomas Gleixner 
501500462a9SThomas Gleixner 	if (delta < LVL_START(1)) {
502500462a9SThomas Gleixner 		idx = calc_index(expires, 0);
503500462a9SThomas Gleixner 	} else if (delta < LVL_START(2)) {
504500462a9SThomas Gleixner 		idx = calc_index(expires, 1);
505500462a9SThomas Gleixner 	} else if (delta < LVL_START(3)) {
506500462a9SThomas Gleixner 		idx = calc_index(expires, 2);
507500462a9SThomas Gleixner 	} else if (delta < LVL_START(4)) {
508500462a9SThomas Gleixner 		idx = calc_index(expires, 3);
509500462a9SThomas Gleixner 	} else if (delta < LVL_START(5)) {
510500462a9SThomas Gleixner 		idx = calc_index(expires, 4);
511500462a9SThomas Gleixner 	} else if (delta < LVL_START(6)) {
512500462a9SThomas Gleixner 		idx = calc_index(expires, 5);
513500462a9SThomas Gleixner 	} else if (delta < LVL_START(7)) {
514500462a9SThomas Gleixner 		idx = calc_index(expires, 6);
515500462a9SThomas Gleixner 	} else if (LVL_DEPTH > 8 && delta < LVL_START(8)) {
516500462a9SThomas Gleixner 		idx = calc_index(expires, 7);
517500462a9SThomas Gleixner 	} else if ((long) delta < 0) {
518ffdf0477SAnna-Maria Gleixner 		idx = clk & LVL_MASK;
5195cee9645SThomas Gleixner 	} else {
520500462a9SThomas Gleixner 		/*
521500462a9SThomas Gleixner 		 * Force expire obscene large timeouts to expire at the
522500462a9SThomas Gleixner 		 * capacity limit of the wheel.
5235cee9645SThomas Gleixner 		 */
524*e2a71bdeSFrederic Weisbecker 		if (delta >= WHEEL_TIMEOUT_CUTOFF)
525*e2a71bdeSFrederic Weisbecker 			expires = clk + WHEEL_TIMEOUT_MAX;
5261bd04bf6SThomas Gleixner 
527500462a9SThomas Gleixner 		idx = calc_index(expires, LVL_DEPTH - 1);
528500462a9SThomas Gleixner 	}
529ffdf0477SAnna-Maria Gleixner 	return idx;
530ffdf0477SAnna-Maria Gleixner }
531ffdf0477SAnna-Maria Gleixner 
532500462a9SThomas Gleixner /*
533ffdf0477SAnna-Maria Gleixner  * Enqueue the timer into the hash bucket, mark it pending in
534500462a9SThomas Gleixner  * the bitmap and store the index in the timer flags.
535500462a9SThomas Gleixner  */
536ffdf0477SAnna-Maria Gleixner static void enqueue_timer(struct timer_base *base, struct timer_list *timer,
537ffdf0477SAnna-Maria Gleixner 			  unsigned int idx)
538ffdf0477SAnna-Maria Gleixner {
539ffdf0477SAnna-Maria Gleixner 	hlist_add_head(&timer->entry, base->vectors + idx);
540500462a9SThomas Gleixner 	__set_bit(idx, base->pending_map);
541500462a9SThomas Gleixner 	timer_set_idx(timer, idx);
542dc1e7dc5SAnna-Maria Gleixner 
543dc1e7dc5SAnna-Maria Gleixner 	trace_timer_start(timer, timer->expires, timer->flags);
5445cee9645SThomas Gleixner }
5455cee9645SThomas Gleixner 
5465cee9645SThomas Gleixner static void
547ffdf0477SAnna-Maria Gleixner __internal_add_timer(struct timer_base *base, struct timer_list *timer)
5485cee9645SThomas Gleixner {
549ffdf0477SAnna-Maria Gleixner 	unsigned int idx;
5505cee9645SThomas Gleixner 
551ffdf0477SAnna-Maria Gleixner 	idx = calc_wheel_index(timer->expires, base->clk);
552ffdf0477SAnna-Maria Gleixner 	enqueue_timer(base, timer, idx);
5535cee9645SThomas Gleixner }
5545cee9645SThomas Gleixner 
555ffdf0477SAnna-Maria Gleixner static void
556ffdf0477SAnna-Maria Gleixner trigger_dyntick_cpu(struct timer_base *base, struct timer_list *timer)
5575cee9645SThomas Gleixner {
558ae67badaSThomas Gleixner 	if (!is_timers_nohz_active())
559a683f390SThomas Gleixner 		return;
5603bb475a3SThomas Gleixner 
5615cee9645SThomas Gleixner 	/*
562a683f390SThomas Gleixner 	 * TODO: This wants some optimizing similar to the code below, but we
563a683f390SThomas Gleixner 	 * will do that when we switch from push to pull for deferrable timers.
5645cee9645SThomas Gleixner 	 */
565a683f390SThomas Gleixner 	if (timer->flags & TIMER_DEFERRABLE) {
566a683f390SThomas Gleixner 		if (tick_nohz_full_cpu(base->cpu))
5679f6d9baaSViresh Kumar 			wake_up_nohz_cpu(base->cpu);
568a683f390SThomas Gleixner 		return;
5695cee9645SThomas Gleixner 	}
5705cee9645SThomas Gleixner 
5715cee9645SThomas Gleixner 	/*
572a683f390SThomas Gleixner 	 * We might have to IPI the remote CPU if the base is idle and the
573a683f390SThomas Gleixner 	 * timer is not deferrable. If the other CPU is on the way to idle
574a683f390SThomas Gleixner 	 * then it can't set base->is_idle as we hold the base lock:
5755cee9645SThomas Gleixner 	 */
576a683f390SThomas Gleixner 	if (!base->is_idle)
577a683f390SThomas Gleixner 		return;
578a683f390SThomas Gleixner 
579a683f390SThomas Gleixner 	/* Check whether this is the new first expiring timer: */
580a683f390SThomas Gleixner 	if (time_after_eq(timer->expires, base->next_expiry))
581a683f390SThomas Gleixner 		return;
582a683f390SThomas Gleixner 
583a683f390SThomas Gleixner 	/*
584a683f390SThomas Gleixner 	 * Set the next expiry time and kick the CPU so it can reevaluate the
585a683f390SThomas Gleixner 	 * wheel:
586a683f390SThomas Gleixner 	 */
58730c66fc3SFrederic Weisbecker 	if (time_before(timer->expires, base->clk)) {
58830c66fc3SFrederic Weisbecker 		/*
58930c66fc3SFrederic Weisbecker 		 * Prevent from forward_timer_base() moving the base->clk
59030c66fc3SFrederic Weisbecker 		 * backward
59130c66fc3SFrederic Weisbecker 		 */
59230c66fc3SFrederic Weisbecker 		base->next_expiry = base->clk;
59330c66fc3SFrederic Weisbecker 	} else {
594a683f390SThomas Gleixner 		base->next_expiry = timer->expires;
59530c66fc3SFrederic Weisbecker 	}
5965cee9645SThomas Gleixner 	wake_up_nohz_cpu(base->cpu);
5975cee9645SThomas Gleixner }
5985cee9645SThomas Gleixner 
599ffdf0477SAnna-Maria Gleixner static void
600ffdf0477SAnna-Maria Gleixner internal_add_timer(struct timer_base *base, struct timer_list *timer)
601ffdf0477SAnna-Maria Gleixner {
602ffdf0477SAnna-Maria Gleixner 	__internal_add_timer(base, timer);
603ffdf0477SAnna-Maria Gleixner 	trigger_dyntick_cpu(base, timer);
6045cee9645SThomas Gleixner }
6055cee9645SThomas Gleixner 
6065cee9645SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
6075cee9645SThomas Gleixner 
6085cee9645SThomas Gleixner static struct debug_obj_descr timer_debug_descr;
6095cee9645SThomas Gleixner 
6105cee9645SThomas Gleixner static void *timer_debug_hint(void *addr)
6115cee9645SThomas Gleixner {
6125cee9645SThomas Gleixner 	return ((struct timer_list *) addr)->function;
6135cee9645SThomas Gleixner }
6145cee9645SThomas Gleixner 
615b9fdac7fSDu, Changbin static bool timer_is_static_object(void *addr)
616b9fdac7fSDu, Changbin {
617b9fdac7fSDu, Changbin 	struct timer_list *timer = addr;
618b9fdac7fSDu, Changbin 
619b9fdac7fSDu, Changbin 	return (timer->entry.pprev == NULL &&
620b9fdac7fSDu, Changbin 		timer->entry.next == TIMER_ENTRY_STATIC);
621b9fdac7fSDu, Changbin }
622b9fdac7fSDu, Changbin 
6235cee9645SThomas Gleixner /*
6245cee9645SThomas Gleixner  * fixup_init is called when:
6255cee9645SThomas Gleixner  * - an active object is initialized
6265cee9645SThomas Gleixner  */
627e3252464SDu, Changbin static bool timer_fixup_init(void *addr, enum debug_obj_state state)
6285cee9645SThomas Gleixner {
6295cee9645SThomas Gleixner 	struct timer_list *timer = addr;
6305cee9645SThomas Gleixner 
6315cee9645SThomas Gleixner 	switch (state) {
6325cee9645SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
6335cee9645SThomas Gleixner 		del_timer_sync(timer);
6345cee9645SThomas Gleixner 		debug_object_init(timer, &timer_debug_descr);
635e3252464SDu, Changbin 		return true;
6365cee9645SThomas Gleixner 	default:
637e3252464SDu, Changbin 		return false;
6385cee9645SThomas Gleixner 	}
6395cee9645SThomas Gleixner }
6405cee9645SThomas Gleixner 
6415cee9645SThomas Gleixner /* Stub timer callback for improperly used timers. */
642ba16490eSThomas Gleixner static void stub_timer(struct timer_list *unused)
6435cee9645SThomas Gleixner {
6445cee9645SThomas Gleixner 	WARN_ON(1);
6455cee9645SThomas Gleixner }
6465cee9645SThomas Gleixner 
6475cee9645SThomas Gleixner /*
6485cee9645SThomas Gleixner  * fixup_activate is called when:
6495cee9645SThomas Gleixner  * - an active object is activated
650b9fdac7fSDu, Changbin  * - an unknown non-static object is activated
6515cee9645SThomas Gleixner  */
652e3252464SDu, Changbin static bool timer_fixup_activate(void *addr, enum debug_obj_state state)
6535cee9645SThomas Gleixner {
6545cee9645SThomas Gleixner 	struct timer_list *timer = addr;
6555cee9645SThomas Gleixner 
6565cee9645SThomas Gleixner 	switch (state) {
6575cee9645SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
658ba16490eSThomas Gleixner 		timer_setup(timer, stub_timer, 0);
659e3252464SDu, Changbin 		return true;
6605cee9645SThomas Gleixner 
6615cee9645SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
6625cee9645SThomas Gleixner 		WARN_ON(1);
66375b710afSGustavo A. R. Silva 		/* fall through */
6645cee9645SThomas Gleixner 	default:
665e3252464SDu, Changbin 		return false;
6665cee9645SThomas Gleixner 	}
6675cee9645SThomas Gleixner }
6685cee9645SThomas Gleixner 
6695cee9645SThomas Gleixner /*
6705cee9645SThomas Gleixner  * fixup_free is called when:
6715cee9645SThomas Gleixner  * - an active object is freed
6725cee9645SThomas Gleixner  */
673e3252464SDu, Changbin static bool timer_fixup_free(void *addr, enum debug_obj_state state)
6745cee9645SThomas Gleixner {
6755cee9645SThomas Gleixner 	struct timer_list *timer = addr;
6765cee9645SThomas Gleixner 
6775cee9645SThomas Gleixner 	switch (state) {
6785cee9645SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
6795cee9645SThomas Gleixner 		del_timer_sync(timer);
6805cee9645SThomas Gleixner 		debug_object_free(timer, &timer_debug_descr);
681e3252464SDu, Changbin 		return true;
6825cee9645SThomas Gleixner 	default:
683e3252464SDu, Changbin 		return false;
6845cee9645SThomas Gleixner 	}
6855cee9645SThomas Gleixner }
6865cee9645SThomas Gleixner 
6875cee9645SThomas Gleixner /*
6885cee9645SThomas Gleixner  * fixup_assert_init is called when:
6895cee9645SThomas Gleixner  * - an untracked/uninit-ed object is found
6905cee9645SThomas Gleixner  */
691e3252464SDu, Changbin static bool timer_fixup_assert_init(void *addr, enum debug_obj_state state)
6925cee9645SThomas Gleixner {
6935cee9645SThomas Gleixner 	struct timer_list *timer = addr;
6945cee9645SThomas Gleixner 
6955cee9645SThomas Gleixner 	switch (state) {
6965cee9645SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
697ba16490eSThomas Gleixner 		timer_setup(timer, stub_timer, 0);
698e3252464SDu, Changbin 		return true;
6995cee9645SThomas Gleixner 	default:
700e3252464SDu, Changbin 		return false;
7015cee9645SThomas Gleixner 	}
7025cee9645SThomas Gleixner }
7035cee9645SThomas Gleixner 
7045cee9645SThomas Gleixner static struct debug_obj_descr timer_debug_descr = {
7055cee9645SThomas Gleixner 	.name			= "timer_list",
7065cee9645SThomas Gleixner 	.debug_hint		= timer_debug_hint,
707b9fdac7fSDu, Changbin 	.is_static_object	= timer_is_static_object,
7085cee9645SThomas Gleixner 	.fixup_init		= timer_fixup_init,
7095cee9645SThomas Gleixner 	.fixup_activate		= timer_fixup_activate,
7105cee9645SThomas Gleixner 	.fixup_free		= timer_fixup_free,
7115cee9645SThomas Gleixner 	.fixup_assert_init	= timer_fixup_assert_init,
7125cee9645SThomas Gleixner };
7135cee9645SThomas Gleixner 
7145cee9645SThomas Gleixner static inline void debug_timer_init(struct timer_list *timer)
7155cee9645SThomas Gleixner {
7165cee9645SThomas Gleixner 	debug_object_init(timer, &timer_debug_descr);
7175cee9645SThomas Gleixner }
7185cee9645SThomas Gleixner 
7195cee9645SThomas Gleixner static inline void debug_timer_activate(struct timer_list *timer)
7205cee9645SThomas Gleixner {
7215cee9645SThomas Gleixner 	debug_object_activate(timer, &timer_debug_descr);
7225cee9645SThomas Gleixner }
7235cee9645SThomas Gleixner 
7245cee9645SThomas Gleixner static inline void debug_timer_deactivate(struct timer_list *timer)
7255cee9645SThomas Gleixner {
7265cee9645SThomas Gleixner 	debug_object_deactivate(timer, &timer_debug_descr);
7275cee9645SThomas Gleixner }
7285cee9645SThomas Gleixner 
7295cee9645SThomas Gleixner static inline void debug_timer_free(struct timer_list *timer)
7305cee9645SThomas Gleixner {
7315cee9645SThomas Gleixner 	debug_object_free(timer, &timer_debug_descr);
7325cee9645SThomas Gleixner }
7335cee9645SThomas Gleixner 
7345cee9645SThomas Gleixner static inline void debug_timer_assert_init(struct timer_list *timer)
7355cee9645SThomas Gleixner {
7365cee9645SThomas Gleixner 	debug_object_assert_init(timer, &timer_debug_descr);
7375cee9645SThomas Gleixner }
7385cee9645SThomas Gleixner 
739188665b2SKees Cook static void do_init_timer(struct timer_list *timer,
740188665b2SKees Cook 			  void (*func)(struct timer_list *),
741188665b2SKees Cook 			  unsigned int flags,
7425cee9645SThomas Gleixner 			  const char *name, struct lock_class_key *key);
7435cee9645SThomas Gleixner 
744188665b2SKees Cook void init_timer_on_stack_key(struct timer_list *timer,
745188665b2SKees Cook 			     void (*func)(struct timer_list *),
746188665b2SKees Cook 			     unsigned int flags,
7475cee9645SThomas Gleixner 			     const char *name, struct lock_class_key *key)
7485cee9645SThomas Gleixner {
7495cee9645SThomas Gleixner 	debug_object_init_on_stack(timer, &timer_debug_descr);
750188665b2SKees Cook 	do_init_timer(timer, func, flags, name, key);
7515cee9645SThomas Gleixner }
7525cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(init_timer_on_stack_key);
7535cee9645SThomas Gleixner 
7545cee9645SThomas Gleixner void destroy_timer_on_stack(struct timer_list *timer)
7555cee9645SThomas Gleixner {
7565cee9645SThomas Gleixner 	debug_object_free(timer, &timer_debug_descr);
7575cee9645SThomas Gleixner }
7585cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_timer_on_stack);
7595cee9645SThomas Gleixner 
7605cee9645SThomas Gleixner #else
7615cee9645SThomas Gleixner static inline void debug_timer_init(struct timer_list *timer) { }
7625cee9645SThomas Gleixner static inline void debug_timer_activate(struct timer_list *timer) { }
7635cee9645SThomas Gleixner static inline void debug_timer_deactivate(struct timer_list *timer) { }
7645cee9645SThomas Gleixner static inline void debug_timer_assert_init(struct timer_list *timer) { }
7655cee9645SThomas Gleixner #endif
7665cee9645SThomas Gleixner 
7675cee9645SThomas Gleixner static inline void debug_init(struct timer_list *timer)
7685cee9645SThomas Gleixner {
7695cee9645SThomas Gleixner 	debug_timer_init(timer);
7705cee9645SThomas Gleixner 	trace_timer_init(timer);
7715cee9645SThomas Gleixner }
7725cee9645SThomas Gleixner 
7735cee9645SThomas Gleixner static inline void debug_deactivate(struct timer_list *timer)
7745cee9645SThomas Gleixner {
7755cee9645SThomas Gleixner 	debug_timer_deactivate(timer);
7765cee9645SThomas Gleixner 	trace_timer_cancel(timer);
7775cee9645SThomas Gleixner }
7785cee9645SThomas Gleixner 
7795cee9645SThomas Gleixner static inline void debug_assert_init(struct timer_list *timer)
7805cee9645SThomas Gleixner {
7815cee9645SThomas Gleixner 	debug_timer_assert_init(timer);
7825cee9645SThomas Gleixner }
7835cee9645SThomas Gleixner 
784188665b2SKees Cook static void do_init_timer(struct timer_list *timer,
785188665b2SKees Cook 			  void (*func)(struct timer_list *),
786188665b2SKees Cook 			  unsigned int flags,
7875cee9645SThomas Gleixner 			  const char *name, struct lock_class_key *key)
7885cee9645SThomas Gleixner {
7891dabbcecSThomas Gleixner 	timer->entry.pprev = NULL;
790188665b2SKees Cook 	timer->function = func;
7910eeda71bSThomas Gleixner 	timer->flags = flags | raw_smp_processor_id();
7925cee9645SThomas Gleixner 	lockdep_init_map(&timer->lockdep_map, name, key, 0);
7935cee9645SThomas Gleixner }
7945cee9645SThomas Gleixner 
7955cee9645SThomas Gleixner /**
7965cee9645SThomas Gleixner  * init_timer_key - initialize a timer
7975cee9645SThomas Gleixner  * @timer: the timer to be initialized
798188665b2SKees Cook  * @func: timer callback function
7995cee9645SThomas Gleixner  * @flags: timer flags
8005cee9645SThomas Gleixner  * @name: name of the timer
8015cee9645SThomas Gleixner  * @key: lockdep class key of the fake lock used for tracking timer
8025cee9645SThomas Gleixner  *       sync lock dependencies
8035cee9645SThomas Gleixner  *
8045cee9645SThomas Gleixner  * init_timer_key() must be done to a timer prior calling *any* of the
8055cee9645SThomas Gleixner  * other timer functions.
8065cee9645SThomas Gleixner  */
807188665b2SKees Cook void init_timer_key(struct timer_list *timer,
808188665b2SKees Cook 		    void (*func)(struct timer_list *), unsigned int flags,
8095cee9645SThomas Gleixner 		    const char *name, struct lock_class_key *key)
8105cee9645SThomas Gleixner {
8115cee9645SThomas Gleixner 	debug_init(timer);
812188665b2SKees Cook 	do_init_timer(timer, func, flags, name, key);
8135cee9645SThomas Gleixner }
8145cee9645SThomas Gleixner EXPORT_SYMBOL(init_timer_key);
8155cee9645SThomas Gleixner 
8165cee9645SThomas Gleixner static inline void detach_timer(struct timer_list *timer, bool clear_pending)
8175cee9645SThomas Gleixner {
8181dabbcecSThomas Gleixner 	struct hlist_node *entry = &timer->entry;
8195cee9645SThomas Gleixner 
8205cee9645SThomas Gleixner 	debug_deactivate(timer);
8215cee9645SThomas Gleixner 
8221dabbcecSThomas Gleixner 	__hlist_del(entry);
8235cee9645SThomas Gleixner 	if (clear_pending)
8241dabbcecSThomas Gleixner 		entry->pprev = NULL;
8251dabbcecSThomas Gleixner 	entry->next = LIST_POISON2;
8265cee9645SThomas Gleixner }
8275cee9645SThomas Gleixner 
828494af3edSThomas Gleixner static int detach_if_pending(struct timer_list *timer, struct timer_base *base,
8295cee9645SThomas Gleixner 			     bool clear_pending)
8305cee9645SThomas Gleixner {
831500462a9SThomas Gleixner 	unsigned idx = timer_get_idx(timer);
832500462a9SThomas Gleixner 
8335cee9645SThomas Gleixner 	if (!timer_pending(timer))
8345cee9645SThomas Gleixner 		return 0;
8355cee9645SThomas Gleixner 
836500462a9SThomas Gleixner 	if (hlist_is_singular_node(&timer->entry, base->vectors + idx))
837500462a9SThomas Gleixner 		__clear_bit(idx, base->pending_map);
838500462a9SThomas Gleixner 
8395cee9645SThomas Gleixner 	detach_timer(timer, clear_pending);
8405cee9645SThomas Gleixner 	return 1;
8415cee9645SThomas Gleixner }
8425cee9645SThomas Gleixner 
843500462a9SThomas Gleixner static inline struct timer_base *get_timer_cpu_base(u32 tflags, u32 cpu)
844500462a9SThomas Gleixner {
845500462a9SThomas Gleixner 	struct timer_base *base = per_cpu_ptr(&timer_bases[BASE_STD], cpu);
846500462a9SThomas Gleixner 
8475cee9645SThomas Gleixner 	/*
848ced6d5c1SAnna-Maria Gleixner 	 * If the timer is deferrable and NO_HZ_COMMON is set then we need
849ced6d5c1SAnna-Maria Gleixner 	 * to use the deferrable base.
850500462a9SThomas Gleixner 	 */
851ced6d5c1SAnna-Maria Gleixner 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
852500462a9SThomas Gleixner 		base = per_cpu_ptr(&timer_bases[BASE_DEF], cpu);
853500462a9SThomas Gleixner 	return base;
854500462a9SThomas Gleixner }
855500462a9SThomas Gleixner 
856500462a9SThomas Gleixner static inline struct timer_base *get_timer_this_cpu_base(u32 tflags)
857500462a9SThomas Gleixner {
858500462a9SThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
859500462a9SThomas Gleixner 
860500462a9SThomas Gleixner 	/*
861ced6d5c1SAnna-Maria Gleixner 	 * If the timer is deferrable and NO_HZ_COMMON is set then we need
862ced6d5c1SAnna-Maria Gleixner 	 * to use the deferrable base.
863500462a9SThomas Gleixner 	 */
864ced6d5c1SAnna-Maria Gleixner 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
865500462a9SThomas Gleixner 		base = this_cpu_ptr(&timer_bases[BASE_DEF]);
866500462a9SThomas Gleixner 	return base;
867500462a9SThomas Gleixner }
868500462a9SThomas Gleixner 
869500462a9SThomas Gleixner static inline struct timer_base *get_timer_base(u32 tflags)
870500462a9SThomas Gleixner {
871500462a9SThomas Gleixner 	return get_timer_cpu_base(tflags, tflags & TIMER_CPUMASK);
872500462a9SThomas Gleixner }
873500462a9SThomas Gleixner 
874a683f390SThomas Gleixner static inline struct timer_base *
8756bad6bccSThomas Gleixner get_target_base(struct timer_base *base, unsigned tflags)
876500462a9SThomas Gleixner {
877ae67badaSThomas Gleixner #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
878ae67badaSThomas Gleixner 	if (static_branch_likely(&timers_migration_enabled) &&
879ae67badaSThomas Gleixner 	    !(tflags & TIMER_PINNED))
880500462a9SThomas Gleixner 		return get_timer_cpu_base(tflags, get_nohz_timer_target());
881500462a9SThomas Gleixner #endif
882ae67badaSThomas Gleixner 	return get_timer_this_cpu_base(tflags);
883500462a9SThomas Gleixner }
884500462a9SThomas Gleixner 
885a683f390SThomas Gleixner static inline void forward_timer_base(struct timer_base *base)
886a683f390SThomas Gleixner {
887ae67badaSThomas Gleixner #ifdef CONFIG_NO_HZ_COMMON
8882fe59f50SNicholas Piggin 	unsigned long jnow;
8896bad6bccSThomas Gleixner 
890a683f390SThomas Gleixner 	/*
8912fe59f50SNicholas Piggin 	 * We only forward the base when we are idle or have just come out of
8922fe59f50SNicholas Piggin 	 * idle (must_forward_clk logic), and have a delta between base clock
8932fe59f50SNicholas Piggin 	 * and jiffies. In the common case, run_timers will take care of it.
894a683f390SThomas Gleixner 	 */
8952fe59f50SNicholas Piggin 	if (likely(!base->must_forward_clk))
8962fe59f50SNicholas Piggin 		return;
8972fe59f50SNicholas Piggin 
8982fe59f50SNicholas Piggin 	jnow = READ_ONCE(jiffies);
8992fe59f50SNicholas Piggin 	base->must_forward_clk = base->is_idle;
9002fe59f50SNicholas Piggin 	if ((long)(jnow - base->clk) < 2)
901a683f390SThomas Gleixner 		return;
902a683f390SThomas Gleixner 
903a683f390SThomas Gleixner 	/*
904a683f390SThomas Gleixner 	 * If the next expiry value is > jiffies, then we fast forward to
905a683f390SThomas Gleixner 	 * jiffies otherwise we forward to the next expiry value.
906a683f390SThomas Gleixner 	 */
90730c66fc3SFrederic Weisbecker 	if (time_after(base->next_expiry, jnow)) {
9086bad6bccSThomas Gleixner 		base->clk = jnow;
90930c66fc3SFrederic Weisbecker 	} else {
91030c66fc3SFrederic Weisbecker 		if (WARN_ON_ONCE(time_before(base->next_expiry, base->clk)))
91130c66fc3SFrederic Weisbecker 			return;
912a683f390SThomas Gleixner 		base->clk = base->next_expiry;
91330c66fc3SFrederic Weisbecker 	}
914a683f390SThomas Gleixner #endif
915ae67badaSThomas Gleixner }
916a683f390SThomas Gleixner 
917a683f390SThomas Gleixner 
918500462a9SThomas Gleixner /*
919500462a9SThomas Gleixner  * We are using hashed locking: Holding per_cpu(timer_bases[x]).lock means
920500462a9SThomas Gleixner  * that all timers which are tied to this base are locked, and the base itself
921500462a9SThomas Gleixner  * is locked too.
9225cee9645SThomas Gleixner  *
9235cee9645SThomas Gleixner  * So __run_timers/migrate_timers can safely modify all timers which could
924500462a9SThomas Gleixner  * be found in the base->vectors array.
9255cee9645SThomas Gleixner  *
926500462a9SThomas Gleixner  * When a timer is migrating then the TIMER_MIGRATING flag is set and we need
927500462a9SThomas Gleixner  * to wait until the migration is done.
9285cee9645SThomas Gleixner  */
929494af3edSThomas Gleixner static struct timer_base *lock_timer_base(struct timer_list *timer,
9305cee9645SThomas Gleixner 					  unsigned long *flags)
9315cee9645SThomas Gleixner 	__acquires(timer->base->lock)
9325cee9645SThomas Gleixner {
9330eeda71bSThomas Gleixner 	for (;;) {
934494af3edSThomas Gleixner 		struct timer_base *base;
935b831275aSThomas Gleixner 		u32 tf;
936b831275aSThomas Gleixner 
937b831275aSThomas Gleixner 		/*
938b831275aSThomas Gleixner 		 * We need to use READ_ONCE() here, otherwise the compiler
939b831275aSThomas Gleixner 		 * might re-read @tf between the check for TIMER_MIGRATING
940b831275aSThomas Gleixner 		 * and spin_lock().
941b831275aSThomas Gleixner 		 */
942b831275aSThomas Gleixner 		tf = READ_ONCE(timer->flags);
9435cee9645SThomas Gleixner 
9440eeda71bSThomas Gleixner 		if (!(tf & TIMER_MIGRATING)) {
945500462a9SThomas Gleixner 			base = get_timer_base(tf);
9462287d866SSebastian Andrzej Siewior 			raw_spin_lock_irqsave(&base->lock, *flags);
9470eeda71bSThomas Gleixner 			if (timer->flags == tf)
9485cee9645SThomas Gleixner 				return base;
9492287d866SSebastian Andrzej Siewior 			raw_spin_unlock_irqrestore(&base->lock, *flags);
9505cee9645SThomas Gleixner 		}
9515cee9645SThomas Gleixner 		cpu_relax();
9525cee9645SThomas Gleixner 	}
9535cee9645SThomas Gleixner }
9545cee9645SThomas Gleixner 
955b24591e2SDavid Howells #define MOD_TIMER_PENDING_ONLY		0x01
956b24591e2SDavid Howells #define MOD_TIMER_REDUCE		0x02
95790c01894SEric Dumazet #define MOD_TIMER_NOTPENDING		0x04
958b24591e2SDavid Howells 
9595cee9645SThomas Gleixner static inline int
960b24591e2SDavid Howells __mod_timer(struct timer_list *timer, unsigned long expires, unsigned int options)
9615cee9645SThomas Gleixner {
962494af3edSThomas Gleixner 	struct timer_base *base, *new_base;
963f00c0afdSAnna-Maria Gleixner 	unsigned int idx = UINT_MAX;
964f00c0afdSAnna-Maria Gleixner 	unsigned long clk = 0, flags;
965bc7a34b8SThomas Gleixner 	int ret = 0;
9665cee9645SThomas Gleixner 
9674da9152aSThomas Gleixner 	BUG_ON(!timer->function);
9684da9152aSThomas Gleixner 
969500462a9SThomas Gleixner 	/*
970f00c0afdSAnna-Maria Gleixner 	 * This is a common optimization triggered by the networking code - if
971f00c0afdSAnna-Maria Gleixner 	 * the timer is re-modified to have the same timeout or ends up in the
972f00c0afdSAnna-Maria Gleixner 	 * same array bucket then just return:
973500462a9SThomas Gleixner 	 */
97490c01894SEric Dumazet 	if (!(options & MOD_TIMER_NOTPENDING) && timer_pending(timer)) {
9752fe59f50SNicholas Piggin 		/*
9762fe59f50SNicholas Piggin 		 * The downside of this optimization is that it can result in
9772fe59f50SNicholas Piggin 		 * larger granularity than you would get from adding a new
9782fe59f50SNicholas Piggin 		 * timer with this expiry.
9792fe59f50SNicholas Piggin 		 */
980b24591e2SDavid Howells 		long diff = timer->expires - expires;
981b24591e2SDavid Howells 
982b24591e2SDavid Howells 		if (!diff)
983b24591e2SDavid Howells 			return 1;
984b24591e2SDavid Howells 		if (options & MOD_TIMER_REDUCE && diff <= 0)
985500462a9SThomas Gleixner 			return 1;
986f00c0afdSAnna-Maria Gleixner 
9874da9152aSThomas Gleixner 		/*
9884da9152aSThomas Gleixner 		 * We lock timer base and calculate the bucket index right
9894da9152aSThomas Gleixner 		 * here. If the timer ends up in the same bucket, then we
9904da9152aSThomas Gleixner 		 * just update the expiry time and avoid the whole
9914da9152aSThomas Gleixner 		 * dequeue/enqueue dance.
9924da9152aSThomas Gleixner 		 */
9934da9152aSThomas Gleixner 		base = lock_timer_base(timer, &flags);
9942fe59f50SNicholas Piggin 		forward_timer_base(base);
9954da9152aSThomas Gleixner 
996b24591e2SDavid Howells 		if (timer_pending(timer) && (options & MOD_TIMER_REDUCE) &&
997b24591e2SDavid Howells 		    time_before_eq(timer->expires, expires)) {
998b24591e2SDavid Howells 			ret = 1;
999b24591e2SDavid Howells 			goto out_unlock;
1000b24591e2SDavid Howells 		}
1001b24591e2SDavid Howells 
10024da9152aSThomas Gleixner 		clk = base->clk;
1003f00c0afdSAnna-Maria Gleixner 		idx = calc_wheel_index(expires, clk);
1004f00c0afdSAnna-Maria Gleixner 
1005f00c0afdSAnna-Maria Gleixner 		/*
1006f00c0afdSAnna-Maria Gleixner 		 * Retrieve and compare the array index of the pending
1007f00c0afdSAnna-Maria Gleixner 		 * timer. If it matches set the expiry to the new value so a
1008f00c0afdSAnna-Maria Gleixner 		 * subsequent call will exit in the expires check above.
1009f00c0afdSAnna-Maria Gleixner 		 */
1010f00c0afdSAnna-Maria Gleixner 		if (idx == timer_get_idx(timer)) {
1011b24591e2SDavid Howells 			if (!(options & MOD_TIMER_REDUCE))
1012b24591e2SDavid Howells 				timer->expires = expires;
1013b24591e2SDavid Howells 			else if (time_after(timer->expires, expires))
1014f00c0afdSAnna-Maria Gleixner 				timer->expires = expires;
10154da9152aSThomas Gleixner 			ret = 1;
10164da9152aSThomas Gleixner 			goto out_unlock;
1017f00c0afdSAnna-Maria Gleixner 		}
10184da9152aSThomas Gleixner 	} else {
10194da9152aSThomas Gleixner 		base = lock_timer_base(timer, &flags);
10202fe59f50SNicholas Piggin 		forward_timer_base(base);
1021500462a9SThomas Gleixner 	}
1022500462a9SThomas Gleixner 
10235cee9645SThomas Gleixner 	ret = detach_if_pending(timer, base, false);
1024b24591e2SDavid Howells 	if (!ret && (options & MOD_TIMER_PENDING_ONLY))
10255cee9645SThomas Gleixner 		goto out_unlock;
10265cee9645SThomas Gleixner 
1027500462a9SThomas Gleixner 	new_base = get_target_base(base, timer->flags);
10285cee9645SThomas Gleixner 
10295cee9645SThomas Gleixner 	if (base != new_base) {
10305cee9645SThomas Gleixner 		/*
1031500462a9SThomas Gleixner 		 * We are trying to schedule the timer on the new base.
10325cee9645SThomas Gleixner 		 * However we can't change timer's base while it is running,
10335cee9645SThomas Gleixner 		 * otherwise del_timer_sync() can't detect that the timer's
1034500462a9SThomas Gleixner 		 * handler yet has not finished. This also guarantees that the
1035500462a9SThomas Gleixner 		 * timer is serialized wrt itself.
10365cee9645SThomas Gleixner 		 */
10375cee9645SThomas Gleixner 		if (likely(base->running_timer != timer)) {
10385cee9645SThomas Gleixner 			/* See the comment in lock_timer_base() */
10390eeda71bSThomas Gleixner 			timer->flags |= TIMER_MIGRATING;
10400eeda71bSThomas Gleixner 
10412287d866SSebastian Andrzej Siewior 			raw_spin_unlock(&base->lock);
10425cee9645SThomas Gleixner 			base = new_base;
10432287d866SSebastian Andrzej Siewior 			raw_spin_lock(&base->lock);
1044d0023a14SEric Dumazet 			WRITE_ONCE(timer->flags,
1045d0023a14SEric Dumazet 				   (timer->flags & ~TIMER_BASEMASK) | base->cpu);
10466bad6bccSThomas Gleixner 			forward_timer_base(base);
10472fe59f50SNicholas Piggin 		}
10482fe59f50SNicholas Piggin 	}
10496bad6bccSThomas Gleixner 
1050dc1e7dc5SAnna-Maria Gleixner 	debug_timer_activate(timer);
1051fd45bb77SThomas Gleixner 
10525cee9645SThomas Gleixner 	timer->expires = expires;
1053f00c0afdSAnna-Maria Gleixner 	/*
1054f00c0afdSAnna-Maria Gleixner 	 * If 'idx' was calculated above and the base time did not advance
10554da9152aSThomas Gleixner 	 * between calculating 'idx' and possibly switching the base, only
10564da9152aSThomas Gleixner 	 * enqueue_timer() and trigger_dyntick_cpu() is required. Otherwise
10574da9152aSThomas Gleixner 	 * we need to (re)calculate the wheel index via
10584da9152aSThomas Gleixner 	 * internal_add_timer().
1059f00c0afdSAnna-Maria Gleixner 	 */
1060f00c0afdSAnna-Maria Gleixner 	if (idx != UINT_MAX && clk == base->clk) {
1061f00c0afdSAnna-Maria Gleixner 		enqueue_timer(base, timer, idx);
1062f00c0afdSAnna-Maria Gleixner 		trigger_dyntick_cpu(base, timer);
1063f00c0afdSAnna-Maria Gleixner 	} else {
10645cee9645SThomas Gleixner 		internal_add_timer(base, timer);
1065f00c0afdSAnna-Maria Gleixner 	}
10665cee9645SThomas Gleixner 
10675cee9645SThomas Gleixner out_unlock:
10682287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&base->lock, flags);
10695cee9645SThomas Gleixner 
10705cee9645SThomas Gleixner 	return ret;
10715cee9645SThomas Gleixner }
10725cee9645SThomas Gleixner 
10735cee9645SThomas Gleixner /**
10745cee9645SThomas Gleixner  * mod_timer_pending - modify a pending timer's timeout
10755cee9645SThomas Gleixner  * @timer: the pending timer to be modified
10765cee9645SThomas Gleixner  * @expires: new timeout in jiffies
10775cee9645SThomas Gleixner  *
10785cee9645SThomas Gleixner  * mod_timer_pending() is the same for pending timers as mod_timer(),
10795cee9645SThomas Gleixner  * but will not re-activate and modify already deleted timers.
10805cee9645SThomas Gleixner  *
10815cee9645SThomas Gleixner  * It is useful for unserialized use of timers.
10825cee9645SThomas Gleixner  */
10835cee9645SThomas Gleixner int mod_timer_pending(struct timer_list *timer, unsigned long expires)
10845cee9645SThomas Gleixner {
1085b24591e2SDavid Howells 	return __mod_timer(timer, expires, MOD_TIMER_PENDING_ONLY);
10865cee9645SThomas Gleixner }
10875cee9645SThomas Gleixner EXPORT_SYMBOL(mod_timer_pending);
10885cee9645SThomas Gleixner 
10895cee9645SThomas Gleixner /**
10905cee9645SThomas Gleixner  * mod_timer - modify a timer's timeout
10915cee9645SThomas Gleixner  * @timer: the timer to be modified
10925cee9645SThomas Gleixner  * @expires: new timeout in jiffies
10935cee9645SThomas Gleixner  *
10945cee9645SThomas Gleixner  * mod_timer() is a more efficient way to update the expire field of an
10955cee9645SThomas Gleixner  * active timer (if the timer is inactive it will be activated)
10965cee9645SThomas Gleixner  *
10975cee9645SThomas Gleixner  * mod_timer(timer, expires) is equivalent to:
10985cee9645SThomas Gleixner  *
10995cee9645SThomas Gleixner  *     del_timer(timer); timer->expires = expires; add_timer(timer);
11005cee9645SThomas Gleixner  *
11015cee9645SThomas Gleixner  * Note that if there are multiple unserialized concurrent users of the
11025cee9645SThomas Gleixner  * same timer, then mod_timer() is the only safe way to modify the timeout,
11035cee9645SThomas Gleixner  * since add_timer() cannot modify an already running timer.
11045cee9645SThomas Gleixner  *
11055cee9645SThomas Gleixner  * The function returns whether it has modified a pending timer or not.
11065cee9645SThomas Gleixner  * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
11075cee9645SThomas Gleixner  * active timer returns 1.)
11085cee9645SThomas Gleixner  */
11095cee9645SThomas Gleixner int mod_timer(struct timer_list *timer, unsigned long expires)
11105cee9645SThomas Gleixner {
1111b24591e2SDavid Howells 	return __mod_timer(timer, expires, 0);
11125cee9645SThomas Gleixner }
11135cee9645SThomas Gleixner EXPORT_SYMBOL(mod_timer);
11145cee9645SThomas Gleixner 
11155cee9645SThomas Gleixner /**
1116b24591e2SDavid Howells  * timer_reduce - Modify a timer's timeout if it would reduce the timeout
1117b24591e2SDavid Howells  * @timer:	The timer to be modified
1118b24591e2SDavid Howells  * @expires:	New timeout in jiffies
1119b24591e2SDavid Howells  *
1120b24591e2SDavid Howells  * timer_reduce() is very similar to mod_timer(), except that it will only
1121b24591e2SDavid Howells  * modify a running timer if that would reduce the expiration time (it will
1122b24591e2SDavid Howells  * start a timer that isn't running).
1123b24591e2SDavid Howells  */
1124b24591e2SDavid Howells int timer_reduce(struct timer_list *timer, unsigned long expires)
1125b24591e2SDavid Howells {
1126b24591e2SDavid Howells 	return __mod_timer(timer, expires, MOD_TIMER_REDUCE);
1127b24591e2SDavid Howells }
1128b24591e2SDavid Howells EXPORT_SYMBOL(timer_reduce);
1129b24591e2SDavid Howells 
1130b24591e2SDavid Howells /**
11315cee9645SThomas Gleixner  * add_timer - start a timer
11325cee9645SThomas Gleixner  * @timer: the timer to be added
11335cee9645SThomas Gleixner  *
1134c1eba5bcSKees Cook  * The kernel will do a ->function(@timer) callback from the
11355cee9645SThomas Gleixner  * timer interrupt at the ->expires point in the future. The
11365cee9645SThomas Gleixner  * current time is 'jiffies'.
11375cee9645SThomas Gleixner  *
1138c1eba5bcSKees Cook  * The timer's ->expires, ->function fields must be set prior calling this
1139c1eba5bcSKees Cook  * function.
11405cee9645SThomas Gleixner  *
11415cee9645SThomas Gleixner  * Timers with an ->expires field in the past will be executed in the next
11425cee9645SThomas Gleixner  * timer tick.
11435cee9645SThomas Gleixner  */
11445cee9645SThomas Gleixner void add_timer(struct timer_list *timer)
11455cee9645SThomas Gleixner {
11465cee9645SThomas Gleixner 	BUG_ON(timer_pending(timer));
114790c01894SEric Dumazet 	__mod_timer(timer, timer->expires, MOD_TIMER_NOTPENDING);
11485cee9645SThomas Gleixner }
11495cee9645SThomas Gleixner EXPORT_SYMBOL(add_timer);
11505cee9645SThomas Gleixner 
11515cee9645SThomas Gleixner /**
11525cee9645SThomas Gleixner  * add_timer_on - start a timer on a particular CPU
11535cee9645SThomas Gleixner  * @timer: the timer to be added
11545cee9645SThomas Gleixner  * @cpu: the CPU to start it on
11555cee9645SThomas Gleixner  *
11565cee9645SThomas Gleixner  * This is not very scalable on SMP. Double adds are not possible.
11575cee9645SThomas Gleixner  */
11585cee9645SThomas Gleixner void add_timer_on(struct timer_list *timer, int cpu)
11595cee9645SThomas Gleixner {
1160500462a9SThomas Gleixner 	struct timer_base *new_base, *base;
11615cee9645SThomas Gleixner 	unsigned long flags;
11625cee9645SThomas Gleixner 
11635cee9645SThomas Gleixner 	BUG_ON(timer_pending(timer) || !timer->function);
116422b886ddSTejun Heo 
1165500462a9SThomas Gleixner 	new_base = get_timer_cpu_base(timer->flags, cpu);
1166500462a9SThomas Gleixner 
116722b886ddSTejun Heo 	/*
116822b886ddSTejun Heo 	 * If @timer was on a different CPU, it should be migrated with the
116922b886ddSTejun Heo 	 * old base locked to prevent other operations proceeding with the
117022b886ddSTejun Heo 	 * wrong base locked.  See lock_timer_base().
117122b886ddSTejun Heo 	 */
117222b886ddSTejun Heo 	base = lock_timer_base(timer, &flags);
117322b886ddSTejun Heo 	if (base != new_base) {
117422b886ddSTejun Heo 		timer->flags |= TIMER_MIGRATING;
117522b886ddSTejun Heo 
11762287d866SSebastian Andrzej Siewior 		raw_spin_unlock(&base->lock);
117722b886ddSTejun Heo 		base = new_base;
11782287d866SSebastian Andrzej Siewior 		raw_spin_lock(&base->lock);
117922b886ddSTejun Heo 		WRITE_ONCE(timer->flags,
118022b886ddSTejun Heo 			   (timer->flags & ~TIMER_BASEMASK) | cpu);
118122b886ddSTejun Heo 	}
11822fe59f50SNicholas Piggin 	forward_timer_base(base);
118322b886ddSTejun Heo 
1184dc1e7dc5SAnna-Maria Gleixner 	debug_timer_activate(timer);
11855cee9645SThomas Gleixner 	internal_add_timer(base, timer);
11862287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&base->lock, flags);
11875cee9645SThomas Gleixner }
11885cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(add_timer_on);
11895cee9645SThomas Gleixner 
11905cee9645SThomas Gleixner /**
11910ba42a59SMasanari Iida  * del_timer - deactivate a timer.
11925cee9645SThomas Gleixner  * @timer: the timer to be deactivated
11935cee9645SThomas Gleixner  *
11945cee9645SThomas Gleixner  * del_timer() deactivates a timer - this works on both active and inactive
11955cee9645SThomas Gleixner  * timers.
11965cee9645SThomas Gleixner  *
11975cee9645SThomas Gleixner  * The function returns whether it has deactivated a pending timer or not.
11985cee9645SThomas Gleixner  * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
11995cee9645SThomas Gleixner  * active timer returns 1.)
12005cee9645SThomas Gleixner  */
12015cee9645SThomas Gleixner int del_timer(struct timer_list *timer)
12025cee9645SThomas Gleixner {
1203494af3edSThomas Gleixner 	struct timer_base *base;
12045cee9645SThomas Gleixner 	unsigned long flags;
12055cee9645SThomas Gleixner 	int ret = 0;
12065cee9645SThomas Gleixner 
12075cee9645SThomas Gleixner 	debug_assert_init(timer);
12085cee9645SThomas Gleixner 
12095cee9645SThomas Gleixner 	if (timer_pending(timer)) {
12105cee9645SThomas Gleixner 		base = lock_timer_base(timer, &flags);
12115cee9645SThomas Gleixner 		ret = detach_if_pending(timer, base, true);
12122287d866SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&base->lock, flags);
12135cee9645SThomas Gleixner 	}
12145cee9645SThomas Gleixner 
12155cee9645SThomas Gleixner 	return ret;
12165cee9645SThomas Gleixner }
12175cee9645SThomas Gleixner EXPORT_SYMBOL(del_timer);
12185cee9645SThomas Gleixner 
12195cee9645SThomas Gleixner /**
12205cee9645SThomas Gleixner  * try_to_del_timer_sync - Try to deactivate a timer
1221d15bc69aSPeter Meerwald-Stadler  * @timer: timer to delete
12225cee9645SThomas Gleixner  *
12235cee9645SThomas Gleixner  * This function tries to deactivate a timer. Upon successful (ret >= 0)
12245cee9645SThomas Gleixner  * exit the timer is not queued and the handler is not running on any CPU.
12255cee9645SThomas Gleixner  */
12265cee9645SThomas Gleixner int try_to_del_timer_sync(struct timer_list *timer)
12275cee9645SThomas Gleixner {
1228494af3edSThomas Gleixner 	struct timer_base *base;
12295cee9645SThomas Gleixner 	unsigned long flags;
12305cee9645SThomas Gleixner 	int ret = -1;
12315cee9645SThomas Gleixner 
12325cee9645SThomas Gleixner 	debug_assert_init(timer);
12335cee9645SThomas Gleixner 
12345cee9645SThomas Gleixner 	base = lock_timer_base(timer, &flags);
12355cee9645SThomas Gleixner 
1236dfb4357dSKees Cook 	if (base->running_timer != timer)
12375cee9645SThomas Gleixner 		ret = detach_if_pending(timer, base, true);
1238dfb4357dSKees Cook 
12392287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&base->lock, flags);
12405cee9645SThomas Gleixner 
12415cee9645SThomas Gleixner 	return ret;
12425cee9645SThomas Gleixner }
12435cee9645SThomas Gleixner EXPORT_SYMBOL(try_to_del_timer_sync);
12445cee9645SThomas Gleixner 
1245030dcdd1SAnna-Maria Gleixner #ifdef CONFIG_PREEMPT_RT
1246030dcdd1SAnna-Maria Gleixner static __init void timer_base_init_expiry_lock(struct timer_base *base)
1247030dcdd1SAnna-Maria Gleixner {
1248030dcdd1SAnna-Maria Gleixner 	spin_lock_init(&base->expiry_lock);
1249030dcdd1SAnna-Maria Gleixner }
1250030dcdd1SAnna-Maria Gleixner 
1251030dcdd1SAnna-Maria Gleixner static inline void timer_base_lock_expiry(struct timer_base *base)
1252030dcdd1SAnna-Maria Gleixner {
1253030dcdd1SAnna-Maria Gleixner 	spin_lock(&base->expiry_lock);
1254030dcdd1SAnna-Maria Gleixner }
1255030dcdd1SAnna-Maria Gleixner 
1256030dcdd1SAnna-Maria Gleixner static inline void timer_base_unlock_expiry(struct timer_base *base)
1257030dcdd1SAnna-Maria Gleixner {
1258030dcdd1SAnna-Maria Gleixner 	spin_unlock(&base->expiry_lock);
1259030dcdd1SAnna-Maria Gleixner }
1260030dcdd1SAnna-Maria Gleixner 
1261030dcdd1SAnna-Maria Gleixner /*
1262030dcdd1SAnna-Maria Gleixner  * The counterpart to del_timer_wait_running().
1263030dcdd1SAnna-Maria Gleixner  *
1264030dcdd1SAnna-Maria Gleixner  * If there is a waiter for base->expiry_lock, then it was waiting for the
1265030dcdd1SAnna-Maria Gleixner  * timer callback to finish. Drop expiry_lock and reaquire it. That allows
1266030dcdd1SAnna-Maria Gleixner  * the waiter to acquire the lock and make progress.
1267030dcdd1SAnna-Maria Gleixner  */
1268030dcdd1SAnna-Maria Gleixner static void timer_sync_wait_running(struct timer_base *base)
1269030dcdd1SAnna-Maria Gleixner {
1270030dcdd1SAnna-Maria Gleixner 	if (atomic_read(&base->timer_waiters)) {
1271030dcdd1SAnna-Maria Gleixner 		spin_unlock(&base->expiry_lock);
1272030dcdd1SAnna-Maria Gleixner 		spin_lock(&base->expiry_lock);
1273030dcdd1SAnna-Maria Gleixner 	}
1274030dcdd1SAnna-Maria Gleixner }
1275030dcdd1SAnna-Maria Gleixner 
1276030dcdd1SAnna-Maria Gleixner /*
1277030dcdd1SAnna-Maria Gleixner  * This function is called on PREEMPT_RT kernels when the fast path
1278030dcdd1SAnna-Maria Gleixner  * deletion of a timer failed because the timer callback function was
1279030dcdd1SAnna-Maria Gleixner  * running.
1280030dcdd1SAnna-Maria Gleixner  *
1281030dcdd1SAnna-Maria Gleixner  * This prevents priority inversion, if the softirq thread on a remote CPU
1282030dcdd1SAnna-Maria Gleixner  * got preempted, and it prevents a life lock when the task which tries to
1283030dcdd1SAnna-Maria Gleixner  * delete a timer preempted the softirq thread running the timer callback
1284030dcdd1SAnna-Maria Gleixner  * function.
1285030dcdd1SAnna-Maria Gleixner  */
1286030dcdd1SAnna-Maria Gleixner static void del_timer_wait_running(struct timer_list *timer)
1287030dcdd1SAnna-Maria Gleixner {
1288030dcdd1SAnna-Maria Gleixner 	u32 tf;
1289030dcdd1SAnna-Maria Gleixner 
1290030dcdd1SAnna-Maria Gleixner 	tf = READ_ONCE(timer->flags);
1291030dcdd1SAnna-Maria Gleixner 	if (!(tf & TIMER_MIGRATING)) {
1292030dcdd1SAnna-Maria Gleixner 		struct timer_base *base = get_timer_base(tf);
1293030dcdd1SAnna-Maria Gleixner 
1294030dcdd1SAnna-Maria Gleixner 		/*
1295030dcdd1SAnna-Maria Gleixner 		 * Mark the base as contended and grab the expiry lock,
1296030dcdd1SAnna-Maria Gleixner 		 * which is held by the softirq across the timer
1297030dcdd1SAnna-Maria Gleixner 		 * callback. Drop the lock immediately so the softirq can
1298030dcdd1SAnna-Maria Gleixner 		 * expire the next timer. In theory the timer could already
1299030dcdd1SAnna-Maria Gleixner 		 * be running again, but that's more than unlikely and just
1300030dcdd1SAnna-Maria Gleixner 		 * causes another wait loop.
1301030dcdd1SAnna-Maria Gleixner 		 */
1302030dcdd1SAnna-Maria Gleixner 		atomic_inc(&base->timer_waiters);
1303030dcdd1SAnna-Maria Gleixner 		spin_lock_bh(&base->expiry_lock);
1304030dcdd1SAnna-Maria Gleixner 		atomic_dec(&base->timer_waiters);
1305030dcdd1SAnna-Maria Gleixner 		spin_unlock_bh(&base->expiry_lock);
1306030dcdd1SAnna-Maria Gleixner 	}
1307030dcdd1SAnna-Maria Gleixner }
1308030dcdd1SAnna-Maria Gleixner #else
1309030dcdd1SAnna-Maria Gleixner static inline void timer_base_init_expiry_lock(struct timer_base *base) { }
1310030dcdd1SAnna-Maria Gleixner static inline void timer_base_lock_expiry(struct timer_base *base) { }
1311030dcdd1SAnna-Maria Gleixner static inline void timer_base_unlock_expiry(struct timer_base *base) { }
1312030dcdd1SAnna-Maria Gleixner static inline void timer_sync_wait_running(struct timer_base *base) { }
1313030dcdd1SAnna-Maria Gleixner static inline void del_timer_wait_running(struct timer_list *timer) { }
1314030dcdd1SAnna-Maria Gleixner #endif
1315030dcdd1SAnna-Maria Gleixner 
1316030dcdd1SAnna-Maria Gleixner #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT_RT)
13175cee9645SThomas Gleixner /**
13185cee9645SThomas Gleixner  * del_timer_sync - deactivate a timer and wait for the handler to finish.
13195cee9645SThomas Gleixner  * @timer: the timer to be deactivated
13205cee9645SThomas Gleixner  *
13215cee9645SThomas Gleixner  * This function only differs from del_timer() on SMP: besides deactivating
13225cee9645SThomas Gleixner  * the timer it also makes sure the handler has finished executing on other
13235cee9645SThomas Gleixner  * CPUs.
13245cee9645SThomas Gleixner  *
13255cee9645SThomas Gleixner  * Synchronization rules: Callers must prevent restarting of the timer,
13265cee9645SThomas Gleixner  * otherwise this function is meaningless. It must not be called from
13275cee9645SThomas Gleixner  * interrupt contexts unless the timer is an irqsafe one. The caller must
13285cee9645SThomas Gleixner  * not hold locks which would prevent completion of the timer's
13295cee9645SThomas Gleixner  * handler. The timer's handler must not call add_timer_on(). Upon exit the
13305cee9645SThomas Gleixner  * timer is not queued and the handler is not running on any CPU.
13315cee9645SThomas Gleixner  *
13325cee9645SThomas Gleixner  * Note: For !irqsafe timers, you must not hold locks that are held in
13335cee9645SThomas Gleixner  *   interrupt context while calling this function. Even if the lock has
1334bf9c96beSMauro Carvalho Chehab  *   nothing to do with the timer in question.  Here's why::
13355cee9645SThomas Gleixner  *
13365cee9645SThomas Gleixner  *    CPU0                             CPU1
13375cee9645SThomas Gleixner  *    ----                             ----
13385cee9645SThomas Gleixner  *                                     <SOFTIRQ>
13395cee9645SThomas Gleixner  *                                       call_timer_fn();
13405cee9645SThomas Gleixner  *                                       base->running_timer = mytimer;
13415cee9645SThomas Gleixner  *    spin_lock_irq(somelock);
13425cee9645SThomas Gleixner  *                                     <IRQ>
13435cee9645SThomas Gleixner  *                                        spin_lock(somelock);
13445cee9645SThomas Gleixner  *    del_timer_sync(mytimer);
13455cee9645SThomas Gleixner  *    while (base->running_timer == mytimer);
13465cee9645SThomas Gleixner  *
13475cee9645SThomas Gleixner  * Now del_timer_sync() will never return and never release somelock.
13485cee9645SThomas Gleixner  * The interrupt on the other CPU is waiting to grab somelock but
13495cee9645SThomas Gleixner  * it has interrupted the softirq that CPU0 is waiting to finish.
13505cee9645SThomas Gleixner  *
13515cee9645SThomas Gleixner  * The function returns whether it has deactivated a pending timer or not.
13525cee9645SThomas Gleixner  */
13535cee9645SThomas Gleixner int del_timer_sync(struct timer_list *timer)
13545cee9645SThomas Gleixner {
1355030dcdd1SAnna-Maria Gleixner 	int ret;
1356030dcdd1SAnna-Maria Gleixner 
13575cee9645SThomas Gleixner #ifdef CONFIG_LOCKDEP
13585cee9645SThomas Gleixner 	unsigned long flags;
13595cee9645SThomas Gleixner 
13605cee9645SThomas Gleixner 	/*
13615cee9645SThomas Gleixner 	 * If lockdep gives a backtrace here, please reference
13625cee9645SThomas Gleixner 	 * the synchronization rules above.
13635cee9645SThomas Gleixner 	 */
13645cee9645SThomas Gleixner 	local_irq_save(flags);
13655cee9645SThomas Gleixner 	lock_map_acquire(&timer->lockdep_map);
13665cee9645SThomas Gleixner 	lock_map_release(&timer->lockdep_map);
13675cee9645SThomas Gleixner 	local_irq_restore(flags);
13685cee9645SThomas Gleixner #endif
13695cee9645SThomas Gleixner 	/*
13705cee9645SThomas Gleixner 	 * don't use it in hardirq context, because it
13715cee9645SThomas Gleixner 	 * could lead to deadlock.
13725cee9645SThomas Gleixner 	 */
13730eeda71bSThomas Gleixner 	WARN_ON(in_irq() && !(timer->flags & TIMER_IRQSAFE));
1374030dcdd1SAnna-Maria Gleixner 
1375030dcdd1SAnna-Maria Gleixner 	do {
1376030dcdd1SAnna-Maria Gleixner 		ret = try_to_del_timer_sync(timer);
1377030dcdd1SAnna-Maria Gleixner 
1378030dcdd1SAnna-Maria Gleixner 		if (unlikely(ret < 0)) {
1379030dcdd1SAnna-Maria Gleixner 			del_timer_wait_running(timer);
13805cee9645SThomas Gleixner 			cpu_relax();
13815cee9645SThomas Gleixner 		}
1382030dcdd1SAnna-Maria Gleixner 	} while (ret < 0);
1383030dcdd1SAnna-Maria Gleixner 
1384030dcdd1SAnna-Maria Gleixner 	return ret;
13855cee9645SThomas Gleixner }
13865cee9645SThomas Gleixner EXPORT_SYMBOL(del_timer_sync);
13875cee9645SThomas Gleixner #endif
13885cee9645SThomas Gleixner 
1389f28d3d53SAnna-Maria Gleixner static void call_timer_fn(struct timer_list *timer,
1390f28d3d53SAnna-Maria Gleixner 			  void (*fn)(struct timer_list *),
1391f28d3d53SAnna-Maria Gleixner 			  unsigned long baseclk)
13925cee9645SThomas Gleixner {
13935cee9645SThomas Gleixner 	int count = preempt_count();
13945cee9645SThomas Gleixner 
13955cee9645SThomas Gleixner #ifdef CONFIG_LOCKDEP
13965cee9645SThomas Gleixner 	/*
13975cee9645SThomas Gleixner 	 * It is permissible to free the timer from inside the
13985cee9645SThomas Gleixner 	 * function that is called from it, this we need to take into
13995cee9645SThomas Gleixner 	 * account for lockdep too. To avoid bogus "held lock freed"
14005cee9645SThomas Gleixner 	 * warnings as well as problems when looking into
14015cee9645SThomas Gleixner 	 * timer->lockdep_map, make a copy and use that here.
14025cee9645SThomas Gleixner 	 */
14035cee9645SThomas Gleixner 	struct lockdep_map lockdep_map;
14045cee9645SThomas Gleixner 
14055cee9645SThomas Gleixner 	lockdep_copy_map(&lockdep_map, &timer->lockdep_map);
14065cee9645SThomas Gleixner #endif
14075cee9645SThomas Gleixner 	/*
14085cee9645SThomas Gleixner 	 * Couple the lock chain with the lock chain at
14095cee9645SThomas Gleixner 	 * del_timer_sync() by acquiring the lock_map around the fn()
14105cee9645SThomas Gleixner 	 * call here and in del_timer_sync().
14115cee9645SThomas Gleixner 	 */
14125cee9645SThomas Gleixner 	lock_map_acquire(&lockdep_map);
14135cee9645SThomas Gleixner 
1414f28d3d53SAnna-Maria Gleixner 	trace_timer_expire_entry(timer, baseclk);
1415354b46b1SKees Cook 	fn(timer);
14165cee9645SThomas Gleixner 	trace_timer_expire_exit(timer);
14175cee9645SThomas Gleixner 
14185cee9645SThomas Gleixner 	lock_map_release(&lockdep_map);
14195cee9645SThomas Gleixner 
14205cee9645SThomas Gleixner 	if (count != preempt_count()) {
1421d75f773cSSakari Ailus 		WARN_ONCE(1, "timer: %pS preempt leak: %08x -> %08x\n",
14225cee9645SThomas Gleixner 			  fn, count, preempt_count());
14235cee9645SThomas Gleixner 		/*
14245cee9645SThomas Gleixner 		 * Restore the preempt count. That gives us a decent
14255cee9645SThomas Gleixner 		 * chance to survive and extract information. If the
14265cee9645SThomas Gleixner 		 * callback kept a lock held, bad luck, but not worse
14275cee9645SThomas Gleixner 		 * than the BUG() we had.
14285cee9645SThomas Gleixner 		 */
14295cee9645SThomas Gleixner 		preempt_count_set(count);
14305cee9645SThomas Gleixner 	}
14315cee9645SThomas Gleixner }
14325cee9645SThomas Gleixner 
1433500462a9SThomas Gleixner static void expire_timers(struct timer_base *base, struct hlist_head *head)
14345cee9645SThomas Gleixner {
1435f28d3d53SAnna-Maria Gleixner 	/*
1436f28d3d53SAnna-Maria Gleixner 	 * This value is required only for tracing. base->clk was
1437f28d3d53SAnna-Maria Gleixner 	 * incremented directly before expire_timers was called. But expiry
1438f28d3d53SAnna-Maria Gleixner 	 * is related to the old base->clk value.
1439f28d3d53SAnna-Maria Gleixner 	 */
1440f28d3d53SAnna-Maria Gleixner 	unsigned long baseclk = base->clk - 1;
1441f28d3d53SAnna-Maria Gleixner 
14421dabbcecSThomas Gleixner 	while (!hlist_empty(head)) {
1443500462a9SThomas Gleixner 		struct timer_list *timer;
1444354b46b1SKees Cook 		void (*fn)(struct timer_list *);
14455cee9645SThomas Gleixner 
14461dabbcecSThomas Gleixner 		timer = hlist_entry(head->first, struct timer_list, entry);
14475cee9645SThomas Gleixner 
14485cee9645SThomas Gleixner 		base->running_timer = timer;
1449500462a9SThomas Gleixner 		detach_timer(timer, true);
14505cee9645SThomas Gleixner 
1451500462a9SThomas Gleixner 		fn = timer->function;
1452500462a9SThomas Gleixner 
1453500462a9SThomas Gleixner 		if (timer->flags & TIMER_IRQSAFE) {
14542287d866SSebastian Andrzej Siewior 			raw_spin_unlock(&base->lock);
1455f28d3d53SAnna-Maria Gleixner 			call_timer_fn(timer, fn, baseclk);
1456030dcdd1SAnna-Maria Gleixner 			base->running_timer = NULL;
14572287d866SSebastian Andrzej Siewior 			raw_spin_lock(&base->lock);
14585cee9645SThomas Gleixner 		} else {
14592287d866SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&base->lock);
1460f28d3d53SAnna-Maria Gleixner 			call_timer_fn(timer, fn, baseclk);
1461030dcdd1SAnna-Maria Gleixner 			base->running_timer = NULL;
1462030dcdd1SAnna-Maria Gleixner 			timer_sync_wait_running(base);
14632287d866SSebastian Andrzej Siewior 			raw_spin_lock_irq(&base->lock);
14645cee9645SThomas Gleixner 		}
14655cee9645SThomas Gleixner 	}
14665cee9645SThomas Gleixner }
1467500462a9SThomas Gleixner 
146823696838SAnna-Maria Gleixner static int __collect_expired_timers(struct timer_base *base,
1469500462a9SThomas Gleixner 				    struct hlist_head *heads)
1470500462a9SThomas Gleixner {
1471500462a9SThomas Gleixner 	unsigned long clk = base->clk;
1472500462a9SThomas Gleixner 	struct hlist_head *vec;
1473500462a9SThomas Gleixner 	int i, levels = 0;
1474500462a9SThomas Gleixner 	unsigned int idx;
1475500462a9SThomas Gleixner 
1476500462a9SThomas Gleixner 	for (i = 0; i < LVL_DEPTH; i++) {
1477500462a9SThomas Gleixner 		idx = (clk & LVL_MASK) + i * LVL_SIZE;
1478500462a9SThomas Gleixner 
1479500462a9SThomas Gleixner 		if (__test_and_clear_bit(idx, base->pending_map)) {
1480500462a9SThomas Gleixner 			vec = base->vectors + idx;
1481500462a9SThomas Gleixner 			hlist_move_list(vec, heads++);
1482500462a9SThomas Gleixner 			levels++;
1483500462a9SThomas Gleixner 		}
1484500462a9SThomas Gleixner 		/* Is it time to look at the next level? */
1485500462a9SThomas Gleixner 		if (clk & LVL_CLK_MASK)
1486500462a9SThomas Gleixner 			break;
1487500462a9SThomas Gleixner 		/* Shift clock for the next level granularity */
1488500462a9SThomas Gleixner 		clk >>= LVL_CLK_SHIFT;
1489500462a9SThomas Gleixner 	}
1490500462a9SThomas Gleixner 	return levels;
14915cee9645SThomas Gleixner }
14925cee9645SThomas Gleixner 
14935cee9645SThomas Gleixner #ifdef CONFIG_NO_HZ_COMMON
14945cee9645SThomas Gleixner /*
149523696838SAnna-Maria Gleixner  * Find the next pending bucket of a level. Search from level start (@offset)
149623696838SAnna-Maria Gleixner  * + @clk upwards and if nothing there, search from start of the level
149723696838SAnna-Maria Gleixner  * (@offset) up to @offset + clk.
14985cee9645SThomas Gleixner  */
1499500462a9SThomas Gleixner static int next_pending_bucket(struct timer_base *base, unsigned offset,
1500500462a9SThomas Gleixner 			       unsigned clk)
15015cee9645SThomas Gleixner {
1502500462a9SThomas Gleixner 	unsigned pos, start = offset + clk;
1503500462a9SThomas Gleixner 	unsigned end = offset + LVL_SIZE;
15045cee9645SThomas Gleixner 
1505500462a9SThomas Gleixner 	pos = find_next_bit(base->pending_map, end, start);
1506500462a9SThomas Gleixner 	if (pos < end)
1507500462a9SThomas Gleixner 		return pos - start;
15085cee9645SThomas Gleixner 
1509500462a9SThomas Gleixner 	pos = find_next_bit(base->pending_map, start, offset);
1510500462a9SThomas Gleixner 	return pos < start ? pos + LVL_SIZE - start : -1;
15115cee9645SThomas Gleixner }
15125cee9645SThomas Gleixner 
1513500462a9SThomas Gleixner /*
151423696838SAnna-Maria Gleixner  * Search the first expiring timer in the various clock levels. Caller must
151523696838SAnna-Maria Gleixner  * hold base->lock.
15165cee9645SThomas Gleixner  */
1517494af3edSThomas Gleixner static unsigned long __next_timer_interrupt(struct timer_base *base)
15185cee9645SThomas Gleixner {
1519500462a9SThomas Gleixner 	unsigned long clk, next, adj;
1520500462a9SThomas Gleixner 	unsigned lvl, offset = 0;
15215cee9645SThomas Gleixner 
1522500462a9SThomas Gleixner 	next = base->clk + NEXT_TIMER_MAX_DELTA;
1523500462a9SThomas Gleixner 	clk = base->clk;
1524500462a9SThomas Gleixner 	for (lvl = 0; lvl < LVL_DEPTH; lvl++, offset += LVL_SIZE) {
1525500462a9SThomas Gleixner 		int pos = next_pending_bucket(base, offset, clk & LVL_MASK);
15265cee9645SThomas Gleixner 
1527500462a9SThomas Gleixner 		if (pos >= 0) {
1528500462a9SThomas Gleixner 			unsigned long tmp = clk + (unsigned long) pos;
15295cee9645SThomas Gleixner 
1530500462a9SThomas Gleixner 			tmp <<= LVL_SHIFT(lvl);
1531500462a9SThomas Gleixner 			if (time_before(tmp, next))
1532500462a9SThomas Gleixner 				next = tmp;
15335cee9645SThomas Gleixner 		}
15345cee9645SThomas Gleixner 		/*
1535500462a9SThomas Gleixner 		 * Clock for the next level. If the current level clock lower
1536500462a9SThomas Gleixner 		 * bits are zero, we look at the next level as is. If not we
1537500462a9SThomas Gleixner 		 * need to advance it by one because that's going to be the
1538500462a9SThomas Gleixner 		 * next expiring bucket in that level. base->clk is the next
1539500462a9SThomas Gleixner 		 * expiring jiffie. So in case of:
1540500462a9SThomas Gleixner 		 *
1541500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1542500462a9SThomas Gleixner 		 *  0    0    0    0    0    0
1543500462a9SThomas Gleixner 		 *
1544500462a9SThomas Gleixner 		 * we have to look at all levels @index 0. With
1545500462a9SThomas Gleixner 		 *
1546500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1547500462a9SThomas Gleixner 		 *  0    0    0    0    0    2
1548500462a9SThomas Gleixner 		 *
1549500462a9SThomas Gleixner 		 * LVL0 has the next expiring bucket @index 2. The upper
1550500462a9SThomas Gleixner 		 * levels have the next expiring bucket @index 1.
1551500462a9SThomas Gleixner 		 *
1552500462a9SThomas Gleixner 		 * In case that the propagation wraps the next level the same
1553500462a9SThomas Gleixner 		 * rules apply:
1554500462a9SThomas Gleixner 		 *
1555500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1556500462a9SThomas Gleixner 		 *  0    0    0    0    F    2
1557500462a9SThomas Gleixner 		 *
1558500462a9SThomas Gleixner 		 * So after looking at LVL0 we get:
1559500462a9SThomas Gleixner 		 *
1560500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1
1561500462a9SThomas Gleixner 		 *  0    0    0    1    0
1562500462a9SThomas Gleixner 		 *
1563500462a9SThomas Gleixner 		 * So no propagation from LVL1 to LVL2 because that happened
1564500462a9SThomas Gleixner 		 * with the add already, but then we need to propagate further
1565500462a9SThomas Gleixner 		 * from LVL2 to LVL3.
1566500462a9SThomas Gleixner 		 *
1567500462a9SThomas Gleixner 		 * So the simple check whether the lower bits of the current
1568500462a9SThomas Gleixner 		 * level are 0 or not is sufficient for all cases.
15695cee9645SThomas Gleixner 		 */
1570500462a9SThomas Gleixner 		adj = clk & LVL_CLK_MASK ? 1 : 0;
1571500462a9SThomas Gleixner 		clk >>= LVL_CLK_SHIFT;
1572500462a9SThomas Gleixner 		clk += adj;
15735cee9645SThomas Gleixner 	}
1574500462a9SThomas Gleixner 	return next;
15755cee9645SThomas Gleixner }
15765cee9645SThomas Gleixner 
15775cee9645SThomas Gleixner /*
15785cee9645SThomas Gleixner  * Check, if the next hrtimer event is before the next timer wheel
15795cee9645SThomas Gleixner  * event:
15805cee9645SThomas Gleixner  */
1581c1ad348bSThomas Gleixner static u64 cmp_next_hrtimer_event(u64 basem, u64 expires)
15825cee9645SThomas Gleixner {
1583c1ad348bSThomas Gleixner 	u64 nextevt = hrtimer_get_next_event();
15845cee9645SThomas Gleixner 
1585c1ad348bSThomas Gleixner 	/*
1586c1ad348bSThomas Gleixner 	 * If high resolution timers are enabled
1587c1ad348bSThomas Gleixner 	 * hrtimer_get_next_event() returns KTIME_MAX.
1588c1ad348bSThomas Gleixner 	 */
1589c1ad348bSThomas Gleixner 	if (expires <= nextevt)
15905cee9645SThomas Gleixner 		return expires;
15915cee9645SThomas Gleixner 
15925cee9645SThomas Gleixner 	/*
1593c1ad348bSThomas Gleixner 	 * If the next timer is already expired, return the tick base
1594c1ad348bSThomas Gleixner 	 * time so the tick is fired immediately.
15955cee9645SThomas Gleixner 	 */
1596c1ad348bSThomas Gleixner 	if (nextevt <= basem)
1597c1ad348bSThomas Gleixner 		return basem;
15985cee9645SThomas Gleixner 
15995cee9645SThomas Gleixner 	/*
1600c1ad348bSThomas Gleixner 	 * Round up to the next jiffie. High resolution timers are
1601c1ad348bSThomas Gleixner 	 * off, so the hrtimers are expired in the tick and we need to
1602c1ad348bSThomas Gleixner 	 * make sure that this tick really expires the timer to avoid
1603c1ad348bSThomas Gleixner 	 * a ping pong of the nohz stop code.
1604c1ad348bSThomas Gleixner 	 *
1605c1ad348bSThomas Gleixner 	 * Use DIV_ROUND_UP_ULL to prevent gcc calling __divdi3
16065cee9645SThomas Gleixner 	 */
1607c1ad348bSThomas Gleixner 	return DIV_ROUND_UP_ULL(nextevt, TICK_NSEC) * TICK_NSEC;
16085cee9645SThomas Gleixner }
16095cee9645SThomas Gleixner 
16105cee9645SThomas Gleixner /**
1611c1ad348bSThomas Gleixner  * get_next_timer_interrupt - return the time (clock mono) of the next timer
1612c1ad348bSThomas Gleixner  * @basej:	base time jiffies
1613c1ad348bSThomas Gleixner  * @basem:	base time clock monotonic
1614c1ad348bSThomas Gleixner  *
1615c1ad348bSThomas Gleixner  * Returns the tick aligned clock monotonic time of the next pending
1616c1ad348bSThomas Gleixner  * timer or KTIME_MAX if no timer is pending.
16175cee9645SThomas Gleixner  */
1618c1ad348bSThomas Gleixner u64 get_next_timer_interrupt(unsigned long basej, u64 basem)
16195cee9645SThomas Gleixner {
1620500462a9SThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1621c1ad348bSThomas Gleixner 	u64 expires = KTIME_MAX;
1622c1ad348bSThomas Gleixner 	unsigned long nextevt;
162346c8f0b0SChris Metcalf 	bool is_max_delta;
16245cee9645SThomas Gleixner 
16255cee9645SThomas Gleixner 	/*
16265cee9645SThomas Gleixner 	 * Pretend that there is no timer pending if the cpu is offline.
16275cee9645SThomas Gleixner 	 * Possible pending timers will be migrated later to an active cpu.
16285cee9645SThomas Gleixner 	 */
16295cee9645SThomas Gleixner 	if (cpu_is_offline(smp_processor_id()))
16305cee9645SThomas Gleixner 		return expires;
16315cee9645SThomas Gleixner 
16322287d866SSebastian Andrzej Siewior 	raw_spin_lock(&base->lock);
1633500462a9SThomas Gleixner 	nextevt = __next_timer_interrupt(base);
163446c8f0b0SChris Metcalf 	is_max_delta = (nextevt == base->clk + NEXT_TIMER_MAX_DELTA);
1635a683f390SThomas Gleixner 	base->next_expiry = nextevt;
1636a683f390SThomas Gleixner 	/*
1637041ad7bcSThomas Gleixner 	 * We have a fresh next event. Check whether we can forward the
1638041ad7bcSThomas Gleixner 	 * base. We can only do that when @basej is past base->clk
1639041ad7bcSThomas Gleixner 	 * otherwise we might rewind base->clk.
1640a683f390SThomas Gleixner 	 */
1641041ad7bcSThomas Gleixner 	if (time_after(basej, base->clk)) {
1642041ad7bcSThomas Gleixner 		if (time_after(nextevt, basej))
1643041ad7bcSThomas Gleixner 			base->clk = basej;
1644a683f390SThomas Gleixner 		else if (time_after(nextevt, base->clk))
1645a683f390SThomas Gleixner 			base->clk = nextevt;
1646041ad7bcSThomas Gleixner 	}
1647a683f390SThomas Gleixner 
1648a683f390SThomas Gleixner 	if (time_before_eq(nextevt, basej)) {
1649c1ad348bSThomas Gleixner 		expires = basem;
1650a683f390SThomas Gleixner 		base->is_idle = false;
1651a683f390SThomas Gleixner 	} else {
165246c8f0b0SChris Metcalf 		if (!is_max_delta)
165334f41c03SMatija Glavinic Pecotic 			expires = basem + (u64)(nextevt - basej) * TICK_NSEC;
1654a683f390SThomas Gleixner 		/*
16552fe59f50SNicholas Piggin 		 * If we expect to sleep more than a tick, mark the base idle.
16562fe59f50SNicholas Piggin 		 * Also the tick is stopped so any added timer must forward
16572fe59f50SNicholas Piggin 		 * the base clk itself to keep granularity small. This idle
16582fe59f50SNicholas Piggin 		 * logic is only maintained for the BASE_STD base, deferrable
16592fe59f50SNicholas Piggin 		 * timers may still see large granularity skew (by design).
1660a683f390SThomas Gleixner 		 */
16612fe59f50SNicholas Piggin 		if ((expires - basem) > TICK_NSEC) {
16622fe59f50SNicholas Piggin 			base->must_forward_clk = true;
1663a683f390SThomas Gleixner 			base->is_idle = true;
16645cee9645SThomas Gleixner 		}
16652fe59f50SNicholas Piggin 	}
16662287d866SSebastian Andrzej Siewior 	raw_spin_unlock(&base->lock);
16675cee9645SThomas Gleixner 
1668c1ad348bSThomas Gleixner 	return cmp_next_hrtimer_event(basem, expires);
16695cee9645SThomas Gleixner }
167023696838SAnna-Maria Gleixner 
1671a683f390SThomas Gleixner /**
1672a683f390SThomas Gleixner  * timer_clear_idle - Clear the idle state of the timer base
1673a683f390SThomas Gleixner  *
1674a683f390SThomas Gleixner  * Called with interrupts disabled
1675a683f390SThomas Gleixner  */
1676a683f390SThomas Gleixner void timer_clear_idle(void)
1677a683f390SThomas Gleixner {
1678a683f390SThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1679a683f390SThomas Gleixner 
1680a683f390SThomas Gleixner 	/*
1681a683f390SThomas Gleixner 	 * We do this unlocked. The worst outcome is a remote enqueue sending
1682a683f390SThomas Gleixner 	 * a pointless IPI, but taking the lock would just make the window for
1683a683f390SThomas Gleixner 	 * sending the IPI a few instructions smaller for the cost of taking
1684a683f390SThomas Gleixner 	 * the lock in the exit from idle path.
1685a683f390SThomas Gleixner 	 */
1686a683f390SThomas Gleixner 	base->is_idle = false;
1687a683f390SThomas Gleixner }
1688a683f390SThomas Gleixner 
168923696838SAnna-Maria Gleixner static int collect_expired_timers(struct timer_base *base,
169023696838SAnna-Maria Gleixner 				  struct hlist_head *heads)
169123696838SAnna-Maria Gleixner {
1692e430d802SLi RongQing 	unsigned long now = READ_ONCE(jiffies);
1693e430d802SLi RongQing 
169423696838SAnna-Maria Gleixner 	/*
169523696838SAnna-Maria Gleixner 	 * NOHZ optimization. After a long idle sleep we need to forward the
169623696838SAnna-Maria Gleixner 	 * base to current jiffies. Avoid a loop by searching the bitfield for
169723696838SAnna-Maria Gleixner 	 * the next expiring timer.
169823696838SAnna-Maria Gleixner 	 */
1699e430d802SLi RongQing 	if ((long)(now - base->clk) > 2) {
170023696838SAnna-Maria Gleixner 		unsigned long next = __next_timer_interrupt(base);
170123696838SAnna-Maria Gleixner 
170223696838SAnna-Maria Gleixner 		/*
170323696838SAnna-Maria Gleixner 		 * If the next timer is ahead of time forward to current
1704a683f390SThomas Gleixner 		 * jiffies, otherwise forward to the next expiry time:
170523696838SAnna-Maria Gleixner 		 */
1706e430d802SLi RongQing 		if (time_after(next, now)) {
1707c310ce4dSZhenzhong Duan 			/*
1708c310ce4dSZhenzhong Duan 			 * The call site will increment base->clk and then
1709c310ce4dSZhenzhong Duan 			 * terminate the expiry loop immediately.
1710c310ce4dSZhenzhong Duan 			 */
1711e430d802SLi RongQing 			base->clk = now;
171223696838SAnna-Maria Gleixner 			return 0;
171323696838SAnna-Maria Gleixner 		}
171423696838SAnna-Maria Gleixner 		base->clk = next;
171523696838SAnna-Maria Gleixner 	}
171623696838SAnna-Maria Gleixner 	return __collect_expired_timers(base, heads);
171723696838SAnna-Maria Gleixner }
171823696838SAnna-Maria Gleixner #else
171923696838SAnna-Maria Gleixner static inline int collect_expired_timers(struct timer_base *base,
172023696838SAnna-Maria Gleixner 					 struct hlist_head *heads)
172123696838SAnna-Maria Gleixner {
172223696838SAnna-Maria Gleixner 	return __collect_expired_timers(base, heads);
172323696838SAnna-Maria Gleixner }
17245cee9645SThomas Gleixner #endif
17255cee9645SThomas Gleixner 
17265cee9645SThomas Gleixner /*
17275cee9645SThomas Gleixner  * Called from the timer interrupt handler to charge one tick to the current
17285cee9645SThomas Gleixner  * process.  user_tick is 1 if the tick is user time, 0 for system.
17295cee9645SThomas Gleixner  */
17305cee9645SThomas Gleixner void update_process_times(int user_tick)
17315cee9645SThomas Gleixner {
17325cee9645SThomas Gleixner 	struct task_struct *p = current;
17335cee9645SThomas Gleixner 
17345cee9645SThomas Gleixner 	/* Note: this timer irq context must be accounted for as well. */
17355cee9645SThomas Gleixner 	account_process_tick(p, user_tick);
17365cee9645SThomas Gleixner 	run_local_timers();
1737c98cac60SPaul E. McKenney 	rcu_sched_clock_irq(user_tick);
17385cee9645SThomas Gleixner #ifdef CONFIG_IRQ_WORK
17395cee9645SThomas Gleixner 	if (in_irq())
174076a33061SFrederic Weisbecker 		irq_work_tick();
17415cee9645SThomas Gleixner #endif
17425cee9645SThomas Gleixner 	scheduler_tick();
1743baa73d9eSNicolas Pitre 	if (IS_ENABLED(CONFIG_POSIX_TIMERS))
1744dce3e8fdSThomas Gleixner 		run_posix_cpu_timers();
17455cee9645SThomas Gleixner }
17465cee9645SThomas Gleixner 
174773420feaSAnna-Maria Gleixner /**
174873420feaSAnna-Maria Gleixner  * __run_timers - run all expired timers (if any) on this CPU.
174973420feaSAnna-Maria Gleixner  * @base: the timer vector to be processed.
175073420feaSAnna-Maria Gleixner  */
175173420feaSAnna-Maria Gleixner static inline void __run_timers(struct timer_base *base)
175273420feaSAnna-Maria Gleixner {
175373420feaSAnna-Maria Gleixner 	struct hlist_head heads[LVL_DEPTH];
175473420feaSAnna-Maria Gleixner 	int levels;
175573420feaSAnna-Maria Gleixner 
175673420feaSAnna-Maria Gleixner 	if (!time_after_eq(jiffies, base->clk))
175773420feaSAnna-Maria Gleixner 		return;
175873420feaSAnna-Maria Gleixner 
1759030dcdd1SAnna-Maria Gleixner 	timer_base_lock_expiry(base);
17602287d866SSebastian Andrzej Siewior 	raw_spin_lock_irq(&base->lock);
176173420feaSAnna-Maria Gleixner 
1762363e934dSGaurav Kohli 	/*
1763363e934dSGaurav Kohli 	 * timer_base::must_forward_clk must be cleared before running
1764363e934dSGaurav Kohli 	 * timers so that any timer functions that call mod_timer() will
1765363e934dSGaurav Kohli 	 * not try to forward the base. Idle tracking / clock forwarding
1766363e934dSGaurav Kohli 	 * logic is only used with BASE_STD timers.
1767363e934dSGaurav Kohli 	 *
1768363e934dSGaurav Kohli 	 * The must_forward_clk flag is cleared unconditionally also for
1769363e934dSGaurav Kohli 	 * the deferrable base. The deferrable base is not affected by idle
1770363e934dSGaurav Kohli 	 * tracking and never forwarded, so clearing the flag is a NOOP.
1771363e934dSGaurav Kohli 	 *
1772363e934dSGaurav Kohli 	 * The fact that the deferrable base is never forwarded can cause
1773363e934dSGaurav Kohli 	 * large variations in granularity for deferrable timers, but they
1774363e934dSGaurav Kohli 	 * can be deferred for long periods due to idle anyway.
1775363e934dSGaurav Kohli 	 */
1776363e934dSGaurav Kohli 	base->must_forward_clk = false;
1777363e934dSGaurav Kohli 
177873420feaSAnna-Maria Gleixner 	while (time_after_eq(jiffies, base->clk)) {
177973420feaSAnna-Maria Gleixner 
178073420feaSAnna-Maria Gleixner 		levels = collect_expired_timers(base, heads);
178173420feaSAnna-Maria Gleixner 		base->clk++;
178273420feaSAnna-Maria Gleixner 
178373420feaSAnna-Maria Gleixner 		while (levels--)
178473420feaSAnna-Maria Gleixner 			expire_timers(base, heads + levels);
178573420feaSAnna-Maria Gleixner 	}
17862287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&base->lock);
1787030dcdd1SAnna-Maria Gleixner 	timer_base_unlock_expiry(base);
178873420feaSAnna-Maria Gleixner }
178973420feaSAnna-Maria Gleixner 
17905cee9645SThomas Gleixner /*
17915cee9645SThomas Gleixner  * This function runs timers and the timer-tq in bottom half context.
17925cee9645SThomas Gleixner  */
17930766f788SEmese Revfy static __latent_entropy void run_timer_softirq(struct softirq_action *h)
17945cee9645SThomas Gleixner {
1795500462a9SThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
17965cee9645SThomas Gleixner 
17975cee9645SThomas Gleixner 	__run_timers(base);
1798ced6d5c1SAnna-Maria Gleixner 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON))
1799500462a9SThomas Gleixner 		__run_timers(this_cpu_ptr(&timer_bases[BASE_DEF]));
18005cee9645SThomas Gleixner }
18015cee9645SThomas Gleixner 
18025cee9645SThomas Gleixner /*
18035cee9645SThomas Gleixner  * Called by the local, per-CPU timer interrupt on SMP.
18045cee9645SThomas Gleixner  */
18055cee9645SThomas Gleixner void run_local_timers(void)
18065cee9645SThomas Gleixner {
18074e85876aSThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
18084e85876aSThomas Gleixner 
18095cee9645SThomas Gleixner 	hrtimer_run_queues();
18104e85876aSThomas Gleixner 	/* Raise the softirq only if required. */
18114e85876aSThomas Gleixner 	if (time_before(jiffies, base->clk)) {
1812ed4bbf79SThomas Gleixner 		if (!IS_ENABLED(CONFIG_NO_HZ_COMMON))
18134e85876aSThomas Gleixner 			return;
18144e85876aSThomas Gleixner 		/* CPU is awake, so check the deferrable base. */
18154e85876aSThomas Gleixner 		base++;
18164e85876aSThomas Gleixner 		if (time_before(jiffies, base->clk))
18174e85876aSThomas Gleixner 			return;
18184e85876aSThomas Gleixner 	}
18195cee9645SThomas Gleixner 	raise_softirq(TIMER_SOFTIRQ);
18205cee9645SThomas Gleixner }
18215cee9645SThomas Gleixner 
182258e1177bSKees Cook /*
182358e1177bSKees Cook  * Since schedule_timeout()'s timer is defined on the stack, it must store
182458e1177bSKees Cook  * the target task on the stack as well.
182558e1177bSKees Cook  */
182658e1177bSKees Cook struct process_timer {
182758e1177bSKees Cook 	struct timer_list timer;
182858e1177bSKees Cook 	struct task_struct *task;
182958e1177bSKees Cook };
183058e1177bSKees Cook 
183158e1177bSKees Cook static void process_timeout(struct timer_list *t)
18325cee9645SThomas Gleixner {
183358e1177bSKees Cook 	struct process_timer *timeout = from_timer(timeout, t, timer);
183458e1177bSKees Cook 
183558e1177bSKees Cook 	wake_up_process(timeout->task);
18365cee9645SThomas Gleixner }
18375cee9645SThomas Gleixner 
18385cee9645SThomas Gleixner /**
18395cee9645SThomas Gleixner  * schedule_timeout - sleep until timeout
18405cee9645SThomas Gleixner  * @timeout: timeout value in jiffies
18415cee9645SThomas Gleixner  *
18426e317c32SAlexander Popov  * Make the current task sleep until @timeout jiffies have elapsed.
18436e317c32SAlexander Popov  * The function behavior depends on the current task state
18446e317c32SAlexander Popov  * (see also set_current_state() description):
18455cee9645SThomas Gleixner  *
18466e317c32SAlexander Popov  * %TASK_RUNNING - the scheduler is called, but the task does not sleep
18476e317c32SAlexander Popov  * at all. That happens because sched_submit_work() does nothing for
18486e317c32SAlexander Popov  * tasks in %TASK_RUNNING state.
18495cee9645SThomas Gleixner  *
18505cee9645SThomas Gleixner  * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
18514b7e9cf9SDouglas Anderson  * pass before the routine returns unless the current task is explicitly
18526e317c32SAlexander Popov  * woken up, (e.g. by wake_up_process()).
18535cee9645SThomas Gleixner  *
18545cee9645SThomas Gleixner  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
18554b7e9cf9SDouglas Anderson  * delivered to the current task or the current task is explicitly woken
18564b7e9cf9SDouglas Anderson  * up.
18575cee9645SThomas Gleixner  *
18586e317c32SAlexander Popov  * The current task state is guaranteed to be %TASK_RUNNING when this
18595cee9645SThomas Gleixner  * routine returns.
18605cee9645SThomas Gleixner  *
18615cee9645SThomas Gleixner  * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
18625cee9645SThomas Gleixner  * the CPU away without a bound on the timeout. In this case the return
18635cee9645SThomas Gleixner  * value will be %MAX_SCHEDULE_TIMEOUT.
18645cee9645SThomas Gleixner  *
18654b7e9cf9SDouglas Anderson  * Returns 0 when the timer has expired otherwise the remaining time in
18664b7e9cf9SDouglas Anderson  * jiffies will be returned. In all cases the return value is guaranteed
18674b7e9cf9SDouglas Anderson  * to be non-negative.
18685cee9645SThomas Gleixner  */
18695cee9645SThomas Gleixner signed long __sched schedule_timeout(signed long timeout)
18705cee9645SThomas Gleixner {
187158e1177bSKees Cook 	struct process_timer timer;
18725cee9645SThomas Gleixner 	unsigned long expire;
18735cee9645SThomas Gleixner 
18745cee9645SThomas Gleixner 	switch (timeout)
18755cee9645SThomas Gleixner 	{
18765cee9645SThomas Gleixner 	case MAX_SCHEDULE_TIMEOUT:
18775cee9645SThomas Gleixner 		/*
18785cee9645SThomas Gleixner 		 * These two special cases are useful to be comfortable
18795cee9645SThomas Gleixner 		 * in the caller. Nothing more. We could take
18805cee9645SThomas Gleixner 		 * MAX_SCHEDULE_TIMEOUT from one of the negative value
18815cee9645SThomas Gleixner 		 * but I' d like to return a valid offset (>=0) to allow
18825cee9645SThomas Gleixner 		 * the caller to do everything it want with the retval.
18835cee9645SThomas Gleixner 		 */
18845cee9645SThomas Gleixner 		schedule();
18855cee9645SThomas Gleixner 		goto out;
18865cee9645SThomas Gleixner 	default:
18875cee9645SThomas Gleixner 		/*
18885cee9645SThomas Gleixner 		 * Another bit of PARANOID. Note that the retval will be
18895cee9645SThomas Gleixner 		 * 0 since no piece of kernel is supposed to do a check
18905cee9645SThomas Gleixner 		 * for a negative retval of schedule_timeout() (since it
18915cee9645SThomas Gleixner 		 * should never happens anyway). You just have the printk()
18925cee9645SThomas Gleixner 		 * that will tell you if something is gone wrong and where.
18935cee9645SThomas Gleixner 		 */
18945cee9645SThomas Gleixner 		if (timeout < 0) {
18955cee9645SThomas Gleixner 			printk(KERN_ERR "schedule_timeout: wrong timeout "
18965cee9645SThomas Gleixner 				"value %lx\n", timeout);
18975cee9645SThomas Gleixner 			dump_stack();
18985cee9645SThomas Gleixner 			current->state = TASK_RUNNING;
18995cee9645SThomas Gleixner 			goto out;
19005cee9645SThomas Gleixner 		}
19015cee9645SThomas Gleixner 	}
19025cee9645SThomas Gleixner 
19035cee9645SThomas Gleixner 	expire = timeout + jiffies;
19045cee9645SThomas Gleixner 
190558e1177bSKees Cook 	timer.task = current;
190658e1177bSKees Cook 	timer_setup_on_stack(&timer.timer, process_timeout, 0);
190790c01894SEric Dumazet 	__mod_timer(&timer.timer, expire, MOD_TIMER_NOTPENDING);
19085cee9645SThomas Gleixner 	schedule();
190958e1177bSKees Cook 	del_singleshot_timer_sync(&timer.timer);
19105cee9645SThomas Gleixner 
19115cee9645SThomas Gleixner 	/* Remove the timer from the object tracker */
191258e1177bSKees Cook 	destroy_timer_on_stack(&timer.timer);
19135cee9645SThomas Gleixner 
19145cee9645SThomas Gleixner 	timeout = expire - jiffies;
19155cee9645SThomas Gleixner 
19165cee9645SThomas Gleixner  out:
19175cee9645SThomas Gleixner 	return timeout < 0 ? 0 : timeout;
19185cee9645SThomas Gleixner }
19195cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout);
19205cee9645SThomas Gleixner 
19215cee9645SThomas Gleixner /*
19225cee9645SThomas Gleixner  * We can use __set_current_state() here because schedule_timeout() calls
19235cee9645SThomas Gleixner  * schedule() unconditionally.
19245cee9645SThomas Gleixner  */
19255cee9645SThomas Gleixner signed long __sched schedule_timeout_interruptible(signed long timeout)
19265cee9645SThomas Gleixner {
19275cee9645SThomas Gleixner 	__set_current_state(TASK_INTERRUPTIBLE);
19285cee9645SThomas Gleixner 	return schedule_timeout(timeout);
19295cee9645SThomas Gleixner }
19305cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout_interruptible);
19315cee9645SThomas Gleixner 
19325cee9645SThomas Gleixner signed long __sched schedule_timeout_killable(signed long timeout)
19335cee9645SThomas Gleixner {
19345cee9645SThomas Gleixner 	__set_current_state(TASK_KILLABLE);
19355cee9645SThomas Gleixner 	return schedule_timeout(timeout);
19365cee9645SThomas Gleixner }
19375cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout_killable);
19385cee9645SThomas Gleixner 
19395cee9645SThomas Gleixner signed long __sched schedule_timeout_uninterruptible(signed long timeout)
19405cee9645SThomas Gleixner {
19415cee9645SThomas Gleixner 	__set_current_state(TASK_UNINTERRUPTIBLE);
19425cee9645SThomas Gleixner 	return schedule_timeout(timeout);
19435cee9645SThomas Gleixner }
19445cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout_uninterruptible);
19455cee9645SThomas Gleixner 
194669b27bafSAndrew Morton /*
194769b27bafSAndrew Morton  * Like schedule_timeout_uninterruptible(), except this task will not contribute
194869b27bafSAndrew Morton  * to load average.
194969b27bafSAndrew Morton  */
195069b27bafSAndrew Morton signed long __sched schedule_timeout_idle(signed long timeout)
195169b27bafSAndrew Morton {
195269b27bafSAndrew Morton 	__set_current_state(TASK_IDLE);
195369b27bafSAndrew Morton 	return schedule_timeout(timeout);
195469b27bafSAndrew Morton }
195569b27bafSAndrew Morton EXPORT_SYMBOL(schedule_timeout_idle);
195669b27bafSAndrew Morton 
19575cee9645SThomas Gleixner #ifdef CONFIG_HOTPLUG_CPU
1958494af3edSThomas Gleixner static void migrate_timer_list(struct timer_base *new_base, struct hlist_head *head)
19595cee9645SThomas Gleixner {
19605cee9645SThomas Gleixner 	struct timer_list *timer;
19610eeda71bSThomas Gleixner 	int cpu = new_base->cpu;
19625cee9645SThomas Gleixner 
19631dabbcecSThomas Gleixner 	while (!hlist_empty(head)) {
19641dabbcecSThomas Gleixner 		timer = hlist_entry(head->first, struct timer_list, entry);
19655cee9645SThomas Gleixner 		detach_timer(timer, false);
19660eeda71bSThomas Gleixner 		timer->flags = (timer->flags & ~TIMER_BASEMASK) | cpu;
19675cee9645SThomas Gleixner 		internal_add_timer(new_base, timer);
19685cee9645SThomas Gleixner 	}
19695cee9645SThomas Gleixner }
19705cee9645SThomas Gleixner 
197126456f87SThomas Gleixner int timers_prepare_cpu(unsigned int cpu)
197226456f87SThomas Gleixner {
197326456f87SThomas Gleixner 	struct timer_base *base;
197426456f87SThomas Gleixner 	int b;
197526456f87SThomas Gleixner 
197626456f87SThomas Gleixner 	for (b = 0; b < NR_BASES; b++) {
197726456f87SThomas Gleixner 		base = per_cpu_ptr(&timer_bases[b], cpu);
197826456f87SThomas Gleixner 		base->clk = jiffies;
197926456f87SThomas Gleixner 		base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
198026456f87SThomas Gleixner 		base->is_idle = false;
198126456f87SThomas Gleixner 		base->must_forward_clk = true;
198226456f87SThomas Gleixner 	}
198326456f87SThomas Gleixner 	return 0;
198426456f87SThomas Gleixner }
198526456f87SThomas Gleixner 
198624f73b99SRichard Cochran int timers_dead_cpu(unsigned int cpu)
19875cee9645SThomas Gleixner {
1988494af3edSThomas Gleixner 	struct timer_base *old_base;
1989494af3edSThomas Gleixner 	struct timer_base *new_base;
1990500462a9SThomas Gleixner 	int b, i;
19915cee9645SThomas Gleixner 
19925cee9645SThomas Gleixner 	BUG_ON(cpu_online(cpu));
1993500462a9SThomas Gleixner 
1994500462a9SThomas Gleixner 	for (b = 0; b < NR_BASES; b++) {
1995500462a9SThomas Gleixner 		old_base = per_cpu_ptr(&timer_bases[b], cpu);
1996500462a9SThomas Gleixner 		new_base = get_cpu_ptr(&timer_bases[b]);
19975cee9645SThomas Gleixner 		/*
19985cee9645SThomas Gleixner 		 * The caller is globally serialized and nobody else
19995cee9645SThomas Gleixner 		 * takes two locks at once, deadlock is not possible.
20005cee9645SThomas Gleixner 		 */
20012287d866SSebastian Andrzej Siewior 		raw_spin_lock_irq(&new_base->lock);
20022287d866SSebastian Andrzej Siewior 		raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
20035cee9645SThomas Gleixner 
2004c52232a4SLingutla Chandrasekhar 		/*
2005c52232a4SLingutla Chandrasekhar 		 * The current CPUs base clock might be stale. Update it
2006c52232a4SLingutla Chandrasekhar 		 * before moving the timers over.
2007c52232a4SLingutla Chandrasekhar 		 */
2008c52232a4SLingutla Chandrasekhar 		forward_timer_base(new_base);
2009c52232a4SLingutla Chandrasekhar 
20105cee9645SThomas Gleixner 		BUG_ON(old_base->running_timer);
20115cee9645SThomas Gleixner 
2012500462a9SThomas Gleixner 		for (i = 0; i < WHEEL_SIZE; i++)
2013500462a9SThomas Gleixner 			migrate_timer_list(new_base, old_base->vectors + i);
20148def9060SViresh Kumar 
20152287d866SSebastian Andrzej Siewior 		raw_spin_unlock(&old_base->lock);
20162287d866SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&new_base->lock);
2017494af3edSThomas Gleixner 		put_cpu_ptr(&timer_bases);
20185cee9645SThomas Gleixner 	}
201924f73b99SRichard Cochran 	return 0;
20205cee9645SThomas Gleixner }
20215cee9645SThomas Gleixner 
20223650b57fSPeter Zijlstra #endif /* CONFIG_HOTPLUG_CPU */
20235cee9645SThomas Gleixner 
20240eeda71bSThomas Gleixner static void __init init_timer_cpu(int cpu)
20258def9060SViresh Kumar {
2026500462a9SThomas Gleixner 	struct timer_base *base;
2027500462a9SThomas Gleixner 	int i;
20283650b57fSPeter Zijlstra 
2029500462a9SThomas Gleixner 	for (i = 0; i < NR_BASES; i++) {
2030500462a9SThomas Gleixner 		base = per_cpu_ptr(&timer_bases[i], cpu);
20318def9060SViresh Kumar 		base->cpu = cpu;
20322287d866SSebastian Andrzej Siewior 		raw_spin_lock_init(&base->lock);
2033494af3edSThomas Gleixner 		base->clk = jiffies;
2034030dcdd1SAnna-Maria Gleixner 		timer_base_init_expiry_lock(base);
2035500462a9SThomas Gleixner 	}
20368def9060SViresh Kumar }
20378def9060SViresh Kumar 
20388def9060SViresh Kumar static void __init init_timer_cpus(void)
20398def9060SViresh Kumar {
20408def9060SViresh Kumar 	int cpu;
20418def9060SViresh Kumar 
20420eeda71bSThomas Gleixner 	for_each_possible_cpu(cpu)
20430eeda71bSThomas Gleixner 		init_timer_cpu(cpu);
20448def9060SViresh Kumar }
20455cee9645SThomas Gleixner 
20465cee9645SThomas Gleixner void __init init_timers(void)
20475cee9645SThomas Gleixner {
20488def9060SViresh Kumar 	init_timer_cpus();
20495cee9645SThomas Gleixner 	open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
20505cee9645SThomas Gleixner }
20515cee9645SThomas Gleixner 
20525cee9645SThomas Gleixner /**
20535cee9645SThomas Gleixner  * msleep - sleep safely even with waitqueue interruptions
20545cee9645SThomas Gleixner  * @msecs: Time in milliseconds to sleep for
20555cee9645SThomas Gleixner  */
20565cee9645SThomas Gleixner void msleep(unsigned int msecs)
20575cee9645SThomas Gleixner {
20585cee9645SThomas Gleixner 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
20595cee9645SThomas Gleixner 
20605cee9645SThomas Gleixner 	while (timeout)
20615cee9645SThomas Gleixner 		timeout = schedule_timeout_uninterruptible(timeout);
20625cee9645SThomas Gleixner }
20635cee9645SThomas Gleixner 
20645cee9645SThomas Gleixner EXPORT_SYMBOL(msleep);
20655cee9645SThomas Gleixner 
20665cee9645SThomas Gleixner /**
20675cee9645SThomas Gleixner  * msleep_interruptible - sleep waiting for signals
20685cee9645SThomas Gleixner  * @msecs: Time in milliseconds to sleep for
20695cee9645SThomas Gleixner  */
20705cee9645SThomas Gleixner unsigned long msleep_interruptible(unsigned int msecs)
20715cee9645SThomas Gleixner {
20725cee9645SThomas Gleixner 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
20735cee9645SThomas Gleixner 
20745cee9645SThomas Gleixner 	while (timeout && !signal_pending(current))
20755cee9645SThomas Gleixner 		timeout = schedule_timeout_interruptible(timeout);
20765cee9645SThomas Gleixner 	return jiffies_to_msecs(timeout);
20775cee9645SThomas Gleixner }
20785cee9645SThomas Gleixner 
20795cee9645SThomas Gleixner EXPORT_SYMBOL(msleep_interruptible);
20805cee9645SThomas Gleixner 
20815cee9645SThomas Gleixner /**
2082b5227d03SBjorn Helgaas  * usleep_range - Sleep for an approximate time
20835cee9645SThomas Gleixner  * @min: Minimum time in usecs to sleep
20845cee9645SThomas Gleixner  * @max: Maximum time in usecs to sleep
2085b5227d03SBjorn Helgaas  *
2086b5227d03SBjorn Helgaas  * In non-atomic context where the exact wakeup time is flexible, use
2087b5227d03SBjorn Helgaas  * usleep_range() instead of udelay().  The sleep improves responsiveness
2088b5227d03SBjorn Helgaas  * by avoiding the CPU-hogging busy-wait of udelay(), and the range reduces
2089b5227d03SBjorn Helgaas  * power usage by allowing hrtimers to take advantage of an already-
2090b5227d03SBjorn Helgaas  * scheduled interrupt instead of scheduling a new one just for this sleep.
20915cee9645SThomas Gleixner  */
20922ad5d327SThomas Gleixner void __sched usleep_range(unsigned long min, unsigned long max)
20935cee9645SThomas Gleixner {
20946c5e9059SDouglas Anderson 	ktime_t exp = ktime_add_us(ktime_get(), min);
20956c5e9059SDouglas Anderson 	u64 delta = (u64)(max - min) * NSEC_PER_USEC;
20966c5e9059SDouglas Anderson 
20976c5e9059SDouglas Anderson 	for (;;) {
20985cee9645SThomas Gleixner 		__set_current_state(TASK_UNINTERRUPTIBLE);
20996c5e9059SDouglas Anderson 		/* Do not return before the requested sleep time has elapsed */
21006c5e9059SDouglas Anderson 		if (!schedule_hrtimeout_range(&exp, delta, HRTIMER_MODE_ABS))
21016c5e9059SDouglas Anderson 			break;
21026c5e9059SDouglas Anderson 	}
21035cee9645SThomas Gleixner }
21045cee9645SThomas Gleixner EXPORT_SYMBOL(usleep_range);
2105