xref: /linux-6.15/kernel/time/timer.c (revision bb663f0f)
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>
46f227e3ecSWilly Tarreau #include <linux/random.h>
47efaa0227Stangmeng #include <linux/sysctl.h>
485cee9645SThomas Gleixner 
497c0f6ba6SLinus Torvalds #include <linux/uaccess.h>
505cee9645SThomas Gleixner #include <asm/unistd.h>
515cee9645SThomas Gleixner #include <asm/div64.h>
525cee9645SThomas Gleixner #include <asm/timex.h>
535cee9645SThomas Gleixner #include <asm/io.h>
545cee9645SThomas Gleixner 
55c1ad348bSThomas Gleixner #include "tick-internal.h"
56c1ad348bSThomas Gleixner 
575cee9645SThomas Gleixner #define CREATE_TRACE_POINTS
585cee9645SThomas Gleixner #include <trace/events/timer.h>
595cee9645SThomas Gleixner 
605cee9645SThomas Gleixner __visible u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
615cee9645SThomas Gleixner 
625cee9645SThomas Gleixner EXPORT_SYMBOL(jiffies_64);
635cee9645SThomas Gleixner 
645cee9645SThomas Gleixner /*
65500462a9SThomas Gleixner  * The timer wheel has LVL_DEPTH array levels. Each level provides an array of
66500462a9SThomas Gleixner  * LVL_SIZE buckets. Each level is driven by its own clock and therefor each
67500462a9SThomas Gleixner  * level has a different granularity.
68500462a9SThomas Gleixner  *
69500462a9SThomas Gleixner  * The level granularity is:		LVL_CLK_DIV ^ lvl
70500462a9SThomas Gleixner  * The level clock frequency is:	HZ / (LVL_CLK_DIV ^ level)
71500462a9SThomas Gleixner  *
72500462a9SThomas Gleixner  * The array level of a newly armed timer depends on the relative expiry
73500462a9SThomas Gleixner  * time. The farther the expiry time is away the higher the array level and
74500462a9SThomas Gleixner  * therefor the granularity becomes.
75500462a9SThomas Gleixner  *
76500462a9SThomas Gleixner  * Contrary to the original timer wheel implementation, which aims for 'exact'
77500462a9SThomas Gleixner  * expiry of the timers, this implementation removes the need for recascading
78500462a9SThomas Gleixner  * the timers into the lower array levels. The previous 'classic' timer wheel
79500462a9SThomas Gleixner  * implementation of the kernel already violated the 'exact' expiry by adding
80500462a9SThomas Gleixner  * slack to the expiry time to provide batched expiration. The granularity
81500462a9SThomas Gleixner  * levels provide implicit batching.
82500462a9SThomas Gleixner  *
83500462a9SThomas Gleixner  * This is an optimization of the original timer wheel implementation for the
84500462a9SThomas Gleixner  * majority of the timer wheel use cases: timeouts. The vast majority of
85500462a9SThomas Gleixner  * timeout timers (networking, disk I/O ...) are canceled before expiry. If
86500462a9SThomas Gleixner  * the timeout expires it indicates that normal operation is disturbed, so it
87500462a9SThomas Gleixner  * does not matter much whether the timeout comes with a slight delay.
88500462a9SThomas Gleixner  *
89500462a9SThomas Gleixner  * The only exception to this are networking timers with a small expiry
90500462a9SThomas Gleixner  * time. They rely on the granularity. Those fit into the first wheel level,
91500462a9SThomas Gleixner  * which has HZ granularity.
92500462a9SThomas Gleixner  *
93500462a9SThomas Gleixner  * We don't have cascading anymore. timers with a expiry time above the
94500462a9SThomas Gleixner  * capacity of the last wheel level are force expired at the maximum timeout
95500462a9SThomas Gleixner  * value of the last wheel level. From data sampling we know that the maximum
96500462a9SThomas Gleixner  * value observed is 5 days (network connection tracking), so this should not
97500462a9SThomas Gleixner  * be an issue.
98500462a9SThomas Gleixner  *
99500462a9SThomas Gleixner  * The currently chosen array constants values are a good compromise between
100500462a9SThomas Gleixner  * array size and granularity.
101500462a9SThomas Gleixner  *
102500462a9SThomas Gleixner  * This results in the following granularity and range levels:
103500462a9SThomas Gleixner  *
104500462a9SThomas Gleixner  * HZ 1000 steps
105500462a9SThomas Gleixner  * Level Offset  Granularity            Range
106500462a9SThomas Gleixner  *  0      0         1 ms                0 ms -         63 ms
107500462a9SThomas Gleixner  *  1     64         8 ms               64 ms -        511 ms
108500462a9SThomas Gleixner  *  2    128        64 ms              512 ms -       4095 ms (512ms - ~4s)
109500462a9SThomas Gleixner  *  3    192       512 ms             4096 ms -      32767 ms (~4s - ~32s)
110500462a9SThomas Gleixner  *  4    256      4096 ms (~4s)      32768 ms -     262143 ms (~32s - ~4m)
111500462a9SThomas Gleixner  *  5    320     32768 ms (~32s)    262144 ms -    2097151 ms (~4m - ~34m)
112500462a9SThomas Gleixner  *  6    384    262144 ms (~4m)    2097152 ms -   16777215 ms (~34m - ~4h)
113500462a9SThomas Gleixner  *  7    448   2097152 ms (~34m)  16777216 ms -  134217727 ms (~4h - ~1d)
114500462a9SThomas Gleixner  *  8    512  16777216 ms (~4h)  134217728 ms - 1073741822 ms (~1d - ~12d)
115500462a9SThomas Gleixner  *
116500462a9SThomas Gleixner  * HZ  300
117500462a9SThomas Gleixner  * Level Offset  Granularity            Range
118500462a9SThomas Gleixner  *  0	   0         3 ms                0 ms -        210 ms
119500462a9SThomas Gleixner  *  1	  64        26 ms              213 ms -       1703 ms (213ms - ~1s)
120500462a9SThomas Gleixner  *  2	 128       213 ms             1706 ms -      13650 ms (~1s - ~13s)
121500462a9SThomas Gleixner  *  3	 192      1706 ms (~1s)      13653 ms -     109223 ms (~13s - ~1m)
122500462a9SThomas Gleixner  *  4	 256     13653 ms (~13s)    109226 ms -     873810 ms (~1m - ~14m)
123500462a9SThomas Gleixner  *  5	 320    109226 ms (~1m)     873813 ms -    6990503 ms (~14m - ~1h)
124500462a9SThomas Gleixner  *  6	 384    873813 ms (~14m)   6990506 ms -   55924050 ms (~1h - ~15h)
125500462a9SThomas Gleixner  *  7	 448   6990506 ms (~1h)   55924053 ms -  447392423 ms (~15h - ~5d)
126500462a9SThomas Gleixner  *  8    512  55924053 ms (~15h) 447392426 ms - 3579139406 ms (~5d - ~41d)
127500462a9SThomas Gleixner  *
128500462a9SThomas Gleixner  * HZ  250
129500462a9SThomas Gleixner  * Level Offset  Granularity            Range
130500462a9SThomas Gleixner  *  0	   0         4 ms                0 ms -        255 ms
131500462a9SThomas Gleixner  *  1	  64        32 ms              256 ms -       2047 ms (256ms - ~2s)
132500462a9SThomas Gleixner  *  2	 128       256 ms             2048 ms -      16383 ms (~2s - ~16s)
133500462a9SThomas Gleixner  *  3	 192      2048 ms (~2s)      16384 ms -     131071 ms (~16s - ~2m)
134500462a9SThomas Gleixner  *  4	 256     16384 ms (~16s)    131072 ms -    1048575 ms (~2m - ~17m)
135500462a9SThomas Gleixner  *  5	 320    131072 ms (~2m)    1048576 ms -    8388607 ms (~17m - ~2h)
136500462a9SThomas Gleixner  *  6	 384   1048576 ms (~17m)   8388608 ms -   67108863 ms (~2h - ~18h)
137500462a9SThomas Gleixner  *  7	 448   8388608 ms (~2h)   67108864 ms -  536870911 ms (~18h - ~6d)
138500462a9SThomas Gleixner  *  8    512  67108864 ms (~18h) 536870912 ms - 4294967288 ms (~6d - ~49d)
139500462a9SThomas Gleixner  *
140500462a9SThomas Gleixner  * HZ  100
141500462a9SThomas Gleixner  * Level Offset  Granularity            Range
142500462a9SThomas Gleixner  *  0	   0         10 ms               0 ms -        630 ms
143500462a9SThomas Gleixner  *  1	  64         80 ms             640 ms -       5110 ms (640ms - ~5s)
144500462a9SThomas Gleixner  *  2	 128        640 ms            5120 ms -      40950 ms (~5s - ~40s)
145500462a9SThomas Gleixner  *  3	 192       5120 ms (~5s)     40960 ms -     327670 ms (~40s - ~5m)
146500462a9SThomas Gleixner  *  4	 256      40960 ms (~40s)   327680 ms -    2621430 ms (~5m - ~43m)
147500462a9SThomas Gleixner  *  5	 320     327680 ms (~5m)   2621440 ms -   20971510 ms (~43m - ~5h)
148500462a9SThomas Gleixner  *  6	 384    2621440 ms (~43m) 20971520 ms -  167772150 ms (~5h - ~1d)
149500462a9SThomas Gleixner  *  7	 448   20971520 ms (~5h) 167772160 ms - 1342177270 ms (~1d - ~15d)
1505cee9645SThomas Gleixner  */
1515cee9645SThomas Gleixner 
152500462a9SThomas Gleixner /* Clock divisor for the next level */
153500462a9SThomas Gleixner #define LVL_CLK_SHIFT	3
154500462a9SThomas Gleixner #define LVL_CLK_DIV	(1UL << LVL_CLK_SHIFT)
155500462a9SThomas Gleixner #define LVL_CLK_MASK	(LVL_CLK_DIV - 1)
156500462a9SThomas Gleixner #define LVL_SHIFT(n)	((n) * LVL_CLK_SHIFT)
157500462a9SThomas Gleixner #define LVL_GRAN(n)	(1UL << LVL_SHIFT(n))
1585cee9645SThomas Gleixner 
159500462a9SThomas Gleixner /*
160500462a9SThomas Gleixner  * The time start value for each level to select the bucket at enqueue
16144688972SFrederic Weisbecker  * time. We start from the last possible delta of the previous level
16244688972SFrederic Weisbecker  * so that we can later add an extra LVL_GRAN(n) to n (see calc_index()).
163500462a9SThomas Gleixner  */
164500462a9SThomas Gleixner #define LVL_START(n)	((LVL_SIZE - 1) << (((n) - 1) * LVL_CLK_SHIFT))
1655cee9645SThomas Gleixner 
166500462a9SThomas Gleixner /* Size of each clock level */
167500462a9SThomas Gleixner #define LVL_BITS	6
168500462a9SThomas Gleixner #define LVL_SIZE	(1UL << LVL_BITS)
169500462a9SThomas Gleixner #define LVL_MASK	(LVL_SIZE - 1)
170500462a9SThomas Gleixner #define LVL_OFFS(n)	((n) * LVL_SIZE)
171500462a9SThomas Gleixner 
172500462a9SThomas Gleixner /* Level depth */
173500462a9SThomas Gleixner #if HZ > 100
174500462a9SThomas Gleixner # define LVL_DEPTH	9
175500462a9SThomas Gleixner # else
176500462a9SThomas Gleixner # define LVL_DEPTH	8
177500462a9SThomas Gleixner #endif
178500462a9SThomas Gleixner 
179500462a9SThomas Gleixner /* The cutoff (max. capacity of the wheel) */
180500462a9SThomas Gleixner #define WHEEL_TIMEOUT_CUTOFF	(LVL_START(LVL_DEPTH))
181500462a9SThomas Gleixner #define WHEEL_TIMEOUT_MAX	(WHEEL_TIMEOUT_CUTOFF - LVL_GRAN(LVL_DEPTH - 1))
182500462a9SThomas Gleixner 
183500462a9SThomas Gleixner /*
184500462a9SThomas Gleixner  * The resulting wheel size. If NOHZ is configured we allocate two
185500462a9SThomas Gleixner  * wheels so we have a separate storage for the deferrable timers.
186500462a9SThomas Gleixner  */
187500462a9SThomas Gleixner #define WHEEL_SIZE	(LVL_SIZE * LVL_DEPTH)
188500462a9SThomas Gleixner 
189500462a9SThomas Gleixner #ifdef CONFIG_NO_HZ_COMMON
190500462a9SThomas Gleixner # define NR_BASES	2
191500462a9SThomas Gleixner # define BASE_STD	0
192500462a9SThomas Gleixner # define BASE_DEF	1
193500462a9SThomas Gleixner #else
194500462a9SThomas Gleixner # define NR_BASES	1
195500462a9SThomas Gleixner # define BASE_STD	0
196500462a9SThomas Gleixner # define BASE_DEF	0
197500462a9SThomas Gleixner #endif
1985cee9645SThomas Gleixner 
199494af3edSThomas Gleixner struct timer_base {
2002287d866SSebastian Andrzej Siewior 	raw_spinlock_t		lock;
2015cee9645SThomas Gleixner 	struct timer_list	*running_timer;
202030dcdd1SAnna-Maria Gleixner #ifdef CONFIG_PREEMPT_RT
203030dcdd1SAnna-Maria Gleixner 	spinlock_t		expiry_lock;
204030dcdd1SAnna-Maria Gleixner 	atomic_t		timer_waiters;
205030dcdd1SAnna-Maria Gleixner #endif
206494af3edSThomas Gleixner 	unsigned long		clk;
207a683f390SThomas Gleixner 	unsigned long		next_expiry;
208500462a9SThomas Gleixner 	unsigned int		cpu;
20931cd0e11SFrederic Weisbecker 	bool			next_expiry_recalc;
210a683f390SThomas Gleixner 	bool			is_idle;
211aebacb7fSNicolas Saenz Julienne 	bool			timers_pending;
212500462a9SThomas Gleixner 	DECLARE_BITMAP(pending_map, WHEEL_SIZE);
213500462a9SThomas Gleixner 	struct hlist_head	vectors[WHEEL_SIZE];
2145cee9645SThomas Gleixner } ____cacheline_aligned;
2155cee9645SThomas Gleixner 
216500462a9SThomas Gleixner static DEFINE_PER_CPU(struct timer_base, timer_bases[NR_BASES]);
2175cee9645SThomas Gleixner 
218ae67badaSThomas Gleixner #ifdef CONFIG_NO_HZ_COMMON
219ae67badaSThomas Gleixner 
22014c80341SAnna-Maria Gleixner static DEFINE_STATIC_KEY_FALSE(timers_nohz_active);
221ae67badaSThomas Gleixner static DEFINE_MUTEX(timer_keys_mutex);
222ae67badaSThomas Gleixner 
223ae67badaSThomas Gleixner static void timer_update_keys(struct work_struct *work);
224ae67badaSThomas Gleixner static DECLARE_WORK(timer_update_work, timer_update_keys);
225ae67badaSThomas Gleixner 
226ae67badaSThomas Gleixner #ifdef CONFIG_SMP
227efaa0227Stangmeng static unsigned int sysctl_timer_migration = 1;
228bc7a34b8SThomas Gleixner 
229ae67badaSThomas Gleixner DEFINE_STATIC_KEY_FALSE(timers_migration_enabled);
230ae67badaSThomas Gleixner 
231ae67badaSThomas Gleixner static void timers_update_migration(void)
232bc7a34b8SThomas Gleixner {
233ae67badaSThomas Gleixner 	if (sysctl_timer_migration && tick_nohz_active)
234ae67badaSThomas Gleixner 		static_branch_enable(&timers_migration_enabled);
235ae67badaSThomas Gleixner 	else
236ae67badaSThomas Gleixner 		static_branch_disable(&timers_migration_enabled);
237bc7a34b8SThomas Gleixner }
238efaa0227Stangmeng 
239efaa0227Stangmeng #ifdef CONFIG_SYSCTL
240efaa0227Stangmeng static int timer_migration_handler(struct ctl_table *table, int write,
241efaa0227Stangmeng 			    void *buffer, size_t *lenp, loff_t *ppos)
242efaa0227Stangmeng {
243efaa0227Stangmeng 	int ret;
244efaa0227Stangmeng 
245efaa0227Stangmeng 	mutex_lock(&timer_keys_mutex);
246efaa0227Stangmeng 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
247efaa0227Stangmeng 	if (!ret && write)
248efaa0227Stangmeng 		timers_update_migration();
249efaa0227Stangmeng 	mutex_unlock(&timer_keys_mutex);
250efaa0227Stangmeng 	return ret;
251efaa0227Stangmeng }
252efaa0227Stangmeng 
253efaa0227Stangmeng static struct ctl_table timer_sysctl[] = {
254efaa0227Stangmeng 	{
255efaa0227Stangmeng 		.procname	= "timer_migration",
256efaa0227Stangmeng 		.data		= &sysctl_timer_migration,
257efaa0227Stangmeng 		.maxlen		= sizeof(unsigned int),
258efaa0227Stangmeng 		.mode		= 0644,
259efaa0227Stangmeng 		.proc_handler	= timer_migration_handler,
260efaa0227Stangmeng 		.extra1		= SYSCTL_ZERO,
261efaa0227Stangmeng 		.extra2		= SYSCTL_ONE,
262efaa0227Stangmeng 	},
263efaa0227Stangmeng 	{}
264efaa0227Stangmeng };
265efaa0227Stangmeng 
266efaa0227Stangmeng static int __init timer_sysctl_init(void)
267efaa0227Stangmeng {
268efaa0227Stangmeng 	register_sysctl("kernel", timer_sysctl);
269efaa0227Stangmeng 	return 0;
270efaa0227Stangmeng }
271efaa0227Stangmeng device_initcall(timer_sysctl_init);
272efaa0227Stangmeng #endif /* CONFIG_SYSCTL */
273efaa0227Stangmeng #else /* CONFIG_SMP */
274ae67badaSThomas Gleixner static inline void timers_update_migration(void) { }
275ae67badaSThomas Gleixner #endif /* !CONFIG_SMP */
276ae67badaSThomas Gleixner 
277ae67badaSThomas Gleixner static void timer_update_keys(struct work_struct *work)
278ae67badaSThomas Gleixner {
279ae67badaSThomas Gleixner 	mutex_lock(&timer_keys_mutex);
280ae67badaSThomas Gleixner 	timers_update_migration();
281ae67badaSThomas Gleixner 	static_branch_enable(&timers_nohz_active);
282ae67badaSThomas Gleixner 	mutex_unlock(&timer_keys_mutex);
283ae67badaSThomas Gleixner }
284ae67badaSThomas Gleixner 
285ae67badaSThomas Gleixner void timers_update_nohz(void)
286ae67badaSThomas Gleixner {
287ae67badaSThomas Gleixner 	schedule_work(&timer_update_work);
288bc7a34b8SThomas Gleixner }
289bc7a34b8SThomas Gleixner 
29014c80341SAnna-Maria Gleixner static inline bool is_timers_nohz_active(void)
29114c80341SAnna-Maria Gleixner {
29214c80341SAnna-Maria Gleixner 	return static_branch_unlikely(&timers_nohz_active);
29314c80341SAnna-Maria Gleixner }
29414c80341SAnna-Maria Gleixner #else
29514c80341SAnna-Maria Gleixner static inline bool is_timers_nohz_active(void) { return false; }
296ae67badaSThomas Gleixner #endif /* NO_HZ_COMMON */
297bc7a34b8SThomas Gleixner 
2985cee9645SThomas Gleixner static unsigned long round_jiffies_common(unsigned long j, int cpu,
2995cee9645SThomas Gleixner 		bool force_up)
3005cee9645SThomas Gleixner {
3015cee9645SThomas Gleixner 	int rem;
3025cee9645SThomas Gleixner 	unsigned long original = j;
3035cee9645SThomas Gleixner 
3045cee9645SThomas Gleixner 	/*
3055cee9645SThomas Gleixner 	 * We don't want all cpus firing their timers at once hitting the
3065cee9645SThomas Gleixner 	 * same lock or cachelines, so we skew each extra cpu with an extra
3075cee9645SThomas Gleixner 	 * 3 jiffies. This 3 jiffies came originally from the mm/ code which
3085cee9645SThomas Gleixner 	 * already did this.
3095cee9645SThomas Gleixner 	 * The skew is done by adding 3*cpunr, then round, then subtract this
3105cee9645SThomas Gleixner 	 * extra offset again.
3115cee9645SThomas Gleixner 	 */
3125cee9645SThomas Gleixner 	j += cpu * 3;
3135cee9645SThomas Gleixner 
3145cee9645SThomas Gleixner 	rem = j % HZ;
3155cee9645SThomas Gleixner 
3165cee9645SThomas Gleixner 	/*
3175cee9645SThomas Gleixner 	 * If the target jiffie is just after a whole second (which can happen
3185cee9645SThomas Gleixner 	 * due to delays of the timer irq, long irq off times etc etc) then
3195cee9645SThomas Gleixner 	 * we should round down to the whole second, not up. Use 1/4th second
3205cee9645SThomas Gleixner 	 * as cutoff for this rounding as an extreme upper bound for this.
3215cee9645SThomas Gleixner 	 * But never round down if @force_up is set.
3225cee9645SThomas Gleixner 	 */
3235cee9645SThomas Gleixner 	if (rem < HZ/4 && !force_up) /* round down */
3245cee9645SThomas Gleixner 		j = j - rem;
3255cee9645SThomas Gleixner 	else /* round up */
3265cee9645SThomas Gleixner 		j = j - rem + HZ;
3275cee9645SThomas Gleixner 
3285cee9645SThomas Gleixner 	/* now that we have rounded, subtract the extra skew again */
3295cee9645SThomas Gleixner 	j -= cpu * 3;
3305cee9645SThomas Gleixner 
3315cee9645SThomas Gleixner 	/*
3325cee9645SThomas Gleixner 	 * Make sure j is still in the future. Otherwise return the
3335cee9645SThomas Gleixner 	 * unmodified value.
3345cee9645SThomas Gleixner 	 */
3355cee9645SThomas Gleixner 	return time_is_after_jiffies(j) ? j : original;
3365cee9645SThomas Gleixner }
3375cee9645SThomas Gleixner 
3385cee9645SThomas Gleixner /**
3395cee9645SThomas Gleixner  * __round_jiffies - function to round jiffies to a full second
3405cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
3415cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
3425cee9645SThomas Gleixner  *
3435cee9645SThomas Gleixner  * __round_jiffies() rounds an absolute time 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(unsigned long j, int cpu)
3595cee9645SThomas Gleixner {
3605cee9645SThomas Gleixner 	return round_jiffies_common(j, cpu, false);
3615cee9645SThomas Gleixner }
3625cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies);
3635cee9645SThomas Gleixner 
3645cee9645SThomas Gleixner /**
3655cee9645SThomas Gleixner  * __round_jiffies_relative - function to round jiffies to a full second
3665cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
3675cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
3685cee9645SThomas Gleixner  *
3695cee9645SThomas Gleixner  * __round_jiffies_relative() rounds a time delta  in the future (in jiffies)
3705cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
3715cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
3725cee9645SThomas Gleixner  * they fire approximately every X seconds.
3735cee9645SThomas Gleixner  *
3745cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
3755cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
3765cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
3775cee9645SThomas Gleixner  *
3785cee9645SThomas Gleixner  * The exact rounding is skewed for each processor to avoid all
3795cee9645SThomas Gleixner  * processors firing at the exact same time, which could lead
3805cee9645SThomas Gleixner  * to lock contention or spurious cache line bouncing.
3815cee9645SThomas Gleixner  *
3825cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
3835cee9645SThomas Gleixner  */
3845cee9645SThomas Gleixner unsigned long __round_jiffies_relative(unsigned long j, int cpu)
3855cee9645SThomas Gleixner {
3865cee9645SThomas Gleixner 	unsigned long j0 = jiffies;
3875cee9645SThomas Gleixner 
3885cee9645SThomas Gleixner 	/* Use j0 because jiffies might change while we run */
3895cee9645SThomas Gleixner 	return round_jiffies_common(j + j0, cpu, false) - j0;
3905cee9645SThomas Gleixner }
3915cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies_relative);
3925cee9645SThomas Gleixner 
3935cee9645SThomas Gleixner /**
3945cee9645SThomas Gleixner  * round_jiffies - function to round jiffies to a full second
3955cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
3965cee9645SThomas Gleixner  *
3975cee9645SThomas Gleixner  * round_jiffies() rounds an absolute time in the future (in jiffies)
3985cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
3995cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
4005cee9645SThomas Gleixner  * they fire approximately every X seconds.
4015cee9645SThomas Gleixner  *
4025cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
4035cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
4045cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
4055cee9645SThomas Gleixner  *
4065cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
4075cee9645SThomas Gleixner  */
4085cee9645SThomas Gleixner unsigned long round_jiffies(unsigned long j)
4095cee9645SThomas Gleixner {
4105cee9645SThomas Gleixner 	return round_jiffies_common(j, raw_smp_processor_id(), false);
4115cee9645SThomas Gleixner }
4125cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies);
4135cee9645SThomas Gleixner 
4145cee9645SThomas Gleixner /**
4155cee9645SThomas Gleixner  * round_jiffies_relative - function to round jiffies to a full second
4165cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
4175cee9645SThomas Gleixner  *
4185cee9645SThomas Gleixner  * round_jiffies_relative() rounds a time delta  in the future (in jiffies)
4195cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
4205cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
4215cee9645SThomas Gleixner  * they fire approximately every X seconds.
4225cee9645SThomas Gleixner  *
4235cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
4245cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
4255cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
4265cee9645SThomas Gleixner  *
4275cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
4285cee9645SThomas Gleixner  */
4295cee9645SThomas Gleixner unsigned long round_jiffies_relative(unsigned long j)
4305cee9645SThomas Gleixner {
4315cee9645SThomas Gleixner 	return __round_jiffies_relative(j, raw_smp_processor_id());
4325cee9645SThomas Gleixner }
4335cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies_relative);
4345cee9645SThomas Gleixner 
4355cee9645SThomas Gleixner /**
4365cee9645SThomas Gleixner  * __round_jiffies_up - function to round jiffies up to a full second
4375cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
4385cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
4395cee9645SThomas Gleixner  *
4405cee9645SThomas Gleixner  * This is the same as __round_jiffies() except that it will never
4415cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
4425cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
4435cee9645SThomas Gleixner  * early.
4445cee9645SThomas Gleixner  */
4455cee9645SThomas Gleixner unsigned long __round_jiffies_up(unsigned long j, int cpu)
4465cee9645SThomas Gleixner {
4475cee9645SThomas Gleixner 	return round_jiffies_common(j, cpu, true);
4485cee9645SThomas Gleixner }
4495cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies_up);
4505cee9645SThomas Gleixner 
4515cee9645SThomas Gleixner /**
4525cee9645SThomas Gleixner  * __round_jiffies_up_relative - function to round jiffies up to a full second
4535cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
4545cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
4555cee9645SThomas Gleixner  *
4565cee9645SThomas Gleixner  * This is the same as __round_jiffies_relative() except that it will never
4575cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
4585cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
4595cee9645SThomas Gleixner  * early.
4605cee9645SThomas Gleixner  */
4615cee9645SThomas Gleixner unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
4625cee9645SThomas Gleixner {
4635cee9645SThomas Gleixner 	unsigned long j0 = jiffies;
4645cee9645SThomas Gleixner 
4655cee9645SThomas Gleixner 	/* Use j0 because jiffies might change while we run */
4665cee9645SThomas Gleixner 	return round_jiffies_common(j + j0, cpu, true) - j0;
4675cee9645SThomas Gleixner }
4685cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies_up_relative);
4695cee9645SThomas Gleixner 
4705cee9645SThomas Gleixner /**
4715cee9645SThomas Gleixner  * round_jiffies_up - function to round jiffies up to a full second
4725cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
4735cee9645SThomas Gleixner  *
4745cee9645SThomas Gleixner  * This is the same as round_jiffies() except that it will never
4755cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
4765cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
4775cee9645SThomas Gleixner  * early.
4785cee9645SThomas Gleixner  */
4795cee9645SThomas Gleixner unsigned long round_jiffies_up(unsigned long j)
4805cee9645SThomas Gleixner {
4815cee9645SThomas Gleixner 	return round_jiffies_common(j, raw_smp_processor_id(), true);
4825cee9645SThomas Gleixner }
4835cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies_up);
4845cee9645SThomas Gleixner 
4855cee9645SThomas Gleixner /**
4865cee9645SThomas Gleixner  * round_jiffies_up_relative - function to round jiffies up to a full second
4875cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
4885cee9645SThomas Gleixner  *
4895cee9645SThomas Gleixner  * This is the same as round_jiffies_relative() except that it will never
4905cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
4915cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
4925cee9645SThomas Gleixner  * early.
4935cee9645SThomas Gleixner  */
4945cee9645SThomas Gleixner unsigned long round_jiffies_up_relative(unsigned long j)
4955cee9645SThomas Gleixner {
4965cee9645SThomas Gleixner 	return __round_jiffies_up_relative(j, raw_smp_processor_id());
4975cee9645SThomas Gleixner }
4985cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies_up_relative);
4995cee9645SThomas Gleixner 
5005cee9645SThomas Gleixner 
501500462a9SThomas Gleixner static inline unsigned int timer_get_idx(struct timer_list *timer)
5025cee9645SThomas Gleixner {
503500462a9SThomas Gleixner 	return (timer->flags & TIMER_ARRAYMASK) >> TIMER_ARRAYSHIFT;
5045cee9645SThomas Gleixner }
505500462a9SThomas Gleixner 
506500462a9SThomas Gleixner static inline void timer_set_idx(struct timer_list *timer, unsigned int idx)
507500462a9SThomas Gleixner {
508500462a9SThomas Gleixner 	timer->flags = (timer->flags & ~TIMER_ARRAYMASK) |
509500462a9SThomas Gleixner 			idx << TIMER_ARRAYSHIFT;
510500462a9SThomas Gleixner }
511500462a9SThomas Gleixner 
512500462a9SThomas Gleixner /*
513500462a9SThomas Gleixner  * Helper function to calculate the array index for a given expiry
514500462a9SThomas Gleixner  * time.
515500462a9SThomas Gleixner  */
5161f32cab0SAnna-Maria Behnsen static inline unsigned calc_index(unsigned long expires, unsigned lvl,
5171f32cab0SAnna-Maria Behnsen 				  unsigned long *bucket_expiry)
518500462a9SThomas Gleixner {
51944688972SFrederic Weisbecker 
52044688972SFrederic Weisbecker 	/*
52144688972SFrederic Weisbecker 	 * The timer wheel has to guarantee that a timer does not fire
52244688972SFrederic Weisbecker 	 * early. Early expiry can happen due to:
52344688972SFrederic Weisbecker 	 * - Timer is armed at the edge of a tick
52444688972SFrederic Weisbecker 	 * - Truncation of the expiry time in the outer wheel levels
52544688972SFrederic Weisbecker 	 *
52644688972SFrederic Weisbecker 	 * Round up with level granularity to prevent this.
52744688972SFrederic Weisbecker 	 */
528a2026e44SThomas Gleixner 	expires = (expires >> LVL_SHIFT(lvl)) + 1;
5291f32cab0SAnna-Maria Behnsen 	*bucket_expiry = expires << LVL_SHIFT(lvl);
530500462a9SThomas Gleixner 	return LVL_OFFS(lvl) + (expires & LVL_MASK);
531500462a9SThomas Gleixner }
532500462a9SThomas Gleixner 
5331f32cab0SAnna-Maria Behnsen static int calc_wheel_index(unsigned long expires, unsigned long clk,
5341f32cab0SAnna-Maria Behnsen 			    unsigned long *bucket_expiry)
5355cee9645SThomas Gleixner {
536ffdf0477SAnna-Maria Gleixner 	unsigned long delta = expires - clk;
537500462a9SThomas Gleixner 	unsigned int idx;
5385cee9645SThomas Gleixner 
539500462a9SThomas Gleixner 	if (delta < LVL_START(1)) {
5401f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 0, bucket_expiry);
541500462a9SThomas Gleixner 	} else if (delta < LVL_START(2)) {
5421f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 1, bucket_expiry);
543500462a9SThomas Gleixner 	} else if (delta < LVL_START(3)) {
5441f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 2, bucket_expiry);
545500462a9SThomas Gleixner 	} else if (delta < LVL_START(4)) {
5461f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 3, bucket_expiry);
547500462a9SThomas Gleixner 	} else if (delta < LVL_START(5)) {
5481f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 4, bucket_expiry);
549500462a9SThomas Gleixner 	} else if (delta < LVL_START(6)) {
5501f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 5, bucket_expiry);
551500462a9SThomas Gleixner 	} else if (delta < LVL_START(7)) {
5521f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 6, bucket_expiry);
553500462a9SThomas Gleixner 	} else if (LVL_DEPTH > 8 && delta < LVL_START(8)) {
5541f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 7, bucket_expiry);
555500462a9SThomas Gleixner 	} else if ((long) delta < 0) {
556ffdf0477SAnna-Maria Gleixner 		idx = clk & LVL_MASK;
5571f32cab0SAnna-Maria Behnsen 		*bucket_expiry = clk;
5585cee9645SThomas Gleixner 	} else {
559500462a9SThomas Gleixner 		/*
560500462a9SThomas Gleixner 		 * Force expire obscene large timeouts to expire at the
561500462a9SThomas Gleixner 		 * capacity limit of the wheel.
5625cee9645SThomas Gleixner 		 */
563e2a71bdeSFrederic Weisbecker 		if (delta >= WHEEL_TIMEOUT_CUTOFF)
564e2a71bdeSFrederic Weisbecker 			expires = clk + WHEEL_TIMEOUT_MAX;
5651bd04bf6SThomas Gleixner 
5661f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, LVL_DEPTH - 1, bucket_expiry);
567500462a9SThomas Gleixner 	}
568ffdf0477SAnna-Maria Gleixner 	return idx;
569ffdf0477SAnna-Maria Gleixner }
570ffdf0477SAnna-Maria Gleixner 
571ffdf0477SAnna-Maria Gleixner static void
572ffdf0477SAnna-Maria Gleixner trigger_dyntick_cpu(struct timer_base *base, struct timer_list *timer)
5735cee9645SThomas Gleixner {
574ae67badaSThomas Gleixner 	if (!is_timers_nohz_active())
575a683f390SThomas Gleixner 		return;
5763bb475a3SThomas Gleixner 
5775cee9645SThomas Gleixner 	/*
578a683f390SThomas Gleixner 	 * TODO: This wants some optimizing similar to the code below, but we
579a683f390SThomas Gleixner 	 * will do that when we switch from push to pull for deferrable timers.
5805cee9645SThomas Gleixner 	 */
581a683f390SThomas Gleixner 	if (timer->flags & TIMER_DEFERRABLE) {
582a683f390SThomas Gleixner 		if (tick_nohz_full_cpu(base->cpu))
5839f6d9baaSViresh Kumar 			wake_up_nohz_cpu(base->cpu);
584a683f390SThomas Gleixner 		return;
5855cee9645SThomas Gleixner 	}
5865cee9645SThomas Gleixner 
5875cee9645SThomas Gleixner 	/*
588a683f390SThomas Gleixner 	 * We might have to IPI the remote CPU if the base is idle and the
589a683f390SThomas Gleixner 	 * timer is not deferrable. If the other CPU is on the way to idle
590a683f390SThomas Gleixner 	 * then it can't set base->is_idle as we hold the base lock:
5915cee9645SThomas Gleixner 	 */
592dc2a0f1fSFrederic Weisbecker 	if (base->is_idle)
5935cee9645SThomas Gleixner 		wake_up_nohz_cpu(base->cpu);
5945cee9645SThomas Gleixner }
5955cee9645SThomas Gleixner 
5969a2b764bSFrederic Weisbecker /*
5979a2b764bSFrederic Weisbecker  * Enqueue the timer into the hash bucket, mark it pending in
5989a2b764bSFrederic Weisbecker  * the bitmap, store the index in the timer flags then wake up
5999a2b764bSFrederic Weisbecker  * the target CPU if needed.
6009a2b764bSFrederic Weisbecker  */
6019a2b764bSFrederic Weisbecker static void enqueue_timer(struct timer_base *base, struct timer_list *timer,
6029a2b764bSFrederic Weisbecker 			  unsigned int idx, unsigned long bucket_expiry)
603ffdf0477SAnna-Maria Gleixner {
604dc2a0f1fSFrederic Weisbecker 
6059a2b764bSFrederic Weisbecker 	hlist_add_head(&timer->entry, base->vectors + idx);
6069a2b764bSFrederic Weisbecker 	__set_bit(idx, base->pending_map);
6079a2b764bSFrederic Weisbecker 	timer_set_idx(timer, idx);
6089a2b764bSFrederic Weisbecker 
6099a2b764bSFrederic Weisbecker 	trace_timer_start(timer, timer->expires, timer->flags);
610dc2a0f1fSFrederic Weisbecker 
611dc2a0f1fSFrederic Weisbecker 	/*
612dc2a0f1fSFrederic Weisbecker 	 * Check whether this is the new first expiring timer. The
613dc2a0f1fSFrederic Weisbecker 	 * effective expiry time of the timer is required here
614dc2a0f1fSFrederic Weisbecker 	 * (bucket_expiry) instead of timer->expires.
615dc2a0f1fSFrederic Weisbecker 	 */
616dc2a0f1fSFrederic Weisbecker 	if (time_before(bucket_expiry, base->next_expiry)) {
617dc2a0f1fSFrederic Weisbecker 		/*
618dc2a0f1fSFrederic Weisbecker 		 * Set the next expiry time and kick the CPU so it
619dc2a0f1fSFrederic Weisbecker 		 * can reevaluate the wheel:
620dc2a0f1fSFrederic Weisbecker 		 */
621dc2a0f1fSFrederic Weisbecker 		base->next_expiry = bucket_expiry;
622aebacb7fSNicolas Saenz Julienne 		base->timers_pending = true;
62331cd0e11SFrederic Weisbecker 		base->next_expiry_recalc = false;
624ffdf0477SAnna-Maria Gleixner 		trigger_dyntick_cpu(base, timer);
6255cee9645SThomas Gleixner 	}
6269a2b764bSFrederic Weisbecker }
6279a2b764bSFrederic Weisbecker 
6289a2b764bSFrederic Weisbecker static void internal_add_timer(struct timer_base *base, struct timer_list *timer)
6295cee9645SThomas Gleixner {
6301f32cab0SAnna-Maria Behnsen 	unsigned long bucket_expiry;
6319a2b764bSFrederic Weisbecker 	unsigned int idx;
6321f32cab0SAnna-Maria Behnsen 
6339a2b764bSFrederic Weisbecker 	idx = calc_wheel_index(timer->expires, base->clk, &bucket_expiry);
6349a2b764bSFrederic Weisbecker 	enqueue_timer(base, timer, idx, bucket_expiry);
6355cee9645SThomas Gleixner }
6365cee9645SThomas Gleixner 
6375cee9645SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
6385cee9645SThomas Gleixner 
639f9e62f31SStephen Boyd static const struct debug_obj_descr timer_debug_descr;
6405cee9645SThomas Gleixner 
641317f29c1SStephen Boyd struct timer_hint {
642317f29c1SStephen Boyd 	void	(*function)(struct timer_list *t);
643317f29c1SStephen Boyd 	long	offset;
644317f29c1SStephen Boyd };
645317f29c1SStephen Boyd 
646317f29c1SStephen Boyd #define TIMER_HINT(fn, container, timr, hintfn)			\
647317f29c1SStephen Boyd 	{							\
648317f29c1SStephen Boyd 		.function = fn,					\
649317f29c1SStephen Boyd 		.offset	  = offsetof(container, hintfn) -	\
650317f29c1SStephen Boyd 			    offsetof(container, timr)		\
651317f29c1SStephen Boyd 	}
652317f29c1SStephen Boyd 
653317f29c1SStephen Boyd static const struct timer_hint timer_hints[] = {
654317f29c1SStephen Boyd 	TIMER_HINT(delayed_work_timer_fn,
655317f29c1SStephen Boyd 		   struct delayed_work, timer, work.func),
656317f29c1SStephen Boyd 	TIMER_HINT(kthread_delayed_work_timer_fn,
657317f29c1SStephen Boyd 		   struct kthread_delayed_work, timer, work.func),
658317f29c1SStephen Boyd };
659317f29c1SStephen Boyd 
6605cee9645SThomas Gleixner static void *timer_debug_hint(void *addr)
6615cee9645SThomas Gleixner {
662317f29c1SStephen Boyd 	struct timer_list *timer = addr;
663317f29c1SStephen Boyd 	int i;
664317f29c1SStephen Boyd 
665317f29c1SStephen Boyd 	for (i = 0; i < ARRAY_SIZE(timer_hints); i++) {
666317f29c1SStephen Boyd 		if (timer_hints[i].function == timer->function) {
667317f29c1SStephen Boyd 			void (**fn)(void) = addr + timer_hints[i].offset;
668317f29c1SStephen Boyd 
669317f29c1SStephen Boyd 			return *fn;
670317f29c1SStephen Boyd 		}
671317f29c1SStephen Boyd 	}
672317f29c1SStephen Boyd 
673317f29c1SStephen Boyd 	return timer->function;
6745cee9645SThomas Gleixner }
6755cee9645SThomas Gleixner 
676b9fdac7fSDu, Changbin static bool timer_is_static_object(void *addr)
677b9fdac7fSDu, Changbin {
678b9fdac7fSDu, Changbin 	struct timer_list *timer = addr;
679b9fdac7fSDu, Changbin 
680b9fdac7fSDu, Changbin 	return (timer->entry.pprev == NULL &&
681b9fdac7fSDu, Changbin 		timer->entry.next == TIMER_ENTRY_STATIC);
682b9fdac7fSDu, Changbin }
683b9fdac7fSDu, Changbin 
6845cee9645SThomas Gleixner /*
6855cee9645SThomas Gleixner  * fixup_init is called when:
6865cee9645SThomas Gleixner  * - an active object is initialized
6875cee9645SThomas Gleixner  */
688e3252464SDu, Changbin static bool timer_fixup_init(void *addr, enum debug_obj_state state)
6895cee9645SThomas Gleixner {
6905cee9645SThomas Gleixner 	struct timer_list *timer = addr;
6915cee9645SThomas Gleixner 
6925cee9645SThomas Gleixner 	switch (state) {
6935cee9645SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
6945cee9645SThomas Gleixner 		del_timer_sync(timer);
6955cee9645SThomas Gleixner 		debug_object_init(timer, &timer_debug_descr);
696e3252464SDu, Changbin 		return true;
6975cee9645SThomas Gleixner 	default:
698e3252464SDu, Changbin 		return false;
6995cee9645SThomas Gleixner 	}
7005cee9645SThomas Gleixner }
7015cee9645SThomas Gleixner 
7025cee9645SThomas Gleixner /* Stub timer callback for improperly used timers. */
703ba16490eSThomas Gleixner static void stub_timer(struct timer_list *unused)
7045cee9645SThomas Gleixner {
7055cee9645SThomas Gleixner 	WARN_ON(1);
7065cee9645SThomas Gleixner }
7075cee9645SThomas Gleixner 
7085cee9645SThomas Gleixner /*
7095cee9645SThomas Gleixner  * fixup_activate is called when:
7105cee9645SThomas Gleixner  * - an active object is activated
711b9fdac7fSDu, Changbin  * - an unknown non-static object is activated
7125cee9645SThomas Gleixner  */
713e3252464SDu, Changbin static bool timer_fixup_activate(void *addr, enum debug_obj_state state)
7145cee9645SThomas Gleixner {
7155cee9645SThomas Gleixner 	struct timer_list *timer = addr;
7165cee9645SThomas Gleixner 
7175cee9645SThomas Gleixner 	switch (state) {
7185cee9645SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
719ba16490eSThomas Gleixner 		timer_setup(timer, stub_timer, 0);
720e3252464SDu, Changbin 		return true;
7215cee9645SThomas Gleixner 
7225cee9645SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
7235cee9645SThomas Gleixner 		WARN_ON(1);
724df561f66SGustavo A. R. Silva 		fallthrough;
7255cee9645SThomas Gleixner 	default:
726e3252464SDu, Changbin 		return false;
7275cee9645SThomas Gleixner 	}
7285cee9645SThomas Gleixner }
7295cee9645SThomas Gleixner 
7305cee9645SThomas Gleixner /*
7315cee9645SThomas Gleixner  * fixup_free is called when:
7325cee9645SThomas Gleixner  * - an active object is freed
7335cee9645SThomas Gleixner  */
734e3252464SDu, Changbin static bool timer_fixup_free(void *addr, enum debug_obj_state state)
7355cee9645SThomas Gleixner {
7365cee9645SThomas Gleixner 	struct timer_list *timer = addr;
7375cee9645SThomas Gleixner 
7385cee9645SThomas Gleixner 	switch (state) {
7395cee9645SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
7405cee9645SThomas Gleixner 		del_timer_sync(timer);
7415cee9645SThomas Gleixner 		debug_object_free(timer, &timer_debug_descr);
742e3252464SDu, Changbin 		return true;
7435cee9645SThomas Gleixner 	default:
744e3252464SDu, Changbin 		return false;
7455cee9645SThomas Gleixner 	}
7465cee9645SThomas Gleixner }
7475cee9645SThomas Gleixner 
7485cee9645SThomas Gleixner /*
7495cee9645SThomas Gleixner  * fixup_assert_init is called when:
7505cee9645SThomas Gleixner  * - an untracked/uninit-ed object is found
7515cee9645SThomas Gleixner  */
752e3252464SDu, Changbin static bool timer_fixup_assert_init(void *addr, enum debug_obj_state state)
7535cee9645SThomas Gleixner {
7545cee9645SThomas Gleixner 	struct timer_list *timer = addr;
7555cee9645SThomas Gleixner 
7565cee9645SThomas Gleixner 	switch (state) {
7575cee9645SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
758ba16490eSThomas Gleixner 		timer_setup(timer, stub_timer, 0);
759e3252464SDu, Changbin 		return true;
7605cee9645SThomas Gleixner 	default:
761e3252464SDu, Changbin 		return false;
7625cee9645SThomas Gleixner 	}
7635cee9645SThomas Gleixner }
7645cee9645SThomas Gleixner 
765f9e62f31SStephen Boyd static const struct debug_obj_descr timer_debug_descr = {
7665cee9645SThomas Gleixner 	.name			= "timer_list",
7675cee9645SThomas Gleixner 	.debug_hint		= timer_debug_hint,
768b9fdac7fSDu, Changbin 	.is_static_object	= timer_is_static_object,
7695cee9645SThomas Gleixner 	.fixup_init		= timer_fixup_init,
7705cee9645SThomas Gleixner 	.fixup_activate		= timer_fixup_activate,
7715cee9645SThomas Gleixner 	.fixup_free		= timer_fixup_free,
7725cee9645SThomas Gleixner 	.fixup_assert_init	= timer_fixup_assert_init,
7735cee9645SThomas Gleixner };
7745cee9645SThomas Gleixner 
7755cee9645SThomas Gleixner static inline void debug_timer_init(struct timer_list *timer)
7765cee9645SThomas Gleixner {
7775cee9645SThomas Gleixner 	debug_object_init(timer, &timer_debug_descr);
7785cee9645SThomas Gleixner }
7795cee9645SThomas Gleixner 
7805cee9645SThomas Gleixner static inline void debug_timer_activate(struct timer_list *timer)
7815cee9645SThomas Gleixner {
7825cee9645SThomas Gleixner 	debug_object_activate(timer, &timer_debug_descr);
7835cee9645SThomas Gleixner }
7845cee9645SThomas Gleixner 
7855cee9645SThomas Gleixner static inline void debug_timer_deactivate(struct timer_list *timer)
7865cee9645SThomas Gleixner {
7875cee9645SThomas Gleixner 	debug_object_deactivate(timer, &timer_debug_descr);
7885cee9645SThomas Gleixner }
7895cee9645SThomas Gleixner 
7905cee9645SThomas Gleixner static inline void debug_timer_assert_init(struct timer_list *timer)
7915cee9645SThomas Gleixner {
7925cee9645SThomas Gleixner 	debug_object_assert_init(timer, &timer_debug_descr);
7935cee9645SThomas Gleixner }
7945cee9645SThomas Gleixner 
795188665b2SKees Cook static void do_init_timer(struct timer_list *timer,
796188665b2SKees Cook 			  void (*func)(struct timer_list *),
797188665b2SKees Cook 			  unsigned int flags,
7985cee9645SThomas Gleixner 			  const char *name, struct lock_class_key *key);
7995cee9645SThomas Gleixner 
800188665b2SKees Cook void init_timer_on_stack_key(struct timer_list *timer,
801188665b2SKees Cook 			     void (*func)(struct timer_list *),
802188665b2SKees Cook 			     unsigned int flags,
8035cee9645SThomas Gleixner 			     const char *name, struct lock_class_key *key)
8045cee9645SThomas Gleixner {
8055cee9645SThomas Gleixner 	debug_object_init_on_stack(timer, &timer_debug_descr);
806188665b2SKees Cook 	do_init_timer(timer, func, flags, name, key);
8075cee9645SThomas Gleixner }
8085cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(init_timer_on_stack_key);
8095cee9645SThomas Gleixner 
8105cee9645SThomas Gleixner void destroy_timer_on_stack(struct timer_list *timer)
8115cee9645SThomas Gleixner {
8125cee9645SThomas Gleixner 	debug_object_free(timer, &timer_debug_descr);
8135cee9645SThomas Gleixner }
8145cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_timer_on_stack);
8155cee9645SThomas Gleixner 
8165cee9645SThomas Gleixner #else
8175cee9645SThomas Gleixner static inline void debug_timer_init(struct timer_list *timer) { }
8185cee9645SThomas Gleixner static inline void debug_timer_activate(struct timer_list *timer) { }
8195cee9645SThomas Gleixner static inline void debug_timer_deactivate(struct timer_list *timer) { }
8205cee9645SThomas Gleixner static inline void debug_timer_assert_init(struct timer_list *timer) { }
8215cee9645SThomas Gleixner #endif
8225cee9645SThomas Gleixner 
8235cee9645SThomas Gleixner static inline void debug_init(struct timer_list *timer)
8245cee9645SThomas Gleixner {
8255cee9645SThomas Gleixner 	debug_timer_init(timer);
8265cee9645SThomas Gleixner 	trace_timer_init(timer);
8275cee9645SThomas Gleixner }
8285cee9645SThomas Gleixner 
8295cee9645SThomas Gleixner static inline void debug_deactivate(struct timer_list *timer)
8305cee9645SThomas Gleixner {
8315cee9645SThomas Gleixner 	debug_timer_deactivate(timer);
8325cee9645SThomas Gleixner 	trace_timer_cancel(timer);
8335cee9645SThomas Gleixner }
8345cee9645SThomas Gleixner 
8355cee9645SThomas Gleixner static inline void debug_assert_init(struct timer_list *timer)
8365cee9645SThomas Gleixner {
8375cee9645SThomas Gleixner 	debug_timer_assert_init(timer);
8385cee9645SThomas Gleixner }
8395cee9645SThomas Gleixner 
840188665b2SKees Cook static void do_init_timer(struct timer_list *timer,
841188665b2SKees Cook 			  void (*func)(struct timer_list *),
842188665b2SKees Cook 			  unsigned int flags,
8435cee9645SThomas Gleixner 			  const char *name, struct lock_class_key *key)
8445cee9645SThomas Gleixner {
8451dabbcecSThomas Gleixner 	timer->entry.pprev = NULL;
846188665b2SKees Cook 	timer->function = func;
847b952caf2SQianli Zhao 	if (WARN_ON_ONCE(flags & ~TIMER_INIT_FLAGS))
848b952caf2SQianli Zhao 		flags &= TIMER_INIT_FLAGS;
8490eeda71bSThomas Gleixner 	timer->flags = flags | raw_smp_processor_id();
8505cee9645SThomas Gleixner 	lockdep_init_map(&timer->lockdep_map, name, key, 0);
8515cee9645SThomas Gleixner }
8525cee9645SThomas Gleixner 
8535cee9645SThomas Gleixner /**
8545cee9645SThomas Gleixner  * init_timer_key - initialize a timer
8555cee9645SThomas Gleixner  * @timer: the timer to be initialized
856188665b2SKees Cook  * @func: timer callback function
8575cee9645SThomas Gleixner  * @flags: timer flags
8585cee9645SThomas Gleixner  * @name: name of the timer
8595cee9645SThomas Gleixner  * @key: lockdep class key of the fake lock used for tracking timer
8605cee9645SThomas Gleixner  *       sync lock dependencies
8615cee9645SThomas Gleixner  *
8625cee9645SThomas Gleixner  * init_timer_key() must be done to a timer prior calling *any* of the
8635cee9645SThomas Gleixner  * other timer functions.
8645cee9645SThomas Gleixner  */
865188665b2SKees Cook void init_timer_key(struct timer_list *timer,
866188665b2SKees Cook 		    void (*func)(struct timer_list *), unsigned int flags,
8675cee9645SThomas Gleixner 		    const char *name, struct lock_class_key *key)
8685cee9645SThomas Gleixner {
8695cee9645SThomas Gleixner 	debug_init(timer);
870188665b2SKees Cook 	do_init_timer(timer, func, flags, name, key);
8715cee9645SThomas Gleixner }
8725cee9645SThomas Gleixner EXPORT_SYMBOL(init_timer_key);
8735cee9645SThomas Gleixner 
8745cee9645SThomas Gleixner static inline void detach_timer(struct timer_list *timer, bool clear_pending)
8755cee9645SThomas Gleixner {
8761dabbcecSThomas Gleixner 	struct hlist_node *entry = &timer->entry;
8775cee9645SThomas Gleixner 
8785cee9645SThomas Gleixner 	debug_deactivate(timer);
8795cee9645SThomas Gleixner 
8801dabbcecSThomas Gleixner 	__hlist_del(entry);
8815cee9645SThomas Gleixner 	if (clear_pending)
8821dabbcecSThomas Gleixner 		entry->pprev = NULL;
8831dabbcecSThomas Gleixner 	entry->next = LIST_POISON2;
8845cee9645SThomas Gleixner }
8855cee9645SThomas Gleixner 
886494af3edSThomas Gleixner static int detach_if_pending(struct timer_list *timer, struct timer_base *base,
8875cee9645SThomas Gleixner 			     bool clear_pending)
8885cee9645SThomas Gleixner {
889500462a9SThomas Gleixner 	unsigned idx = timer_get_idx(timer);
890500462a9SThomas Gleixner 
8915cee9645SThomas Gleixner 	if (!timer_pending(timer))
8925cee9645SThomas Gleixner 		return 0;
8935cee9645SThomas Gleixner 
89431cd0e11SFrederic Weisbecker 	if (hlist_is_singular_node(&timer->entry, base->vectors + idx)) {
895500462a9SThomas Gleixner 		__clear_bit(idx, base->pending_map);
89631cd0e11SFrederic Weisbecker 		base->next_expiry_recalc = true;
89731cd0e11SFrederic Weisbecker 	}
898500462a9SThomas Gleixner 
8995cee9645SThomas Gleixner 	detach_timer(timer, clear_pending);
9005cee9645SThomas Gleixner 	return 1;
9015cee9645SThomas Gleixner }
9025cee9645SThomas Gleixner 
903500462a9SThomas Gleixner static inline struct timer_base *get_timer_cpu_base(u32 tflags, u32 cpu)
904500462a9SThomas Gleixner {
905500462a9SThomas Gleixner 	struct timer_base *base = per_cpu_ptr(&timer_bases[BASE_STD], cpu);
906500462a9SThomas Gleixner 
9075cee9645SThomas Gleixner 	/*
908ced6d5c1SAnna-Maria Gleixner 	 * If the timer is deferrable and NO_HZ_COMMON is set then we need
909ced6d5c1SAnna-Maria Gleixner 	 * to use the deferrable base.
910500462a9SThomas Gleixner 	 */
911ced6d5c1SAnna-Maria Gleixner 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
912500462a9SThomas Gleixner 		base = per_cpu_ptr(&timer_bases[BASE_DEF], cpu);
913500462a9SThomas Gleixner 	return base;
914500462a9SThomas Gleixner }
915500462a9SThomas Gleixner 
916500462a9SThomas Gleixner static inline struct timer_base *get_timer_this_cpu_base(u32 tflags)
917500462a9SThomas Gleixner {
918500462a9SThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
919500462a9SThomas Gleixner 
920500462a9SThomas Gleixner 	/*
921ced6d5c1SAnna-Maria Gleixner 	 * If the timer is deferrable and NO_HZ_COMMON is set then we need
922ced6d5c1SAnna-Maria Gleixner 	 * to use the deferrable base.
923500462a9SThomas Gleixner 	 */
924ced6d5c1SAnna-Maria Gleixner 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
925500462a9SThomas Gleixner 		base = this_cpu_ptr(&timer_bases[BASE_DEF]);
926500462a9SThomas Gleixner 	return base;
927500462a9SThomas Gleixner }
928500462a9SThomas Gleixner 
929500462a9SThomas Gleixner static inline struct timer_base *get_timer_base(u32 tflags)
930500462a9SThomas Gleixner {
931500462a9SThomas Gleixner 	return get_timer_cpu_base(tflags, tflags & TIMER_CPUMASK);
932500462a9SThomas Gleixner }
933500462a9SThomas Gleixner 
934a683f390SThomas Gleixner static inline struct timer_base *
9356bad6bccSThomas Gleixner get_target_base(struct timer_base *base, unsigned tflags)
936500462a9SThomas Gleixner {
937ae67badaSThomas Gleixner #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
938ae67badaSThomas Gleixner 	if (static_branch_likely(&timers_migration_enabled) &&
939ae67badaSThomas Gleixner 	    !(tflags & TIMER_PINNED))
940500462a9SThomas Gleixner 		return get_timer_cpu_base(tflags, get_nohz_timer_target());
941500462a9SThomas Gleixner #endif
942ae67badaSThomas Gleixner 	return get_timer_this_cpu_base(tflags);
943500462a9SThomas Gleixner }
944500462a9SThomas Gleixner 
945a683f390SThomas Gleixner static inline void forward_timer_base(struct timer_base *base)
946a683f390SThomas Gleixner {
9470975fb56SFrederic Weisbecker 	unsigned long jnow = READ_ONCE(jiffies);
9486bad6bccSThomas Gleixner 
949a683f390SThomas Gleixner 	/*
9500975fb56SFrederic Weisbecker 	 * No need to forward if we are close enough below jiffies.
9510975fb56SFrederic Weisbecker 	 * Also while executing timers, base->clk is 1 offset ahead
9524bf07f65SIngo Molnar 	 * of jiffies to avoid endless requeuing to current jiffies.
953a683f390SThomas Gleixner 	 */
95436cd28a4SFrederic Weisbecker 	if ((long)(jnow - base->clk) < 1)
955a683f390SThomas Gleixner 		return;
956a683f390SThomas Gleixner 
957a683f390SThomas Gleixner 	/*
958a683f390SThomas Gleixner 	 * If the next expiry value is > jiffies, then we fast forward to
959a683f390SThomas Gleixner 	 * jiffies otherwise we forward to the next expiry value.
960a683f390SThomas Gleixner 	 */
96130c66fc3SFrederic Weisbecker 	if (time_after(base->next_expiry, jnow)) {
9626bad6bccSThomas Gleixner 		base->clk = jnow;
96330c66fc3SFrederic Weisbecker 	} else {
96430c66fc3SFrederic Weisbecker 		if (WARN_ON_ONCE(time_before(base->next_expiry, base->clk)))
96530c66fc3SFrederic Weisbecker 			return;
966a683f390SThomas Gleixner 		base->clk = base->next_expiry;
96730c66fc3SFrederic Weisbecker 	}
968ae67badaSThomas Gleixner }
969a683f390SThomas Gleixner 
970a683f390SThomas Gleixner 
971500462a9SThomas Gleixner /*
972500462a9SThomas Gleixner  * We are using hashed locking: Holding per_cpu(timer_bases[x]).lock means
973500462a9SThomas Gleixner  * that all timers which are tied to this base are locked, and the base itself
974500462a9SThomas Gleixner  * is locked too.
9755cee9645SThomas Gleixner  *
9765cee9645SThomas Gleixner  * So __run_timers/migrate_timers can safely modify all timers which could
977500462a9SThomas Gleixner  * be found in the base->vectors array.
9785cee9645SThomas Gleixner  *
979500462a9SThomas Gleixner  * When a timer is migrating then the TIMER_MIGRATING flag is set and we need
980500462a9SThomas Gleixner  * to wait until the migration is done.
9815cee9645SThomas Gleixner  */
982494af3edSThomas Gleixner static struct timer_base *lock_timer_base(struct timer_list *timer,
9835cee9645SThomas Gleixner 					  unsigned long *flags)
9845cee9645SThomas Gleixner 	__acquires(timer->base->lock)
9855cee9645SThomas Gleixner {
9860eeda71bSThomas Gleixner 	for (;;) {
987494af3edSThomas Gleixner 		struct timer_base *base;
988b831275aSThomas Gleixner 		u32 tf;
989b831275aSThomas Gleixner 
990b831275aSThomas Gleixner 		/*
991b831275aSThomas Gleixner 		 * We need to use READ_ONCE() here, otherwise the compiler
992b831275aSThomas Gleixner 		 * might re-read @tf between the check for TIMER_MIGRATING
993b831275aSThomas Gleixner 		 * and spin_lock().
994b831275aSThomas Gleixner 		 */
995b831275aSThomas Gleixner 		tf = READ_ONCE(timer->flags);
9965cee9645SThomas Gleixner 
9970eeda71bSThomas Gleixner 		if (!(tf & TIMER_MIGRATING)) {
998500462a9SThomas Gleixner 			base = get_timer_base(tf);
9992287d866SSebastian Andrzej Siewior 			raw_spin_lock_irqsave(&base->lock, *flags);
10000eeda71bSThomas Gleixner 			if (timer->flags == tf)
10015cee9645SThomas Gleixner 				return base;
10022287d866SSebastian Andrzej Siewior 			raw_spin_unlock_irqrestore(&base->lock, *flags);
10035cee9645SThomas Gleixner 		}
10045cee9645SThomas Gleixner 		cpu_relax();
10055cee9645SThomas Gleixner 	}
10065cee9645SThomas Gleixner }
10075cee9645SThomas Gleixner 
1008b24591e2SDavid Howells #define MOD_TIMER_PENDING_ONLY		0x01
1009b24591e2SDavid Howells #define MOD_TIMER_REDUCE		0x02
101090c01894SEric Dumazet #define MOD_TIMER_NOTPENDING		0x04
1011b24591e2SDavid Howells 
10125cee9645SThomas Gleixner static inline int
1013b24591e2SDavid Howells __mod_timer(struct timer_list *timer, unsigned long expires, unsigned int options)
10145cee9645SThomas Gleixner {
10151f32cab0SAnna-Maria Behnsen 	unsigned long clk = 0, flags, bucket_expiry;
1016494af3edSThomas Gleixner 	struct timer_base *base, *new_base;
1017f00c0afdSAnna-Maria Gleixner 	unsigned int idx = UINT_MAX;
1018bc7a34b8SThomas Gleixner 	int ret = 0;
10195cee9645SThomas Gleixner 
10204da9152aSThomas Gleixner 	BUG_ON(!timer->function);
10214da9152aSThomas Gleixner 
1022500462a9SThomas Gleixner 	/*
1023f00c0afdSAnna-Maria Gleixner 	 * This is a common optimization triggered by the networking code - if
1024f00c0afdSAnna-Maria Gleixner 	 * the timer is re-modified to have the same timeout or ends up in the
1025f00c0afdSAnna-Maria Gleixner 	 * same array bucket then just return:
1026500462a9SThomas Gleixner 	 */
102790c01894SEric Dumazet 	if (!(options & MOD_TIMER_NOTPENDING) && timer_pending(timer)) {
10282fe59f50SNicholas Piggin 		/*
10292fe59f50SNicholas Piggin 		 * The downside of this optimization is that it can result in
10302fe59f50SNicholas Piggin 		 * larger granularity than you would get from adding a new
10312fe59f50SNicholas Piggin 		 * timer with this expiry.
10322fe59f50SNicholas Piggin 		 */
1033b24591e2SDavid Howells 		long diff = timer->expires - expires;
1034b24591e2SDavid Howells 
1035b24591e2SDavid Howells 		if (!diff)
1036b24591e2SDavid Howells 			return 1;
1037b24591e2SDavid Howells 		if (options & MOD_TIMER_REDUCE && diff <= 0)
1038500462a9SThomas Gleixner 			return 1;
1039f00c0afdSAnna-Maria Gleixner 
10404da9152aSThomas Gleixner 		/*
10414da9152aSThomas Gleixner 		 * We lock timer base and calculate the bucket index right
10424da9152aSThomas Gleixner 		 * here. If the timer ends up in the same bucket, then we
10434da9152aSThomas Gleixner 		 * just update the expiry time and avoid the whole
10444da9152aSThomas Gleixner 		 * dequeue/enqueue dance.
10454da9152aSThomas Gleixner 		 */
10464da9152aSThomas Gleixner 		base = lock_timer_base(timer, &flags);
10472fe59f50SNicholas Piggin 		forward_timer_base(base);
10484da9152aSThomas Gleixner 
1049b24591e2SDavid Howells 		if (timer_pending(timer) && (options & MOD_TIMER_REDUCE) &&
1050b24591e2SDavid Howells 		    time_before_eq(timer->expires, expires)) {
1051b24591e2SDavid Howells 			ret = 1;
1052b24591e2SDavid Howells 			goto out_unlock;
1053b24591e2SDavid Howells 		}
1054b24591e2SDavid Howells 
10554da9152aSThomas Gleixner 		clk = base->clk;
10561f32cab0SAnna-Maria Behnsen 		idx = calc_wheel_index(expires, clk, &bucket_expiry);
1057f00c0afdSAnna-Maria Gleixner 
1058f00c0afdSAnna-Maria Gleixner 		/*
1059f00c0afdSAnna-Maria Gleixner 		 * Retrieve and compare the array index of the pending
1060f00c0afdSAnna-Maria Gleixner 		 * timer. If it matches set the expiry to the new value so a
1061f00c0afdSAnna-Maria Gleixner 		 * subsequent call will exit in the expires check above.
1062f00c0afdSAnna-Maria Gleixner 		 */
1063f00c0afdSAnna-Maria Gleixner 		if (idx == timer_get_idx(timer)) {
1064b24591e2SDavid Howells 			if (!(options & MOD_TIMER_REDUCE))
1065b24591e2SDavid Howells 				timer->expires = expires;
1066b24591e2SDavid Howells 			else if (time_after(timer->expires, expires))
1067f00c0afdSAnna-Maria Gleixner 				timer->expires = expires;
10684da9152aSThomas Gleixner 			ret = 1;
10694da9152aSThomas Gleixner 			goto out_unlock;
1070f00c0afdSAnna-Maria Gleixner 		}
10714da9152aSThomas Gleixner 	} else {
10724da9152aSThomas Gleixner 		base = lock_timer_base(timer, &flags);
10732fe59f50SNicholas Piggin 		forward_timer_base(base);
1074500462a9SThomas Gleixner 	}
1075500462a9SThomas Gleixner 
10765cee9645SThomas Gleixner 	ret = detach_if_pending(timer, base, false);
1077b24591e2SDavid Howells 	if (!ret && (options & MOD_TIMER_PENDING_ONLY))
10785cee9645SThomas Gleixner 		goto out_unlock;
10795cee9645SThomas Gleixner 
1080500462a9SThomas Gleixner 	new_base = get_target_base(base, timer->flags);
10815cee9645SThomas Gleixner 
10825cee9645SThomas Gleixner 	if (base != new_base) {
10835cee9645SThomas Gleixner 		/*
1084500462a9SThomas Gleixner 		 * We are trying to schedule the timer on the new base.
10855cee9645SThomas Gleixner 		 * However we can't change timer's base while it is running,
10869b13df3fSThomas Gleixner 		 * otherwise timer_delete_sync() can't detect that the timer's
1087500462a9SThomas Gleixner 		 * handler yet has not finished. This also guarantees that the
1088500462a9SThomas Gleixner 		 * timer is serialized wrt itself.
10895cee9645SThomas Gleixner 		 */
10905cee9645SThomas Gleixner 		if (likely(base->running_timer != timer)) {
10915cee9645SThomas Gleixner 			/* See the comment in lock_timer_base() */
10920eeda71bSThomas Gleixner 			timer->flags |= TIMER_MIGRATING;
10930eeda71bSThomas Gleixner 
10942287d866SSebastian Andrzej Siewior 			raw_spin_unlock(&base->lock);
10955cee9645SThomas Gleixner 			base = new_base;
10962287d866SSebastian Andrzej Siewior 			raw_spin_lock(&base->lock);
1097d0023a14SEric Dumazet 			WRITE_ONCE(timer->flags,
1098d0023a14SEric Dumazet 				   (timer->flags & ~TIMER_BASEMASK) | base->cpu);
10996bad6bccSThomas Gleixner 			forward_timer_base(base);
11002fe59f50SNicholas Piggin 		}
11012fe59f50SNicholas Piggin 	}
11026bad6bccSThomas Gleixner 
1103dc1e7dc5SAnna-Maria Gleixner 	debug_timer_activate(timer);
1104fd45bb77SThomas Gleixner 
11055cee9645SThomas Gleixner 	timer->expires = expires;
1106f00c0afdSAnna-Maria Gleixner 	/*
1107f00c0afdSAnna-Maria Gleixner 	 * If 'idx' was calculated above and the base time did not advance
11084da9152aSThomas Gleixner 	 * between calculating 'idx' and possibly switching the base, only
11099a2b764bSFrederic Weisbecker 	 * enqueue_timer() is required. Otherwise we need to (re)calculate
11109a2b764bSFrederic Weisbecker 	 * the wheel index via internal_add_timer().
1111f00c0afdSAnna-Maria Gleixner 	 */
11129a2b764bSFrederic Weisbecker 	if (idx != UINT_MAX && clk == base->clk)
11139a2b764bSFrederic Weisbecker 		enqueue_timer(base, timer, idx, bucket_expiry);
11149a2b764bSFrederic Weisbecker 	else
11155cee9645SThomas Gleixner 		internal_add_timer(base, timer);
11165cee9645SThomas Gleixner 
11175cee9645SThomas Gleixner out_unlock:
11182287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&base->lock, flags);
11195cee9645SThomas Gleixner 
11205cee9645SThomas Gleixner 	return ret;
11215cee9645SThomas Gleixner }
11225cee9645SThomas Gleixner 
11235cee9645SThomas Gleixner /**
112414f043f1SThomas Gleixner  * mod_timer_pending - Modify a pending timer's timeout
112514f043f1SThomas Gleixner  * @timer:	The pending timer to be modified
112614f043f1SThomas Gleixner  * @expires:	New absolute timeout in jiffies
11275cee9645SThomas Gleixner  *
112814f043f1SThomas Gleixner  * mod_timer_pending() is the same for pending timers as mod_timer(), but
112914f043f1SThomas Gleixner  * will not activate inactive timers.
11305cee9645SThomas Gleixner  *
113114f043f1SThomas Gleixner  * Return:
113214f043f1SThomas Gleixner  * * %0 - The timer was inactive and not modified
113314f043f1SThomas Gleixner  * * %1 - The timer was active and requeued to expire at @expires
11345cee9645SThomas Gleixner  */
11355cee9645SThomas Gleixner int mod_timer_pending(struct timer_list *timer, unsigned long expires)
11365cee9645SThomas Gleixner {
1137b24591e2SDavid Howells 	return __mod_timer(timer, expires, MOD_TIMER_PENDING_ONLY);
11385cee9645SThomas Gleixner }
11395cee9645SThomas Gleixner EXPORT_SYMBOL(mod_timer_pending);
11405cee9645SThomas Gleixner 
11415cee9645SThomas Gleixner /**
114214f043f1SThomas Gleixner  * mod_timer - Modify a timer's timeout
114314f043f1SThomas Gleixner  * @timer:	The timer to be modified
114414f043f1SThomas Gleixner  * @expires:	New absolute timeout in jiffies
11455cee9645SThomas Gleixner  *
11465cee9645SThomas Gleixner  * mod_timer(timer, expires) is equivalent to:
11475cee9645SThomas Gleixner  *
11485cee9645SThomas Gleixner  *     del_timer(timer); timer->expires = expires; add_timer(timer);
11495cee9645SThomas Gleixner  *
115014f043f1SThomas Gleixner  * mod_timer() is more efficient than the above open coded sequence. In
115114f043f1SThomas Gleixner  * case that the timer is inactive, the del_timer() part is a NOP. The
115214f043f1SThomas Gleixner  * timer is in any case activated with the new expiry time @expires.
115314f043f1SThomas Gleixner  *
11545cee9645SThomas Gleixner  * Note that if there are multiple unserialized concurrent users of the
11555cee9645SThomas Gleixner  * same timer, then mod_timer() is the only safe way to modify the timeout,
11565cee9645SThomas Gleixner  * since add_timer() cannot modify an already running timer.
11575cee9645SThomas Gleixner  *
115814f043f1SThomas Gleixner  * Return:
115914f043f1SThomas Gleixner  * * %0 - The timer was inactive and started
116014f043f1SThomas Gleixner  * * %1 - The timer was active and requeued to expire at @expires or
116114f043f1SThomas Gleixner  *	  the timer was active and not modified because @expires did
116214f043f1SThomas Gleixner  *	  not change the effective expiry time
11635cee9645SThomas Gleixner  */
11645cee9645SThomas Gleixner int mod_timer(struct timer_list *timer, unsigned long expires)
11655cee9645SThomas Gleixner {
1166b24591e2SDavid Howells 	return __mod_timer(timer, expires, 0);
11675cee9645SThomas Gleixner }
11685cee9645SThomas Gleixner EXPORT_SYMBOL(mod_timer);
11695cee9645SThomas Gleixner 
11705cee9645SThomas Gleixner /**
1171b24591e2SDavid Howells  * timer_reduce - Modify a timer's timeout if it would reduce the timeout
1172b24591e2SDavid Howells  * @timer:	The timer to be modified
117314f043f1SThomas Gleixner  * @expires:	New absolute timeout in jiffies
1174b24591e2SDavid Howells  *
1175b24591e2SDavid Howells  * timer_reduce() is very similar to mod_timer(), except that it will only
117614f043f1SThomas Gleixner  * modify an enqueued timer if that would reduce the expiration time. If
117714f043f1SThomas Gleixner  * @timer is not enqueued it starts the timer.
117814f043f1SThomas Gleixner  *
117914f043f1SThomas Gleixner  * Return:
118014f043f1SThomas Gleixner  * * %0 - The timer was inactive and started
118114f043f1SThomas Gleixner  * * %1 - The timer was active and requeued to expire at @expires or
118214f043f1SThomas Gleixner  *	  the timer was active and not modified because @expires
118314f043f1SThomas Gleixner  *	  did not change the effective expiry time such that the
118414f043f1SThomas Gleixner  *	  timer would expire earlier than already scheduled
1185b24591e2SDavid Howells  */
1186b24591e2SDavid Howells int timer_reduce(struct timer_list *timer, unsigned long expires)
1187b24591e2SDavid Howells {
1188b24591e2SDavid Howells 	return __mod_timer(timer, expires, MOD_TIMER_REDUCE);
1189b24591e2SDavid Howells }
1190b24591e2SDavid Howells EXPORT_SYMBOL(timer_reduce);
1191b24591e2SDavid Howells 
1192b24591e2SDavid Howells /**
119314f043f1SThomas Gleixner  * add_timer - Start a timer
119414f043f1SThomas Gleixner  * @timer:	The timer to be started
11955cee9645SThomas Gleixner  *
119614f043f1SThomas Gleixner  * Start @timer to expire at @timer->expires in the future. @timer->expires
119714f043f1SThomas Gleixner  * is the absolute expiry time measured in 'jiffies'. When the timer expires
119814f043f1SThomas Gleixner  * timer->function(timer) will be invoked from soft interrupt context.
11995cee9645SThomas Gleixner  *
120014f043f1SThomas Gleixner  * The @timer->expires and @timer->function fields must be set prior
120114f043f1SThomas Gleixner  * to calling this function.
12025cee9645SThomas Gleixner  *
120314f043f1SThomas Gleixner  * If @timer->expires is already in the past @timer will be queued to
120414f043f1SThomas Gleixner  * expire at the next timer tick.
120514f043f1SThomas Gleixner  *
120614f043f1SThomas Gleixner  * This can only operate on an inactive timer. Attempts to invoke this on
120714f043f1SThomas Gleixner  * an active timer are rejected with a warning.
12085cee9645SThomas Gleixner  */
12095cee9645SThomas Gleixner void add_timer(struct timer_list *timer)
12105cee9645SThomas Gleixner {
121182ed6f7eSThomas Gleixner 	if (WARN_ON_ONCE(timer_pending(timer)))
121282ed6f7eSThomas Gleixner 		return;
121390c01894SEric Dumazet 	__mod_timer(timer, timer->expires, MOD_TIMER_NOTPENDING);
12145cee9645SThomas Gleixner }
12155cee9645SThomas Gleixner EXPORT_SYMBOL(add_timer);
12165cee9645SThomas Gleixner 
12175cee9645SThomas Gleixner /**
121814f043f1SThomas Gleixner  * add_timer_on - Start a timer on a particular CPU
121914f043f1SThomas Gleixner  * @timer:	The timer to be started
122014f043f1SThomas Gleixner  * @cpu:	The CPU to start it on
12215cee9645SThomas Gleixner  *
122214f043f1SThomas Gleixner  * Same as add_timer() except that it starts the timer on the given CPU.
122314f043f1SThomas Gleixner  *
122414f043f1SThomas Gleixner  * See add_timer() for further details.
12255cee9645SThomas Gleixner  */
12265cee9645SThomas Gleixner void add_timer_on(struct timer_list *timer, int cpu)
12275cee9645SThomas Gleixner {
1228500462a9SThomas Gleixner 	struct timer_base *new_base, *base;
12295cee9645SThomas Gleixner 	unsigned long flags;
12305cee9645SThomas Gleixner 
123182ed6f7eSThomas Gleixner 	if (WARN_ON_ONCE(timer_pending(timer) || !timer->function))
123282ed6f7eSThomas Gleixner 		return;
123322b886ddSTejun Heo 
1234500462a9SThomas Gleixner 	new_base = get_timer_cpu_base(timer->flags, cpu);
1235500462a9SThomas Gleixner 
123622b886ddSTejun Heo 	/*
123722b886ddSTejun Heo 	 * If @timer was on a different CPU, it should be migrated with the
123822b886ddSTejun Heo 	 * old base locked to prevent other operations proceeding with the
123922b886ddSTejun Heo 	 * wrong base locked.  See lock_timer_base().
124022b886ddSTejun Heo 	 */
124122b886ddSTejun Heo 	base = lock_timer_base(timer, &flags);
124222b886ddSTejun Heo 	if (base != new_base) {
124322b886ddSTejun Heo 		timer->flags |= TIMER_MIGRATING;
124422b886ddSTejun Heo 
12452287d866SSebastian Andrzej Siewior 		raw_spin_unlock(&base->lock);
124622b886ddSTejun Heo 		base = new_base;
12472287d866SSebastian Andrzej Siewior 		raw_spin_lock(&base->lock);
124822b886ddSTejun Heo 		WRITE_ONCE(timer->flags,
124922b886ddSTejun Heo 			   (timer->flags & ~TIMER_BASEMASK) | cpu);
125022b886ddSTejun Heo 	}
12512fe59f50SNicholas Piggin 	forward_timer_base(base);
125222b886ddSTejun Heo 
1253dc1e7dc5SAnna-Maria Gleixner 	debug_timer_activate(timer);
12545cee9645SThomas Gleixner 	internal_add_timer(base, timer);
12552287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&base->lock, flags);
12565cee9645SThomas Gleixner }
12575cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(add_timer_on);
12585cee9645SThomas Gleixner 
12595cee9645SThomas Gleixner /**
1260*bb663f0fSThomas Gleixner  * timer_delete - Deactivate a timer
126114f043f1SThomas Gleixner  * @timer:	The timer to be deactivated
12625cee9645SThomas Gleixner  *
126314f043f1SThomas Gleixner  * The function only deactivates a pending timer, but contrary to
12649b13df3fSThomas Gleixner  * timer_delete_sync() it does not take into account whether the timer's
126514f043f1SThomas Gleixner  * callback function is concurrently executed on a different CPU or not.
126614f043f1SThomas Gleixner  * It neither prevents rearming of the timer. If @timer can be rearmed
126714f043f1SThomas Gleixner  * concurrently then the return value of this function is meaningless.
12685cee9645SThomas Gleixner  *
126914f043f1SThomas Gleixner  * Return:
127014f043f1SThomas Gleixner  * * %0 - The timer was not pending
127114f043f1SThomas Gleixner  * * %1 - The timer was pending and deactivated
12725cee9645SThomas Gleixner  */
1273*bb663f0fSThomas Gleixner int timer_delete(struct timer_list *timer)
12745cee9645SThomas Gleixner {
1275494af3edSThomas Gleixner 	struct timer_base *base;
12765cee9645SThomas Gleixner 	unsigned long flags;
12775cee9645SThomas Gleixner 	int ret = 0;
12785cee9645SThomas Gleixner 
12795cee9645SThomas Gleixner 	debug_assert_init(timer);
12805cee9645SThomas Gleixner 
12815cee9645SThomas Gleixner 	if (timer_pending(timer)) {
12825cee9645SThomas Gleixner 		base = lock_timer_base(timer, &flags);
12835cee9645SThomas Gleixner 		ret = detach_if_pending(timer, base, true);
12842287d866SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&base->lock, flags);
12855cee9645SThomas Gleixner 	}
12865cee9645SThomas Gleixner 
12875cee9645SThomas Gleixner 	return ret;
12885cee9645SThomas Gleixner }
1289*bb663f0fSThomas Gleixner EXPORT_SYMBOL(timer_delete);
12905cee9645SThomas Gleixner 
12915cee9645SThomas Gleixner /**
12925cee9645SThomas Gleixner  * try_to_del_timer_sync - Try to deactivate a timer
129314f043f1SThomas Gleixner  * @timer:	Timer to deactivate
12945cee9645SThomas Gleixner  *
129514f043f1SThomas Gleixner  * This function tries to deactivate a timer. On success the timer is not
129614f043f1SThomas Gleixner  * queued and the timer callback function is not running on any CPU.
129714f043f1SThomas Gleixner  *
129814f043f1SThomas Gleixner  * This function does not guarantee that the timer cannot be rearmed right
129914f043f1SThomas Gleixner  * after dropping the base lock. That needs to be prevented by the calling
130014f043f1SThomas Gleixner  * code if necessary.
130114f043f1SThomas Gleixner  *
130214f043f1SThomas Gleixner  * Return:
130314f043f1SThomas Gleixner  * * %0  - The timer was not pending
130414f043f1SThomas Gleixner  * * %1  - The timer was pending and deactivated
130514f043f1SThomas Gleixner  * * %-1 - The timer callback function is running on a different CPU
13065cee9645SThomas Gleixner  */
13075cee9645SThomas Gleixner int try_to_del_timer_sync(struct timer_list *timer)
13085cee9645SThomas Gleixner {
1309494af3edSThomas Gleixner 	struct timer_base *base;
13105cee9645SThomas Gleixner 	unsigned long flags;
13115cee9645SThomas Gleixner 	int ret = -1;
13125cee9645SThomas Gleixner 
13135cee9645SThomas Gleixner 	debug_assert_init(timer);
13145cee9645SThomas Gleixner 
13155cee9645SThomas Gleixner 	base = lock_timer_base(timer, &flags);
13165cee9645SThomas Gleixner 
1317dfb4357dSKees Cook 	if (base->running_timer != timer)
13185cee9645SThomas Gleixner 		ret = detach_if_pending(timer, base, true);
1319dfb4357dSKees Cook 
13202287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&base->lock, flags);
13215cee9645SThomas Gleixner 
13225cee9645SThomas Gleixner 	return ret;
13235cee9645SThomas Gleixner }
13245cee9645SThomas Gleixner EXPORT_SYMBOL(try_to_del_timer_sync);
13255cee9645SThomas Gleixner 
1326030dcdd1SAnna-Maria Gleixner #ifdef CONFIG_PREEMPT_RT
1327030dcdd1SAnna-Maria Gleixner static __init void timer_base_init_expiry_lock(struct timer_base *base)
1328030dcdd1SAnna-Maria Gleixner {
1329030dcdd1SAnna-Maria Gleixner 	spin_lock_init(&base->expiry_lock);
1330030dcdd1SAnna-Maria Gleixner }
1331030dcdd1SAnna-Maria Gleixner 
1332030dcdd1SAnna-Maria Gleixner static inline void timer_base_lock_expiry(struct timer_base *base)
1333030dcdd1SAnna-Maria Gleixner {
1334030dcdd1SAnna-Maria Gleixner 	spin_lock(&base->expiry_lock);
1335030dcdd1SAnna-Maria Gleixner }
1336030dcdd1SAnna-Maria Gleixner 
1337030dcdd1SAnna-Maria Gleixner static inline void timer_base_unlock_expiry(struct timer_base *base)
1338030dcdd1SAnna-Maria Gleixner {
1339030dcdd1SAnna-Maria Gleixner 	spin_unlock(&base->expiry_lock);
1340030dcdd1SAnna-Maria Gleixner }
1341030dcdd1SAnna-Maria Gleixner 
1342030dcdd1SAnna-Maria Gleixner /*
1343030dcdd1SAnna-Maria Gleixner  * The counterpart to del_timer_wait_running().
1344030dcdd1SAnna-Maria Gleixner  *
1345030dcdd1SAnna-Maria Gleixner  * If there is a waiter for base->expiry_lock, then it was waiting for the
13464bf07f65SIngo Molnar  * timer callback to finish. Drop expiry_lock and reacquire it. That allows
1347030dcdd1SAnna-Maria Gleixner  * the waiter to acquire the lock and make progress.
1348030dcdd1SAnna-Maria Gleixner  */
1349030dcdd1SAnna-Maria Gleixner static void timer_sync_wait_running(struct timer_base *base)
1350030dcdd1SAnna-Maria Gleixner {
1351030dcdd1SAnna-Maria Gleixner 	if (atomic_read(&base->timer_waiters)) {
1352bb7262b2SThomas Gleixner 		raw_spin_unlock_irq(&base->lock);
1353030dcdd1SAnna-Maria Gleixner 		spin_unlock(&base->expiry_lock);
1354030dcdd1SAnna-Maria Gleixner 		spin_lock(&base->expiry_lock);
1355bb7262b2SThomas Gleixner 		raw_spin_lock_irq(&base->lock);
1356030dcdd1SAnna-Maria Gleixner 	}
1357030dcdd1SAnna-Maria Gleixner }
1358030dcdd1SAnna-Maria Gleixner 
1359030dcdd1SAnna-Maria Gleixner /*
1360030dcdd1SAnna-Maria Gleixner  * This function is called on PREEMPT_RT kernels when the fast path
1361030dcdd1SAnna-Maria Gleixner  * deletion of a timer failed because the timer callback function was
1362030dcdd1SAnna-Maria Gleixner  * running.
1363030dcdd1SAnna-Maria Gleixner  *
1364030dcdd1SAnna-Maria Gleixner  * This prevents priority inversion, if the softirq thread on a remote CPU
1365030dcdd1SAnna-Maria Gleixner  * got preempted, and it prevents a life lock when the task which tries to
1366030dcdd1SAnna-Maria Gleixner  * delete a timer preempted the softirq thread running the timer callback
1367030dcdd1SAnna-Maria Gleixner  * function.
1368030dcdd1SAnna-Maria Gleixner  */
1369030dcdd1SAnna-Maria Gleixner static void del_timer_wait_running(struct timer_list *timer)
1370030dcdd1SAnna-Maria Gleixner {
1371030dcdd1SAnna-Maria Gleixner 	u32 tf;
1372030dcdd1SAnna-Maria Gleixner 
1373030dcdd1SAnna-Maria Gleixner 	tf = READ_ONCE(timer->flags);
1374c725dafcSSebastian Andrzej Siewior 	if (!(tf & (TIMER_MIGRATING | TIMER_IRQSAFE))) {
1375030dcdd1SAnna-Maria Gleixner 		struct timer_base *base = get_timer_base(tf);
1376030dcdd1SAnna-Maria Gleixner 
1377030dcdd1SAnna-Maria Gleixner 		/*
1378030dcdd1SAnna-Maria Gleixner 		 * Mark the base as contended and grab the expiry lock,
1379030dcdd1SAnna-Maria Gleixner 		 * which is held by the softirq across the timer
1380030dcdd1SAnna-Maria Gleixner 		 * callback. Drop the lock immediately so the softirq can
1381030dcdd1SAnna-Maria Gleixner 		 * expire the next timer. In theory the timer could already
1382030dcdd1SAnna-Maria Gleixner 		 * be running again, but that's more than unlikely and just
1383030dcdd1SAnna-Maria Gleixner 		 * causes another wait loop.
1384030dcdd1SAnna-Maria Gleixner 		 */
1385030dcdd1SAnna-Maria Gleixner 		atomic_inc(&base->timer_waiters);
1386030dcdd1SAnna-Maria Gleixner 		spin_lock_bh(&base->expiry_lock);
1387030dcdd1SAnna-Maria Gleixner 		atomic_dec(&base->timer_waiters);
1388030dcdd1SAnna-Maria Gleixner 		spin_unlock_bh(&base->expiry_lock);
1389030dcdd1SAnna-Maria Gleixner 	}
1390030dcdd1SAnna-Maria Gleixner }
1391030dcdd1SAnna-Maria Gleixner #else
1392030dcdd1SAnna-Maria Gleixner static inline void timer_base_init_expiry_lock(struct timer_base *base) { }
1393030dcdd1SAnna-Maria Gleixner static inline void timer_base_lock_expiry(struct timer_base *base) { }
1394030dcdd1SAnna-Maria Gleixner static inline void timer_base_unlock_expiry(struct timer_base *base) { }
1395030dcdd1SAnna-Maria Gleixner static inline void timer_sync_wait_running(struct timer_base *base) { }
1396030dcdd1SAnna-Maria Gleixner static inline void del_timer_wait_running(struct timer_list *timer) { }
1397030dcdd1SAnna-Maria Gleixner #endif
1398030dcdd1SAnna-Maria Gleixner 
13995cee9645SThomas Gleixner /**
14009b13df3fSThomas Gleixner  * timer_delete_sync - Deactivate a timer and wait for the handler to finish.
140114f043f1SThomas Gleixner  * @timer:	The timer to be deactivated
14025cee9645SThomas Gleixner  *
14035cee9645SThomas Gleixner  * Synchronization rules: Callers must prevent restarting of the timer,
14045cee9645SThomas Gleixner  * otherwise this function is meaningless. It must not be called from
14055cee9645SThomas Gleixner  * interrupt contexts unless the timer is an irqsafe one. The caller must
140614f043f1SThomas Gleixner  * not hold locks which would prevent completion of the timer's callback
140714f043f1SThomas Gleixner  * function. The timer's handler must not call add_timer_on(). Upon exit
140814f043f1SThomas Gleixner  * the timer is not queued and the handler is not running on any CPU.
14095cee9645SThomas Gleixner  *
141014f043f1SThomas Gleixner  * For !irqsafe timers, the caller must not hold locks that are held in
141114f043f1SThomas Gleixner  * interrupt context. Even if the lock has nothing to do with the timer in
141214f043f1SThomas Gleixner  * question.  Here's why::
14135cee9645SThomas Gleixner  *
14145cee9645SThomas Gleixner  *    CPU0                             CPU1
14155cee9645SThomas Gleixner  *    ----                             ----
14165cee9645SThomas Gleixner  *                                     <SOFTIRQ>
14175cee9645SThomas Gleixner  *                                       call_timer_fn();
14185cee9645SThomas Gleixner  *                                       base->running_timer = mytimer;
14195cee9645SThomas Gleixner  *    spin_lock_irq(somelock);
14205cee9645SThomas Gleixner  *                                     <IRQ>
14215cee9645SThomas Gleixner  *                                        spin_lock(somelock);
14229b13df3fSThomas Gleixner  *    timer_delete_sync(mytimer);
14235cee9645SThomas Gleixner  *    while (base->running_timer == mytimer);
14245cee9645SThomas Gleixner  *
14259b13df3fSThomas Gleixner  * Now timer_delete_sync() will never return and never release somelock.
142614f043f1SThomas Gleixner  * The interrupt on the other CPU is waiting to grab somelock but it has
142714f043f1SThomas Gleixner  * interrupted the softirq that CPU0 is waiting to finish.
14285cee9645SThomas Gleixner  *
142914f043f1SThomas Gleixner  * This function cannot guarantee that the timer is not rearmed again by
143014f043f1SThomas Gleixner  * some concurrent or preempting code, right after it dropped the base
143114f043f1SThomas Gleixner  * lock. If there is the possibility of a concurrent rearm then the return
143214f043f1SThomas Gleixner  * value of the function is meaningless.
143314f043f1SThomas Gleixner  *
143414f043f1SThomas Gleixner  * Return:
143514f043f1SThomas Gleixner  * * %0	- The timer was not pending
143614f043f1SThomas Gleixner  * * %1	- The timer was pending and deactivated
14375cee9645SThomas Gleixner  */
14389b13df3fSThomas Gleixner int timer_delete_sync(struct timer_list *timer)
14395cee9645SThomas Gleixner {
1440030dcdd1SAnna-Maria Gleixner 	int ret;
1441030dcdd1SAnna-Maria Gleixner 
14425cee9645SThomas Gleixner #ifdef CONFIG_LOCKDEP
14435cee9645SThomas Gleixner 	unsigned long flags;
14445cee9645SThomas Gleixner 
14455cee9645SThomas Gleixner 	/*
14465cee9645SThomas Gleixner 	 * If lockdep gives a backtrace here, please reference
14475cee9645SThomas Gleixner 	 * the synchronization rules above.
14485cee9645SThomas Gleixner 	 */
14495cee9645SThomas Gleixner 	local_irq_save(flags);
14505cee9645SThomas Gleixner 	lock_map_acquire(&timer->lockdep_map);
14515cee9645SThomas Gleixner 	lock_map_release(&timer->lockdep_map);
14525cee9645SThomas Gleixner 	local_irq_restore(flags);
14535cee9645SThomas Gleixner #endif
14545cee9645SThomas Gleixner 	/*
14555cee9645SThomas Gleixner 	 * don't use it in hardirq context, because it
14565cee9645SThomas Gleixner 	 * could lead to deadlock.
14575cee9645SThomas Gleixner 	 */
14588be3f96cSye xingchen 	WARN_ON(in_hardirq() && !(timer->flags & TIMER_IRQSAFE));
1459030dcdd1SAnna-Maria Gleixner 
1460c725dafcSSebastian Andrzej Siewior 	/*
1461c725dafcSSebastian Andrzej Siewior 	 * Must be able to sleep on PREEMPT_RT because of the slowpath in
1462c725dafcSSebastian Andrzej Siewior 	 * del_timer_wait_running().
1463c725dafcSSebastian Andrzej Siewior 	 */
1464c725dafcSSebastian Andrzej Siewior 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(timer->flags & TIMER_IRQSAFE))
1465c725dafcSSebastian Andrzej Siewior 		lockdep_assert_preemption_enabled();
1466c725dafcSSebastian Andrzej Siewior 
1467030dcdd1SAnna-Maria Gleixner 	do {
1468030dcdd1SAnna-Maria Gleixner 		ret = try_to_del_timer_sync(timer);
1469030dcdd1SAnna-Maria Gleixner 
1470030dcdd1SAnna-Maria Gleixner 		if (unlikely(ret < 0)) {
1471030dcdd1SAnna-Maria Gleixner 			del_timer_wait_running(timer);
14725cee9645SThomas Gleixner 			cpu_relax();
14735cee9645SThomas Gleixner 		}
1474030dcdd1SAnna-Maria Gleixner 	} while (ret < 0);
1475030dcdd1SAnna-Maria Gleixner 
1476030dcdd1SAnna-Maria Gleixner 	return ret;
14775cee9645SThomas Gleixner }
14789b13df3fSThomas Gleixner EXPORT_SYMBOL(timer_delete_sync);
14795cee9645SThomas Gleixner 
1480f28d3d53SAnna-Maria Gleixner static void call_timer_fn(struct timer_list *timer,
1481f28d3d53SAnna-Maria Gleixner 			  void (*fn)(struct timer_list *),
1482f28d3d53SAnna-Maria Gleixner 			  unsigned long baseclk)
14835cee9645SThomas Gleixner {
14845cee9645SThomas Gleixner 	int count = preempt_count();
14855cee9645SThomas Gleixner 
14865cee9645SThomas Gleixner #ifdef CONFIG_LOCKDEP
14875cee9645SThomas Gleixner 	/*
14885cee9645SThomas Gleixner 	 * It is permissible to free the timer from inside the
14895cee9645SThomas Gleixner 	 * function that is called from it, this we need to take into
14905cee9645SThomas Gleixner 	 * account for lockdep too. To avoid bogus "held lock freed"
14915cee9645SThomas Gleixner 	 * warnings as well as problems when looking into
14925cee9645SThomas Gleixner 	 * timer->lockdep_map, make a copy and use that here.
14935cee9645SThomas Gleixner 	 */
14945cee9645SThomas Gleixner 	struct lockdep_map lockdep_map;
14955cee9645SThomas Gleixner 
14965cee9645SThomas Gleixner 	lockdep_copy_map(&lockdep_map, &timer->lockdep_map);
14975cee9645SThomas Gleixner #endif
14985cee9645SThomas Gleixner 	/*
14995cee9645SThomas Gleixner 	 * Couple the lock chain with the lock chain at
15009b13df3fSThomas Gleixner 	 * timer_delete_sync() by acquiring the lock_map around the fn()
15019b13df3fSThomas Gleixner 	 * call here and in timer_delete_sync().
15025cee9645SThomas Gleixner 	 */
15035cee9645SThomas Gleixner 	lock_map_acquire(&lockdep_map);
15045cee9645SThomas Gleixner 
1505f28d3d53SAnna-Maria Gleixner 	trace_timer_expire_entry(timer, baseclk);
1506354b46b1SKees Cook 	fn(timer);
15075cee9645SThomas Gleixner 	trace_timer_expire_exit(timer);
15085cee9645SThomas Gleixner 
15095cee9645SThomas Gleixner 	lock_map_release(&lockdep_map);
15105cee9645SThomas Gleixner 
15115cee9645SThomas Gleixner 	if (count != preempt_count()) {
1512d75f773cSSakari Ailus 		WARN_ONCE(1, "timer: %pS preempt leak: %08x -> %08x\n",
15135cee9645SThomas Gleixner 			  fn, count, preempt_count());
15145cee9645SThomas Gleixner 		/*
15155cee9645SThomas Gleixner 		 * Restore the preempt count. That gives us a decent
15165cee9645SThomas Gleixner 		 * chance to survive and extract information. If the
15175cee9645SThomas Gleixner 		 * callback kept a lock held, bad luck, but not worse
15185cee9645SThomas Gleixner 		 * than the BUG() we had.
15195cee9645SThomas Gleixner 		 */
15205cee9645SThomas Gleixner 		preempt_count_set(count);
15215cee9645SThomas Gleixner 	}
15225cee9645SThomas Gleixner }
15235cee9645SThomas Gleixner 
1524500462a9SThomas Gleixner static void expire_timers(struct timer_base *base, struct hlist_head *head)
15255cee9645SThomas Gleixner {
1526f28d3d53SAnna-Maria Gleixner 	/*
1527f28d3d53SAnna-Maria Gleixner 	 * This value is required only for tracing. base->clk was
1528f28d3d53SAnna-Maria Gleixner 	 * incremented directly before expire_timers was called. But expiry
1529f28d3d53SAnna-Maria Gleixner 	 * is related to the old base->clk value.
1530f28d3d53SAnna-Maria Gleixner 	 */
1531f28d3d53SAnna-Maria Gleixner 	unsigned long baseclk = base->clk - 1;
1532f28d3d53SAnna-Maria Gleixner 
15331dabbcecSThomas Gleixner 	while (!hlist_empty(head)) {
1534500462a9SThomas Gleixner 		struct timer_list *timer;
1535354b46b1SKees Cook 		void (*fn)(struct timer_list *);
15365cee9645SThomas Gleixner 
15371dabbcecSThomas Gleixner 		timer = hlist_entry(head->first, struct timer_list, entry);
15385cee9645SThomas Gleixner 
15395cee9645SThomas Gleixner 		base->running_timer = timer;
1540500462a9SThomas Gleixner 		detach_timer(timer, true);
15415cee9645SThomas Gleixner 
1542500462a9SThomas Gleixner 		fn = timer->function;
1543500462a9SThomas Gleixner 
1544500462a9SThomas Gleixner 		if (timer->flags & TIMER_IRQSAFE) {
15452287d866SSebastian Andrzej Siewior 			raw_spin_unlock(&base->lock);
1546f28d3d53SAnna-Maria Gleixner 			call_timer_fn(timer, fn, baseclk);
15472287d866SSebastian Andrzej Siewior 			raw_spin_lock(&base->lock);
1548bb7262b2SThomas Gleixner 			base->running_timer = NULL;
15495cee9645SThomas Gleixner 		} else {
15502287d866SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&base->lock);
1551f28d3d53SAnna-Maria Gleixner 			call_timer_fn(timer, fn, baseclk);
1552bb7262b2SThomas Gleixner 			raw_spin_lock_irq(&base->lock);
1553030dcdd1SAnna-Maria Gleixner 			base->running_timer = NULL;
1554030dcdd1SAnna-Maria Gleixner 			timer_sync_wait_running(base);
15555cee9645SThomas Gleixner 		}
15565cee9645SThomas Gleixner 	}
15575cee9645SThomas Gleixner }
1558500462a9SThomas Gleixner 
1559d4f7dae8SFrederic Weisbecker static int collect_expired_timers(struct timer_base *base,
1560500462a9SThomas Gleixner 				  struct hlist_head *heads)
1561500462a9SThomas Gleixner {
1562d4f7dae8SFrederic Weisbecker 	unsigned long clk = base->clk = base->next_expiry;
1563500462a9SThomas Gleixner 	struct hlist_head *vec;
1564500462a9SThomas Gleixner 	int i, levels = 0;
1565500462a9SThomas Gleixner 	unsigned int idx;
1566500462a9SThomas Gleixner 
1567500462a9SThomas Gleixner 	for (i = 0; i < LVL_DEPTH; i++) {
1568500462a9SThomas Gleixner 		idx = (clk & LVL_MASK) + i * LVL_SIZE;
1569500462a9SThomas Gleixner 
1570500462a9SThomas Gleixner 		if (__test_and_clear_bit(idx, base->pending_map)) {
1571500462a9SThomas Gleixner 			vec = base->vectors + idx;
1572500462a9SThomas Gleixner 			hlist_move_list(vec, heads++);
1573500462a9SThomas Gleixner 			levels++;
1574500462a9SThomas Gleixner 		}
1575500462a9SThomas Gleixner 		/* Is it time to look at the next level? */
1576500462a9SThomas Gleixner 		if (clk & LVL_CLK_MASK)
1577500462a9SThomas Gleixner 			break;
1578500462a9SThomas Gleixner 		/* Shift clock for the next level granularity */
1579500462a9SThomas Gleixner 		clk >>= LVL_CLK_SHIFT;
1580500462a9SThomas Gleixner 	}
1581500462a9SThomas Gleixner 	return levels;
15825cee9645SThomas Gleixner }
15835cee9645SThomas Gleixner 
15845cee9645SThomas Gleixner /*
158523696838SAnna-Maria Gleixner  * Find the next pending bucket of a level. Search from level start (@offset)
158623696838SAnna-Maria Gleixner  * + @clk upwards and if nothing there, search from start of the level
158723696838SAnna-Maria Gleixner  * (@offset) up to @offset + clk.
15885cee9645SThomas Gleixner  */
1589500462a9SThomas Gleixner static int next_pending_bucket(struct timer_base *base, unsigned offset,
1590500462a9SThomas Gleixner 			       unsigned clk)
15915cee9645SThomas Gleixner {
1592500462a9SThomas Gleixner 	unsigned pos, start = offset + clk;
1593500462a9SThomas Gleixner 	unsigned end = offset + LVL_SIZE;
15945cee9645SThomas Gleixner 
1595500462a9SThomas Gleixner 	pos = find_next_bit(base->pending_map, end, start);
1596500462a9SThomas Gleixner 	if (pos < end)
1597500462a9SThomas Gleixner 		return pos - start;
15985cee9645SThomas Gleixner 
1599500462a9SThomas Gleixner 	pos = find_next_bit(base->pending_map, start, offset);
1600500462a9SThomas Gleixner 	return pos < start ? pos + LVL_SIZE - start : -1;
16015cee9645SThomas Gleixner }
16025cee9645SThomas Gleixner 
1603500462a9SThomas Gleixner /*
160423696838SAnna-Maria Gleixner  * Search the first expiring timer in the various clock levels. Caller must
160523696838SAnna-Maria Gleixner  * hold base->lock.
16065cee9645SThomas Gleixner  */
1607494af3edSThomas Gleixner static unsigned long __next_timer_interrupt(struct timer_base *base)
16085cee9645SThomas Gleixner {
1609500462a9SThomas Gleixner 	unsigned long clk, next, adj;
1610500462a9SThomas Gleixner 	unsigned lvl, offset = 0;
16115cee9645SThomas Gleixner 
1612500462a9SThomas Gleixner 	next = base->clk + NEXT_TIMER_MAX_DELTA;
1613500462a9SThomas Gleixner 	clk = base->clk;
1614500462a9SThomas Gleixner 	for (lvl = 0; lvl < LVL_DEPTH; lvl++, offset += LVL_SIZE) {
1615500462a9SThomas Gleixner 		int pos = next_pending_bucket(base, offset, clk & LVL_MASK);
1616001ec1b3SFrederic Weisbecker 		unsigned long lvl_clk = clk & LVL_CLK_MASK;
16175cee9645SThomas Gleixner 
1618500462a9SThomas Gleixner 		if (pos >= 0) {
1619500462a9SThomas Gleixner 			unsigned long tmp = clk + (unsigned long) pos;
16205cee9645SThomas Gleixner 
1621500462a9SThomas Gleixner 			tmp <<= LVL_SHIFT(lvl);
1622500462a9SThomas Gleixner 			if (time_before(tmp, next))
1623500462a9SThomas Gleixner 				next = tmp;
1624001ec1b3SFrederic Weisbecker 
1625001ec1b3SFrederic Weisbecker 			/*
1626001ec1b3SFrederic Weisbecker 			 * If the next expiration happens before we reach
1627001ec1b3SFrederic Weisbecker 			 * the next level, no need to check further.
1628001ec1b3SFrederic Weisbecker 			 */
1629001ec1b3SFrederic Weisbecker 			if (pos <= ((LVL_CLK_DIV - lvl_clk) & LVL_CLK_MASK))
1630001ec1b3SFrederic Weisbecker 				break;
16315cee9645SThomas Gleixner 		}
16325cee9645SThomas Gleixner 		/*
1633500462a9SThomas Gleixner 		 * Clock for the next level. If the current level clock lower
1634500462a9SThomas Gleixner 		 * bits are zero, we look at the next level as is. If not we
1635500462a9SThomas Gleixner 		 * need to advance it by one because that's going to be the
1636500462a9SThomas Gleixner 		 * next expiring bucket in that level. base->clk is the next
1637500462a9SThomas Gleixner 		 * expiring jiffie. So in case of:
1638500462a9SThomas Gleixner 		 *
1639500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1640500462a9SThomas Gleixner 		 *  0    0    0    0    0    0
1641500462a9SThomas Gleixner 		 *
1642500462a9SThomas Gleixner 		 * we have to look at all levels @index 0. With
1643500462a9SThomas Gleixner 		 *
1644500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1645500462a9SThomas Gleixner 		 *  0    0    0    0    0    2
1646500462a9SThomas Gleixner 		 *
1647500462a9SThomas Gleixner 		 * LVL0 has the next expiring bucket @index 2. The upper
1648500462a9SThomas Gleixner 		 * levels have the next expiring bucket @index 1.
1649500462a9SThomas Gleixner 		 *
1650500462a9SThomas Gleixner 		 * In case that the propagation wraps the next level the same
1651500462a9SThomas Gleixner 		 * rules apply:
1652500462a9SThomas Gleixner 		 *
1653500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1654500462a9SThomas Gleixner 		 *  0    0    0    0    F    2
1655500462a9SThomas Gleixner 		 *
1656500462a9SThomas Gleixner 		 * So after looking at LVL0 we get:
1657500462a9SThomas Gleixner 		 *
1658500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1
1659500462a9SThomas Gleixner 		 *  0    0    0    1    0
1660500462a9SThomas Gleixner 		 *
1661500462a9SThomas Gleixner 		 * So no propagation from LVL1 to LVL2 because that happened
1662500462a9SThomas Gleixner 		 * with the add already, but then we need to propagate further
1663500462a9SThomas Gleixner 		 * from LVL2 to LVL3.
1664500462a9SThomas Gleixner 		 *
1665500462a9SThomas Gleixner 		 * So the simple check whether the lower bits of the current
1666500462a9SThomas Gleixner 		 * level are 0 or not is sufficient for all cases.
16675cee9645SThomas Gleixner 		 */
1668001ec1b3SFrederic Weisbecker 		adj = lvl_clk ? 1 : 0;
1669500462a9SThomas Gleixner 		clk >>= LVL_CLK_SHIFT;
1670500462a9SThomas Gleixner 		clk += adj;
16715cee9645SThomas Gleixner 	}
167231cd0e11SFrederic Weisbecker 
167331cd0e11SFrederic Weisbecker 	base->next_expiry_recalc = false;
1674aebacb7fSNicolas Saenz Julienne 	base->timers_pending = !(next == base->clk + NEXT_TIMER_MAX_DELTA);
167531cd0e11SFrederic Weisbecker 
1676500462a9SThomas Gleixner 	return next;
16775cee9645SThomas Gleixner }
16785cee9645SThomas Gleixner 
1679dc2a0f1fSFrederic Weisbecker #ifdef CONFIG_NO_HZ_COMMON
16805cee9645SThomas Gleixner /*
16815cee9645SThomas Gleixner  * Check, if the next hrtimer event is before the next timer wheel
16825cee9645SThomas Gleixner  * event:
16835cee9645SThomas Gleixner  */
1684c1ad348bSThomas Gleixner static u64 cmp_next_hrtimer_event(u64 basem, u64 expires)
16855cee9645SThomas Gleixner {
1686c1ad348bSThomas Gleixner 	u64 nextevt = hrtimer_get_next_event();
16875cee9645SThomas Gleixner 
1688c1ad348bSThomas Gleixner 	/*
1689c1ad348bSThomas Gleixner 	 * If high resolution timers are enabled
1690c1ad348bSThomas Gleixner 	 * hrtimer_get_next_event() returns KTIME_MAX.
1691c1ad348bSThomas Gleixner 	 */
1692c1ad348bSThomas Gleixner 	if (expires <= nextevt)
16935cee9645SThomas Gleixner 		return expires;
16945cee9645SThomas Gleixner 
16955cee9645SThomas Gleixner 	/*
1696c1ad348bSThomas Gleixner 	 * If the next timer is already expired, return the tick base
1697c1ad348bSThomas Gleixner 	 * time so the tick is fired immediately.
16985cee9645SThomas Gleixner 	 */
1699c1ad348bSThomas Gleixner 	if (nextevt <= basem)
1700c1ad348bSThomas Gleixner 		return basem;
17015cee9645SThomas Gleixner 
17025cee9645SThomas Gleixner 	/*
1703c1ad348bSThomas Gleixner 	 * Round up to the next jiffie. High resolution timers are
1704c1ad348bSThomas Gleixner 	 * off, so the hrtimers are expired in the tick and we need to
1705c1ad348bSThomas Gleixner 	 * make sure that this tick really expires the timer to avoid
1706c1ad348bSThomas Gleixner 	 * a ping pong of the nohz stop code.
1707c1ad348bSThomas Gleixner 	 *
1708c1ad348bSThomas Gleixner 	 * Use DIV_ROUND_UP_ULL to prevent gcc calling __divdi3
17095cee9645SThomas Gleixner 	 */
1710c1ad348bSThomas Gleixner 	return DIV_ROUND_UP_ULL(nextevt, TICK_NSEC) * TICK_NSEC;
17115cee9645SThomas Gleixner }
17125cee9645SThomas Gleixner 
17135cee9645SThomas Gleixner /**
1714c1ad348bSThomas Gleixner  * get_next_timer_interrupt - return the time (clock mono) of the next timer
1715c1ad348bSThomas Gleixner  * @basej:	base time jiffies
1716c1ad348bSThomas Gleixner  * @basem:	base time clock monotonic
1717c1ad348bSThomas Gleixner  *
1718c1ad348bSThomas Gleixner  * Returns the tick aligned clock monotonic time of the next pending
1719c1ad348bSThomas Gleixner  * timer or KTIME_MAX if no timer is pending.
17205cee9645SThomas Gleixner  */
1721c1ad348bSThomas Gleixner u64 get_next_timer_interrupt(unsigned long basej, u64 basem)
17225cee9645SThomas Gleixner {
1723500462a9SThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1724c1ad348bSThomas Gleixner 	u64 expires = KTIME_MAX;
1725c1ad348bSThomas Gleixner 	unsigned long nextevt;
17265cee9645SThomas Gleixner 
17275cee9645SThomas Gleixner 	/*
17285cee9645SThomas Gleixner 	 * Pretend that there is no timer pending if the cpu is offline.
17295cee9645SThomas Gleixner 	 * Possible pending timers will be migrated later to an active cpu.
17305cee9645SThomas Gleixner 	 */
17315cee9645SThomas Gleixner 	if (cpu_is_offline(smp_processor_id()))
17325cee9645SThomas Gleixner 		return expires;
17335cee9645SThomas Gleixner 
17342287d866SSebastian Andrzej Siewior 	raw_spin_lock(&base->lock);
173531cd0e11SFrederic Weisbecker 	if (base->next_expiry_recalc)
173631cd0e11SFrederic Weisbecker 		base->next_expiry = __next_timer_interrupt(base);
173731cd0e11SFrederic Weisbecker 	nextevt = base->next_expiry;
173831cd0e11SFrederic Weisbecker 
1739a683f390SThomas Gleixner 	/*
1740041ad7bcSThomas Gleixner 	 * We have a fresh next event. Check whether we can forward the
1741041ad7bcSThomas Gleixner 	 * base. We can only do that when @basej is past base->clk
1742041ad7bcSThomas Gleixner 	 * otherwise we might rewind base->clk.
1743a683f390SThomas Gleixner 	 */
1744041ad7bcSThomas Gleixner 	if (time_after(basej, base->clk)) {
1745041ad7bcSThomas Gleixner 		if (time_after(nextevt, basej))
1746041ad7bcSThomas Gleixner 			base->clk = basej;
1747a683f390SThomas Gleixner 		else if (time_after(nextevt, base->clk))
1748a683f390SThomas Gleixner 			base->clk = nextevt;
1749041ad7bcSThomas Gleixner 	}
1750a683f390SThomas Gleixner 
1751a683f390SThomas Gleixner 	if (time_before_eq(nextevt, basej)) {
1752c1ad348bSThomas Gleixner 		expires = basem;
1753a683f390SThomas Gleixner 		base->is_idle = false;
1754a683f390SThomas Gleixner 	} else {
1755aebacb7fSNicolas Saenz Julienne 		if (base->timers_pending)
175634f41c03SMatija Glavinic Pecotic 			expires = basem + (u64)(nextevt - basej) * TICK_NSEC;
1757a683f390SThomas Gleixner 		/*
17582fe59f50SNicholas Piggin 		 * If we expect to sleep more than a tick, mark the base idle.
17592fe59f50SNicholas Piggin 		 * Also the tick is stopped so any added timer must forward
17602fe59f50SNicholas Piggin 		 * the base clk itself to keep granularity small. This idle
17612fe59f50SNicholas Piggin 		 * logic is only maintained for the BASE_STD base, deferrable
17622fe59f50SNicholas Piggin 		 * timers may still see large granularity skew (by design).
1763a683f390SThomas Gleixner 		 */
17641f8a4212SFrederic Weisbecker 		if ((expires - basem) > TICK_NSEC)
1765a683f390SThomas Gleixner 			base->is_idle = true;
17665cee9645SThomas Gleixner 	}
17672287d866SSebastian Andrzej Siewior 	raw_spin_unlock(&base->lock);
17685cee9645SThomas Gleixner 
1769c1ad348bSThomas Gleixner 	return cmp_next_hrtimer_event(basem, expires);
17705cee9645SThomas Gleixner }
177123696838SAnna-Maria Gleixner 
1772a683f390SThomas Gleixner /**
1773a683f390SThomas Gleixner  * timer_clear_idle - Clear the idle state of the timer base
1774a683f390SThomas Gleixner  *
1775a683f390SThomas Gleixner  * Called with interrupts disabled
1776a683f390SThomas Gleixner  */
1777a683f390SThomas Gleixner void timer_clear_idle(void)
1778a683f390SThomas Gleixner {
1779a683f390SThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1780a683f390SThomas Gleixner 
1781a683f390SThomas Gleixner 	/*
1782a683f390SThomas Gleixner 	 * We do this unlocked. The worst outcome is a remote enqueue sending
1783a683f390SThomas Gleixner 	 * a pointless IPI, but taking the lock would just make the window for
1784a683f390SThomas Gleixner 	 * sending the IPI a few instructions smaller for the cost of taking
1785a683f390SThomas Gleixner 	 * the lock in the exit from idle path.
1786a683f390SThomas Gleixner 	 */
1787a683f390SThomas Gleixner 	base->is_idle = false;
1788a683f390SThomas Gleixner }
17895cee9645SThomas Gleixner #endif
17905cee9645SThomas Gleixner 
179173420feaSAnna-Maria Gleixner /**
179273420feaSAnna-Maria Gleixner  * __run_timers - run all expired timers (if any) on this CPU.
179373420feaSAnna-Maria Gleixner  * @base: the timer vector to be processed.
179473420feaSAnna-Maria Gleixner  */
179573420feaSAnna-Maria Gleixner static inline void __run_timers(struct timer_base *base)
179673420feaSAnna-Maria Gleixner {
179773420feaSAnna-Maria Gleixner 	struct hlist_head heads[LVL_DEPTH];
179873420feaSAnna-Maria Gleixner 	int levels;
179973420feaSAnna-Maria Gleixner 
1800d4f7dae8SFrederic Weisbecker 	if (time_before(jiffies, base->next_expiry))
180173420feaSAnna-Maria Gleixner 		return;
180273420feaSAnna-Maria Gleixner 
1803030dcdd1SAnna-Maria Gleixner 	timer_base_lock_expiry(base);
18042287d866SSebastian Andrzej Siewior 	raw_spin_lock_irq(&base->lock);
180573420feaSAnna-Maria Gleixner 
1806d4f7dae8SFrederic Weisbecker 	while (time_after_eq(jiffies, base->clk) &&
1807d4f7dae8SFrederic Weisbecker 	       time_after_eq(jiffies, base->next_expiry)) {
180873420feaSAnna-Maria Gleixner 		levels = collect_expired_timers(base, heads);
180931cd0e11SFrederic Weisbecker 		/*
1810c54bc0fcSAnna-Maria Behnsen 		 * The two possible reasons for not finding any expired
1811c54bc0fcSAnna-Maria Behnsen 		 * timer at this clk are that all matching timers have been
1812c54bc0fcSAnna-Maria Behnsen 		 * dequeued or no timer has been queued since
1813c54bc0fcSAnna-Maria Behnsen 		 * base::next_expiry was set to base::clk +
1814c54bc0fcSAnna-Maria Behnsen 		 * NEXT_TIMER_MAX_DELTA.
181531cd0e11SFrederic Weisbecker 		 */
1816c54bc0fcSAnna-Maria Behnsen 		WARN_ON_ONCE(!levels && !base->next_expiry_recalc
1817c54bc0fcSAnna-Maria Behnsen 			     && base->timers_pending);
181873420feaSAnna-Maria Gleixner 		base->clk++;
1819dc2a0f1fSFrederic Weisbecker 		base->next_expiry = __next_timer_interrupt(base);
182073420feaSAnna-Maria Gleixner 
182173420feaSAnna-Maria Gleixner 		while (levels--)
182273420feaSAnna-Maria Gleixner 			expire_timers(base, heads + levels);
182373420feaSAnna-Maria Gleixner 	}
18242287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&base->lock);
1825030dcdd1SAnna-Maria Gleixner 	timer_base_unlock_expiry(base);
182673420feaSAnna-Maria Gleixner }
182773420feaSAnna-Maria Gleixner 
18285cee9645SThomas Gleixner /*
18295cee9645SThomas Gleixner  * This function runs timers and the timer-tq in bottom half context.
18305cee9645SThomas Gleixner  */
18310766f788SEmese Revfy static __latent_entropy void run_timer_softirq(struct softirq_action *h)
18325cee9645SThomas Gleixner {
1833500462a9SThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
18345cee9645SThomas Gleixner 
18355cee9645SThomas Gleixner 	__run_timers(base);
1836ced6d5c1SAnna-Maria Gleixner 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON))
1837500462a9SThomas Gleixner 		__run_timers(this_cpu_ptr(&timer_bases[BASE_DEF]));
18385cee9645SThomas Gleixner }
18395cee9645SThomas Gleixner 
18405cee9645SThomas Gleixner /*
18415cee9645SThomas Gleixner  * Called by the local, per-CPU timer interrupt on SMP.
18425cee9645SThomas Gleixner  */
1843cc947f2bSThomas Gleixner static void run_local_timers(void)
18445cee9645SThomas Gleixner {
18454e85876aSThomas Gleixner 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
18464e85876aSThomas Gleixner 
18475cee9645SThomas Gleixner 	hrtimer_run_queues();
18484e85876aSThomas Gleixner 	/* Raise the softirq only if required. */
1849d4f7dae8SFrederic Weisbecker 	if (time_before(jiffies, base->next_expiry)) {
1850ed4bbf79SThomas Gleixner 		if (!IS_ENABLED(CONFIG_NO_HZ_COMMON))
18514e85876aSThomas Gleixner 			return;
18524e85876aSThomas Gleixner 		/* CPU is awake, so check the deferrable base. */
18534e85876aSThomas Gleixner 		base++;
1854d4f7dae8SFrederic Weisbecker 		if (time_before(jiffies, base->next_expiry))
18554e85876aSThomas Gleixner 			return;
18564e85876aSThomas Gleixner 	}
18575cee9645SThomas Gleixner 	raise_softirq(TIMER_SOFTIRQ);
18585cee9645SThomas Gleixner }
18595cee9645SThomas Gleixner 
186058e1177bSKees Cook /*
1861cc947f2bSThomas Gleixner  * Called from the timer interrupt handler to charge one tick to the current
1862cc947f2bSThomas Gleixner  * process.  user_tick is 1 if the tick is user time, 0 for system.
1863cc947f2bSThomas Gleixner  */
1864cc947f2bSThomas Gleixner void update_process_times(int user_tick)
1865cc947f2bSThomas Gleixner {
1866cc947f2bSThomas Gleixner 	struct task_struct *p = current;
1867cc947f2bSThomas Gleixner 
1868cc947f2bSThomas Gleixner 	/* Note: this timer irq context must be accounted for as well. */
1869cc947f2bSThomas Gleixner 	account_process_tick(p, user_tick);
1870cc947f2bSThomas Gleixner 	run_local_timers();
1871cc947f2bSThomas Gleixner 	rcu_sched_clock_irq(user_tick);
1872cc947f2bSThomas Gleixner #ifdef CONFIG_IRQ_WORK
1873cc947f2bSThomas Gleixner 	if (in_irq())
1874cc947f2bSThomas Gleixner 		irq_work_tick();
1875cc947f2bSThomas Gleixner #endif
1876cc947f2bSThomas Gleixner 	scheduler_tick();
1877cc947f2bSThomas Gleixner 	if (IS_ENABLED(CONFIG_POSIX_TIMERS))
1878cc947f2bSThomas Gleixner 		run_posix_cpu_timers();
1879cc947f2bSThomas Gleixner }
1880cc947f2bSThomas Gleixner 
1881cc947f2bSThomas Gleixner /*
188258e1177bSKees Cook  * Since schedule_timeout()'s timer is defined on the stack, it must store
188358e1177bSKees Cook  * the target task on the stack as well.
188458e1177bSKees Cook  */
188558e1177bSKees Cook struct process_timer {
188658e1177bSKees Cook 	struct timer_list timer;
188758e1177bSKees Cook 	struct task_struct *task;
188858e1177bSKees Cook };
188958e1177bSKees Cook 
189058e1177bSKees Cook static void process_timeout(struct timer_list *t)
18915cee9645SThomas Gleixner {
189258e1177bSKees Cook 	struct process_timer *timeout = from_timer(timeout, t, timer);
189358e1177bSKees Cook 
189458e1177bSKees Cook 	wake_up_process(timeout->task);
18955cee9645SThomas Gleixner }
18965cee9645SThomas Gleixner 
18975cee9645SThomas Gleixner /**
18985cee9645SThomas Gleixner  * schedule_timeout - sleep until timeout
18995cee9645SThomas Gleixner  * @timeout: timeout value in jiffies
19005cee9645SThomas Gleixner  *
19016e317c32SAlexander Popov  * Make the current task sleep until @timeout jiffies have elapsed.
19026e317c32SAlexander Popov  * The function behavior depends on the current task state
19036e317c32SAlexander Popov  * (see also set_current_state() description):
19045cee9645SThomas Gleixner  *
19056e317c32SAlexander Popov  * %TASK_RUNNING - the scheduler is called, but the task does not sleep
19066e317c32SAlexander Popov  * at all. That happens because sched_submit_work() does nothing for
19076e317c32SAlexander Popov  * tasks in %TASK_RUNNING state.
19085cee9645SThomas Gleixner  *
19095cee9645SThomas Gleixner  * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
19104b7e9cf9SDouglas Anderson  * pass before the routine returns unless the current task is explicitly
19116e317c32SAlexander Popov  * woken up, (e.g. by wake_up_process()).
19125cee9645SThomas Gleixner  *
19135cee9645SThomas Gleixner  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
19144b7e9cf9SDouglas Anderson  * delivered to the current task or the current task is explicitly woken
19154b7e9cf9SDouglas Anderson  * up.
19165cee9645SThomas Gleixner  *
19176e317c32SAlexander Popov  * The current task state is guaranteed to be %TASK_RUNNING when this
19185cee9645SThomas Gleixner  * routine returns.
19195cee9645SThomas Gleixner  *
19205cee9645SThomas Gleixner  * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
19215cee9645SThomas Gleixner  * the CPU away without a bound on the timeout. In this case the return
19225cee9645SThomas Gleixner  * value will be %MAX_SCHEDULE_TIMEOUT.
19235cee9645SThomas Gleixner  *
19244b7e9cf9SDouglas Anderson  * Returns 0 when the timer has expired otherwise the remaining time in
19254b7e9cf9SDouglas Anderson  * jiffies will be returned. In all cases the return value is guaranteed
19264b7e9cf9SDouglas Anderson  * to be non-negative.
19275cee9645SThomas Gleixner  */
19285cee9645SThomas Gleixner signed long __sched schedule_timeout(signed long timeout)
19295cee9645SThomas Gleixner {
193058e1177bSKees Cook 	struct process_timer timer;
19315cee9645SThomas Gleixner 	unsigned long expire;
19325cee9645SThomas Gleixner 
19335cee9645SThomas Gleixner 	switch (timeout)
19345cee9645SThomas Gleixner 	{
19355cee9645SThomas Gleixner 	case MAX_SCHEDULE_TIMEOUT:
19365cee9645SThomas Gleixner 		/*
19375cee9645SThomas Gleixner 		 * These two special cases are useful to be comfortable
19385cee9645SThomas Gleixner 		 * in the caller. Nothing more. We could take
19395cee9645SThomas Gleixner 		 * MAX_SCHEDULE_TIMEOUT from one of the negative value
19405cee9645SThomas Gleixner 		 * but I' d like to return a valid offset (>=0) to allow
19415cee9645SThomas Gleixner 		 * the caller to do everything it want with the retval.
19425cee9645SThomas Gleixner 		 */
19435cee9645SThomas Gleixner 		schedule();
19445cee9645SThomas Gleixner 		goto out;
19455cee9645SThomas Gleixner 	default:
19465cee9645SThomas Gleixner 		/*
19475cee9645SThomas Gleixner 		 * Another bit of PARANOID. Note that the retval will be
19485cee9645SThomas Gleixner 		 * 0 since no piece of kernel is supposed to do a check
19495cee9645SThomas Gleixner 		 * for a negative retval of schedule_timeout() (since it
19505cee9645SThomas Gleixner 		 * should never happens anyway). You just have the printk()
19515cee9645SThomas Gleixner 		 * that will tell you if something is gone wrong and where.
19525cee9645SThomas Gleixner 		 */
19535cee9645SThomas Gleixner 		if (timeout < 0) {
19545cee9645SThomas Gleixner 			printk(KERN_ERR "schedule_timeout: wrong timeout "
19555cee9645SThomas Gleixner 				"value %lx\n", timeout);
19565cee9645SThomas Gleixner 			dump_stack();
1957600642aeSPeter Zijlstra 			__set_current_state(TASK_RUNNING);
19585cee9645SThomas Gleixner 			goto out;
19595cee9645SThomas Gleixner 		}
19605cee9645SThomas Gleixner 	}
19615cee9645SThomas Gleixner 
19625cee9645SThomas Gleixner 	expire = timeout + jiffies;
19635cee9645SThomas Gleixner 
196458e1177bSKees Cook 	timer.task = current;
196558e1177bSKees Cook 	timer_setup_on_stack(&timer.timer, process_timeout, 0);
196690c01894SEric Dumazet 	__mod_timer(&timer.timer, expire, MOD_TIMER_NOTPENDING);
19675cee9645SThomas Gleixner 	schedule();
19689a5a3056SThomas Gleixner 	del_timer_sync(&timer.timer);
19695cee9645SThomas Gleixner 
19705cee9645SThomas Gleixner 	/* Remove the timer from the object tracker */
197158e1177bSKees Cook 	destroy_timer_on_stack(&timer.timer);
19725cee9645SThomas Gleixner 
19735cee9645SThomas Gleixner 	timeout = expire - jiffies;
19745cee9645SThomas Gleixner 
19755cee9645SThomas Gleixner  out:
19765cee9645SThomas Gleixner 	return timeout < 0 ? 0 : timeout;
19775cee9645SThomas Gleixner }
19785cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout);
19795cee9645SThomas Gleixner 
19805cee9645SThomas Gleixner /*
19815cee9645SThomas Gleixner  * We can use __set_current_state() here because schedule_timeout() calls
19825cee9645SThomas Gleixner  * schedule() unconditionally.
19835cee9645SThomas Gleixner  */
19845cee9645SThomas Gleixner signed long __sched schedule_timeout_interruptible(signed long timeout)
19855cee9645SThomas Gleixner {
19865cee9645SThomas Gleixner 	__set_current_state(TASK_INTERRUPTIBLE);
19875cee9645SThomas Gleixner 	return schedule_timeout(timeout);
19885cee9645SThomas Gleixner }
19895cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout_interruptible);
19905cee9645SThomas Gleixner 
19915cee9645SThomas Gleixner signed long __sched schedule_timeout_killable(signed long timeout)
19925cee9645SThomas Gleixner {
19935cee9645SThomas Gleixner 	__set_current_state(TASK_KILLABLE);
19945cee9645SThomas Gleixner 	return schedule_timeout(timeout);
19955cee9645SThomas Gleixner }
19965cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout_killable);
19975cee9645SThomas Gleixner 
19985cee9645SThomas Gleixner signed long __sched schedule_timeout_uninterruptible(signed long timeout)
19995cee9645SThomas Gleixner {
20005cee9645SThomas Gleixner 	__set_current_state(TASK_UNINTERRUPTIBLE);
20015cee9645SThomas Gleixner 	return schedule_timeout(timeout);
20025cee9645SThomas Gleixner }
20035cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout_uninterruptible);
20045cee9645SThomas Gleixner 
200569b27bafSAndrew Morton /*
200669b27bafSAndrew Morton  * Like schedule_timeout_uninterruptible(), except this task will not contribute
200769b27bafSAndrew Morton  * to load average.
200869b27bafSAndrew Morton  */
200969b27bafSAndrew Morton signed long __sched schedule_timeout_idle(signed long timeout)
201069b27bafSAndrew Morton {
201169b27bafSAndrew Morton 	__set_current_state(TASK_IDLE);
201269b27bafSAndrew Morton 	return schedule_timeout(timeout);
201369b27bafSAndrew Morton }
201469b27bafSAndrew Morton EXPORT_SYMBOL(schedule_timeout_idle);
201569b27bafSAndrew Morton 
20165cee9645SThomas Gleixner #ifdef CONFIG_HOTPLUG_CPU
2017494af3edSThomas Gleixner static void migrate_timer_list(struct timer_base *new_base, struct hlist_head *head)
20185cee9645SThomas Gleixner {
20195cee9645SThomas Gleixner 	struct timer_list *timer;
20200eeda71bSThomas Gleixner 	int cpu = new_base->cpu;
20215cee9645SThomas Gleixner 
20221dabbcecSThomas Gleixner 	while (!hlist_empty(head)) {
20231dabbcecSThomas Gleixner 		timer = hlist_entry(head->first, struct timer_list, entry);
20245cee9645SThomas Gleixner 		detach_timer(timer, false);
20250eeda71bSThomas Gleixner 		timer->flags = (timer->flags & ~TIMER_BASEMASK) | cpu;
20265cee9645SThomas Gleixner 		internal_add_timer(new_base, timer);
20275cee9645SThomas Gleixner 	}
20285cee9645SThomas Gleixner }
20295cee9645SThomas Gleixner 
203026456f87SThomas Gleixner int timers_prepare_cpu(unsigned int cpu)
203126456f87SThomas Gleixner {
203226456f87SThomas Gleixner 	struct timer_base *base;
203326456f87SThomas Gleixner 	int b;
203426456f87SThomas Gleixner 
203526456f87SThomas Gleixner 	for (b = 0; b < NR_BASES; b++) {
203626456f87SThomas Gleixner 		base = per_cpu_ptr(&timer_bases[b], cpu);
203726456f87SThomas Gleixner 		base->clk = jiffies;
203826456f87SThomas Gleixner 		base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
20392731aa7dSAnna-Maria Behnsen 		base->next_expiry_recalc = false;
2040aebacb7fSNicolas Saenz Julienne 		base->timers_pending = false;
204126456f87SThomas Gleixner 		base->is_idle = false;
204226456f87SThomas Gleixner 	}
204326456f87SThomas Gleixner 	return 0;
204426456f87SThomas Gleixner }
204526456f87SThomas Gleixner 
204624f73b99SRichard Cochran int timers_dead_cpu(unsigned int cpu)
20475cee9645SThomas Gleixner {
2048494af3edSThomas Gleixner 	struct timer_base *old_base;
2049494af3edSThomas Gleixner 	struct timer_base *new_base;
2050500462a9SThomas Gleixner 	int b, i;
20515cee9645SThomas Gleixner 
2052500462a9SThomas Gleixner 	for (b = 0; b < NR_BASES; b++) {
2053500462a9SThomas Gleixner 		old_base = per_cpu_ptr(&timer_bases[b], cpu);
2054500462a9SThomas Gleixner 		new_base = get_cpu_ptr(&timer_bases[b]);
20555cee9645SThomas Gleixner 		/*
20565cee9645SThomas Gleixner 		 * The caller is globally serialized and nobody else
20575cee9645SThomas Gleixner 		 * takes two locks at once, deadlock is not possible.
20585cee9645SThomas Gleixner 		 */
20592287d866SSebastian Andrzej Siewior 		raw_spin_lock_irq(&new_base->lock);
20602287d866SSebastian Andrzej Siewior 		raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
20615cee9645SThomas Gleixner 
2062c52232a4SLingutla Chandrasekhar 		/*
2063c52232a4SLingutla Chandrasekhar 		 * The current CPUs base clock might be stale. Update it
2064c52232a4SLingutla Chandrasekhar 		 * before moving the timers over.
2065c52232a4SLingutla Chandrasekhar 		 */
2066c52232a4SLingutla Chandrasekhar 		forward_timer_base(new_base);
2067c52232a4SLingutla Chandrasekhar 
206882ed6f7eSThomas Gleixner 		WARN_ON_ONCE(old_base->running_timer);
206982ed6f7eSThomas Gleixner 		old_base->running_timer = NULL;
20705cee9645SThomas Gleixner 
2071500462a9SThomas Gleixner 		for (i = 0; i < WHEEL_SIZE; i++)
2072500462a9SThomas Gleixner 			migrate_timer_list(new_base, old_base->vectors + i);
20738def9060SViresh Kumar 
20742287d866SSebastian Andrzej Siewior 		raw_spin_unlock(&old_base->lock);
20752287d866SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&new_base->lock);
2076494af3edSThomas Gleixner 		put_cpu_ptr(&timer_bases);
20775cee9645SThomas Gleixner 	}
207824f73b99SRichard Cochran 	return 0;
20795cee9645SThomas Gleixner }
20805cee9645SThomas Gleixner 
20813650b57fSPeter Zijlstra #endif /* CONFIG_HOTPLUG_CPU */
20825cee9645SThomas Gleixner 
20830eeda71bSThomas Gleixner static void __init init_timer_cpu(int cpu)
20848def9060SViresh Kumar {
2085500462a9SThomas Gleixner 	struct timer_base *base;
2086500462a9SThomas Gleixner 	int i;
20873650b57fSPeter Zijlstra 
2088500462a9SThomas Gleixner 	for (i = 0; i < NR_BASES; i++) {
2089500462a9SThomas Gleixner 		base = per_cpu_ptr(&timer_bases[i], cpu);
20908def9060SViresh Kumar 		base->cpu = cpu;
20912287d866SSebastian Andrzej Siewior 		raw_spin_lock_init(&base->lock);
2092494af3edSThomas Gleixner 		base->clk = jiffies;
2093dc2a0f1fSFrederic Weisbecker 		base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
2094030dcdd1SAnna-Maria Gleixner 		timer_base_init_expiry_lock(base);
2095500462a9SThomas Gleixner 	}
20968def9060SViresh Kumar }
20978def9060SViresh Kumar 
20988def9060SViresh Kumar static void __init init_timer_cpus(void)
20998def9060SViresh Kumar {
21008def9060SViresh Kumar 	int cpu;
21018def9060SViresh Kumar 
21020eeda71bSThomas Gleixner 	for_each_possible_cpu(cpu)
21030eeda71bSThomas Gleixner 		init_timer_cpu(cpu);
21048def9060SViresh Kumar }
21055cee9645SThomas Gleixner 
21065cee9645SThomas Gleixner void __init init_timers(void)
21075cee9645SThomas Gleixner {
21088def9060SViresh Kumar 	init_timer_cpus();
21091fb497ddSThomas Gleixner 	posix_cputimers_init_work();
21105cee9645SThomas Gleixner 	open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
21115cee9645SThomas Gleixner }
21125cee9645SThomas Gleixner 
21135cee9645SThomas Gleixner /**
21145cee9645SThomas Gleixner  * msleep - sleep safely even with waitqueue interruptions
21155cee9645SThomas Gleixner  * @msecs: Time in milliseconds to sleep for
21165cee9645SThomas Gleixner  */
21175cee9645SThomas Gleixner void msleep(unsigned int msecs)
21185cee9645SThomas Gleixner {
21195cee9645SThomas Gleixner 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
21205cee9645SThomas Gleixner 
21215cee9645SThomas Gleixner 	while (timeout)
21225cee9645SThomas Gleixner 		timeout = schedule_timeout_uninterruptible(timeout);
21235cee9645SThomas Gleixner }
21245cee9645SThomas Gleixner 
21255cee9645SThomas Gleixner EXPORT_SYMBOL(msleep);
21265cee9645SThomas Gleixner 
21275cee9645SThomas Gleixner /**
21285cee9645SThomas Gleixner  * msleep_interruptible - sleep waiting for signals
21295cee9645SThomas Gleixner  * @msecs: Time in milliseconds to sleep for
21305cee9645SThomas Gleixner  */
21315cee9645SThomas Gleixner unsigned long msleep_interruptible(unsigned int msecs)
21325cee9645SThomas Gleixner {
21335cee9645SThomas Gleixner 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
21345cee9645SThomas Gleixner 
21355cee9645SThomas Gleixner 	while (timeout && !signal_pending(current))
21365cee9645SThomas Gleixner 		timeout = schedule_timeout_interruptible(timeout);
21375cee9645SThomas Gleixner 	return jiffies_to_msecs(timeout);
21385cee9645SThomas Gleixner }
21395cee9645SThomas Gleixner 
21405cee9645SThomas Gleixner EXPORT_SYMBOL(msleep_interruptible);
21415cee9645SThomas Gleixner 
21425cee9645SThomas Gleixner /**
2143e4779015SSeongJae Park  * usleep_range_state - Sleep for an approximate time in a given state
21445cee9645SThomas Gleixner  * @min:	Minimum time in usecs to sleep
21455cee9645SThomas Gleixner  * @max:	Maximum time in usecs to sleep
2146e4779015SSeongJae Park  * @state:	State of the current task that will be while sleeping
2147b5227d03SBjorn Helgaas  *
2148b5227d03SBjorn Helgaas  * In non-atomic context where the exact wakeup time is flexible, use
2149e4779015SSeongJae Park  * usleep_range_state() instead of udelay().  The sleep improves responsiveness
2150b5227d03SBjorn Helgaas  * by avoiding the CPU-hogging busy-wait of udelay(), and the range reduces
2151b5227d03SBjorn Helgaas  * power usage by allowing hrtimers to take advantage of an already-
2152b5227d03SBjorn Helgaas  * scheduled interrupt instead of scheduling a new one just for this sleep.
21535cee9645SThomas Gleixner  */
2154e4779015SSeongJae Park void __sched usleep_range_state(unsigned long min, unsigned long max,
2155e4779015SSeongJae Park 				unsigned int state)
21565cee9645SThomas Gleixner {
21576c5e9059SDouglas Anderson 	ktime_t exp = ktime_add_us(ktime_get(), min);
21586c5e9059SDouglas Anderson 	u64 delta = (u64)(max - min) * NSEC_PER_USEC;
21596c5e9059SDouglas Anderson 
21606c5e9059SDouglas Anderson 	for (;;) {
2161e4779015SSeongJae Park 		__set_current_state(state);
21626c5e9059SDouglas Anderson 		/* Do not return before the requested sleep time has elapsed */
21636c5e9059SDouglas Anderson 		if (!schedule_hrtimeout_range(&exp, delta, HRTIMER_MODE_ABS))
21646c5e9059SDouglas Anderson 			break;
21656c5e9059SDouglas Anderson 	}
21665cee9645SThomas Gleixner }
2167e4779015SSeongJae Park EXPORT_SYMBOL(usleep_range_state);
2168