xref: /linux-6.15/kernel/time/timer.c (revision 78eb4ea2)
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"
567ee98877SAnna-Maria Behnsen #include "timer_migration.h"
57c1ad348bSThomas Gleixner 
585cee9645SThomas Gleixner #define CREATE_TRACE_POINTS
595cee9645SThomas Gleixner #include <trace/events/timer.h>
605cee9645SThomas Gleixner 
615cee9645SThomas Gleixner __visible u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
625cee9645SThomas Gleixner 
635cee9645SThomas Gleixner EXPORT_SYMBOL(jiffies_64);
645cee9645SThomas Gleixner 
655cee9645SThomas Gleixner /*
66500462a9SThomas Gleixner  * The timer wheel has LVL_DEPTH array levels. Each level provides an array of
679e643ab5SRandy Dunlap  * LVL_SIZE buckets. Each level is driven by its own clock and therefore each
68500462a9SThomas Gleixner  * level has a different granularity.
69500462a9SThomas Gleixner  *
709e643ab5SRandy Dunlap  * The level granularity is:		LVL_CLK_DIV ^ level
71500462a9SThomas Gleixner  * The level clock frequency is:	HZ / (LVL_CLK_DIV ^ level)
72500462a9SThomas Gleixner  *
73500462a9SThomas Gleixner  * The array level of a newly armed timer depends on the relative expiry
74500462a9SThomas Gleixner  * time. The farther the expiry time is away the higher the array level and
759e643ab5SRandy Dunlap  * therefore the granularity becomes.
76500462a9SThomas Gleixner  *
77500462a9SThomas Gleixner  * Contrary to the original timer wheel implementation, which aims for 'exact'
78500462a9SThomas Gleixner  * expiry of the timers, this implementation removes the need for recascading
79500462a9SThomas Gleixner  * the timers into the lower array levels. The previous 'classic' timer wheel
80500462a9SThomas Gleixner  * implementation of the kernel already violated the 'exact' expiry by adding
81500462a9SThomas Gleixner  * slack to the expiry time to provide batched expiration. The granularity
82500462a9SThomas Gleixner  * levels provide implicit batching.
83500462a9SThomas Gleixner  *
84500462a9SThomas Gleixner  * This is an optimization of the original timer wheel implementation for the
85500462a9SThomas Gleixner  * majority of the timer wheel use cases: timeouts. The vast majority of
86500462a9SThomas Gleixner  * timeout timers (networking, disk I/O ...) are canceled before expiry. If
87500462a9SThomas Gleixner  * the timeout expires it indicates that normal operation is disturbed, so it
88500462a9SThomas Gleixner  * does not matter much whether the timeout comes with a slight delay.
89500462a9SThomas Gleixner  *
90500462a9SThomas Gleixner  * The only exception to this are networking timers with a small expiry
91500462a9SThomas Gleixner  * time. They rely on the granularity. Those fit into the first wheel level,
92500462a9SThomas Gleixner  * which has HZ granularity.
93500462a9SThomas Gleixner  *
94500462a9SThomas Gleixner  * We don't have cascading anymore. timers with a expiry time above the
95500462a9SThomas Gleixner  * capacity of the last wheel level are force expired at the maximum timeout
96500462a9SThomas Gleixner  * value of the last wheel level. From data sampling we know that the maximum
97500462a9SThomas Gleixner  * value observed is 5 days (network connection tracking), so this should not
98500462a9SThomas Gleixner  * be an issue.
99500462a9SThomas Gleixner  *
100500462a9SThomas Gleixner  * The currently chosen array constants values are a good compromise between
101500462a9SThomas Gleixner  * array size and granularity.
102500462a9SThomas Gleixner  *
103500462a9SThomas Gleixner  * This results in the following granularity and range levels:
104500462a9SThomas Gleixner  *
105500462a9SThomas Gleixner  * HZ 1000 steps
106500462a9SThomas Gleixner  * Level Offset  Granularity            Range
107500462a9SThomas Gleixner  *  0      0         1 ms                0 ms -         63 ms
108500462a9SThomas Gleixner  *  1     64         8 ms               64 ms -        511 ms
109500462a9SThomas Gleixner  *  2    128        64 ms              512 ms -       4095 ms (512ms - ~4s)
110500462a9SThomas Gleixner  *  3    192       512 ms             4096 ms -      32767 ms (~4s - ~32s)
111500462a9SThomas Gleixner  *  4    256      4096 ms (~4s)      32768 ms -     262143 ms (~32s - ~4m)
112500462a9SThomas Gleixner  *  5    320     32768 ms (~32s)    262144 ms -    2097151 ms (~4m - ~34m)
113500462a9SThomas Gleixner  *  6    384    262144 ms (~4m)    2097152 ms -   16777215 ms (~34m - ~4h)
114500462a9SThomas Gleixner  *  7    448   2097152 ms (~34m)  16777216 ms -  134217727 ms (~4h - ~1d)
115500462a9SThomas Gleixner  *  8    512  16777216 ms (~4h)  134217728 ms - 1073741822 ms (~1d - ~12d)
116500462a9SThomas Gleixner  *
117500462a9SThomas Gleixner  * HZ  300
118500462a9SThomas Gleixner  * Level Offset  Granularity            Range
119500462a9SThomas Gleixner  *  0	   0         3 ms                0 ms -        210 ms
120500462a9SThomas Gleixner  *  1	  64        26 ms              213 ms -       1703 ms (213ms - ~1s)
121500462a9SThomas Gleixner  *  2	 128       213 ms             1706 ms -      13650 ms (~1s - ~13s)
122500462a9SThomas Gleixner  *  3	 192      1706 ms (~1s)      13653 ms -     109223 ms (~13s - ~1m)
123500462a9SThomas Gleixner  *  4	 256     13653 ms (~13s)    109226 ms -     873810 ms (~1m - ~14m)
124500462a9SThomas Gleixner  *  5	 320    109226 ms (~1m)     873813 ms -    6990503 ms (~14m - ~1h)
125500462a9SThomas Gleixner  *  6	 384    873813 ms (~14m)   6990506 ms -   55924050 ms (~1h - ~15h)
126500462a9SThomas Gleixner  *  7	 448   6990506 ms (~1h)   55924053 ms -  447392423 ms (~15h - ~5d)
127500462a9SThomas Gleixner  *  8    512  55924053 ms (~15h) 447392426 ms - 3579139406 ms (~5d - ~41d)
128500462a9SThomas Gleixner  *
129500462a9SThomas Gleixner  * HZ  250
130500462a9SThomas Gleixner  * Level Offset  Granularity            Range
131500462a9SThomas Gleixner  *  0	   0         4 ms                0 ms -        255 ms
132500462a9SThomas Gleixner  *  1	  64        32 ms              256 ms -       2047 ms (256ms - ~2s)
133500462a9SThomas Gleixner  *  2	 128       256 ms             2048 ms -      16383 ms (~2s - ~16s)
134500462a9SThomas Gleixner  *  3	 192      2048 ms (~2s)      16384 ms -     131071 ms (~16s - ~2m)
135500462a9SThomas Gleixner  *  4	 256     16384 ms (~16s)    131072 ms -    1048575 ms (~2m - ~17m)
136500462a9SThomas Gleixner  *  5	 320    131072 ms (~2m)    1048576 ms -    8388607 ms (~17m - ~2h)
137500462a9SThomas Gleixner  *  6	 384   1048576 ms (~17m)   8388608 ms -   67108863 ms (~2h - ~18h)
138500462a9SThomas Gleixner  *  7	 448   8388608 ms (~2h)   67108864 ms -  536870911 ms (~18h - ~6d)
139500462a9SThomas Gleixner  *  8    512  67108864 ms (~18h) 536870912 ms - 4294967288 ms (~6d - ~49d)
140500462a9SThomas Gleixner  *
141500462a9SThomas Gleixner  * HZ  100
142500462a9SThomas Gleixner  * Level Offset  Granularity            Range
143500462a9SThomas Gleixner  *  0	   0         10 ms               0 ms -        630 ms
144500462a9SThomas Gleixner  *  1	  64         80 ms             640 ms -       5110 ms (640ms - ~5s)
145500462a9SThomas Gleixner  *  2	 128        640 ms            5120 ms -      40950 ms (~5s - ~40s)
146500462a9SThomas Gleixner  *  3	 192       5120 ms (~5s)     40960 ms -     327670 ms (~40s - ~5m)
147500462a9SThomas Gleixner  *  4	 256      40960 ms (~40s)   327680 ms -    2621430 ms (~5m - ~43m)
148500462a9SThomas Gleixner  *  5	 320     327680 ms (~5m)   2621440 ms -   20971510 ms (~43m - ~5h)
149500462a9SThomas Gleixner  *  6	 384    2621440 ms (~43m) 20971520 ms -  167772150 ms (~5h - ~1d)
150500462a9SThomas Gleixner  *  7	 448   20971520 ms (~5h) 167772160 ms - 1342177270 ms (~1d - ~15d)
1515cee9645SThomas Gleixner  */
1525cee9645SThomas Gleixner 
153500462a9SThomas Gleixner /* Clock divisor for the next level */
154500462a9SThomas Gleixner #define LVL_CLK_SHIFT	3
155500462a9SThomas Gleixner #define LVL_CLK_DIV	(1UL << LVL_CLK_SHIFT)
156500462a9SThomas Gleixner #define LVL_CLK_MASK	(LVL_CLK_DIV - 1)
157500462a9SThomas Gleixner #define LVL_SHIFT(n)	((n) * LVL_CLK_SHIFT)
158500462a9SThomas Gleixner #define LVL_GRAN(n)	(1UL << LVL_SHIFT(n))
1595cee9645SThomas Gleixner 
160500462a9SThomas Gleixner /*
161500462a9SThomas Gleixner  * The time start value for each level to select the bucket at enqueue
16244688972SFrederic Weisbecker  * time. We start from the last possible delta of the previous level
16344688972SFrederic Weisbecker  * so that we can later add an extra LVL_GRAN(n) to n (see calc_index()).
164500462a9SThomas Gleixner  */
165500462a9SThomas Gleixner #define LVL_START(n)	((LVL_SIZE - 1) << (((n) - 1) * LVL_CLK_SHIFT))
1665cee9645SThomas Gleixner 
167500462a9SThomas Gleixner /* Size of each clock level */
168500462a9SThomas Gleixner #define LVL_BITS	6
169500462a9SThomas Gleixner #define LVL_SIZE	(1UL << LVL_BITS)
170500462a9SThomas Gleixner #define LVL_MASK	(LVL_SIZE - 1)
171500462a9SThomas Gleixner #define LVL_OFFS(n)	((n) * LVL_SIZE)
172500462a9SThomas Gleixner 
173500462a9SThomas Gleixner /* Level depth */
174500462a9SThomas Gleixner #if HZ > 100
175500462a9SThomas Gleixner # define LVL_DEPTH	9
176500462a9SThomas Gleixner # else
177500462a9SThomas Gleixner # define LVL_DEPTH	8
178500462a9SThomas Gleixner #endif
179500462a9SThomas Gleixner 
180500462a9SThomas Gleixner /* The cutoff (max. capacity of the wheel) */
181500462a9SThomas Gleixner #define WHEEL_TIMEOUT_CUTOFF	(LVL_START(LVL_DEPTH))
182500462a9SThomas Gleixner #define WHEEL_TIMEOUT_MAX	(WHEEL_TIMEOUT_CUTOFF - LVL_GRAN(LVL_DEPTH - 1))
183500462a9SThomas Gleixner 
184500462a9SThomas Gleixner /*
185500462a9SThomas Gleixner  * The resulting wheel size. If NOHZ is configured we allocate two
186500462a9SThomas Gleixner  * wheels so we have a separate storage for the deferrable timers.
187500462a9SThomas Gleixner  */
188500462a9SThomas Gleixner #define WHEEL_SIZE	(LVL_SIZE * LVL_DEPTH)
189500462a9SThomas Gleixner 
190500462a9SThomas Gleixner #ifdef CONFIG_NO_HZ_COMMON
19183a665dcSAnna-Maria Behnsen /*
19283a665dcSAnna-Maria Behnsen  * If multiple bases need to be locked, use the base ordering for lock
19383a665dcSAnna-Maria Behnsen  * nesting, i.e. lowest number first.
19483a665dcSAnna-Maria Behnsen  */
19583a665dcSAnna-Maria Behnsen # define NR_BASES	3
19683a665dcSAnna-Maria Behnsen # define BASE_LOCAL	0
19783a665dcSAnna-Maria Behnsen # define BASE_GLOBAL	1
19883a665dcSAnna-Maria Behnsen # define BASE_DEF	2
199500462a9SThomas Gleixner #else
200500462a9SThomas Gleixner # define NR_BASES	1
20183a665dcSAnna-Maria Behnsen # define BASE_LOCAL	0
20283a665dcSAnna-Maria Behnsen # define BASE_GLOBAL	0
203500462a9SThomas Gleixner # define BASE_DEF	0
204500462a9SThomas Gleixner #endif
2055cee9645SThomas Gleixner 
206892abd35SAnna-Maria Behnsen /**
207892abd35SAnna-Maria Behnsen  * struct timer_base - Per CPU timer base (number of base depends on config)
208892abd35SAnna-Maria Behnsen  * @lock:		Lock protecting the timer_base
209892abd35SAnna-Maria Behnsen  * @running_timer:	When expiring timers, the lock is dropped. To make
2109e643ab5SRandy Dunlap  *			sure not to race against deleting/modifying a
211892abd35SAnna-Maria Behnsen  *			currently running timer, the pointer is set to the
212892abd35SAnna-Maria Behnsen  *			timer, which expires at the moment. If no timer is
213892abd35SAnna-Maria Behnsen  *			running, the pointer is NULL.
214892abd35SAnna-Maria Behnsen  * @expiry_lock:	PREEMPT_RT only: Lock is taken in softirq around
215892abd35SAnna-Maria Behnsen  *			timer expiry callback execution and when trying to
216892abd35SAnna-Maria Behnsen  *			delete a running timer and it wasn't successful in
217892abd35SAnna-Maria Behnsen  *			the first glance. It prevents priority inversion
218892abd35SAnna-Maria Behnsen  *			when callback was preempted on a remote CPU and a
219892abd35SAnna-Maria Behnsen  *			caller tries to delete the running timer. It also
220892abd35SAnna-Maria Behnsen  *			prevents a life lock, when the task which tries to
221892abd35SAnna-Maria Behnsen  *			delete a timer preempted the softirq thread which
222892abd35SAnna-Maria Behnsen  *			is running the timer callback function.
223892abd35SAnna-Maria Behnsen  * @timer_waiters:	PREEMPT_RT only: Tells, if there is a waiter
224892abd35SAnna-Maria Behnsen  *			waiting for the end of the timer callback function
225892abd35SAnna-Maria Behnsen  *			execution.
226892abd35SAnna-Maria Behnsen  * @clk:		clock of the timer base; is updated before enqueue
227892abd35SAnna-Maria Behnsen  *			of a timer; during expiry, it is 1 offset ahead of
228892abd35SAnna-Maria Behnsen  *			jiffies to avoid endless requeuing to current
229892abd35SAnna-Maria Behnsen  *			jiffies
230892abd35SAnna-Maria Behnsen  * @next_expiry:	expiry value of the first timer; it is updated when
231892abd35SAnna-Maria Behnsen  *			finding the next timer and during enqueue; the
232892abd35SAnna-Maria Behnsen  *			value is not valid, when next_expiry_recalc is set
233892abd35SAnna-Maria Behnsen  * @cpu:		Number of CPU the timer base belongs to
234892abd35SAnna-Maria Behnsen  * @next_expiry_recalc: States, whether a recalculation of next_expiry is
235892abd35SAnna-Maria Behnsen  *			required. Value is set true, when a timer was
236892abd35SAnna-Maria Behnsen  *			deleted.
237892abd35SAnna-Maria Behnsen  * @is_idle:		Is set, when timer_base is idle. It is triggered by NOHZ
238892abd35SAnna-Maria Behnsen  *			code. This state is only used in standard
239892abd35SAnna-Maria Behnsen  *			base. Deferrable timers, which are enqueued remotely
240892abd35SAnna-Maria Behnsen  *			never wake up an idle CPU. So no matter of supporting it
241892abd35SAnna-Maria Behnsen  *			for this base.
242892abd35SAnna-Maria Behnsen  * @timers_pending:	Is set, when a timer is pending in the base. It is only
243892abd35SAnna-Maria Behnsen  *			reliable when next_expiry_recalc is not set.
244892abd35SAnna-Maria Behnsen  * @pending_map:	bitmap of the timer wheel; each bit reflects a
245892abd35SAnna-Maria Behnsen  *			bucket of the wheel. When a bit is set, at least a
246892abd35SAnna-Maria Behnsen  *			single timer is enqueued in the related bucket.
247892abd35SAnna-Maria Behnsen  * @vectors:		Array of lists; Each array member reflects a bucket
248892abd35SAnna-Maria Behnsen  *			of the timer wheel. The list contains all timers
249892abd35SAnna-Maria Behnsen  *			which are enqueued into a specific bucket.
250892abd35SAnna-Maria Behnsen  */
251494af3edSThomas Gleixner struct timer_base {
2522287d866SSebastian Andrzej Siewior 	raw_spinlock_t		lock;
2535cee9645SThomas Gleixner 	struct timer_list	*running_timer;
254030dcdd1SAnna-Maria Gleixner #ifdef CONFIG_PREEMPT_RT
255030dcdd1SAnna-Maria Gleixner 	spinlock_t		expiry_lock;
256030dcdd1SAnna-Maria Gleixner 	atomic_t		timer_waiters;
257030dcdd1SAnna-Maria Gleixner #endif
258494af3edSThomas Gleixner 	unsigned long		clk;
259a683f390SThomas Gleixner 	unsigned long		next_expiry;
260500462a9SThomas Gleixner 	unsigned int		cpu;
26131cd0e11SFrederic Weisbecker 	bool			next_expiry_recalc;
262a683f390SThomas Gleixner 	bool			is_idle;
263aebacb7fSNicolas Saenz Julienne 	bool			timers_pending;
264500462a9SThomas Gleixner 	DECLARE_BITMAP(pending_map, WHEEL_SIZE);
265500462a9SThomas Gleixner 	struct hlist_head	vectors[WHEEL_SIZE];
2665cee9645SThomas Gleixner } ____cacheline_aligned;
2675cee9645SThomas Gleixner 
268500462a9SThomas Gleixner static DEFINE_PER_CPU(struct timer_base, timer_bases[NR_BASES]);
2695cee9645SThomas Gleixner 
270ae67badaSThomas Gleixner #ifdef CONFIG_NO_HZ_COMMON
271ae67badaSThomas Gleixner 
27214c80341SAnna-Maria Gleixner static DEFINE_STATIC_KEY_FALSE(timers_nohz_active);
273ae67badaSThomas Gleixner static DEFINE_MUTEX(timer_keys_mutex);
274ae67badaSThomas Gleixner 
275ae67badaSThomas Gleixner static void timer_update_keys(struct work_struct *work);
276ae67badaSThomas Gleixner static DECLARE_WORK(timer_update_work, timer_update_keys);
277ae67badaSThomas Gleixner 
278ae67badaSThomas Gleixner #ifdef CONFIG_SMP
279efaa0227Stangmeng static unsigned int sysctl_timer_migration = 1;
280bc7a34b8SThomas Gleixner 
281ae67badaSThomas Gleixner DEFINE_STATIC_KEY_FALSE(timers_migration_enabled);
282ae67badaSThomas Gleixner 
283ae67badaSThomas Gleixner static void timers_update_migration(void)
284bc7a34b8SThomas Gleixner {
285ae67badaSThomas Gleixner 	if (sysctl_timer_migration && tick_nohz_active)
286ae67badaSThomas Gleixner 		static_branch_enable(&timers_migration_enabled);
287ae67badaSThomas Gleixner 	else
288ae67badaSThomas Gleixner 		static_branch_disable(&timers_migration_enabled);
289bc7a34b8SThomas Gleixner }
290efaa0227Stangmeng 
291efaa0227Stangmeng #ifdef CONFIG_SYSCTL
292*78eb4ea2SJoel Granados static int timer_migration_handler(const struct ctl_table *table, int write,
293efaa0227Stangmeng 			    void *buffer, size_t *lenp, loff_t *ppos)
294efaa0227Stangmeng {
295efaa0227Stangmeng 	int ret;
296efaa0227Stangmeng 
297efaa0227Stangmeng 	mutex_lock(&timer_keys_mutex);
298efaa0227Stangmeng 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
299efaa0227Stangmeng 	if (!ret && write)
300efaa0227Stangmeng 		timers_update_migration();
301efaa0227Stangmeng 	mutex_unlock(&timer_keys_mutex);
302efaa0227Stangmeng 	return ret;
303efaa0227Stangmeng }
304efaa0227Stangmeng 
305efaa0227Stangmeng static struct ctl_table timer_sysctl[] = {
306efaa0227Stangmeng 	{
307efaa0227Stangmeng 		.procname	= "timer_migration",
308efaa0227Stangmeng 		.data		= &sysctl_timer_migration,
309efaa0227Stangmeng 		.maxlen		= sizeof(unsigned int),
310efaa0227Stangmeng 		.mode		= 0644,
311efaa0227Stangmeng 		.proc_handler	= timer_migration_handler,
312efaa0227Stangmeng 		.extra1		= SYSCTL_ZERO,
313efaa0227Stangmeng 		.extra2		= SYSCTL_ONE,
314efaa0227Stangmeng 	},
315efaa0227Stangmeng };
316efaa0227Stangmeng 
317efaa0227Stangmeng static int __init timer_sysctl_init(void)
318efaa0227Stangmeng {
319efaa0227Stangmeng 	register_sysctl("kernel", timer_sysctl);
320efaa0227Stangmeng 	return 0;
321efaa0227Stangmeng }
322efaa0227Stangmeng device_initcall(timer_sysctl_init);
323efaa0227Stangmeng #endif /* CONFIG_SYSCTL */
324efaa0227Stangmeng #else /* CONFIG_SMP */
325ae67badaSThomas Gleixner static inline void timers_update_migration(void) { }
326ae67badaSThomas Gleixner #endif /* !CONFIG_SMP */
327ae67badaSThomas Gleixner 
328ae67badaSThomas Gleixner static void timer_update_keys(struct work_struct *work)
329ae67badaSThomas Gleixner {
330ae67badaSThomas Gleixner 	mutex_lock(&timer_keys_mutex);
331ae67badaSThomas Gleixner 	timers_update_migration();
332ae67badaSThomas Gleixner 	static_branch_enable(&timers_nohz_active);
333ae67badaSThomas Gleixner 	mutex_unlock(&timer_keys_mutex);
334ae67badaSThomas Gleixner }
335ae67badaSThomas Gleixner 
336ae67badaSThomas Gleixner void timers_update_nohz(void)
337ae67badaSThomas Gleixner {
338ae67badaSThomas Gleixner 	schedule_work(&timer_update_work);
339bc7a34b8SThomas Gleixner }
340bc7a34b8SThomas Gleixner 
34114c80341SAnna-Maria Gleixner static inline bool is_timers_nohz_active(void)
34214c80341SAnna-Maria Gleixner {
34314c80341SAnna-Maria Gleixner 	return static_branch_unlikely(&timers_nohz_active);
34414c80341SAnna-Maria Gleixner }
34514c80341SAnna-Maria Gleixner #else
34614c80341SAnna-Maria Gleixner static inline bool is_timers_nohz_active(void) { return false; }
347ae67badaSThomas Gleixner #endif /* NO_HZ_COMMON */
348bc7a34b8SThomas Gleixner 
3495cee9645SThomas Gleixner static unsigned long round_jiffies_common(unsigned long j, int cpu,
3505cee9645SThomas Gleixner 		bool force_up)
3515cee9645SThomas Gleixner {
3525cee9645SThomas Gleixner 	int rem;
3535cee9645SThomas Gleixner 	unsigned long original = j;
3545cee9645SThomas Gleixner 
3555cee9645SThomas Gleixner 	/*
3565cee9645SThomas Gleixner 	 * We don't want all cpus firing their timers at once hitting the
3575cee9645SThomas Gleixner 	 * same lock or cachelines, so we skew each extra cpu with an extra
3585cee9645SThomas Gleixner 	 * 3 jiffies. This 3 jiffies came originally from the mm/ code which
3595cee9645SThomas Gleixner 	 * already did this.
3605cee9645SThomas Gleixner 	 * The skew is done by adding 3*cpunr, then round, then subtract this
3615cee9645SThomas Gleixner 	 * extra offset again.
3625cee9645SThomas Gleixner 	 */
3635cee9645SThomas Gleixner 	j += cpu * 3;
3645cee9645SThomas Gleixner 
3655cee9645SThomas Gleixner 	rem = j % HZ;
3665cee9645SThomas Gleixner 
3675cee9645SThomas Gleixner 	/*
3685cee9645SThomas Gleixner 	 * If the target jiffie is just after a whole second (which can happen
3695cee9645SThomas Gleixner 	 * due to delays of the timer irq, long irq off times etc etc) then
3705cee9645SThomas Gleixner 	 * we should round down to the whole second, not up. Use 1/4th second
3715cee9645SThomas Gleixner 	 * as cutoff for this rounding as an extreme upper bound for this.
3725cee9645SThomas Gleixner 	 * But never round down if @force_up is set.
3735cee9645SThomas Gleixner 	 */
3745cee9645SThomas Gleixner 	if (rem < HZ/4 && !force_up) /* round down */
3755cee9645SThomas Gleixner 		j = j - rem;
3765cee9645SThomas Gleixner 	else /* round up */
3775cee9645SThomas Gleixner 		j = j - rem + HZ;
3785cee9645SThomas Gleixner 
3795cee9645SThomas Gleixner 	/* now that we have rounded, subtract the extra skew again */
3805cee9645SThomas Gleixner 	j -= cpu * 3;
3815cee9645SThomas Gleixner 
3825cee9645SThomas Gleixner 	/*
3835cee9645SThomas Gleixner 	 * Make sure j is still in the future. Otherwise return the
3845cee9645SThomas Gleixner 	 * unmodified value.
3855cee9645SThomas Gleixner 	 */
3865cee9645SThomas Gleixner 	return time_is_after_jiffies(j) ? j : original;
3875cee9645SThomas Gleixner }
3885cee9645SThomas Gleixner 
3895cee9645SThomas Gleixner /**
3905cee9645SThomas Gleixner  * __round_jiffies - function to round jiffies to a full second
3915cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
3925cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
3935cee9645SThomas Gleixner  *
3945cee9645SThomas Gleixner  * __round_jiffies() rounds an absolute time in the future (in jiffies)
3955cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
3965cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
3975cee9645SThomas Gleixner  * they fire approximately every X seconds.
3985cee9645SThomas Gleixner  *
3995cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
4005cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
4015cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
4025cee9645SThomas Gleixner  *
4035cee9645SThomas Gleixner  * The exact rounding is skewed for each processor to avoid all
4045cee9645SThomas Gleixner  * processors firing at the exact same time, which could lead
4055cee9645SThomas Gleixner  * to lock contention or spurious cache line bouncing.
4065cee9645SThomas Gleixner  *
4075cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
4085cee9645SThomas Gleixner  */
4095cee9645SThomas Gleixner unsigned long __round_jiffies(unsigned long j, int cpu)
4105cee9645SThomas Gleixner {
4115cee9645SThomas Gleixner 	return round_jiffies_common(j, cpu, false);
4125cee9645SThomas Gleixner }
4135cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies);
4145cee9645SThomas Gleixner 
4155cee9645SThomas Gleixner /**
4165cee9645SThomas Gleixner  * __round_jiffies_relative - function to round jiffies to a full second
4175cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
4185cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
4195cee9645SThomas Gleixner  *
4205cee9645SThomas Gleixner  * __round_jiffies_relative() rounds a time delta  in the future (in jiffies)
4215cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
4225cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
4235cee9645SThomas Gleixner  * they fire approximately every X seconds.
4245cee9645SThomas Gleixner  *
4255cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
4265cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
4275cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
4285cee9645SThomas Gleixner  *
4295cee9645SThomas Gleixner  * The exact rounding is skewed for each processor to avoid all
4305cee9645SThomas Gleixner  * processors firing at the exact same time, which could lead
4315cee9645SThomas Gleixner  * to lock contention or spurious cache line bouncing.
4325cee9645SThomas Gleixner  *
4335cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
4345cee9645SThomas Gleixner  */
4355cee9645SThomas Gleixner unsigned long __round_jiffies_relative(unsigned long j, int cpu)
4365cee9645SThomas Gleixner {
4375cee9645SThomas Gleixner 	unsigned long j0 = jiffies;
4385cee9645SThomas Gleixner 
4395cee9645SThomas Gleixner 	/* Use j0 because jiffies might change while we run */
4405cee9645SThomas Gleixner 	return round_jiffies_common(j + j0, cpu, false) - j0;
4415cee9645SThomas Gleixner }
4425cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies_relative);
4435cee9645SThomas Gleixner 
4445cee9645SThomas Gleixner /**
4455cee9645SThomas Gleixner  * round_jiffies - function to round jiffies to a full second
4465cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
4475cee9645SThomas Gleixner  *
4485cee9645SThomas Gleixner  * round_jiffies() rounds an absolute time in the future (in jiffies)
4495cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
4505cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
4515cee9645SThomas Gleixner  * they fire approximately every X seconds.
4525cee9645SThomas Gleixner  *
4535cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
4545cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
4555cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
4565cee9645SThomas Gleixner  *
4575cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
4585cee9645SThomas Gleixner  */
4595cee9645SThomas Gleixner unsigned long round_jiffies(unsigned long j)
4605cee9645SThomas Gleixner {
4615cee9645SThomas Gleixner 	return round_jiffies_common(j, raw_smp_processor_id(), false);
4625cee9645SThomas Gleixner }
4635cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies);
4645cee9645SThomas Gleixner 
4655cee9645SThomas Gleixner /**
4665cee9645SThomas Gleixner  * round_jiffies_relative - function to round jiffies to a full second
4675cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
4685cee9645SThomas Gleixner  *
4695cee9645SThomas Gleixner  * round_jiffies_relative() rounds a time delta  in the future (in jiffies)
4705cee9645SThomas Gleixner  * up or down to (approximately) full seconds. This is useful for timers
4715cee9645SThomas Gleixner  * for which the exact time they fire does not matter too much, as long as
4725cee9645SThomas Gleixner  * they fire approximately every X seconds.
4735cee9645SThomas Gleixner  *
4745cee9645SThomas Gleixner  * By rounding these timers to whole seconds, all such timers will fire
4755cee9645SThomas Gleixner  * at the same time, rather than at various times spread out. The goal
4765cee9645SThomas Gleixner  * of this is to have the CPU wake up less, which saves power.
4775cee9645SThomas Gleixner  *
4785cee9645SThomas Gleixner  * The return value is the rounded version of the @j parameter.
4795cee9645SThomas Gleixner  */
4805cee9645SThomas Gleixner unsigned long round_jiffies_relative(unsigned long j)
4815cee9645SThomas Gleixner {
4825cee9645SThomas Gleixner 	return __round_jiffies_relative(j, raw_smp_processor_id());
4835cee9645SThomas Gleixner }
4845cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies_relative);
4855cee9645SThomas Gleixner 
4865cee9645SThomas Gleixner /**
4875cee9645SThomas Gleixner  * __round_jiffies_up - function to round jiffies up to a full second
4885cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
4895cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
4905cee9645SThomas Gleixner  *
4915cee9645SThomas Gleixner  * This is the same as __round_jiffies() except that it will never
4925cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
4935cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
4945cee9645SThomas Gleixner  * early.
4955cee9645SThomas Gleixner  */
4965cee9645SThomas Gleixner unsigned long __round_jiffies_up(unsigned long j, int cpu)
4975cee9645SThomas Gleixner {
4985cee9645SThomas Gleixner 	return round_jiffies_common(j, cpu, true);
4995cee9645SThomas Gleixner }
5005cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies_up);
5015cee9645SThomas Gleixner 
5025cee9645SThomas Gleixner /**
5035cee9645SThomas Gleixner  * __round_jiffies_up_relative - function to round jiffies up to a full second
5045cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
5055cee9645SThomas Gleixner  * @cpu: the processor number on which the timeout will happen
5065cee9645SThomas Gleixner  *
5075cee9645SThomas Gleixner  * This is the same as __round_jiffies_relative() except that it will never
5085cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
5095cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
5105cee9645SThomas Gleixner  * early.
5115cee9645SThomas Gleixner  */
5125cee9645SThomas Gleixner unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
5135cee9645SThomas Gleixner {
5145cee9645SThomas Gleixner 	unsigned long j0 = jiffies;
5155cee9645SThomas Gleixner 
5165cee9645SThomas Gleixner 	/* Use j0 because jiffies might change while we run */
5175cee9645SThomas Gleixner 	return round_jiffies_common(j + j0, cpu, true) - j0;
5185cee9645SThomas Gleixner }
5195cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(__round_jiffies_up_relative);
5205cee9645SThomas Gleixner 
5215cee9645SThomas Gleixner /**
5225cee9645SThomas Gleixner  * round_jiffies_up - function to round jiffies up to a full second
5235cee9645SThomas Gleixner  * @j: the time in (absolute) jiffies that should be rounded
5245cee9645SThomas Gleixner  *
5255cee9645SThomas Gleixner  * This is the same as round_jiffies() except that it will never
5265cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
5275cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
5285cee9645SThomas Gleixner  * early.
5295cee9645SThomas Gleixner  */
5305cee9645SThomas Gleixner unsigned long round_jiffies_up(unsigned long j)
5315cee9645SThomas Gleixner {
5325cee9645SThomas Gleixner 	return round_jiffies_common(j, raw_smp_processor_id(), true);
5335cee9645SThomas Gleixner }
5345cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies_up);
5355cee9645SThomas Gleixner 
5365cee9645SThomas Gleixner /**
5375cee9645SThomas Gleixner  * round_jiffies_up_relative - function to round jiffies up to a full second
5385cee9645SThomas Gleixner  * @j: the time in (relative) jiffies that should be rounded
5395cee9645SThomas Gleixner  *
5405cee9645SThomas Gleixner  * This is the same as round_jiffies_relative() except that it will never
5415cee9645SThomas Gleixner  * round down.  This is useful for timeouts for which the exact time
5425cee9645SThomas Gleixner  * of firing does not matter too much, as long as they don't fire too
5435cee9645SThomas Gleixner  * early.
5445cee9645SThomas Gleixner  */
5455cee9645SThomas Gleixner unsigned long round_jiffies_up_relative(unsigned long j)
5465cee9645SThomas Gleixner {
5475cee9645SThomas Gleixner 	return __round_jiffies_up_relative(j, raw_smp_processor_id());
5485cee9645SThomas Gleixner }
5495cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(round_jiffies_up_relative);
5505cee9645SThomas Gleixner 
5515cee9645SThomas Gleixner 
552500462a9SThomas Gleixner static inline unsigned int timer_get_idx(struct timer_list *timer)
5535cee9645SThomas Gleixner {
554500462a9SThomas Gleixner 	return (timer->flags & TIMER_ARRAYMASK) >> TIMER_ARRAYSHIFT;
5555cee9645SThomas Gleixner }
556500462a9SThomas Gleixner 
557500462a9SThomas Gleixner static inline void timer_set_idx(struct timer_list *timer, unsigned int idx)
558500462a9SThomas Gleixner {
559500462a9SThomas Gleixner 	timer->flags = (timer->flags & ~TIMER_ARRAYMASK) |
560500462a9SThomas Gleixner 			idx << TIMER_ARRAYSHIFT;
561500462a9SThomas Gleixner }
562500462a9SThomas Gleixner 
563500462a9SThomas Gleixner /*
564500462a9SThomas Gleixner  * Helper function to calculate the array index for a given expiry
565500462a9SThomas Gleixner  * time.
566500462a9SThomas Gleixner  */
5671f32cab0SAnna-Maria Behnsen static inline unsigned calc_index(unsigned long expires, unsigned lvl,
5681f32cab0SAnna-Maria Behnsen 				  unsigned long *bucket_expiry)
569500462a9SThomas Gleixner {
57044688972SFrederic Weisbecker 
57144688972SFrederic Weisbecker 	/*
57244688972SFrederic Weisbecker 	 * The timer wheel has to guarantee that a timer does not fire
57344688972SFrederic Weisbecker 	 * early. Early expiry can happen due to:
57444688972SFrederic Weisbecker 	 * - Timer is armed at the edge of a tick
57544688972SFrederic Weisbecker 	 * - Truncation of the expiry time in the outer wheel levels
57644688972SFrederic Weisbecker 	 *
57744688972SFrederic Weisbecker 	 * Round up with level granularity to prevent this.
57844688972SFrederic Weisbecker 	 */
579a2026e44SThomas Gleixner 	expires = (expires >> LVL_SHIFT(lvl)) + 1;
5801f32cab0SAnna-Maria Behnsen 	*bucket_expiry = expires << LVL_SHIFT(lvl);
581500462a9SThomas Gleixner 	return LVL_OFFS(lvl) + (expires & LVL_MASK);
582500462a9SThomas Gleixner }
583500462a9SThomas Gleixner 
5841f32cab0SAnna-Maria Behnsen static int calc_wheel_index(unsigned long expires, unsigned long clk,
5851f32cab0SAnna-Maria Behnsen 			    unsigned long *bucket_expiry)
5865cee9645SThomas Gleixner {
587ffdf0477SAnna-Maria Gleixner 	unsigned long delta = expires - clk;
588500462a9SThomas Gleixner 	unsigned int idx;
5895cee9645SThomas Gleixner 
590500462a9SThomas Gleixner 	if (delta < LVL_START(1)) {
5911f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 0, bucket_expiry);
592500462a9SThomas Gleixner 	} else if (delta < LVL_START(2)) {
5931f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 1, bucket_expiry);
594500462a9SThomas Gleixner 	} else if (delta < LVL_START(3)) {
5951f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 2, bucket_expiry);
596500462a9SThomas Gleixner 	} else if (delta < LVL_START(4)) {
5971f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 3, bucket_expiry);
598500462a9SThomas Gleixner 	} else if (delta < LVL_START(5)) {
5991f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 4, bucket_expiry);
600500462a9SThomas Gleixner 	} else if (delta < LVL_START(6)) {
6011f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 5, bucket_expiry);
602500462a9SThomas Gleixner 	} else if (delta < LVL_START(7)) {
6031f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 6, bucket_expiry);
604500462a9SThomas Gleixner 	} else if (LVL_DEPTH > 8 && delta < LVL_START(8)) {
6051f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, 7, bucket_expiry);
606500462a9SThomas Gleixner 	} else if ((long) delta < 0) {
607ffdf0477SAnna-Maria Gleixner 		idx = clk & LVL_MASK;
6081f32cab0SAnna-Maria Behnsen 		*bucket_expiry = clk;
6095cee9645SThomas Gleixner 	} else {
610500462a9SThomas Gleixner 		/*
611500462a9SThomas Gleixner 		 * Force expire obscene large timeouts to expire at the
612500462a9SThomas Gleixner 		 * capacity limit of the wheel.
6135cee9645SThomas Gleixner 		 */
614e2a71bdeSFrederic Weisbecker 		if (delta >= WHEEL_TIMEOUT_CUTOFF)
615e2a71bdeSFrederic Weisbecker 			expires = clk + WHEEL_TIMEOUT_MAX;
6161bd04bf6SThomas Gleixner 
6171f32cab0SAnna-Maria Behnsen 		idx = calc_index(expires, LVL_DEPTH - 1, bucket_expiry);
618500462a9SThomas Gleixner 	}
619ffdf0477SAnna-Maria Gleixner 	return idx;
620ffdf0477SAnna-Maria Gleixner }
621ffdf0477SAnna-Maria Gleixner 
622ffdf0477SAnna-Maria Gleixner static void
623ffdf0477SAnna-Maria Gleixner trigger_dyntick_cpu(struct timer_base *base, struct timer_list *timer)
6245cee9645SThomas Gleixner {
6255cee9645SThomas Gleixner 	/*
626d124c339SAnna-Maria Behnsen 	 * Deferrable timers do not prevent the CPU from entering dynticks and
627d124c339SAnna-Maria Behnsen 	 * are not taken into account on the idle/nohz_full path. An IPI when a
628d124c339SAnna-Maria Behnsen 	 * new deferrable timer is enqueued will wake up the remote CPU but
629d124c339SAnna-Maria Behnsen 	 * nothing will be done with the deferrable timer base. Therefore skip
630d124c339SAnna-Maria Behnsen 	 * the remote IPI for deferrable timers completely.
6315cee9645SThomas Gleixner 	 */
632d124c339SAnna-Maria Behnsen 	if (!is_timers_nohz_active() || timer->flags & TIMER_DEFERRABLE)
633a683f390SThomas Gleixner 		return;
6349f6d9baaSViresh Kumar 
6359f6d9baaSViresh Kumar 	/*
636a683f390SThomas Gleixner 	 * We might have to IPI the remote CPU if the base is idle and the
637b2cf7507SAnna-Maria Behnsen 	 * timer is pinned. If it is a non pinned timer, it is only queued
638b2cf7507SAnna-Maria Behnsen 	 * on the remote CPU, when timer was running during queueing. Then
639b2cf7507SAnna-Maria Behnsen 	 * everything is handled by remote CPU anyway. If the other CPU is
640b2cf7507SAnna-Maria Behnsen 	 * on the way to idle then it can't set base->is_idle as we hold
641b2cf7507SAnna-Maria Behnsen 	 * the base lock:
6429f6d9baaSViresh Kumar 	 */
643b2cf7507SAnna-Maria Behnsen 	if (base->is_idle) {
64403877039SFrederic Weisbecker 		WARN_ON_ONCE(!(timer->flags & TIMER_PINNED ||
64503877039SFrederic Weisbecker 			       tick_nohz_full_cpu(base->cpu)));
6469f6d9baaSViresh Kumar 		wake_up_nohz_cpu(base->cpu);
6475cee9645SThomas Gleixner 	}
648b2cf7507SAnna-Maria Behnsen }
6495cee9645SThomas Gleixner 
6509a2b764bSFrederic Weisbecker /*
6519a2b764bSFrederic Weisbecker  * Enqueue the timer into the hash bucket, mark it pending in
6529a2b764bSFrederic Weisbecker  * the bitmap, store the index in the timer flags then wake up
6539a2b764bSFrederic Weisbecker  * the target CPU if needed.
6549a2b764bSFrederic Weisbecker  */
6559a2b764bSFrederic Weisbecker static void enqueue_timer(struct timer_base *base, struct timer_list *timer,
6569a2b764bSFrederic Weisbecker 			  unsigned int idx, unsigned long bucket_expiry)
657ffdf0477SAnna-Maria Gleixner {
658dc2a0f1fSFrederic Weisbecker 
6599a2b764bSFrederic Weisbecker 	hlist_add_head(&timer->entry, base->vectors + idx);
6609a2b764bSFrederic Weisbecker 	__set_bit(idx, base->pending_map);
6619a2b764bSFrederic Weisbecker 	timer_set_idx(timer, idx);
6629a2b764bSFrederic Weisbecker 
663dbcdcb62SAnna-Maria Behnsen 	trace_timer_start(timer, bucket_expiry);
664dc2a0f1fSFrederic Weisbecker 
665dc2a0f1fSFrederic Weisbecker 	/*
666dc2a0f1fSFrederic Weisbecker 	 * Check whether this is the new first expiring timer. The
667dc2a0f1fSFrederic Weisbecker 	 * effective expiry time of the timer is required here
668dc2a0f1fSFrederic Weisbecker 	 * (bucket_expiry) instead of timer->expires.
669dc2a0f1fSFrederic Weisbecker 	 */
670dc2a0f1fSFrederic Weisbecker 	if (time_before(bucket_expiry, base->next_expiry)) {
671dc2a0f1fSFrederic Weisbecker 		/*
672dc2a0f1fSFrederic Weisbecker 		 * Set the next expiry time and kick the CPU so it
673dc2a0f1fSFrederic Weisbecker 		 * can reevaluate the wheel:
674dc2a0f1fSFrederic Weisbecker 		 */
675dc2a0f1fSFrederic Weisbecker 		base->next_expiry = bucket_expiry;
676aebacb7fSNicolas Saenz Julienne 		base->timers_pending = true;
67731cd0e11SFrederic Weisbecker 		base->next_expiry_recalc = false;
678ffdf0477SAnna-Maria Gleixner 		trigger_dyntick_cpu(base, timer);
6795cee9645SThomas Gleixner 	}
6809a2b764bSFrederic Weisbecker }
6819a2b764bSFrederic Weisbecker 
6829a2b764bSFrederic Weisbecker static void internal_add_timer(struct timer_base *base, struct timer_list *timer)
6835cee9645SThomas Gleixner {
6841f32cab0SAnna-Maria Behnsen 	unsigned long bucket_expiry;
6859a2b764bSFrederic Weisbecker 	unsigned int idx;
6861f32cab0SAnna-Maria Behnsen 
6879a2b764bSFrederic Weisbecker 	idx = calc_wheel_index(timer->expires, base->clk, &bucket_expiry);
6889a2b764bSFrederic Weisbecker 	enqueue_timer(base, timer, idx, bucket_expiry);
6895cee9645SThomas Gleixner }
6905cee9645SThomas Gleixner 
6915cee9645SThomas Gleixner #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
6925cee9645SThomas Gleixner 
693f9e62f31SStephen Boyd static const struct debug_obj_descr timer_debug_descr;
6945cee9645SThomas Gleixner 
695317f29c1SStephen Boyd struct timer_hint {
696317f29c1SStephen Boyd 	void	(*function)(struct timer_list *t);
697317f29c1SStephen Boyd 	long	offset;
698317f29c1SStephen Boyd };
699317f29c1SStephen Boyd 
700317f29c1SStephen Boyd #define TIMER_HINT(fn, container, timr, hintfn)			\
701317f29c1SStephen Boyd 	{							\
702317f29c1SStephen Boyd 		.function = fn,					\
703317f29c1SStephen Boyd 		.offset	  = offsetof(container, hintfn) -	\
704317f29c1SStephen Boyd 			    offsetof(container, timr)		\
705317f29c1SStephen Boyd 	}
706317f29c1SStephen Boyd 
707317f29c1SStephen Boyd static const struct timer_hint timer_hints[] = {
708317f29c1SStephen Boyd 	TIMER_HINT(delayed_work_timer_fn,
709317f29c1SStephen Boyd 		   struct delayed_work, timer, work.func),
710317f29c1SStephen Boyd 	TIMER_HINT(kthread_delayed_work_timer_fn,
711317f29c1SStephen Boyd 		   struct kthread_delayed_work, timer, work.func),
712317f29c1SStephen Boyd };
713317f29c1SStephen Boyd 
7145cee9645SThomas Gleixner static void *timer_debug_hint(void *addr)
7155cee9645SThomas Gleixner {
716317f29c1SStephen Boyd 	struct timer_list *timer = addr;
717317f29c1SStephen Boyd 	int i;
718317f29c1SStephen Boyd 
719317f29c1SStephen Boyd 	for (i = 0; i < ARRAY_SIZE(timer_hints); i++) {
720317f29c1SStephen Boyd 		if (timer_hints[i].function == timer->function) {
721317f29c1SStephen Boyd 			void (**fn)(void) = addr + timer_hints[i].offset;
722317f29c1SStephen Boyd 
723317f29c1SStephen Boyd 			return *fn;
724317f29c1SStephen Boyd 		}
725317f29c1SStephen Boyd 	}
726317f29c1SStephen Boyd 
727317f29c1SStephen Boyd 	return timer->function;
7285cee9645SThomas Gleixner }
7295cee9645SThomas Gleixner 
730b9fdac7fSDu, Changbin static bool timer_is_static_object(void *addr)
731b9fdac7fSDu, Changbin {
732b9fdac7fSDu, Changbin 	struct timer_list *timer = addr;
733b9fdac7fSDu, Changbin 
734b9fdac7fSDu, Changbin 	return (timer->entry.pprev == NULL &&
735b9fdac7fSDu, Changbin 		timer->entry.next == TIMER_ENTRY_STATIC);
736b9fdac7fSDu, Changbin }
737b9fdac7fSDu, Changbin 
7385cee9645SThomas Gleixner /*
7399e643ab5SRandy Dunlap  * timer_fixup_init is called when:
7405cee9645SThomas Gleixner  * - an active object is initialized
7415cee9645SThomas Gleixner  */
742e3252464SDu, Changbin static bool timer_fixup_init(void *addr, enum debug_obj_state state)
7435cee9645SThomas Gleixner {
7445cee9645SThomas Gleixner 	struct timer_list *timer = addr;
7455cee9645SThomas Gleixner 
7465cee9645SThomas Gleixner 	switch (state) {
7475cee9645SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
7485cee9645SThomas Gleixner 		del_timer_sync(timer);
7495cee9645SThomas Gleixner 		debug_object_init(timer, &timer_debug_descr);
750e3252464SDu, Changbin 		return true;
7515cee9645SThomas Gleixner 	default:
752e3252464SDu, Changbin 		return false;
7535cee9645SThomas Gleixner 	}
7545cee9645SThomas Gleixner }
7555cee9645SThomas Gleixner 
7565cee9645SThomas Gleixner /* Stub timer callback for improperly used timers. */
757ba16490eSThomas Gleixner static void stub_timer(struct timer_list *unused)
7585cee9645SThomas Gleixner {
7595cee9645SThomas Gleixner 	WARN_ON(1);
7605cee9645SThomas Gleixner }
7615cee9645SThomas Gleixner 
7625cee9645SThomas Gleixner /*
7639e643ab5SRandy Dunlap  * timer_fixup_activate is called when:
7645cee9645SThomas Gleixner  * - an active object is activated
765b9fdac7fSDu, Changbin  * - an unknown non-static object is activated
7665cee9645SThomas Gleixner  */
767e3252464SDu, Changbin static bool timer_fixup_activate(void *addr, enum debug_obj_state state)
7685cee9645SThomas Gleixner {
7695cee9645SThomas Gleixner 	struct timer_list *timer = addr;
7705cee9645SThomas Gleixner 
7715cee9645SThomas Gleixner 	switch (state) {
7725cee9645SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
773ba16490eSThomas Gleixner 		timer_setup(timer, stub_timer, 0);
774e3252464SDu, Changbin 		return true;
7755cee9645SThomas Gleixner 
7765cee9645SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
7775cee9645SThomas Gleixner 		WARN_ON(1);
778df561f66SGustavo A. R. Silva 		fallthrough;
7795cee9645SThomas Gleixner 	default:
780e3252464SDu, Changbin 		return false;
7815cee9645SThomas Gleixner 	}
7825cee9645SThomas Gleixner }
7835cee9645SThomas Gleixner 
7845cee9645SThomas Gleixner /*
7859e643ab5SRandy Dunlap  * timer_fixup_free is called when:
7865cee9645SThomas Gleixner  * - an active object is freed
7875cee9645SThomas Gleixner  */
788e3252464SDu, Changbin static bool timer_fixup_free(void *addr, enum debug_obj_state state)
7895cee9645SThomas Gleixner {
7905cee9645SThomas Gleixner 	struct timer_list *timer = addr;
7915cee9645SThomas Gleixner 
7925cee9645SThomas Gleixner 	switch (state) {
7935cee9645SThomas Gleixner 	case ODEBUG_STATE_ACTIVE:
7945cee9645SThomas Gleixner 		del_timer_sync(timer);
7955cee9645SThomas Gleixner 		debug_object_free(timer, &timer_debug_descr);
796e3252464SDu, Changbin 		return true;
7975cee9645SThomas Gleixner 	default:
798e3252464SDu, Changbin 		return false;
7995cee9645SThomas Gleixner 	}
8005cee9645SThomas Gleixner }
8015cee9645SThomas Gleixner 
8025cee9645SThomas Gleixner /*
8039e643ab5SRandy Dunlap  * timer_fixup_assert_init is called when:
8045cee9645SThomas Gleixner  * - an untracked/uninit-ed object is found
8055cee9645SThomas Gleixner  */
806e3252464SDu, Changbin static bool timer_fixup_assert_init(void *addr, enum debug_obj_state state)
8075cee9645SThomas Gleixner {
8085cee9645SThomas Gleixner 	struct timer_list *timer = addr;
8095cee9645SThomas Gleixner 
8105cee9645SThomas Gleixner 	switch (state) {
8115cee9645SThomas Gleixner 	case ODEBUG_STATE_NOTAVAILABLE:
812ba16490eSThomas Gleixner 		timer_setup(timer, stub_timer, 0);
813e3252464SDu, Changbin 		return true;
8145cee9645SThomas Gleixner 	default:
815e3252464SDu, Changbin 		return false;
8165cee9645SThomas Gleixner 	}
8175cee9645SThomas Gleixner }
8185cee9645SThomas Gleixner 
819f9e62f31SStephen Boyd static const struct debug_obj_descr timer_debug_descr = {
8205cee9645SThomas Gleixner 	.name			= "timer_list",
8215cee9645SThomas Gleixner 	.debug_hint		= timer_debug_hint,
822b9fdac7fSDu, Changbin 	.is_static_object	= timer_is_static_object,
8235cee9645SThomas Gleixner 	.fixup_init		= timer_fixup_init,
8245cee9645SThomas Gleixner 	.fixup_activate		= timer_fixup_activate,
8255cee9645SThomas Gleixner 	.fixup_free		= timer_fixup_free,
8265cee9645SThomas Gleixner 	.fixup_assert_init	= timer_fixup_assert_init,
8275cee9645SThomas Gleixner };
8285cee9645SThomas Gleixner 
8295cee9645SThomas Gleixner static inline void debug_timer_init(struct timer_list *timer)
8305cee9645SThomas Gleixner {
8315cee9645SThomas Gleixner 	debug_object_init(timer, &timer_debug_descr);
8325cee9645SThomas Gleixner }
8335cee9645SThomas Gleixner 
8345cee9645SThomas Gleixner static inline void debug_timer_activate(struct timer_list *timer)
8355cee9645SThomas Gleixner {
8365cee9645SThomas Gleixner 	debug_object_activate(timer, &timer_debug_descr);
8375cee9645SThomas Gleixner }
8385cee9645SThomas Gleixner 
8395cee9645SThomas Gleixner static inline void debug_timer_deactivate(struct timer_list *timer)
8405cee9645SThomas Gleixner {
8415cee9645SThomas Gleixner 	debug_object_deactivate(timer, &timer_debug_descr);
8425cee9645SThomas Gleixner }
8435cee9645SThomas Gleixner 
8445cee9645SThomas Gleixner static inline void debug_timer_assert_init(struct timer_list *timer)
8455cee9645SThomas Gleixner {
8465cee9645SThomas Gleixner 	debug_object_assert_init(timer, &timer_debug_descr);
8475cee9645SThomas Gleixner }
8485cee9645SThomas Gleixner 
849188665b2SKees Cook static void do_init_timer(struct timer_list *timer,
850188665b2SKees Cook 			  void (*func)(struct timer_list *),
851188665b2SKees Cook 			  unsigned int flags,
8525cee9645SThomas Gleixner 			  const char *name, struct lock_class_key *key);
8535cee9645SThomas Gleixner 
854188665b2SKees Cook void init_timer_on_stack_key(struct timer_list *timer,
855188665b2SKees Cook 			     void (*func)(struct timer_list *),
856188665b2SKees Cook 			     unsigned int flags,
8575cee9645SThomas Gleixner 			     const char *name, struct lock_class_key *key)
8585cee9645SThomas Gleixner {
8595cee9645SThomas Gleixner 	debug_object_init_on_stack(timer, &timer_debug_descr);
860188665b2SKees Cook 	do_init_timer(timer, func, flags, name, key);
8615cee9645SThomas Gleixner }
8625cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(init_timer_on_stack_key);
8635cee9645SThomas Gleixner 
8645cee9645SThomas Gleixner void destroy_timer_on_stack(struct timer_list *timer)
8655cee9645SThomas Gleixner {
8665cee9645SThomas Gleixner 	debug_object_free(timer, &timer_debug_descr);
8675cee9645SThomas Gleixner }
8685cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(destroy_timer_on_stack);
8695cee9645SThomas Gleixner 
8705cee9645SThomas Gleixner #else
8715cee9645SThomas Gleixner static inline void debug_timer_init(struct timer_list *timer) { }
8725cee9645SThomas Gleixner static inline void debug_timer_activate(struct timer_list *timer) { }
8735cee9645SThomas Gleixner static inline void debug_timer_deactivate(struct timer_list *timer) { }
8745cee9645SThomas Gleixner static inline void debug_timer_assert_init(struct timer_list *timer) { }
8755cee9645SThomas Gleixner #endif
8765cee9645SThomas Gleixner 
8775cee9645SThomas Gleixner static inline void debug_init(struct timer_list *timer)
8785cee9645SThomas Gleixner {
8795cee9645SThomas Gleixner 	debug_timer_init(timer);
8805cee9645SThomas Gleixner 	trace_timer_init(timer);
8815cee9645SThomas Gleixner }
8825cee9645SThomas Gleixner 
8835cee9645SThomas Gleixner static inline void debug_deactivate(struct timer_list *timer)
8845cee9645SThomas Gleixner {
8855cee9645SThomas Gleixner 	debug_timer_deactivate(timer);
8865cee9645SThomas Gleixner 	trace_timer_cancel(timer);
8875cee9645SThomas Gleixner }
8885cee9645SThomas Gleixner 
8895cee9645SThomas Gleixner static inline void debug_assert_init(struct timer_list *timer)
8905cee9645SThomas Gleixner {
8915cee9645SThomas Gleixner 	debug_timer_assert_init(timer);
8925cee9645SThomas Gleixner }
8935cee9645SThomas Gleixner 
894188665b2SKees Cook static void do_init_timer(struct timer_list *timer,
895188665b2SKees Cook 			  void (*func)(struct timer_list *),
896188665b2SKees Cook 			  unsigned int flags,
8975cee9645SThomas Gleixner 			  const char *name, struct lock_class_key *key)
8985cee9645SThomas Gleixner {
8991dabbcecSThomas Gleixner 	timer->entry.pprev = NULL;
900188665b2SKees Cook 	timer->function = func;
901b952caf2SQianli Zhao 	if (WARN_ON_ONCE(flags & ~TIMER_INIT_FLAGS))
902b952caf2SQianli Zhao 		flags &= TIMER_INIT_FLAGS;
9030eeda71bSThomas Gleixner 	timer->flags = flags | raw_smp_processor_id();
9045cee9645SThomas Gleixner 	lockdep_init_map(&timer->lockdep_map, name, key, 0);
9055cee9645SThomas Gleixner }
9065cee9645SThomas Gleixner 
9075cee9645SThomas Gleixner /**
9085cee9645SThomas Gleixner  * init_timer_key - initialize a timer
9095cee9645SThomas Gleixner  * @timer: the timer to be initialized
910188665b2SKees Cook  * @func: timer callback function
9115cee9645SThomas Gleixner  * @flags: timer flags
9125cee9645SThomas Gleixner  * @name: name of the timer
9135cee9645SThomas Gleixner  * @key: lockdep class key of the fake lock used for tracking timer
9145cee9645SThomas Gleixner  *       sync lock dependencies
9155cee9645SThomas Gleixner  *
9169e643ab5SRandy Dunlap  * init_timer_key() must be done to a timer prior to calling *any* of the
9175cee9645SThomas Gleixner  * other timer functions.
9185cee9645SThomas Gleixner  */
919188665b2SKees Cook void init_timer_key(struct timer_list *timer,
920188665b2SKees Cook 		    void (*func)(struct timer_list *), unsigned int flags,
9215cee9645SThomas Gleixner 		    const char *name, struct lock_class_key *key)
9225cee9645SThomas Gleixner {
9235cee9645SThomas Gleixner 	debug_init(timer);
924188665b2SKees Cook 	do_init_timer(timer, func, flags, name, key);
9255cee9645SThomas Gleixner }
9265cee9645SThomas Gleixner EXPORT_SYMBOL(init_timer_key);
9275cee9645SThomas Gleixner 
9285cee9645SThomas Gleixner static inline void detach_timer(struct timer_list *timer, bool clear_pending)
9295cee9645SThomas Gleixner {
9301dabbcecSThomas Gleixner 	struct hlist_node *entry = &timer->entry;
9315cee9645SThomas Gleixner 
9325cee9645SThomas Gleixner 	debug_deactivate(timer);
9335cee9645SThomas Gleixner 
9341dabbcecSThomas Gleixner 	__hlist_del(entry);
9355cee9645SThomas Gleixner 	if (clear_pending)
9361dabbcecSThomas Gleixner 		entry->pprev = NULL;
9371dabbcecSThomas Gleixner 	entry->next = LIST_POISON2;
9385cee9645SThomas Gleixner }
9395cee9645SThomas Gleixner 
940494af3edSThomas Gleixner static int detach_if_pending(struct timer_list *timer, struct timer_base *base,
9415cee9645SThomas Gleixner 			     bool clear_pending)
9425cee9645SThomas Gleixner {
943500462a9SThomas Gleixner 	unsigned idx = timer_get_idx(timer);
944500462a9SThomas Gleixner 
9455cee9645SThomas Gleixner 	if (!timer_pending(timer))
9465cee9645SThomas Gleixner 		return 0;
9475cee9645SThomas Gleixner 
94831cd0e11SFrederic Weisbecker 	if (hlist_is_singular_node(&timer->entry, base->vectors + idx)) {
949500462a9SThomas Gleixner 		__clear_bit(idx, base->pending_map);
95031cd0e11SFrederic Weisbecker 		base->next_expiry_recalc = true;
95131cd0e11SFrederic Weisbecker 	}
952500462a9SThomas Gleixner 
9535cee9645SThomas Gleixner 	detach_timer(timer, clear_pending);
9545cee9645SThomas Gleixner 	return 1;
9555cee9645SThomas Gleixner }
9565cee9645SThomas Gleixner 
957500462a9SThomas Gleixner static inline struct timer_base *get_timer_cpu_base(u32 tflags, u32 cpu)
958500462a9SThomas Gleixner {
95983a665dcSAnna-Maria Behnsen 	int index = tflags & TIMER_PINNED ? BASE_LOCAL : BASE_GLOBAL;
96083a665dcSAnna-Maria Behnsen 	struct timer_base *base;
96183a665dcSAnna-Maria Behnsen 
96283a665dcSAnna-Maria Behnsen 	base = per_cpu_ptr(&timer_bases[index], cpu);
963500462a9SThomas Gleixner 
9645cee9645SThomas Gleixner 	/*
965ced6d5c1SAnna-Maria Gleixner 	 * If the timer is deferrable and NO_HZ_COMMON is set then we need
966ced6d5c1SAnna-Maria Gleixner 	 * to use the deferrable base.
967500462a9SThomas Gleixner 	 */
968ced6d5c1SAnna-Maria Gleixner 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
969500462a9SThomas Gleixner 		base = per_cpu_ptr(&timer_bases[BASE_DEF], cpu);
970500462a9SThomas Gleixner 	return base;
971500462a9SThomas Gleixner }
972500462a9SThomas Gleixner 
973500462a9SThomas Gleixner static inline struct timer_base *get_timer_this_cpu_base(u32 tflags)
974500462a9SThomas Gleixner {
97583a665dcSAnna-Maria Behnsen 	int index = tflags & TIMER_PINNED ? BASE_LOCAL : BASE_GLOBAL;
97683a665dcSAnna-Maria Behnsen 	struct timer_base *base;
97783a665dcSAnna-Maria Behnsen 
97883a665dcSAnna-Maria Behnsen 	base = this_cpu_ptr(&timer_bases[index]);
979500462a9SThomas Gleixner 
980500462a9SThomas Gleixner 	/*
981ced6d5c1SAnna-Maria Gleixner 	 * If the timer is deferrable and NO_HZ_COMMON is set then we need
982ced6d5c1SAnna-Maria Gleixner 	 * to use the deferrable base.
983500462a9SThomas Gleixner 	 */
984ced6d5c1SAnna-Maria Gleixner 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
985500462a9SThomas Gleixner 		base = this_cpu_ptr(&timer_bases[BASE_DEF]);
986500462a9SThomas Gleixner 	return base;
987500462a9SThomas Gleixner }
988500462a9SThomas Gleixner 
989500462a9SThomas Gleixner static inline struct timer_base *get_timer_base(u32 tflags)
990500462a9SThomas Gleixner {
991500462a9SThomas Gleixner 	return get_timer_cpu_base(tflags, tflags & TIMER_CPUMASK);
992500462a9SThomas Gleixner }
993500462a9SThomas Gleixner 
9941e490484SAnna-Maria Behnsen static inline void __forward_timer_base(struct timer_base *base,
9951e490484SAnna-Maria Behnsen 					unsigned long basej)
996a683f390SThomas Gleixner {
997a683f390SThomas Gleixner 	/*
9988a2c9c7eSAnna-Maria Behnsen 	 * Check whether we can forward the base. We can only do that when
9998a2c9c7eSAnna-Maria Behnsen 	 * @basej is past base->clk otherwise we might rewind base->clk.
1000a683f390SThomas Gleixner 	 */
10011e490484SAnna-Maria Behnsen 	if (time_before_eq(basej, base->clk))
1002a683f390SThomas Gleixner 		return;
1003a683f390SThomas Gleixner 
1004a683f390SThomas Gleixner 	/*
1005a683f390SThomas Gleixner 	 * If the next expiry value is > jiffies, then we fast forward to
1006a683f390SThomas Gleixner 	 * jiffies otherwise we forward to the next expiry value.
1007a683f390SThomas Gleixner 	 */
10081e490484SAnna-Maria Behnsen 	if (time_after(base->next_expiry, basej)) {
10091e490484SAnna-Maria Behnsen 		base->clk = basej;
101030c66fc3SFrederic Weisbecker 	} else {
101130c66fc3SFrederic Weisbecker 		if (WARN_ON_ONCE(time_before(base->next_expiry, base->clk)))
101230c66fc3SFrederic Weisbecker 			return;
1013a683f390SThomas Gleixner 		base->clk = base->next_expiry;
101430c66fc3SFrederic Weisbecker 	}
10151e490484SAnna-Maria Behnsen 
1016ae67badaSThomas Gleixner }
1017a683f390SThomas Gleixner 
10181e490484SAnna-Maria Behnsen static inline void forward_timer_base(struct timer_base *base)
10191e490484SAnna-Maria Behnsen {
10201e490484SAnna-Maria Behnsen 	__forward_timer_base(base, READ_ONCE(jiffies));
10211e490484SAnna-Maria Behnsen }
1022a683f390SThomas Gleixner 
1023500462a9SThomas Gleixner /*
1024500462a9SThomas Gleixner  * We are using hashed locking: Holding per_cpu(timer_bases[x]).lock means
1025500462a9SThomas Gleixner  * that all timers which are tied to this base are locked, and the base itself
1026500462a9SThomas Gleixner  * is locked too.
10275cee9645SThomas Gleixner  *
10285cee9645SThomas Gleixner  * So __run_timers/migrate_timers can safely modify all timers which could
1029500462a9SThomas Gleixner  * be found in the base->vectors array.
10305cee9645SThomas Gleixner  *
1031500462a9SThomas Gleixner  * When a timer is migrating then the TIMER_MIGRATING flag is set and we need
1032500462a9SThomas Gleixner  * to wait until the migration is done.
10335cee9645SThomas Gleixner  */
1034494af3edSThomas Gleixner static struct timer_base *lock_timer_base(struct timer_list *timer,
10355cee9645SThomas Gleixner 					  unsigned long *flags)
10365cee9645SThomas Gleixner 	__acquires(timer->base->lock)
10375cee9645SThomas Gleixner {
10380eeda71bSThomas Gleixner 	for (;;) {
1039494af3edSThomas Gleixner 		struct timer_base *base;
1040b831275aSThomas Gleixner 		u32 tf;
1041b831275aSThomas Gleixner 
1042b831275aSThomas Gleixner 		/*
1043b831275aSThomas Gleixner 		 * We need to use READ_ONCE() here, otherwise the compiler
1044b831275aSThomas Gleixner 		 * might re-read @tf between the check for TIMER_MIGRATING
1045b831275aSThomas Gleixner 		 * and spin_lock().
1046b831275aSThomas Gleixner 		 */
1047b831275aSThomas Gleixner 		tf = READ_ONCE(timer->flags);
10485cee9645SThomas Gleixner 
10490eeda71bSThomas Gleixner 		if (!(tf & TIMER_MIGRATING)) {
1050500462a9SThomas Gleixner 			base = get_timer_base(tf);
10512287d866SSebastian Andrzej Siewior 			raw_spin_lock_irqsave(&base->lock, *flags);
10520eeda71bSThomas Gleixner 			if (timer->flags == tf)
10535cee9645SThomas Gleixner 				return base;
10542287d866SSebastian Andrzej Siewior 			raw_spin_unlock_irqrestore(&base->lock, *flags);
10555cee9645SThomas Gleixner 		}
10565cee9645SThomas Gleixner 		cpu_relax();
10575cee9645SThomas Gleixner 	}
10585cee9645SThomas Gleixner }
10595cee9645SThomas Gleixner 
1060b24591e2SDavid Howells #define MOD_TIMER_PENDING_ONLY		0x01
1061b24591e2SDavid Howells #define MOD_TIMER_REDUCE		0x02
106290c01894SEric Dumazet #define MOD_TIMER_NOTPENDING		0x04
1063b24591e2SDavid Howells 
10645cee9645SThomas Gleixner static inline int
1065b24591e2SDavid Howells __mod_timer(struct timer_list *timer, unsigned long expires, unsigned int options)
10665cee9645SThomas Gleixner {
10671f32cab0SAnna-Maria Behnsen 	unsigned long clk = 0, flags, bucket_expiry;
1068494af3edSThomas Gleixner 	struct timer_base *base, *new_base;
1069f00c0afdSAnna-Maria Gleixner 	unsigned int idx = UINT_MAX;
1070bc7a34b8SThomas Gleixner 	int ret = 0;
10715cee9645SThomas Gleixner 
1072d02e382cSThomas Gleixner 	debug_assert_init(timer);
10734da9152aSThomas Gleixner 
1074500462a9SThomas Gleixner 	/*
1075f00c0afdSAnna-Maria Gleixner 	 * This is a common optimization triggered by the networking code - if
1076f00c0afdSAnna-Maria Gleixner 	 * the timer is re-modified to have the same timeout or ends up in the
1077f00c0afdSAnna-Maria Gleixner 	 * same array bucket then just return:
1078500462a9SThomas Gleixner 	 */
107990c01894SEric Dumazet 	if (!(options & MOD_TIMER_NOTPENDING) && timer_pending(timer)) {
10802fe59f50SNicholas Piggin 		/*
10812fe59f50SNicholas Piggin 		 * The downside of this optimization is that it can result in
10822fe59f50SNicholas Piggin 		 * larger granularity than you would get from adding a new
10832fe59f50SNicholas Piggin 		 * timer with this expiry.
10842fe59f50SNicholas Piggin 		 */
1085b24591e2SDavid Howells 		long diff = timer->expires - expires;
1086b24591e2SDavid Howells 
1087b24591e2SDavid Howells 		if (!diff)
1088b24591e2SDavid Howells 			return 1;
1089b24591e2SDavid Howells 		if (options & MOD_TIMER_REDUCE && diff <= 0)
1090500462a9SThomas Gleixner 			return 1;
1091f00c0afdSAnna-Maria Gleixner 
10924da9152aSThomas Gleixner 		/*
10934da9152aSThomas Gleixner 		 * We lock timer base and calculate the bucket index right
10944da9152aSThomas Gleixner 		 * here. If the timer ends up in the same bucket, then we
10954da9152aSThomas Gleixner 		 * just update the expiry time and avoid the whole
10964da9152aSThomas Gleixner 		 * dequeue/enqueue dance.
10974da9152aSThomas Gleixner 		 */
10984da9152aSThomas Gleixner 		base = lock_timer_base(timer, &flags);
1099d02e382cSThomas Gleixner 		/*
1100d02e382cSThomas Gleixner 		 * Has @timer been shutdown? This needs to be evaluated
1101d02e382cSThomas Gleixner 		 * while holding base lock to prevent a race against the
1102d02e382cSThomas Gleixner 		 * shutdown code.
1103d02e382cSThomas Gleixner 		 */
1104d02e382cSThomas Gleixner 		if (!timer->function)
1105d02e382cSThomas Gleixner 			goto out_unlock;
1106d02e382cSThomas Gleixner 
11072fe59f50SNicholas Piggin 		forward_timer_base(base);
11084da9152aSThomas Gleixner 
1109b24591e2SDavid Howells 		if (timer_pending(timer) && (options & MOD_TIMER_REDUCE) &&
1110b24591e2SDavid Howells 		    time_before_eq(timer->expires, expires)) {
1111b24591e2SDavid Howells 			ret = 1;
1112b24591e2SDavid Howells 			goto out_unlock;
1113b24591e2SDavid Howells 		}
1114b24591e2SDavid Howells 
11154da9152aSThomas Gleixner 		clk = base->clk;
11161f32cab0SAnna-Maria Behnsen 		idx = calc_wheel_index(expires, clk, &bucket_expiry);
1117f00c0afdSAnna-Maria Gleixner 
1118f00c0afdSAnna-Maria Gleixner 		/*
1119f00c0afdSAnna-Maria Gleixner 		 * Retrieve and compare the array index of the pending
1120f00c0afdSAnna-Maria Gleixner 		 * timer. If it matches set the expiry to the new value so a
1121f00c0afdSAnna-Maria Gleixner 		 * subsequent call will exit in the expires check above.
1122f00c0afdSAnna-Maria Gleixner 		 */
1123f00c0afdSAnna-Maria Gleixner 		if (idx == timer_get_idx(timer)) {
1124b24591e2SDavid Howells 			if (!(options & MOD_TIMER_REDUCE))
1125b24591e2SDavid Howells 				timer->expires = expires;
1126b24591e2SDavid Howells 			else if (time_after(timer->expires, expires))
1127f00c0afdSAnna-Maria Gleixner 				timer->expires = expires;
11284da9152aSThomas Gleixner 			ret = 1;
11294da9152aSThomas Gleixner 			goto out_unlock;
1130f00c0afdSAnna-Maria Gleixner 		}
11314da9152aSThomas Gleixner 	} else {
11324da9152aSThomas Gleixner 		base = lock_timer_base(timer, &flags);
1133d02e382cSThomas Gleixner 		/*
1134d02e382cSThomas Gleixner 		 * Has @timer been shutdown? This needs to be evaluated
1135d02e382cSThomas Gleixner 		 * while holding base lock to prevent a race against the
1136d02e382cSThomas Gleixner 		 * shutdown code.
1137d02e382cSThomas Gleixner 		 */
1138d02e382cSThomas Gleixner 		if (!timer->function)
1139d02e382cSThomas Gleixner 			goto out_unlock;
1140d02e382cSThomas Gleixner 
11412fe59f50SNicholas Piggin 		forward_timer_base(base);
1142500462a9SThomas Gleixner 	}
1143500462a9SThomas Gleixner 
11445cee9645SThomas Gleixner 	ret = detach_if_pending(timer, base, false);
1145b24591e2SDavid Howells 	if (!ret && (options & MOD_TIMER_PENDING_ONLY))
11465cee9645SThomas Gleixner 		goto out_unlock;
11475cee9645SThomas Gleixner 
1148b2cf7507SAnna-Maria Behnsen 	new_base = get_timer_this_cpu_base(timer->flags);
11495cee9645SThomas Gleixner 
11505cee9645SThomas Gleixner 	if (base != new_base) {
11515cee9645SThomas Gleixner 		/*
1152500462a9SThomas Gleixner 		 * We are trying to schedule the timer on the new base.
11535cee9645SThomas Gleixner 		 * However we can't change timer's base while it is running,
11549b13df3fSThomas Gleixner 		 * otherwise timer_delete_sync() can't detect that the timer's
1155500462a9SThomas Gleixner 		 * handler yet has not finished. This also guarantees that the
1156500462a9SThomas Gleixner 		 * timer is serialized wrt itself.
11575cee9645SThomas Gleixner 		 */
11585cee9645SThomas Gleixner 		if (likely(base->running_timer != timer)) {
11595cee9645SThomas Gleixner 			/* See the comment in lock_timer_base() */
11600eeda71bSThomas Gleixner 			timer->flags |= TIMER_MIGRATING;
11610eeda71bSThomas Gleixner 
11622287d866SSebastian Andrzej Siewior 			raw_spin_unlock(&base->lock);
11635cee9645SThomas Gleixner 			base = new_base;
11642287d866SSebastian Andrzej Siewior 			raw_spin_lock(&base->lock);
1165d0023a14SEric Dumazet 			WRITE_ONCE(timer->flags,
1166d0023a14SEric Dumazet 				   (timer->flags & ~TIMER_BASEMASK) | base->cpu);
11676bad6bccSThomas Gleixner 			forward_timer_base(base);
11682fe59f50SNicholas Piggin 		}
11692fe59f50SNicholas Piggin 	}
11706bad6bccSThomas Gleixner 
1171dc1e7dc5SAnna-Maria Gleixner 	debug_timer_activate(timer);
1172fd45bb77SThomas Gleixner 
11735cee9645SThomas Gleixner 	timer->expires = expires;
1174f00c0afdSAnna-Maria Gleixner 	/*
1175f00c0afdSAnna-Maria Gleixner 	 * If 'idx' was calculated above and the base time did not advance
11764da9152aSThomas Gleixner 	 * between calculating 'idx' and possibly switching the base, only
11779a2b764bSFrederic Weisbecker 	 * enqueue_timer() is required. Otherwise we need to (re)calculate
11789a2b764bSFrederic Weisbecker 	 * the wheel index via internal_add_timer().
1179f00c0afdSAnna-Maria Gleixner 	 */
11809a2b764bSFrederic Weisbecker 	if (idx != UINT_MAX && clk == base->clk)
11819a2b764bSFrederic Weisbecker 		enqueue_timer(base, timer, idx, bucket_expiry);
11829a2b764bSFrederic Weisbecker 	else
11835cee9645SThomas Gleixner 		internal_add_timer(base, timer);
11845cee9645SThomas Gleixner 
11855cee9645SThomas Gleixner out_unlock:
11862287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&base->lock, flags);
11875cee9645SThomas Gleixner 
11885cee9645SThomas Gleixner 	return ret;
11895cee9645SThomas Gleixner }
11905cee9645SThomas Gleixner 
11915cee9645SThomas Gleixner /**
119214f043f1SThomas Gleixner  * mod_timer_pending - Modify a pending timer's timeout
119314f043f1SThomas Gleixner  * @timer:	The pending timer to be modified
119414f043f1SThomas Gleixner  * @expires:	New absolute timeout in jiffies
11955cee9645SThomas Gleixner  *
119614f043f1SThomas Gleixner  * mod_timer_pending() is the same for pending timers as mod_timer(), but
119714f043f1SThomas Gleixner  * will not activate inactive timers.
11985cee9645SThomas Gleixner  *
1199d02e382cSThomas Gleixner  * If @timer->function == NULL then the start operation is silently
1200d02e382cSThomas Gleixner  * discarded.
1201d02e382cSThomas Gleixner  *
120214f043f1SThomas Gleixner  * Return:
1203d02e382cSThomas Gleixner  * * %0 - The timer was inactive and not modified or was in
1204d02e382cSThomas Gleixner  *	  shutdown state and the operation was discarded
120514f043f1SThomas Gleixner  * * %1 - The timer was active and requeued to expire at @expires
12065cee9645SThomas Gleixner  */
12075cee9645SThomas Gleixner int mod_timer_pending(struct timer_list *timer, unsigned long expires)
12085cee9645SThomas Gleixner {
1209b24591e2SDavid Howells 	return __mod_timer(timer, expires, MOD_TIMER_PENDING_ONLY);
12105cee9645SThomas Gleixner }
12115cee9645SThomas Gleixner EXPORT_SYMBOL(mod_timer_pending);
12125cee9645SThomas Gleixner 
12135cee9645SThomas Gleixner /**
121414f043f1SThomas Gleixner  * mod_timer - Modify a timer's timeout
121514f043f1SThomas Gleixner  * @timer:	The timer to be modified
121614f043f1SThomas Gleixner  * @expires:	New absolute timeout in jiffies
12175cee9645SThomas Gleixner  *
12185cee9645SThomas Gleixner  * mod_timer(timer, expires) is equivalent to:
12195cee9645SThomas Gleixner  *
12205cee9645SThomas Gleixner  *     del_timer(timer); timer->expires = expires; add_timer(timer);
12215cee9645SThomas Gleixner  *
122214f043f1SThomas Gleixner  * mod_timer() is more efficient than the above open coded sequence. In
122314f043f1SThomas Gleixner  * case that the timer is inactive, the del_timer() part is a NOP. The
122414f043f1SThomas Gleixner  * timer is in any case activated with the new expiry time @expires.
122514f043f1SThomas Gleixner  *
12265cee9645SThomas Gleixner  * Note that if there are multiple unserialized concurrent users of the
12275cee9645SThomas Gleixner  * same timer, then mod_timer() is the only safe way to modify the timeout,
12285cee9645SThomas Gleixner  * since add_timer() cannot modify an already running timer.
12295cee9645SThomas Gleixner  *
1230d02e382cSThomas Gleixner  * If @timer->function == NULL then the start operation is silently
1231d02e382cSThomas Gleixner  * discarded. In this case the return value is 0 and meaningless.
1232d02e382cSThomas Gleixner  *
123314f043f1SThomas Gleixner  * Return:
1234d02e382cSThomas Gleixner  * * %0 - The timer was inactive and started or was in shutdown
1235d02e382cSThomas Gleixner  *	  state and the operation was discarded
123614f043f1SThomas Gleixner  * * %1 - The timer was active and requeued to expire at @expires or
123714f043f1SThomas Gleixner  *	  the timer was active and not modified because @expires did
123814f043f1SThomas Gleixner  *	  not change the effective expiry time
12395cee9645SThomas Gleixner  */
12405cee9645SThomas Gleixner int mod_timer(struct timer_list *timer, unsigned long expires)
12415cee9645SThomas Gleixner {
1242b24591e2SDavid Howells 	return __mod_timer(timer, expires, 0);
12435cee9645SThomas Gleixner }
12445cee9645SThomas Gleixner EXPORT_SYMBOL(mod_timer);
12455cee9645SThomas Gleixner 
12465cee9645SThomas Gleixner /**
1247b24591e2SDavid Howells  * timer_reduce - Modify a timer's timeout if it would reduce the timeout
1248b24591e2SDavid Howells  * @timer:	The timer to be modified
124914f043f1SThomas Gleixner  * @expires:	New absolute timeout in jiffies
1250b24591e2SDavid Howells  *
1251b24591e2SDavid Howells  * timer_reduce() is very similar to mod_timer(), except that it will only
125214f043f1SThomas Gleixner  * modify an enqueued timer if that would reduce the expiration time. If
125314f043f1SThomas Gleixner  * @timer is not enqueued it starts the timer.
125414f043f1SThomas Gleixner  *
1255d02e382cSThomas Gleixner  * If @timer->function == NULL then the start operation is silently
1256d02e382cSThomas Gleixner  * discarded.
1257d02e382cSThomas Gleixner  *
125814f043f1SThomas Gleixner  * Return:
1259d02e382cSThomas Gleixner  * * %0 - The timer was inactive and started or was in shutdown
1260d02e382cSThomas Gleixner  *	  state and the operation was discarded
126114f043f1SThomas Gleixner  * * %1 - The timer was active and requeued to expire at @expires or
126214f043f1SThomas Gleixner  *	  the timer was active and not modified because @expires
126314f043f1SThomas Gleixner  *	  did not change the effective expiry time such that the
126414f043f1SThomas Gleixner  *	  timer would expire earlier than already scheduled
1265b24591e2SDavid Howells  */
1266b24591e2SDavid Howells int timer_reduce(struct timer_list *timer, unsigned long expires)
1267b24591e2SDavid Howells {
1268b24591e2SDavid Howells 	return __mod_timer(timer, expires, MOD_TIMER_REDUCE);
1269b24591e2SDavid Howells }
1270b24591e2SDavid Howells EXPORT_SYMBOL(timer_reduce);
1271b24591e2SDavid Howells 
1272b24591e2SDavid Howells /**
127314f043f1SThomas Gleixner  * add_timer - Start a timer
127414f043f1SThomas Gleixner  * @timer:	The timer to be started
12755cee9645SThomas Gleixner  *
127614f043f1SThomas Gleixner  * Start @timer to expire at @timer->expires in the future. @timer->expires
127714f043f1SThomas Gleixner  * is the absolute expiry time measured in 'jiffies'. When the timer expires
127814f043f1SThomas Gleixner  * timer->function(timer) will be invoked from soft interrupt context.
12795cee9645SThomas Gleixner  *
128014f043f1SThomas Gleixner  * The @timer->expires and @timer->function fields must be set prior
128114f043f1SThomas Gleixner  * to calling this function.
12825cee9645SThomas Gleixner  *
1283d02e382cSThomas Gleixner  * If @timer->function == NULL then the start operation is silently
1284d02e382cSThomas Gleixner  * discarded.
1285d02e382cSThomas Gleixner  *
128614f043f1SThomas Gleixner  * If @timer->expires is already in the past @timer will be queued to
128714f043f1SThomas Gleixner  * expire at the next timer tick.
128814f043f1SThomas Gleixner  *
128914f043f1SThomas Gleixner  * This can only operate on an inactive timer. Attempts to invoke this on
129014f043f1SThomas Gleixner  * an active timer are rejected with a warning.
12915cee9645SThomas Gleixner  */
12925cee9645SThomas Gleixner void add_timer(struct timer_list *timer)
12935cee9645SThomas Gleixner {
129482ed6f7eSThomas Gleixner 	if (WARN_ON_ONCE(timer_pending(timer)))
129582ed6f7eSThomas Gleixner 		return;
129690c01894SEric Dumazet 	__mod_timer(timer, timer->expires, MOD_TIMER_NOTPENDING);
12975cee9645SThomas Gleixner }
12985cee9645SThomas Gleixner EXPORT_SYMBOL(add_timer);
12995cee9645SThomas Gleixner 
13005cee9645SThomas Gleixner /**
13018e7e247fSAnna-Maria Behnsen  * add_timer_local() - Start a timer on the local CPU
13028e7e247fSAnna-Maria Behnsen  * @timer:	The timer to be started
13038e7e247fSAnna-Maria Behnsen  *
13048e7e247fSAnna-Maria Behnsen  * Same as add_timer() except that the timer flag TIMER_PINNED is set.
13058e7e247fSAnna-Maria Behnsen  *
13068e7e247fSAnna-Maria Behnsen  * See add_timer() for further details.
13078e7e247fSAnna-Maria Behnsen  */
13088e7e247fSAnna-Maria Behnsen void add_timer_local(struct timer_list *timer)
13098e7e247fSAnna-Maria Behnsen {
13108e7e247fSAnna-Maria Behnsen 	if (WARN_ON_ONCE(timer_pending(timer)))
13118e7e247fSAnna-Maria Behnsen 		return;
13128e7e247fSAnna-Maria Behnsen 	timer->flags |= TIMER_PINNED;
13138e7e247fSAnna-Maria Behnsen 	__mod_timer(timer, timer->expires, MOD_TIMER_NOTPENDING);
13148e7e247fSAnna-Maria Behnsen }
13158e7e247fSAnna-Maria Behnsen EXPORT_SYMBOL(add_timer_local);
13168e7e247fSAnna-Maria Behnsen 
13178e7e247fSAnna-Maria Behnsen /**
13188e7e247fSAnna-Maria Behnsen  * add_timer_global() - Start a timer without TIMER_PINNED flag set
13198e7e247fSAnna-Maria Behnsen  * @timer:	The timer to be started
13208e7e247fSAnna-Maria Behnsen  *
13218e7e247fSAnna-Maria Behnsen  * Same as add_timer() except that the timer flag TIMER_PINNED is unset.
13228e7e247fSAnna-Maria Behnsen  *
13238e7e247fSAnna-Maria Behnsen  * See add_timer() for further details.
13248e7e247fSAnna-Maria Behnsen  */
13258e7e247fSAnna-Maria Behnsen void add_timer_global(struct timer_list *timer)
13268e7e247fSAnna-Maria Behnsen {
13278e7e247fSAnna-Maria Behnsen 	if (WARN_ON_ONCE(timer_pending(timer)))
13288e7e247fSAnna-Maria Behnsen 		return;
13298e7e247fSAnna-Maria Behnsen 	timer->flags &= ~TIMER_PINNED;
13308e7e247fSAnna-Maria Behnsen 	__mod_timer(timer, timer->expires, MOD_TIMER_NOTPENDING);
13318e7e247fSAnna-Maria Behnsen }
13328e7e247fSAnna-Maria Behnsen EXPORT_SYMBOL(add_timer_global);
13338e7e247fSAnna-Maria Behnsen 
13348e7e247fSAnna-Maria Behnsen /**
133514f043f1SThomas Gleixner  * add_timer_on - Start a timer on a particular CPU
133614f043f1SThomas Gleixner  * @timer:	The timer to be started
133714f043f1SThomas Gleixner  * @cpu:	The CPU to start it on
13385cee9645SThomas Gleixner  *
1339aae55e9fSAnna-Maria Behnsen  * Same as add_timer() except that it starts the timer on the given CPU and
1340aae55e9fSAnna-Maria Behnsen  * the TIMER_PINNED flag is set. When timer shouldn't be a pinned timer in
1341aae55e9fSAnna-Maria Behnsen  * the next round, add_timer_global() should be used instead as it unsets
1342aae55e9fSAnna-Maria Behnsen  * the TIMER_PINNED flag.
134314f043f1SThomas Gleixner  *
134414f043f1SThomas Gleixner  * See add_timer() for further details.
13455cee9645SThomas Gleixner  */
13465cee9645SThomas Gleixner void add_timer_on(struct timer_list *timer, int cpu)
13475cee9645SThomas Gleixner {
1348500462a9SThomas Gleixner 	struct timer_base *new_base, *base;
13495cee9645SThomas Gleixner 	unsigned long flags;
13505cee9645SThomas Gleixner 
1351d02e382cSThomas Gleixner 	debug_assert_init(timer);
1352d02e382cSThomas Gleixner 
1353d02e382cSThomas Gleixner 	if (WARN_ON_ONCE(timer_pending(timer)))
135482ed6f7eSThomas Gleixner 		return;
135522b886ddSTejun Heo 
1356aae55e9fSAnna-Maria Behnsen 	/* Make sure timer flags have TIMER_PINNED flag set */
1357aae55e9fSAnna-Maria Behnsen 	timer->flags |= TIMER_PINNED;
1358aae55e9fSAnna-Maria Behnsen 
1359500462a9SThomas Gleixner 	new_base = get_timer_cpu_base(timer->flags, cpu);
1360500462a9SThomas Gleixner 
136122b886ddSTejun Heo 	/*
136222b886ddSTejun Heo 	 * If @timer was on a different CPU, it should be migrated with the
136322b886ddSTejun Heo 	 * old base locked to prevent other operations proceeding with the
136422b886ddSTejun Heo 	 * wrong base locked.  See lock_timer_base().
136522b886ddSTejun Heo 	 */
136622b886ddSTejun Heo 	base = lock_timer_base(timer, &flags);
1367d02e382cSThomas Gleixner 	/*
1368d02e382cSThomas Gleixner 	 * Has @timer been shutdown? This needs to be evaluated while
1369d02e382cSThomas Gleixner 	 * holding base lock to prevent a race against the shutdown code.
1370d02e382cSThomas Gleixner 	 */
1371d02e382cSThomas Gleixner 	if (!timer->function)
1372d02e382cSThomas Gleixner 		goto out_unlock;
1373d02e382cSThomas Gleixner 
137422b886ddSTejun Heo 	if (base != new_base) {
137522b886ddSTejun Heo 		timer->flags |= TIMER_MIGRATING;
137622b886ddSTejun Heo 
13772287d866SSebastian Andrzej Siewior 		raw_spin_unlock(&base->lock);
137822b886ddSTejun Heo 		base = new_base;
13792287d866SSebastian Andrzej Siewior 		raw_spin_lock(&base->lock);
138022b886ddSTejun Heo 		WRITE_ONCE(timer->flags,
138122b886ddSTejun Heo 			   (timer->flags & ~TIMER_BASEMASK) | cpu);
138222b886ddSTejun Heo 	}
13832fe59f50SNicholas Piggin 	forward_timer_base(base);
138422b886ddSTejun Heo 
1385dc1e7dc5SAnna-Maria Gleixner 	debug_timer_activate(timer);
13865cee9645SThomas Gleixner 	internal_add_timer(base, timer);
1387d02e382cSThomas Gleixner out_unlock:
13882287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irqrestore(&base->lock, flags);
13895cee9645SThomas Gleixner }
13905cee9645SThomas Gleixner EXPORT_SYMBOL_GPL(add_timer_on);
13915cee9645SThomas Gleixner 
13925cee9645SThomas Gleixner /**
13938553b5f2SThomas Gleixner  * __timer_delete - Internal function: Deactivate a timer
139414f043f1SThomas Gleixner  * @timer:	The timer to be deactivated
13950cc04e80SThomas Gleixner  * @shutdown:	If true, this indicates that the timer is about to be
13960cc04e80SThomas Gleixner  *		shutdown permanently.
13970cc04e80SThomas Gleixner  *
13980cc04e80SThomas Gleixner  * If @shutdown is true then @timer->function is set to NULL under the
13990cc04e80SThomas Gleixner  * timer base lock which prevents further rearming of the time. In that
14000cc04e80SThomas Gleixner  * case any attempt to rearm @timer after this function returns will be
14010cc04e80SThomas Gleixner  * silently ignored.
14025cee9645SThomas Gleixner  *
140314f043f1SThomas Gleixner  * Return:
140414f043f1SThomas Gleixner  * * %0 - The timer was not pending
140514f043f1SThomas Gleixner  * * %1 - The timer was pending and deactivated
14065cee9645SThomas Gleixner  */
14070cc04e80SThomas Gleixner static int __timer_delete(struct timer_list *timer, bool shutdown)
14085cee9645SThomas Gleixner {
1409494af3edSThomas Gleixner 	struct timer_base *base;
14105cee9645SThomas Gleixner 	unsigned long flags;
14115cee9645SThomas Gleixner 	int ret = 0;
14125cee9645SThomas Gleixner 
14135cee9645SThomas Gleixner 	debug_assert_init(timer);
14145cee9645SThomas Gleixner 
14150cc04e80SThomas Gleixner 	/*
14160cc04e80SThomas Gleixner 	 * If @shutdown is set then the lock has to be taken whether the
14170cc04e80SThomas Gleixner 	 * timer is pending or not to protect against a concurrent rearm
14180cc04e80SThomas Gleixner 	 * which might hit between the lockless pending check and the lock
14199e643ab5SRandy Dunlap 	 * acquisition. By taking the lock it is ensured that such a newly
14200cc04e80SThomas Gleixner 	 * enqueued timer is dequeued and cannot end up with
14210cc04e80SThomas Gleixner 	 * timer->function == NULL in the expiry code.
14220cc04e80SThomas Gleixner 	 *
14230cc04e80SThomas Gleixner 	 * If timer->function is currently executed, then this makes sure
14240cc04e80SThomas Gleixner 	 * that the callback cannot requeue the timer.
14250cc04e80SThomas Gleixner 	 */
14260cc04e80SThomas Gleixner 	if (timer_pending(timer) || shutdown) {
14275cee9645SThomas Gleixner 		base = lock_timer_base(timer, &flags);
14285cee9645SThomas Gleixner 		ret = detach_if_pending(timer, base, true);
14290cc04e80SThomas Gleixner 		if (shutdown)
14300cc04e80SThomas Gleixner 			timer->function = NULL;
14312287d866SSebastian Andrzej Siewior 		raw_spin_unlock_irqrestore(&base->lock, flags);
14325cee9645SThomas Gleixner 	}
14335cee9645SThomas Gleixner 
14345cee9645SThomas Gleixner 	return ret;
14355cee9645SThomas Gleixner }
14368553b5f2SThomas Gleixner 
14378553b5f2SThomas Gleixner /**
14388553b5f2SThomas Gleixner  * timer_delete - Deactivate a timer
14398553b5f2SThomas Gleixner  * @timer:	The timer to be deactivated
14408553b5f2SThomas Gleixner  *
14418553b5f2SThomas Gleixner  * The function only deactivates a pending timer, but contrary to
14428553b5f2SThomas Gleixner  * timer_delete_sync() it does not take into account whether the timer's
14438553b5f2SThomas Gleixner  * callback function is concurrently executed on a different CPU or not.
14448553b5f2SThomas Gleixner  * It neither prevents rearming of the timer.  If @timer can be rearmed
14458553b5f2SThomas Gleixner  * concurrently then the return value of this function is meaningless.
14468553b5f2SThomas Gleixner  *
14478553b5f2SThomas Gleixner  * Return:
14488553b5f2SThomas Gleixner  * * %0 - The timer was not pending
14498553b5f2SThomas Gleixner  * * %1 - The timer was pending and deactivated
14508553b5f2SThomas Gleixner  */
14518553b5f2SThomas Gleixner int timer_delete(struct timer_list *timer)
14528553b5f2SThomas Gleixner {
14530cc04e80SThomas Gleixner 	return __timer_delete(timer, false);
14548553b5f2SThomas Gleixner }
1455bb663f0fSThomas Gleixner EXPORT_SYMBOL(timer_delete);
14565cee9645SThomas Gleixner 
14575cee9645SThomas Gleixner /**
1458f571faf6SThomas Gleixner  * timer_shutdown - Deactivate a timer and prevent rearming
1459f571faf6SThomas Gleixner  * @timer:	The timer to be deactivated
1460f571faf6SThomas Gleixner  *
1461f571faf6SThomas Gleixner  * The function does not wait for an eventually running timer callback on a
1462f571faf6SThomas Gleixner  * different CPU but it prevents rearming of the timer. Any attempt to arm
1463f571faf6SThomas Gleixner  * @timer after this function returns will be silently ignored.
1464f571faf6SThomas Gleixner  *
1465f571faf6SThomas Gleixner  * This function is useful for teardown code and should only be used when
1466f571faf6SThomas Gleixner  * timer_shutdown_sync() cannot be invoked due to locking or context constraints.
1467f571faf6SThomas Gleixner  *
1468f571faf6SThomas Gleixner  * Return:
1469f571faf6SThomas Gleixner  * * %0 - The timer was not pending
1470f571faf6SThomas Gleixner  * * %1 - The timer was pending
1471f571faf6SThomas Gleixner  */
1472f571faf6SThomas Gleixner int timer_shutdown(struct timer_list *timer)
1473f571faf6SThomas Gleixner {
1474f571faf6SThomas Gleixner 	return __timer_delete(timer, true);
1475f571faf6SThomas Gleixner }
1476f571faf6SThomas Gleixner EXPORT_SYMBOL_GPL(timer_shutdown);
1477f571faf6SThomas Gleixner 
1478f571faf6SThomas Gleixner /**
14798553b5f2SThomas Gleixner  * __try_to_del_timer_sync - Internal function: Try to deactivate a timer
14808553b5f2SThomas Gleixner  * @timer:	Timer to deactivate
14810cc04e80SThomas Gleixner  * @shutdown:	If true, this indicates that the timer is about to be
14820cc04e80SThomas Gleixner  *		shutdown permanently.
14830cc04e80SThomas Gleixner  *
14840cc04e80SThomas Gleixner  * If @shutdown is true then @timer->function is set to NULL under the
14850cc04e80SThomas Gleixner  * timer base lock which prevents further rearming of the timer. Any
14860cc04e80SThomas Gleixner  * attempt to rearm @timer after this function returns will be silently
14870cc04e80SThomas Gleixner  * ignored.
14880cc04e80SThomas Gleixner  *
14890cc04e80SThomas Gleixner  * This function cannot guarantee that the timer cannot be rearmed
14900cc04e80SThomas Gleixner  * right after dropping the base lock if @shutdown is false. That
14910cc04e80SThomas Gleixner  * needs to be prevented by the calling code if necessary.
14928553b5f2SThomas Gleixner  *
14938553b5f2SThomas Gleixner  * Return:
14948553b5f2SThomas Gleixner  * * %0  - The timer was not pending
14958553b5f2SThomas Gleixner  * * %1  - The timer was pending and deactivated
14968553b5f2SThomas Gleixner  * * %-1 - The timer callback function is running on a different CPU
14978553b5f2SThomas Gleixner  */
14980cc04e80SThomas Gleixner static int __try_to_del_timer_sync(struct timer_list *timer, bool shutdown)
14998553b5f2SThomas Gleixner {
15008553b5f2SThomas Gleixner 	struct timer_base *base;
15018553b5f2SThomas Gleixner 	unsigned long flags;
15028553b5f2SThomas Gleixner 	int ret = -1;
15038553b5f2SThomas Gleixner 
15048553b5f2SThomas Gleixner 	debug_assert_init(timer);
15058553b5f2SThomas Gleixner 
15068553b5f2SThomas Gleixner 	base = lock_timer_base(timer, &flags);
15078553b5f2SThomas Gleixner 
15088553b5f2SThomas Gleixner 	if (base->running_timer != timer)
15098553b5f2SThomas Gleixner 		ret = detach_if_pending(timer, base, true);
15100cc04e80SThomas Gleixner 	if (shutdown)
15110cc04e80SThomas Gleixner 		timer->function = NULL;
15128553b5f2SThomas Gleixner 
15138553b5f2SThomas Gleixner 	raw_spin_unlock_irqrestore(&base->lock, flags);
15148553b5f2SThomas Gleixner 
15158553b5f2SThomas Gleixner 	return ret;
15168553b5f2SThomas Gleixner }
15178553b5f2SThomas Gleixner 
15188553b5f2SThomas Gleixner /**
15195cee9645SThomas Gleixner  * try_to_del_timer_sync - Try to deactivate a timer
152014f043f1SThomas Gleixner  * @timer:	Timer to deactivate
15215cee9645SThomas Gleixner  *
152214f043f1SThomas Gleixner  * This function tries to deactivate a timer. On success the timer is not
152314f043f1SThomas Gleixner  * queued and the timer callback function is not running on any CPU.
152414f043f1SThomas Gleixner  *
152514f043f1SThomas Gleixner  * This function does not guarantee that the timer cannot be rearmed right
152614f043f1SThomas Gleixner  * after dropping the base lock. That needs to be prevented by the calling
152714f043f1SThomas Gleixner  * code if necessary.
152814f043f1SThomas Gleixner  *
152914f043f1SThomas Gleixner  * Return:
153014f043f1SThomas Gleixner  * * %0  - The timer was not pending
153114f043f1SThomas Gleixner  * * %1  - The timer was pending and deactivated
153214f043f1SThomas Gleixner  * * %-1 - The timer callback function is running on a different CPU
15335cee9645SThomas Gleixner  */
15345cee9645SThomas Gleixner int try_to_del_timer_sync(struct timer_list *timer)
15355cee9645SThomas Gleixner {
15360cc04e80SThomas Gleixner 	return __try_to_del_timer_sync(timer, false);
15375cee9645SThomas Gleixner }
15385cee9645SThomas Gleixner EXPORT_SYMBOL(try_to_del_timer_sync);
15395cee9645SThomas Gleixner 
1540030dcdd1SAnna-Maria Gleixner #ifdef CONFIG_PREEMPT_RT
1541030dcdd1SAnna-Maria Gleixner static __init void timer_base_init_expiry_lock(struct timer_base *base)
1542030dcdd1SAnna-Maria Gleixner {
1543030dcdd1SAnna-Maria Gleixner 	spin_lock_init(&base->expiry_lock);
1544030dcdd1SAnna-Maria Gleixner }
1545030dcdd1SAnna-Maria Gleixner 
1546030dcdd1SAnna-Maria Gleixner static inline void timer_base_lock_expiry(struct timer_base *base)
1547030dcdd1SAnna-Maria Gleixner {
1548030dcdd1SAnna-Maria Gleixner 	spin_lock(&base->expiry_lock);
1549030dcdd1SAnna-Maria Gleixner }
1550030dcdd1SAnna-Maria Gleixner 
1551030dcdd1SAnna-Maria Gleixner static inline void timer_base_unlock_expiry(struct timer_base *base)
1552030dcdd1SAnna-Maria Gleixner {
1553030dcdd1SAnna-Maria Gleixner 	spin_unlock(&base->expiry_lock);
1554030dcdd1SAnna-Maria Gleixner }
1555030dcdd1SAnna-Maria Gleixner 
1556030dcdd1SAnna-Maria Gleixner /*
1557030dcdd1SAnna-Maria Gleixner  * The counterpart to del_timer_wait_running().
1558030dcdd1SAnna-Maria Gleixner  *
1559030dcdd1SAnna-Maria Gleixner  * If there is a waiter for base->expiry_lock, then it was waiting for the
15604bf07f65SIngo Molnar  * timer callback to finish. Drop expiry_lock and reacquire it. That allows
1561030dcdd1SAnna-Maria Gleixner  * the waiter to acquire the lock and make progress.
1562030dcdd1SAnna-Maria Gleixner  */
1563030dcdd1SAnna-Maria Gleixner static void timer_sync_wait_running(struct timer_base *base)
1564030dcdd1SAnna-Maria Gleixner {
1565030dcdd1SAnna-Maria Gleixner 	if (atomic_read(&base->timer_waiters)) {
1566bb7262b2SThomas Gleixner 		raw_spin_unlock_irq(&base->lock);
1567030dcdd1SAnna-Maria Gleixner 		spin_unlock(&base->expiry_lock);
1568030dcdd1SAnna-Maria Gleixner 		spin_lock(&base->expiry_lock);
1569bb7262b2SThomas Gleixner 		raw_spin_lock_irq(&base->lock);
1570030dcdd1SAnna-Maria Gleixner 	}
1571030dcdd1SAnna-Maria Gleixner }
1572030dcdd1SAnna-Maria Gleixner 
1573030dcdd1SAnna-Maria Gleixner /*
1574030dcdd1SAnna-Maria Gleixner  * This function is called on PREEMPT_RT kernels when the fast path
1575030dcdd1SAnna-Maria Gleixner  * deletion of a timer failed because the timer callback function was
1576030dcdd1SAnna-Maria Gleixner  * running.
1577030dcdd1SAnna-Maria Gleixner  *
1578030dcdd1SAnna-Maria Gleixner  * This prevents priority inversion, if the softirq thread on a remote CPU
1579030dcdd1SAnna-Maria Gleixner  * got preempted, and it prevents a life lock when the task which tries to
1580030dcdd1SAnna-Maria Gleixner  * delete a timer preempted the softirq thread running the timer callback
1581030dcdd1SAnna-Maria Gleixner  * function.
1582030dcdd1SAnna-Maria Gleixner  */
1583030dcdd1SAnna-Maria Gleixner static void del_timer_wait_running(struct timer_list *timer)
1584030dcdd1SAnna-Maria Gleixner {
1585030dcdd1SAnna-Maria Gleixner 	u32 tf;
1586030dcdd1SAnna-Maria Gleixner 
1587030dcdd1SAnna-Maria Gleixner 	tf = READ_ONCE(timer->flags);
1588c725dafcSSebastian Andrzej Siewior 	if (!(tf & (TIMER_MIGRATING | TIMER_IRQSAFE))) {
1589030dcdd1SAnna-Maria Gleixner 		struct timer_base *base = get_timer_base(tf);
1590030dcdd1SAnna-Maria Gleixner 
1591030dcdd1SAnna-Maria Gleixner 		/*
1592030dcdd1SAnna-Maria Gleixner 		 * Mark the base as contended and grab the expiry lock,
1593030dcdd1SAnna-Maria Gleixner 		 * which is held by the softirq across the timer
1594030dcdd1SAnna-Maria Gleixner 		 * callback. Drop the lock immediately so the softirq can
1595030dcdd1SAnna-Maria Gleixner 		 * expire the next timer. In theory the timer could already
1596030dcdd1SAnna-Maria Gleixner 		 * be running again, but that's more than unlikely and just
1597030dcdd1SAnna-Maria Gleixner 		 * causes another wait loop.
1598030dcdd1SAnna-Maria Gleixner 		 */
1599030dcdd1SAnna-Maria Gleixner 		atomic_inc(&base->timer_waiters);
1600030dcdd1SAnna-Maria Gleixner 		spin_lock_bh(&base->expiry_lock);
1601030dcdd1SAnna-Maria Gleixner 		atomic_dec(&base->timer_waiters);
1602030dcdd1SAnna-Maria Gleixner 		spin_unlock_bh(&base->expiry_lock);
1603030dcdd1SAnna-Maria Gleixner 	}
1604030dcdd1SAnna-Maria Gleixner }
1605030dcdd1SAnna-Maria Gleixner #else
1606030dcdd1SAnna-Maria Gleixner static inline void timer_base_init_expiry_lock(struct timer_base *base) { }
1607030dcdd1SAnna-Maria Gleixner static inline void timer_base_lock_expiry(struct timer_base *base) { }
1608030dcdd1SAnna-Maria Gleixner static inline void timer_base_unlock_expiry(struct timer_base *base) { }
1609030dcdd1SAnna-Maria Gleixner static inline void timer_sync_wait_running(struct timer_base *base) { }
1610030dcdd1SAnna-Maria Gleixner static inline void del_timer_wait_running(struct timer_list *timer) { }
1611030dcdd1SAnna-Maria Gleixner #endif
1612030dcdd1SAnna-Maria Gleixner 
16135cee9645SThomas Gleixner /**
16148553b5f2SThomas Gleixner  * __timer_delete_sync - Internal function: Deactivate a timer and wait
16158553b5f2SThomas Gleixner  *			 for the handler to finish.
16168553b5f2SThomas Gleixner  * @timer:	The timer to be deactivated
16170cc04e80SThomas Gleixner  * @shutdown:	If true, @timer->function will be set to NULL under the
16180cc04e80SThomas Gleixner  *		timer base lock which prevents rearming of @timer
16190cc04e80SThomas Gleixner  *
16200cc04e80SThomas Gleixner  * If @shutdown is not set the timer can be rearmed later. If the timer can
16210cc04e80SThomas Gleixner  * be rearmed concurrently, i.e. after dropping the base lock then the
16220cc04e80SThomas Gleixner  * return value is meaningless.
16230cc04e80SThomas Gleixner  *
16240cc04e80SThomas Gleixner  * If @shutdown is set then @timer->function is set to NULL under timer
16250cc04e80SThomas Gleixner  * base lock which prevents rearming of the timer. Any attempt to rearm
16260cc04e80SThomas Gleixner  * a shutdown timer is silently ignored.
16270cc04e80SThomas Gleixner  *
16280cc04e80SThomas Gleixner  * If the timer should be reused after shutdown it has to be initialized
16290cc04e80SThomas Gleixner  * again.
16308553b5f2SThomas Gleixner  *
16318553b5f2SThomas Gleixner  * Return:
16328553b5f2SThomas Gleixner  * * %0	- The timer was not pending
16338553b5f2SThomas Gleixner  * * %1	- The timer was pending and deactivated
16348553b5f2SThomas Gleixner  */
16350cc04e80SThomas Gleixner static int __timer_delete_sync(struct timer_list *timer, bool shutdown)
16368553b5f2SThomas Gleixner {
16378553b5f2SThomas Gleixner 	int ret;
16388553b5f2SThomas Gleixner 
16398553b5f2SThomas Gleixner #ifdef CONFIG_LOCKDEP
16408553b5f2SThomas Gleixner 	unsigned long flags;
16418553b5f2SThomas Gleixner 
16428553b5f2SThomas Gleixner 	/*
16438553b5f2SThomas Gleixner 	 * If lockdep gives a backtrace here, please reference
16448553b5f2SThomas Gleixner 	 * the synchronization rules above.
16458553b5f2SThomas Gleixner 	 */
16468553b5f2SThomas Gleixner 	local_irq_save(flags);
16478553b5f2SThomas Gleixner 	lock_map_acquire(&timer->lockdep_map);
16488553b5f2SThomas Gleixner 	lock_map_release(&timer->lockdep_map);
16498553b5f2SThomas Gleixner 	local_irq_restore(flags);
16508553b5f2SThomas Gleixner #endif
16518553b5f2SThomas Gleixner 	/*
16528553b5f2SThomas Gleixner 	 * don't use it in hardirq context, because it
16538553b5f2SThomas Gleixner 	 * could lead to deadlock.
16548553b5f2SThomas Gleixner 	 */
16558553b5f2SThomas Gleixner 	WARN_ON(in_hardirq() && !(timer->flags & TIMER_IRQSAFE));
16568553b5f2SThomas Gleixner 
16578553b5f2SThomas Gleixner 	/*
16588553b5f2SThomas Gleixner 	 * Must be able to sleep on PREEMPT_RT because of the slowpath in
16598553b5f2SThomas Gleixner 	 * del_timer_wait_running().
16608553b5f2SThomas Gleixner 	 */
16618553b5f2SThomas Gleixner 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(timer->flags & TIMER_IRQSAFE))
16628553b5f2SThomas Gleixner 		lockdep_assert_preemption_enabled();
16638553b5f2SThomas Gleixner 
16648553b5f2SThomas Gleixner 	do {
16650cc04e80SThomas Gleixner 		ret = __try_to_del_timer_sync(timer, shutdown);
16668553b5f2SThomas Gleixner 
16678553b5f2SThomas Gleixner 		if (unlikely(ret < 0)) {
16688553b5f2SThomas Gleixner 			del_timer_wait_running(timer);
16698553b5f2SThomas Gleixner 			cpu_relax();
16708553b5f2SThomas Gleixner 		}
16718553b5f2SThomas Gleixner 	} while (ret < 0);
16728553b5f2SThomas Gleixner 
16738553b5f2SThomas Gleixner 	return ret;
16748553b5f2SThomas Gleixner }
16758553b5f2SThomas Gleixner 
16768553b5f2SThomas Gleixner /**
16779b13df3fSThomas Gleixner  * timer_delete_sync - Deactivate a timer and wait for the handler to finish.
167814f043f1SThomas Gleixner  * @timer:	The timer to be deactivated
16795cee9645SThomas Gleixner  *
16805cee9645SThomas Gleixner  * Synchronization rules: Callers must prevent restarting of the timer,
16815cee9645SThomas Gleixner  * otherwise this function is meaningless. It must not be called from
16825cee9645SThomas Gleixner  * interrupt contexts unless the timer is an irqsafe one. The caller must
168314f043f1SThomas Gleixner  * not hold locks which would prevent completion of the timer's callback
168414f043f1SThomas Gleixner  * function. The timer's handler must not call add_timer_on(). Upon exit
168514f043f1SThomas Gleixner  * the timer is not queued and the handler is not running on any CPU.
16865cee9645SThomas Gleixner  *
168714f043f1SThomas Gleixner  * For !irqsafe timers, the caller must not hold locks that are held in
168814f043f1SThomas Gleixner  * interrupt context. Even if the lock has nothing to do with the timer in
168914f043f1SThomas Gleixner  * question.  Here's why::
16905cee9645SThomas Gleixner  *
16915cee9645SThomas Gleixner  *    CPU0                             CPU1
16925cee9645SThomas Gleixner  *    ----                             ----
16935cee9645SThomas Gleixner  *                                     <SOFTIRQ>
16945cee9645SThomas Gleixner  *                                       call_timer_fn();
16955cee9645SThomas Gleixner  *                                       base->running_timer = mytimer;
16965cee9645SThomas Gleixner  *    spin_lock_irq(somelock);
16975cee9645SThomas Gleixner  *                                     <IRQ>
16985cee9645SThomas Gleixner  *                                        spin_lock(somelock);
16999b13df3fSThomas Gleixner  *    timer_delete_sync(mytimer);
17005cee9645SThomas Gleixner  *    while (base->running_timer == mytimer);
17015cee9645SThomas Gleixner  *
17029b13df3fSThomas Gleixner  * Now timer_delete_sync() will never return and never release somelock.
170314f043f1SThomas Gleixner  * The interrupt on the other CPU is waiting to grab somelock but it has
170414f043f1SThomas Gleixner  * interrupted the softirq that CPU0 is waiting to finish.
17055cee9645SThomas Gleixner  *
170614f043f1SThomas Gleixner  * This function cannot guarantee that the timer is not rearmed again by
170714f043f1SThomas Gleixner  * some concurrent or preempting code, right after it dropped the base
170814f043f1SThomas Gleixner  * lock. If there is the possibility of a concurrent rearm then the return
170914f043f1SThomas Gleixner  * value of the function is meaningless.
171014f043f1SThomas Gleixner  *
1711f571faf6SThomas Gleixner  * If such a guarantee is needed, e.g. for teardown situations then use
1712f571faf6SThomas Gleixner  * timer_shutdown_sync() instead.
1713f571faf6SThomas Gleixner  *
171414f043f1SThomas Gleixner  * Return:
171514f043f1SThomas Gleixner  * * %0	- The timer was not pending
171614f043f1SThomas Gleixner  * * %1	- The timer was pending and deactivated
17175cee9645SThomas Gleixner  */
17189b13df3fSThomas Gleixner int timer_delete_sync(struct timer_list *timer)
17195cee9645SThomas Gleixner {
17200cc04e80SThomas Gleixner 	return __timer_delete_sync(timer, false);
17215cee9645SThomas Gleixner }
17229b13df3fSThomas Gleixner EXPORT_SYMBOL(timer_delete_sync);
17235cee9645SThomas Gleixner 
1724f571faf6SThomas Gleixner /**
1725f571faf6SThomas Gleixner  * timer_shutdown_sync - Shutdown a timer and prevent rearming
1726f571faf6SThomas Gleixner  * @timer: The timer to be shutdown
1727f571faf6SThomas Gleixner  *
1728f571faf6SThomas Gleixner  * When the function returns it is guaranteed that:
1729f571faf6SThomas Gleixner  *   - @timer is not queued
1730f571faf6SThomas Gleixner  *   - The callback function of @timer is not running
1731f571faf6SThomas Gleixner  *   - @timer cannot be enqueued again. Any attempt to rearm
1732f571faf6SThomas Gleixner  *     @timer is silently ignored.
1733f571faf6SThomas Gleixner  *
1734f571faf6SThomas Gleixner  * See timer_delete_sync() for synchronization rules.
1735f571faf6SThomas Gleixner  *
1736f571faf6SThomas Gleixner  * This function is useful for final teardown of an infrastructure where
1737f571faf6SThomas Gleixner  * the timer is subject to a circular dependency problem.
1738f571faf6SThomas Gleixner  *
1739f571faf6SThomas Gleixner  * A common pattern for this is a timer and a workqueue where the timer can
1740f571faf6SThomas Gleixner  * schedule work and work can arm the timer. On shutdown the workqueue must
1741f571faf6SThomas Gleixner  * be destroyed and the timer must be prevented from rearming. Unless the
1742f571faf6SThomas Gleixner  * code has conditionals like 'if (mything->in_shutdown)' to prevent that
1743f571faf6SThomas Gleixner  * there is no way to get this correct with timer_delete_sync().
1744f571faf6SThomas Gleixner  *
1745f571faf6SThomas Gleixner  * timer_shutdown_sync() is solving the problem. The correct ordering of
1746f571faf6SThomas Gleixner  * calls in this case is:
1747f571faf6SThomas Gleixner  *
1748f571faf6SThomas Gleixner  *	timer_shutdown_sync(&mything->timer);
1749f571faf6SThomas Gleixner  *	workqueue_destroy(&mything->workqueue);
1750f571faf6SThomas Gleixner  *
1751f571faf6SThomas Gleixner  * After this 'mything' can be safely freed.
1752f571faf6SThomas Gleixner  *
1753f571faf6SThomas Gleixner  * This obviously implies that the timer is not required to be functional
1754f571faf6SThomas Gleixner  * for the rest of the shutdown operation.
1755f571faf6SThomas Gleixner  *
1756f571faf6SThomas Gleixner  * Return:
1757f571faf6SThomas Gleixner  * * %0 - The timer was not pending
1758f571faf6SThomas Gleixner  * * %1 - The timer was pending
1759f571faf6SThomas Gleixner  */
1760f571faf6SThomas Gleixner int timer_shutdown_sync(struct timer_list *timer)
1761f571faf6SThomas Gleixner {
1762f571faf6SThomas Gleixner 	return __timer_delete_sync(timer, true);
1763f571faf6SThomas Gleixner }
1764f571faf6SThomas Gleixner EXPORT_SYMBOL_GPL(timer_shutdown_sync);
1765f571faf6SThomas Gleixner 
1766f28d3d53SAnna-Maria Gleixner static void call_timer_fn(struct timer_list *timer,
1767f28d3d53SAnna-Maria Gleixner 			  void (*fn)(struct timer_list *),
1768f28d3d53SAnna-Maria Gleixner 			  unsigned long baseclk)
17695cee9645SThomas Gleixner {
17705cee9645SThomas Gleixner 	int count = preempt_count();
17715cee9645SThomas Gleixner 
17725cee9645SThomas Gleixner #ifdef CONFIG_LOCKDEP
17735cee9645SThomas Gleixner 	/*
17745cee9645SThomas Gleixner 	 * It is permissible to free the timer from inside the
17755cee9645SThomas Gleixner 	 * function that is called from it, this we need to take into
17765cee9645SThomas Gleixner 	 * account for lockdep too. To avoid bogus "held lock freed"
17775cee9645SThomas Gleixner 	 * warnings as well as problems when looking into
17785cee9645SThomas Gleixner 	 * timer->lockdep_map, make a copy and use that here.
17795cee9645SThomas Gleixner 	 */
17805cee9645SThomas Gleixner 	struct lockdep_map lockdep_map;
17815cee9645SThomas Gleixner 
17825cee9645SThomas Gleixner 	lockdep_copy_map(&lockdep_map, &timer->lockdep_map);
17835cee9645SThomas Gleixner #endif
17845cee9645SThomas Gleixner 	/*
17855cee9645SThomas Gleixner 	 * Couple the lock chain with the lock chain at
17869b13df3fSThomas Gleixner 	 * timer_delete_sync() by acquiring the lock_map around the fn()
17879b13df3fSThomas Gleixner 	 * call here and in timer_delete_sync().
17885cee9645SThomas Gleixner 	 */
17895cee9645SThomas Gleixner 	lock_map_acquire(&lockdep_map);
17905cee9645SThomas Gleixner 
1791f28d3d53SAnna-Maria Gleixner 	trace_timer_expire_entry(timer, baseclk);
1792354b46b1SKees Cook 	fn(timer);
17935cee9645SThomas Gleixner 	trace_timer_expire_exit(timer);
17945cee9645SThomas Gleixner 
17955cee9645SThomas Gleixner 	lock_map_release(&lockdep_map);
17965cee9645SThomas Gleixner 
17975cee9645SThomas Gleixner 	if (count != preempt_count()) {
1798d75f773cSSakari Ailus 		WARN_ONCE(1, "timer: %pS preempt leak: %08x -> %08x\n",
17995cee9645SThomas Gleixner 			  fn, count, preempt_count());
18005cee9645SThomas Gleixner 		/*
18015cee9645SThomas Gleixner 		 * Restore the preempt count. That gives us a decent
18025cee9645SThomas Gleixner 		 * chance to survive and extract information. If the
18035cee9645SThomas Gleixner 		 * callback kept a lock held, bad luck, but not worse
18045cee9645SThomas Gleixner 		 * than the BUG() we had.
18055cee9645SThomas Gleixner 		 */
18065cee9645SThomas Gleixner 		preempt_count_set(count);
18075cee9645SThomas Gleixner 	}
18085cee9645SThomas Gleixner }
18095cee9645SThomas Gleixner 
1810500462a9SThomas Gleixner static void expire_timers(struct timer_base *base, struct hlist_head *head)
18115cee9645SThomas Gleixner {
1812f28d3d53SAnna-Maria Gleixner 	/*
1813f28d3d53SAnna-Maria Gleixner 	 * This value is required only for tracing. base->clk was
1814f28d3d53SAnna-Maria Gleixner 	 * incremented directly before expire_timers was called. But expiry
1815f28d3d53SAnna-Maria Gleixner 	 * is related to the old base->clk value.
1816f28d3d53SAnna-Maria Gleixner 	 */
1817f28d3d53SAnna-Maria Gleixner 	unsigned long baseclk = base->clk - 1;
1818f28d3d53SAnna-Maria Gleixner 
18191dabbcecSThomas Gleixner 	while (!hlist_empty(head)) {
1820500462a9SThomas Gleixner 		struct timer_list *timer;
1821354b46b1SKees Cook 		void (*fn)(struct timer_list *);
18225cee9645SThomas Gleixner 
18231dabbcecSThomas Gleixner 		timer = hlist_entry(head->first, struct timer_list, entry);
18245cee9645SThomas Gleixner 
18255cee9645SThomas Gleixner 		base->running_timer = timer;
1826500462a9SThomas Gleixner 		detach_timer(timer, true);
18275cee9645SThomas Gleixner 
1828500462a9SThomas Gleixner 		fn = timer->function;
1829500462a9SThomas Gleixner 
1830d02e382cSThomas Gleixner 		if (WARN_ON_ONCE(!fn)) {
1831d02e382cSThomas Gleixner 			/* Should never happen. Emphasis on should! */
1832d02e382cSThomas Gleixner 			base->running_timer = NULL;
1833d02e382cSThomas Gleixner 			continue;
1834d02e382cSThomas Gleixner 		}
1835d02e382cSThomas Gleixner 
1836500462a9SThomas Gleixner 		if (timer->flags & TIMER_IRQSAFE) {
18372287d866SSebastian Andrzej Siewior 			raw_spin_unlock(&base->lock);
1838f28d3d53SAnna-Maria Gleixner 			call_timer_fn(timer, fn, baseclk);
18392287d866SSebastian Andrzej Siewior 			raw_spin_lock(&base->lock);
1840bb7262b2SThomas Gleixner 			base->running_timer = NULL;
18415cee9645SThomas Gleixner 		} else {
18422287d866SSebastian Andrzej Siewior 			raw_spin_unlock_irq(&base->lock);
1843f28d3d53SAnna-Maria Gleixner 			call_timer_fn(timer, fn, baseclk);
1844bb7262b2SThomas Gleixner 			raw_spin_lock_irq(&base->lock);
1845030dcdd1SAnna-Maria Gleixner 			base->running_timer = NULL;
1846030dcdd1SAnna-Maria Gleixner 			timer_sync_wait_running(base);
18475cee9645SThomas Gleixner 		}
18485cee9645SThomas Gleixner 	}
18495cee9645SThomas Gleixner }
1850500462a9SThomas Gleixner 
1851d4f7dae8SFrederic Weisbecker static int collect_expired_timers(struct timer_base *base,
1852500462a9SThomas Gleixner 				  struct hlist_head *heads)
1853500462a9SThomas Gleixner {
1854d4f7dae8SFrederic Weisbecker 	unsigned long clk = base->clk = base->next_expiry;
1855500462a9SThomas Gleixner 	struct hlist_head *vec;
1856500462a9SThomas Gleixner 	int i, levels = 0;
1857500462a9SThomas Gleixner 	unsigned int idx;
1858500462a9SThomas Gleixner 
1859500462a9SThomas Gleixner 	for (i = 0; i < LVL_DEPTH; i++) {
1860500462a9SThomas Gleixner 		idx = (clk & LVL_MASK) + i * LVL_SIZE;
1861500462a9SThomas Gleixner 
1862500462a9SThomas Gleixner 		if (__test_and_clear_bit(idx, base->pending_map)) {
1863500462a9SThomas Gleixner 			vec = base->vectors + idx;
1864500462a9SThomas Gleixner 			hlist_move_list(vec, heads++);
1865500462a9SThomas Gleixner 			levels++;
1866500462a9SThomas Gleixner 		}
1867500462a9SThomas Gleixner 		/* Is it time to look at the next level? */
1868500462a9SThomas Gleixner 		if (clk & LVL_CLK_MASK)
1869500462a9SThomas Gleixner 			break;
1870500462a9SThomas Gleixner 		/* Shift clock for the next level granularity */
1871500462a9SThomas Gleixner 		clk >>= LVL_CLK_SHIFT;
1872500462a9SThomas Gleixner 	}
1873500462a9SThomas Gleixner 	return levels;
18745cee9645SThomas Gleixner }
18755cee9645SThomas Gleixner 
18765cee9645SThomas Gleixner /*
187723696838SAnna-Maria Gleixner  * Find the next pending bucket of a level. Search from level start (@offset)
187823696838SAnna-Maria Gleixner  * + @clk upwards and if nothing there, search from start of the level
187923696838SAnna-Maria Gleixner  * (@offset) up to @offset + clk.
18805cee9645SThomas Gleixner  */
1881500462a9SThomas Gleixner static int next_pending_bucket(struct timer_base *base, unsigned offset,
1882500462a9SThomas Gleixner 			       unsigned clk)
18835cee9645SThomas Gleixner {
1884500462a9SThomas Gleixner 	unsigned pos, start = offset + clk;
1885500462a9SThomas Gleixner 	unsigned end = offset + LVL_SIZE;
18865cee9645SThomas Gleixner 
1887500462a9SThomas Gleixner 	pos = find_next_bit(base->pending_map, end, start);
1888500462a9SThomas Gleixner 	if (pos < end)
1889500462a9SThomas Gleixner 		return pos - start;
18905cee9645SThomas Gleixner 
1891500462a9SThomas Gleixner 	pos = find_next_bit(base->pending_map, start, offset);
1892500462a9SThomas Gleixner 	return pos < start ? pos + LVL_SIZE - start : -1;
18935cee9645SThomas Gleixner }
18945cee9645SThomas Gleixner 
1895500462a9SThomas Gleixner /*
189623696838SAnna-Maria Gleixner  * Search the first expiring timer in the various clock levels. Caller must
189723696838SAnna-Maria Gleixner  * hold base->lock.
1898b5e6f598SAnna-Maria Behnsen  *
1899b5e6f598SAnna-Maria Behnsen  * Store next expiry time in base->next_expiry.
19005cee9645SThomas Gleixner  */
1901b5e6f598SAnna-Maria Behnsen static void next_expiry_recalc(struct timer_base *base)
19025cee9645SThomas Gleixner {
1903500462a9SThomas Gleixner 	unsigned long clk, next, adj;
1904500462a9SThomas Gleixner 	unsigned lvl, offset = 0;
19055cee9645SThomas Gleixner 
1906500462a9SThomas Gleixner 	next = base->clk + NEXT_TIMER_MAX_DELTA;
1907500462a9SThomas Gleixner 	clk = base->clk;
1908500462a9SThomas Gleixner 	for (lvl = 0; lvl < LVL_DEPTH; lvl++, offset += LVL_SIZE) {
1909500462a9SThomas Gleixner 		int pos = next_pending_bucket(base, offset, clk & LVL_MASK);
1910001ec1b3SFrederic Weisbecker 		unsigned long lvl_clk = clk & LVL_CLK_MASK;
19115cee9645SThomas Gleixner 
1912500462a9SThomas Gleixner 		if (pos >= 0) {
1913500462a9SThomas Gleixner 			unsigned long tmp = clk + (unsigned long) pos;
19145cee9645SThomas Gleixner 
1915500462a9SThomas Gleixner 			tmp <<= LVL_SHIFT(lvl);
1916500462a9SThomas Gleixner 			if (time_before(tmp, next))
1917500462a9SThomas Gleixner 				next = tmp;
1918001ec1b3SFrederic Weisbecker 
1919001ec1b3SFrederic Weisbecker 			/*
1920001ec1b3SFrederic Weisbecker 			 * If the next expiration happens before we reach
1921001ec1b3SFrederic Weisbecker 			 * the next level, no need to check further.
1922001ec1b3SFrederic Weisbecker 			 */
1923001ec1b3SFrederic Weisbecker 			if (pos <= ((LVL_CLK_DIV - lvl_clk) & LVL_CLK_MASK))
1924001ec1b3SFrederic Weisbecker 				break;
19255cee9645SThomas Gleixner 		}
19265cee9645SThomas Gleixner 		/*
1927500462a9SThomas Gleixner 		 * Clock for the next level. If the current level clock lower
1928500462a9SThomas Gleixner 		 * bits are zero, we look at the next level as is. If not we
1929500462a9SThomas Gleixner 		 * need to advance it by one because that's going to be the
1930500462a9SThomas Gleixner 		 * next expiring bucket in that level. base->clk is the next
1931500462a9SThomas Gleixner 		 * expiring jiffie. So in case of:
1932500462a9SThomas Gleixner 		 *
1933500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1934500462a9SThomas Gleixner 		 *  0    0    0    0    0    0
1935500462a9SThomas Gleixner 		 *
1936500462a9SThomas Gleixner 		 * we have to look at all levels @index 0. With
1937500462a9SThomas Gleixner 		 *
1938500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1939500462a9SThomas Gleixner 		 *  0    0    0    0    0    2
1940500462a9SThomas Gleixner 		 *
1941500462a9SThomas Gleixner 		 * LVL0 has the next expiring bucket @index 2. The upper
1942500462a9SThomas Gleixner 		 * levels have the next expiring bucket @index 1.
1943500462a9SThomas Gleixner 		 *
1944500462a9SThomas Gleixner 		 * In case that the propagation wraps the next level the same
1945500462a9SThomas Gleixner 		 * rules apply:
1946500462a9SThomas Gleixner 		 *
1947500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1948500462a9SThomas Gleixner 		 *  0    0    0    0    F    2
1949500462a9SThomas Gleixner 		 *
1950500462a9SThomas Gleixner 		 * So after looking at LVL0 we get:
1951500462a9SThomas Gleixner 		 *
1952500462a9SThomas Gleixner 		 * LVL5 LVL4 LVL3 LVL2 LVL1
1953500462a9SThomas Gleixner 		 *  0    0    0    1    0
1954500462a9SThomas Gleixner 		 *
1955500462a9SThomas Gleixner 		 * So no propagation from LVL1 to LVL2 because that happened
1956500462a9SThomas Gleixner 		 * with the add already, but then we need to propagate further
1957500462a9SThomas Gleixner 		 * from LVL2 to LVL3.
1958500462a9SThomas Gleixner 		 *
1959500462a9SThomas Gleixner 		 * So the simple check whether the lower bits of the current
1960500462a9SThomas Gleixner 		 * level are 0 or not is sufficient for all cases.
19615cee9645SThomas Gleixner 		 */
1962001ec1b3SFrederic Weisbecker 		adj = lvl_clk ? 1 : 0;
1963500462a9SThomas Gleixner 		clk >>= LVL_CLK_SHIFT;
1964500462a9SThomas Gleixner 		clk += adj;
19655cee9645SThomas Gleixner 	}
196631cd0e11SFrederic Weisbecker 
1967b5e6f598SAnna-Maria Behnsen 	base->next_expiry = next;
196831cd0e11SFrederic Weisbecker 	base->next_expiry_recalc = false;
1969aebacb7fSNicolas Saenz Julienne 	base->timers_pending = !(next == base->clk + NEXT_TIMER_MAX_DELTA);
19705cee9645SThomas Gleixner }
19715cee9645SThomas Gleixner 
1972dc2a0f1fSFrederic Weisbecker #ifdef CONFIG_NO_HZ_COMMON
19735cee9645SThomas Gleixner /*
19745cee9645SThomas Gleixner  * Check, if the next hrtimer event is before the next timer wheel
19755cee9645SThomas Gleixner  * event:
19765cee9645SThomas Gleixner  */
1977c1ad348bSThomas Gleixner static u64 cmp_next_hrtimer_event(u64 basem, u64 expires)
19785cee9645SThomas Gleixner {
1979c1ad348bSThomas Gleixner 	u64 nextevt = hrtimer_get_next_event();
19805cee9645SThomas Gleixner 
1981c1ad348bSThomas Gleixner 	/*
1982c1ad348bSThomas Gleixner 	 * If high resolution timers are enabled
1983c1ad348bSThomas Gleixner 	 * hrtimer_get_next_event() returns KTIME_MAX.
1984c1ad348bSThomas Gleixner 	 */
1985c1ad348bSThomas Gleixner 	if (expires <= nextevt)
19865cee9645SThomas Gleixner 		return expires;
19875cee9645SThomas Gleixner 
19885cee9645SThomas Gleixner 	/*
1989c1ad348bSThomas Gleixner 	 * If the next timer is already expired, return the tick base
1990c1ad348bSThomas Gleixner 	 * time so the tick is fired immediately.
19915cee9645SThomas Gleixner 	 */
1992c1ad348bSThomas Gleixner 	if (nextevt <= basem)
1993c1ad348bSThomas Gleixner 		return basem;
19945cee9645SThomas Gleixner 
19955cee9645SThomas Gleixner 	/*
1996c1ad348bSThomas Gleixner 	 * Round up to the next jiffie. High resolution timers are
1997c1ad348bSThomas Gleixner 	 * off, so the hrtimers are expired in the tick and we need to
1998c1ad348bSThomas Gleixner 	 * make sure that this tick really expires the timer to avoid
1999c1ad348bSThomas Gleixner 	 * a ping pong of the nohz stop code.
2000c1ad348bSThomas Gleixner 	 *
2001c1ad348bSThomas Gleixner 	 * Use DIV_ROUND_UP_ULL to prevent gcc calling __divdi3
20025cee9645SThomas Gleixner 	 */
2003c1ad348bSThomas Gleixner 	return DIV_ROUND_UP_ULL(nextevt, TICK_NSEC) * TICK_NSEC;
20045cee9645SThomas Gleixner }
20055cee9645SThomas Gleixner 
20069f6a3c60SAnna-Maria Behnsen static unsigned long next_timer_interrupt(struct timer_base *base,
20079f6a3c60SAnna-Maria Behnsen 					  unsigned long basej)
20089f6a3c60SAnna-Maria Behnsen {
20099f6a3c60SAnna-Maria Behnsen 	if (base->next_expiry_recalc)
20109f6a3c60SAnna-Maria Behnsen 		next_expiry_recalc(base);
20119f6a3c60SAnna-Maria Behnsen 
20129f6a3c60SAnna-Maria Behnsen 	/*
20139f6a3c60SAnna-Maria Behnsen 	 * Move next_expiry for the empty base into the future to prevent an
20149f6a3c60SAnna-Maria Behnsen 	 * unnecessary raise of the timer softirq when the next_expiry value
20159f6a3c60SAnna-Maria Behnsen 	 * will be reached even if there is no timer pending.
201683a665dcSAnna-Maria Behnsen 	 *
201783a665dcSAnna-Maria Behnsen 	 * This update is also required to make timer_base::next_expiry values
201883a665dcSAnna-Maria Behnsen 	 * easy comparable to find out which base holds the first pending timer.
20199f6a3c60SAnna-Maria Behnsen 	 */
20209f6a3c60SAnna-Maria Behnsen 	if (!base->timers_pending)
20219f6a3c60SAnna-Maria Behnsen 		base->next_expiry = basej + NEXT_TIMER_MAX_DELTA;
20229f6a3c60SAnna-Maria Behnsen 
20239f6a3c60SAnna-Maria Behnsen 	return base->next_expiry;
20249f6a3c60SAnna-Maria Behnsen }
20259f6a3c60SAnna-Maria Behnsen 
202670b4cf84SAnna-Maria Behnsen static unsigned long fetch_next_timer_interrupt(unsigned long basej, u64 basem,
202770b4cf84SAnna-Maria Behnsen 						struct timer_base *base_local,
202870b4cf84SAnna-Maria Behnsen 						struct timer_base *base_global,
202970b4cf84SAnna-Maria Behnsen 						struct timer_events *tevt)
203070b4cf84SAnna-Maria Behnsen {
203170b4cf84SAnna-Maria Behnsen 	unsigned long nextevt, nextevt_local, nextevt_global;
203270b4cf84SAnna-Maria Behnsen 	bool local_first;
203370b4cf84SAnna-Maria Behnsen 
203470b4cf84SAnna-Maria Behnsen 	nextevt_local = next_timer_interrupt(base_local, basej);
203570b4cf84SAnna-Maria Behnsen 	nextevt_global = next_timer_interrupt(base_global, basej);
203670b4cf84SAnna-Maria Behnsen 
203770b4cf84SAnna-Maria Behnsen 	local_first = time_before_eq(nextevt_local, nextevt_global);
203870b4cf84SAnna-Maria Behnsen 
203970b4cf84SAnna-Maria Behnsen 	nextevt = local_first ? nextevt_local : nextevt_global;
204070b4cf84SAnna-Maria Behnsen 
204170b4cf84SAnna-Maria Behnsen 	/*
204270b4cf84SAnna-Maria Behnsen 	 * If the @nextevt is at max. one tick away, use @nextevt and store
204370b4cf84SAnna-Maria Behnsen 	 * it in the local expiry value. The next global event is irrelevant in
204470b4cf84SAnna-Maria Behnsen 	 * this case and can be left as KTIME_MAX.
204570b4cf84SAnna-Maria Behnsen 	 */
204670b4cf84SAnna-Maria Behnsen 	if (time_before_eq(nextevt, basej + 1)) {
204770b4cf84SAnna-Maria Behnsen 		/* If we missed a tick already, force 0 delta */
204870b4cf84SAnna-Maria Behnsen 		if (time_before(nextevt, basej))
204970b4cf84SAnna-Maria Behnsen 			nextevt = basej;
205070b4cf84SAnna-Maria Behnsen 		tevt->local = basem + (u64)(nextevt - basej) * TICK_NSEC;
2051f73d9257SAnna-Maria Behnsen 
2052f73d9257SAnna-Maria Behnsen 		/*
2053f73d9257SAnna-Maria Behnsen 		 * This is required for the remote check only but it doesn't
2054f73d9257SAnna-Maria Behnsen 		 * hurt, when it is done for both call sites:
2055f73d9257SAnna-Maria Behnsen 		 *
2056f73d9257SAnna-Maria Behnsen 		 * * The remote callers will only take care of the global timers
2057f73d9257SAnna-Maria Behnsen 		 *   as local timers will be handled by CPU itself. When not
2058f73d9257SAnna-Maria Behnsen 		 *   updating tevt->global with the already missed first global
2059f73d9257SAnna-Maria Behnsen 		 *   timer, it is possible that it will be missed completely.
2060f73d9257SAnna-Maria Behnsen 		 *
2061f73d9257SAnna-Maria Behnsen 		 * * The local callers will ignore the tevt->global anyway, when
2062f73d9257SAnna-Maria Behnsen 		 *   nextevt is max. one tick away.
2063f73d9257SAnna-Maria Behnsen 		 */
2064f73d9257SAnna-Maria Behnsen 		if (!local_first)
2065f73d9257SAnna-Maria Behnsen 			tevt->global = tevt->local;
206670b4cf84SAnna-Maria Behnsen 		return nextevt;
206770b4cf84SAnna-Maria Behnsen 	}
206870b4cf84SAnna-Maria Behnsen 
206970b4cf84SAnna-Maria Behnsen 	/*
207070b4cf84SAnna-Maria Behnsen 	 * Update tevt.* values:
207170b4cf84SAnna-Maria Behnsen 	 *
207270b4cf84SAnna-Maria Behnsen 	 * If the local queue expires first, then the global event can be
207370b4cf84SAnna-Maria Behnsen 	 * ignored. If the global queue is empty, nothing to do either.
207470b4cf84SAnna-Maria Behnsen 	 */
207570b4cf84SAnna-Maria Behnsen 	if (!local_first && base_global->timers_pending)
207670b4cf84SAnna-Maria Behnsen 		tevt->global = basem + (u64)(nextevt_global - basej) * TICK_NSEC;
207770b4cf84SAnna-Maria Behnsen 
207870b4cf84SAnna-Maria Behnsen 	if (base_local->timers_pending)
207970b4cf84SAnna-Maria Behnsen 		tevt->local = basem + (u64)(nextevt_local - basej) * TICK_NSEC;
208070b4cf84SAnna-Maria Behnsen 
208170b4cf84SAnna-Maria Behnsen 	return nextevt;
208270b4cf84SAnna-Maria Behnsen }
208370b4cf84SAnna-Maria Behnsen 
2084f73d9257SAnna-Maria Behnsen # ifdef CONFIG_SMP
2085f73d9257SAnna-Maria Behnsen /**
2086f73d9257SAnna-Maria Behnsen  * fetch_next_timer_interrupt_remote() - Store next timers into @tevt
2087f73d9257SAnna-Maria Behnsen  * @basej:	base time jiffies
2088f73d9257SAnna-Maria Behnsen  * @basem:	base time clock monotonic
2089f73d9257SAnna-Maria Behnsen  * @tevt:	Pointer to the storage for the expiry values
2090f73d9257SAnna-Maria Behnsen  * @cpu:	Remote CPU
2091f73d9257SAnna-Maria Behnsen  *
2092f73d9257SAnna-Maria Behnsen  * Stores the next pending local and global timer expiry values in the
2093f73d9257SAnna-Maria Behnsen  * struct pointed to by @tevt. If a queue is empty the corresponding
2094f73d9257SAnna-Maria Behnsen  * field is set to KTIME_MAX. If local event expires before global
2095f73d9257SAnna-Maria Behnsen  * event, global event is set to KTIME_MAX as well.
2096f73d9257SAnna-Maria Behnsen  *
2097f73d9257SAnna-Maria Behnsen  * Caller needs to make sure timer base locks are held (use
2098f73d9257SAnna-Maria Behnsen  * timer_lock_remote_bases() for this purpose).
2099f73d9257SAnna-Maria Behnsen  */
2100f73d9257SAnna-Maria Behnsen void fetch_next_timer_interrupt_remote(unsigned long basej, u64 basem,
2101f73d9257SAnna-Maria Behnsen 				       struct timer_events *tevt,
2102f73d9257SAnna-Maria Behnsen 				       unsigned int cpu)
2103f73d9257SAnna-Maria Behnsen {
2104f73d9257SAnna-Maria Behnsen 	struct timer_base *base_local, *base_global;
2105f73d9257SAnna-Maria Behnsen 
2106f73d9257SAnna-Maria Behnsen 	/* Preset local / global events */
2107f73d9257SAnna-Maria Behnsen 	tevt->local = tevt->global = KTIME_MAX;
2108f73d9257SAnna-Maria Behnsen 
2109f73d9257SAnna-Maria Behnsen 	base_local = per_cpu_ptr(&timer_bases[BASE_LOCAL], cpu);
2110f73d9257SAnna-Maria Behnsen 	base_global = per_cpu_ptr(&timer_bases[BASE_GLOBAL], cpu);
2111f73d9257SAnna-Maria Behnsen 
2112f73d9257SAnna-Maria Behnsen 	lockdep_assert_held(&base_local->lock);
2113f73d9257SAnna-Maria Behnsen 	lockdep_assert_held(&base_global->lock);
2114f73d9257SAnna-Maria Behnsen 
2115f73d9257SAnna-Maria Behnsen 	fetch_next_timer_interrupt(basej, basem, base_local, base_global, tevt);
2116f73d9257SAnna-Maria Behnsen }
2117f73d9257SAnna-Maria Behnsen 
2118f73d9257SAnna-Maria Behnsen /**
2119f73d9257SAnna-Maria Behnsen  * timer_unlock_remote_bases - unlock timer bases of cpu
2120f73d9257SAnna-Maria Behnsen  * @cpu:	Remote CPU
2121f73d9257SAnna-Maria Behnsen  *
2122f73d9257SAnna-Maria Behnsen  * Unlocks the remote timer bases.
2123f73d9257SAnna-Maria Behnsen  */
2124f73d9257SAnna-Maria Behnsen void timer_unlock_remote_bases(unsigned int cpu)
2125f73d9257SAnna-Maria Behnsen 	__releases(timer_bases[BASE_LOCAL]->lock)
2126f73d9257SAnna-Maria Behnsen 	__releases(timer_bases[BASE_GLOBAL]->lock)
2127f73d9257SAnna-Maria Behnsen {
2128f73d9257SAnna-Maria Behnsen 	struct timer_base *base_local, *base_global;
2129f73d9257SAnna-Maria Behnsen 
2130f73d9257SAnna-Maria Behnsen 	base_local = per_cpu_ptr(&timer_bases[BASE_LOCAL], cpu);
2131f73d9257SAnna-Maria Behnsen 	base_global = per_cpu_ptr(&timer_bases[BASE_GLOBAL], cpu);
2132f73d9257SAnna-Maria Behnsen 
2133f73d9257SAnna-Maria Behnsen 	raw_spin_unlock(&base_global->lock);
2134f73d9257SAnna-Maria Behnsen 	raw_spin_unlock(&base_local->lock);
2135f73d9257SAnna-Maria Behnsen }
2136f73d9257SAnna-Maria Behnsen 
2137f73d9257SAnna-Maria Behnsen /**
2138f73d9257SAnna-Maria Behnsen  * timer_lock_remote_bases - lock timer bases of cpu
2139f73d9257SAnna-Maria Behnsen  * @cpu:	Remote CPU
2140f73d9257SAnna-Maria Behnsen  *
2141f73d9257SAnna-Maria Behnsen  * Locks the remote timer bases.
2142f73d9257SAnna-Maria Behnsen  */
2143f73d9257SAnna-Maria Behnsen void timer_lock_remote_bases(unsigned int cpu)
2144f73d9257SAnna-Maria Behnsen 	__acquires(timer_bases[BASE_LOCAL]->lock)
2145f73d9257SAnna-Maria Behnsen 	__acquires(timer_bases[BASE_GLOBAL]->lock)
2146f73d9257SAnna-Maria Behnsen {
2147f73d9257SAnna-Maria Behnsen 	struct timer_base *base_local, *base_global;
2148f73d9257SAnna-Maria Behnsen 
2149f73d9257SAnna-Maria Behnsen 	base_local = per_cpu_ptr(&timer_bases[BASE_LOCAL], cpu);
2150f73d9257SAnna-Maria Behnsen 	base_global = per_cpu_ptr(&timer_bases[BASE_GLOBAL], cpu);
2151f73d9257SAnna-Maria Behnsen 
2152f73d9257SAnna-Maria Behnsen 	lockdep_assert_irqs_disabled();
2153f73d9257SAnna-Maria Behnsen 
2154f73d9257SAnna-Maria Behnsen 	raw_spin_lock(&base_local->lock);
2155f73d9257SAnna-Maria Behnsen 	raw_spin_lock_nested(&base_global->lock, SINGLE_DEPTH_NESTING);
2156f73d9257SAnna-Maria Behnsen }
215757e95a5cSAnna-Maria Behnsen 
215857e95a5cSAnna-Maria Behnsen /**
215957e95a5cSAnna-Maria Behnsen  * timer_base_is_idle() - Return whether timer base is set idle
216057e95a5cSAnna-Maria Behnsen  *
216157e95a5cSAnna-Maria Behnsen  * Returns value of local timer base is_idle value.
216257e95a5cSAnna-Maria Behnsen  */
216357e95a5cSAnna-Maria Behnsen bool timer_base_is_idle(void)
216457e95a5cSAnna-Maria Behnsen {
216557e95a5cSAnna-Maria Behnsen 	return __this_cpu_read(timer_bases[BASE_LOCAL].is_idle);
216657e95a5cSAnna-Maria Behnsen }
21677ee98877SAnna-Maria Behnsen 
21687ee98877SAnna-Maria Behnsen static void __run_timer_base(struct timer_base *base);
21697ee98877SAnna-Maria Behnsen 
21707ee98877SAnna-Maria Behnsen /**
21717ee98877SAnna-Maria Behnsen  * timer_expire_remote() - expire global timers of cpu
21727ee98877SAnna-Maria Behnsen  * @cpu:	Remote CPU
21737ee98877SAnna-Maria Behnsen  *
21747ee98877SAnna-Maria Behnsen  * Expire timers of global base of remote CPU.
21757ee98877SAnna-Maria Behnsen  */
21767ee98877SAnna-Maria Behnsen void timer_expire_remote(unsigned int cpu)
21777ee98877SAnna-Maria Behnsen {
21787ee98877SAnna-Maria Behnsen 	struct timer_base *base = per_cpu_ptr(&timer_bases[BASE_GLOBAL], cpu);
21797ee98877SAnna-Maria Behnsen 
21807ee98877SAnna-Maria Behnsen 	__run_timer_base(base);
21817ee98877SAnna-Maria Behnsen }
21827ee98877SAnna-Maria Behnsen 
21837ee98877SAnna-Maria Behnsen static void timer_use_tmigr(unsigned long basej, u64 basem,
21847ee98877SAnna-Maria Behnsen 			    unsigned long *nextevt, bool *tick_stop_path,
21857ee98877SAnna-Maria Behnsen 			    bool timer_base_idle, struct timer_events *tevt)
21867ee98877SAnna-Maria Behnsen {
21877ee98877SAnna-Maria Behnsen 	u64 next_tmigr;
21887ee98877SAnna-Maria Behnsen 
21897ee98877SAnna-Maria Behnsen 	if (timer_base_idle)
21907ee98877SAnna-Maria Behnsen 		next_tmigr = tmigr_cpu_new_timer(tevt->global);
21917ee98877SAnna-Maria Behnsen 	else if (tick_stop_path)
21927ee98877SAnna-Maria Behnsen 		next_tmigr = tmigr_cpu_deactivate(tevt->global);
21937ee98877SAnna-Maria Behnsen 	else
21947ee98877SAnna-Maria Behnsen 		next_tmigr = tmigr_quick_check(tevt->global);
21957ee98877SAnna-Maria Behnsen 
21967ee98877SAnna-Maria Behnsen 	/*
21977ee98877SAnna-Maria Behnsen 	 * If the CPU is the last going idle in timer migration hierarchy, make
21987ee98877SAnna-Maria Behnsen 	 * sure the CPU will wake up in time to handle remote timers.
21997ee98877SAnna-Maria Behnsen 	 * next_tmigr == KTIME_MAX if other CPUs are still active.
22007ee98877SAnna-Maria Behnsen 	 */
22017ee98877SAnna-Maria Behnsen 	if (next_tmigr < tevt->local) {
22027ee98877SAnna-Maria Behnsen 		u64 tmp;
22037ee98877SAnna-Maria Behnsen 
22047ee98877SAnna-Maria Behnsen 		/* If we missed a tick already, force 0 delta */
22057ee98877SAnna-Maria Behnsen 		if (next_tmigr < basem)
22067ee98877SAnna-Maria Behnsen 			next_tmigr = basem;
22077ee98877SAnna-Maria Behnsen 
22087ee98877SAnna-Maria Behnsen 		tmp = div_u64(next_tmigr - basem, TICK_NSEC);
22097ee98877SAnna-Maria Behnsen 
22107ee98877SAnna-Maria Behnsen 		*nextevt = basej + (unsigned long)tmp;
22117ee98877SAnna-Maria Behnsen 		tevt->local = next_tmigr;
22127ee98877SAnna-Maria Behnsen 	}
22137ee98877SAnna-Maria Behnsen }
22147ee98877SAnna-Maria Behnsen # else
22157ee98877SAnna-Maria Behnsen static void timer_use_tmigr(unsigned long basej, u64 basem,
22167ee98877SAnna-Maria Behnsen 			    unsigned long *nextevt, bool *tick_stop_path,
22177ee98877SAnna-Maria Behnsen 			    bool timer_base_idle, struct timer_events *tevt)
22187ee98877SAnna-Maria Behnsen {
22197ee98877SAnna-Maria Behnsen 	/*
22207ee98877SAnna-Maria Behnsen 	 * Make sure first event is written into tevt->local to not miss a
22217ee98877SAnna-Maria Behnsen 	 * timer on !SMP systems.
22227ee98877SAnna-Maria Behnsen 	 */
22237ee98877SAnna-Maria Behnsen 	tevt->local = min_t(u64, tevt->local, tevt->global);
22247ee98877SAnna-Maria Behnsen }
2225f73d9257SAnna-Maria Behnsen # endif /* CONFIG_SMP */
2226f73d9257SAnna-Maria Behnsen 
2227e2e1d724SAnna-Maria Behnsen static inline u64 __get_next_timer_interrupt(unsigned long basej, u64 basem,
2228e2e1d724SAnna-Maria Behnsen 					     bool *idle)
22295cee9645SThomas Gleixner {
223021927fc8SAnna-Maria Behnsen 	struct timer_events tevt = { .local = KTIME_MAX, .global = KTIME_MAX };
223183a665dcSAnna-Maria Behnsen 	struct timer_base *base_local, *base_global;
223270b4cf84SAnna-Maria Behnsen 	unsigned long nextevt;
22337ee98877SAnna-Maria Behnsen 	bool idle_is_possible;
22345cee9645SThomas Gleixner 
22355cee9645SThomas Gleixner 	/*
223619b344a9SFrederic Weisbecker 	 * When the CPU is offline, the tick is cancelled and nothing is supposed
223719b344a9SFrederic Weisbecker 	 * to try to stop it.
22385cee9645SThomas Gleixner 	 */
223919b344a9SFrederic Weisbecker 	if (WARN_ON_ONCE(cpu_is_offline(smp_processor_id()))) {
2240e2e1d724SAnna-Maria Behnsen 		if (idle)
2241e2e1d724SAnna-Maria Behnsen 			*idle = true;
224221927fc8SAnna-Maria Behnsen 		return tevt.local;
2243e2e1d724SAnna-Maria Behnsen 	}
22445cee9645SThomas Gleixner 
224583a665dcSAnna-Maria Behnsen 	base_local = this_cpu_ptr(&timer_bases[BASE_LOCAL]);
224683a665dcSAnna-Maria Behnsen 	base_global = this_cpu_ptr(&timer_bases[BASE_GLOBAL]);
224731cd0e11SFrederic Weisbecker 
224883a665dcSAnna-Maria Behnsen 	raw_spin_lock(&base_local->lock);
224983a665dcSAnna-Maria Behnsen 	raw_spin_lock_nested(&base_global->lock, SINGLE_DEPTH_NESTING);
225083a665dcSAnna-Maria Behnsen 
225170b4cf84SAnna-Maria Behnsen 	nextevt = fetch_next_timer_interrupt(basej, basem, base_local,
225270b4cf84SAnna-Maria Behnsen 					     base_global, &tevt);
225383a665dcSAnna-Maria Behnsen 
225421927fc8SAnna-Maria Behnsen 	/*
22557ee98877SAnna-Maria Behnsen 	 * If the next event is only one jiffie ahead there is no need to call
22567ee98877SAnna-Maria Behnsen 	 * timer migration hierarchy related functions. The value for the next
22577ee98877SAnna-Maria Behnsen 	 * global timer in @tevt struct equals then KTIME_MAX. This is also
22587ee98877SAnna-Maria Behnsen 	 * true, when the timer base is idle.
22597ee98877SAnna-Maria Behnsen 	 *
22607ee98877SAnna-Maria Behnsen 	 * The proper timer migration hierarchy function depends on the callsite
22617ee98877SAnna-Maria Behnsen 	 * and whether timer base is idle or not. @nextevt will be updated when
22627ee98877SAnna-Maria Behnsen 	 * this CPU needs to handle the first timer migration hierarchy
22637ee98877SAnna-Maria Behnsen 	 * event. See timer_use_tmigr() for detailed information.
22647ee98877SAnna-Maria Behnsen 	 */
22657ee98877SAnna-Maria Behnsen 	idle_is_possible = time_after(nextevt, basej + 1);
22667ee98877SAnna-Maria Behnsen 	if (idle_is_possible)
22677ee98877SAnna-Maria Behnsen 		timer_use_tmigr(basej, basem, &nextevt, idle,
22687ee98877SAnna-Maria Behnsen 				base_local->is_idle, &tevt);
22697ee98877SAnna-Maria Behnsen 
22707ee98877SAnna-Maria Behnsen 	/*
2271bebed664SAnna-Maria Behnsen 	 * We have a fresh next event. Check whether we can forward the
2272bebed664SAnna-Maria Behnsen 	 * base.
2273bebed664SAnna-Maria Behnsen 	 */
227483a665dcSAnna-Maria Behnsen 	__forward_timer_base(base_local, basej);
227583a665dcSAnna-Maria Behnsen 	__forward_timer_base(base_global, basej);
2276bebed664SAnna-Maria Behnsen 
2277bebed664SAnna-Maria Behnsen 	/*
2278e2e1d724SAnna-Maria Behnsen 	 * Set base->is_idle only when caller is timer_base_try_to_set_idle()
2279e2e1d724SAnna-Maria Behnsen 	 */
2280e2e1d724SAnna-Maria Behnsen 	if (idle) {
2281e2e1d724SAnna-Maria Behnsen 		/*
22827ee98877SAnna-Maria Behnsen 		 * Bases are idle if the next event is more than a tick
22837ee98877SAnna-Maria Behnsen 		 * away. Caution: @nextevt could have changed by enqueueing a
22847ee98877SAnna-Maria Behnsen 		 * global timer into timer migration hierarchy. Therefore a new
22857ee98877SAnna-Maria Behnsen 		 * check is required here.
2286bb8caad5SThomas Gleixner 		 *
2287e2e1d724SAnna-Maria Behnsen 		 * If the base is marked idle then any timer add operation must
2288e2e1d724SAnna-Maria Behnsen 		 * forward the base clk itself to keep granularity small. This
228983a665dcSAnna-Maria Behnsen 		 * idle logic is only maintained for the BASE_LOCAL and
229083a665dcSAnna-Maria Behnsen 		 * BASE_GLOBAL base, deferrable timers may still see large
229183a665dcSAnna-Maria Behnsen 		 * granularity skew (by design).
2292a683f390SThomas Gleixner 		 */
229383a665dcSAnna-Maria Behnsen 		if (!base_local->is_idle && time_after(nextevt, basej + 1)) {
2294b2cf7507SAnna-Maria Behnsen 			base_local->is_idle = true;
229503877039SFrederic Weisbecker 			/*
229603877039SFrederic Weisbecker 			 * Global timers queued locally while running in a task
229703877039SFrederic Weisbecker 			 * in nohz_full mode need a self-IPI to kick reprogramming
229803877039SFrederic Weisbecker 			 * in IRQ tail.
229903877039SFrederic Weisbecker 			 */
230003877039SFrederic Weisbecker 			if (tick_nohz_full_cpu(base_local->cpu))
230103877039SFrederic Weisbecker 				base_global->is_idle = true;
230283a665dcSAnna-Maria Behnsen 			trace_timer_base_idle(true, base_local->cpu);
2303e2e1d724SAnna-Maria Behnsen 		}
230483a665dcSAnna-Maria Behnsen 		*idle = base_local->is_idle;
23057ee98877SAnna-Maria Behnsen 
23067ee98877SAnna-Maria Behnsen 		/*
23077ee98877SAnna-Maria Behnsen 		 * When timer base is not set idle, undo the effect of
23089e643ab5SRandy Dunlap 		 * tmigr_cpu_deactivate() to prevent inconsistent states - active
23097ee98877SAnna-Maria Behnsen 		 * timer base but inactive timer migration hierarchy.
23107ee98877SAnna-Maria Behnsen 		 *
23117ee98877SAnna-Maria Behnsen 		 * When timer base was already marked idle, nothing will be
23127ee98877SAnna-Maria Behnsen 		 * changed here.
23137ee98877SAnna-Maria Behnsen 		 */
23147ee98877SAnna-Maria Behnsen 		if (!base_local->is_idle && idle_is_possible)
23157ee98877SAnna-Maria Behnsen 			tmigr_cpu_activate();
2316e2e1d724SAnna-Maria Behnsen 	}
2317bb8caad5SThomas Gleixner 
231883a665dcSAnna-Maria Behnsen 	raw_spin_unlock(&base_global->lock);
231983a665dcSAnna-Maria Behnsen 	raw_spin_unlock(&base_local->lock);
23205cee9645SThomas Gleixner 
23217ee98877SAnna-Maria Behnsen 	return cmp_next_hrtimer_event(basem, tevt.local);
23225cee9645SThomas Gleixner }
232323696838SAnna-Maria Gleixner 
2324a683f390SThomas Gleixner /**
232539ed699fSAnna-Maria Behnsen  * get_next_timer_interrupt() - return the time (clock mono) of the next timer
232639ed699fSAnna-Maria Behnsen  * @basej:	base time jiffies
232739ed699fSAnna-Maria Behnsen  * @basem:	base time clock monotonic
232839ed699fSAnna-Maria Behnsen  *
23297ee98877SAnna-Maria Behnsen  * Returns the tick aligned clock monotonic time of the next pending timer or
23307ee98877SAnna-Maria Behnsen  * KTIME_MAX if no timer is pending. If timer of global base was queued into
23317ee98877SAnna-Maria Behnsen  * timer migration hierarchy, first global timer is not taken into account. If
23327ee98877SAnna-Maria Behnsen  * it was the last CPU of timer migration hierarchy going idle, first global
23337ee98877SAnna-Maria Behnsen  * event is taken into account.
233439ed699fSAnna-Maria Behnsen  */
233539ed699fSAnna-Maria Behnsen u64 get_next_timer_interrupt(unsigned long basej, u64 basem)
233639ed699fSAnna-Maria Behnsen {
2337e2e1d724SAnna-Maria Behnsen 	return __get_next_timer_interrupt(basej, basem, NULL);
2338e2e1d724SAnna-Maria Behnsen }
2339e2e1d724SAnna-Maria Behnsen 
2340e2e1d724SAnna-Maria Behnsen /**
2341e2e1d724SAnna-Maria Behnsen  * timer_base_try_to_set_idle() - Try to set the idle state of the timer bases
2342e2e1d724SAnna-Maria Behnsen  * @basej:	base time jiffies
2343e2e1d724SAnna-Maria Behnsen  * @basem:	base time clock monotonic
234473129cf4SAnna-Maria Behnsen  * @idle:	pointer to store the value of timer_base->is_idle on return;
234573129cf4SAnna-Maria Behnsen  *		*idle contains the information whether tick was already stopped
2346e2e1d724SAnna-Maria Behnsen  *
234773129cf4SAnna-Maria Behnsen  * Returns the tick aligned clock monotonic time of the next pending timer or
234873129cf4SAnna-Maria Behnsen  * KTIME_MAX if no timer is pending. When tick was already stopped KTIME_MAX is
234973129cf4SAnna-Maria Behnsen  * returned as well.
2350e2e1d724SAnna-Maria Behnsen  */
2351e2e1d724SAnna-Maria Behnsen u64 timer_base_try_to_set_idle(unsigned long basej, u64 basem, bool *idle)
2352e2e1d724SAnna-Maria Behnsen {
235373129cf4SAnna-Maria Behnsen 	if (*idle)
235473129cf4SAnna-Maria Behnsen 		return KTIME_MAX;
235573129cf4SAnna-Maria Behnsen 
2356e2e1d724SAnna-Maria Behnsen 	return __get_next_timer_interrupt(basej, basem, idle);
235739ed699fSAnna-Maria Behnsen }
235839ed699fSAnna-Maria Behnsen 
235939ed699fSAnna-Maria Behnsen /**
2360a683f390SThomas Gleixner  * timer_clear_idle - Clear the idle state of the timer base
2361a683f390SThomas Gleixner  *
2362a683f390SThomas Gleixner  * Called with interrupts disabled
2363a683f390SThomas Gleixner  */
2364a683f390SThomas Gleixner void timer_clear_idle(void)
2365a683f390SThomas Gleixner {
2366a683f390SThomas Gleixner 	/*
2367b2cf7507SAnna-Maria Behnsen 	 * We do this unlocked. The worst outcome is a remote pinned timer
2368b2cf7507SAnna-Maria Behnsen 	 * enqueue sending a pointless IPI, but taking the lock would just
2369b2cf7507SAnna-Maria Behnsen 	 * make the window for sending the IPI a few instructions smaller
2370b2cf7507SAnna-Maria Behnsen 	 * for the cost of taking the lock in the exit from idle
2371b2cf7507SAnna-Maria Behnsen 	 * path. Required for BASE_LOCAL only.
2372a683f390SThomas Gleixner 	 */
237383a665dcSAnna-Maria Behnsen 	__this_cpu_write(timer_bases[BASE_LOCAL].is_idle, false);
237403877039SFrederic Weisbecker 	if (tick_nohz_full_cpu(smp_processor_id()))
237503877039SFrederic Weisbecker 		__this_cpu_write(timer_bases[BASE_GLOBAL].is_idle, false);
2376b573c731SAnna-Maria Behnsen 	trace_timer_base_idle(false, smp_processor_id());
23777ee98877SAnna-Maria Behnsen 
23787ee98877SAnna-Maria Behnsen 	/* Activate without holding the timer_base->lock */
23797ee98877SAnna-Maria Behnsen 	tmigr_cpu_activate();
2380b573c731SAnna-Maria Behnsen }
23815cee9645SThomas Gleixner #endif
23825cee9645SThomas Gleixner 
238373420feaSAnna-Maria Gleixner /**
238473420feaSAnna-Maria Gleixner  * __run_timers - run all expired timers (if any) on this CPU.
238573420feaSAnna-Maria Gleixner  * @base: the timer vector to be processed.
238673420feaSAnna-Maria Gleixner  */
238773420feaSAnna-Maria Gleixner static inline void __run_timers(struct timer_base *base)
238873420feaSAnna-Maria Gleixner {
238973420feaSAnna-Maria Gleixner 	struct hlist_head heads[LVL_DEPTH];
239073420feaSAnna-Maria Gleixner 	int levels;
239173420feaSAnna-Maria Gleixner 
239290f5df66SRichard Cochran (linutronix GmbH) 	lockdep_assert_held(&base->lock);
239373420feaSAnna-Maria Gleixner 
239489f01e10SAnna-Maria Behnsen 	if (base->running_timer)
239589f01e10SAnna-Maria Behnsen 		return;
239689f01e10SAnna-Maria Behnsen 
2397d4f7dae8SFrederic Weisbecker 	while (time_after_eq(jiffies, base->clk) &&
2398d4f7dae8SFrederic Weisbecker 	       time_after_eq(jiffies, base->next_expiry)) {
239973420feaSAnna-Maria Gleixner 		levels = collect_expired_timers(base, heads);
240031cd0e11SFrederic Weisbecker 		/*
2401c54bc0fcSAnna-Maria Behnsen 		 * The two possible reasons for not finding any expired
2402c54bc0fcSAnna-Maria Behnsen 		 * timer at this clk are that all matching timers have been
2403c54bc0fcSAnna-Maria Behnsen 		 * dequeued or no timer has been queued since
2404c54bc0fcSAnna-Maria Behnsen 		 * base::next_expiry was set to base::clk +
2405c54bc0fcSAnna-Maria Behnsen 		 * NEXT_TIMER_MAX_DELTA.
240631cd0e11SFrederic Weisbecker 		 */
2407c54bc0fcSAnna-Maria Behnsen 		WARN_ON_ONCE(!levels && !base->next_expiry_recalc
2408c54bc0fcSAnna-Maria Behnsen 			     && base->timers_pending);
24098a2c9c7eSAnna-Maria Behnsen 		/*
24108a2c9c7eSAnna-Maria Behnsen 		 * While executing timers, base->clk is set 1 offset ahead of
24118a2c9c7eSAnna-Maria Behnsen 		 * jiffies to avoid endless requeuing to current jiffies.
24128a2c9c7eSAnna-Maria Behnsen 		 */
241373420feaSAnna-Maria Gleixner 		base->clk++;
2414b5e6f598SAnna-Maria Behnsen 		next_expiry_recalc(base);
241573420feaSAnna-Maria Gleixner 
241673420feaSAnna-Maria Gleixner 		while (levels--)
241773420feaSAnna-Maria Gleixner 			expire_timers(base, heads + levels);
241873420feaSAnna-Maria Gleixner 	}
241990f5df66SRichard Cochran (linutronix GmbH) }
242090f5df66SRichard Cochran (linutronix GmbH) 
242190f5df66SRichard Cochran (linutronix GmbH) static void __run_timer_base(struct timer_base *base)
242290f5df66SRichard Cochran (linutronix GmbH) {
242390f5df66SRichard Cochran (linutronix GmbH) 	if (time_before(jiffies, base->next_expiry))
242490f5df66SRichard Cochran (linutronix GmbH) 		return;
242590f5df66SRichard Cochran (linutronix GmbH) 
242690f5df66SRichard Cochran (linutronix GmbH) 	timer_base_lock_expiry(base);
242790f5df66SRichard Cochran (linutronix GmbH) 	raw_spin_lock_irq(&base->lock);
242890f5df66SRichard Cochran (linutronix GmbH) 	__run_timers(base);
24292287d866SSebastian Andrzej Siewior 	raw_spin_unlock_irq(&base->lock);
2430030dcdd1SAnna-Maria Gleixner 	timer_base_unlock_expiry(base);
243173420feaSAnna-Maria Gleixner }
243273420feaSAnna-Maria Gleixner 
243390f5df66SRichard Cochran (linutronix GmbH) static void run_timer_base(int index)
243490f5df66SRichard Cochran (linutronix GmbH) {
243590f5df66SRichard Cochran (linutronix GmbH) 	struct timer_base *base = this_cpu_ptr(&timer_bases[index]);
243690f5df66SRichard Cochran (linutronix GmbH) 
243790f5df66SRichard Cochran (linutronix GmbH) 	__run_timer_base(base);
243890f5df66SRichard Cochran (linutronix GmbH) }
243990f5df66SRichard Cochran (linutronix GmbH) 
24405cee9645SThomas Gleixner /*
24415cee9645SThomas Gleixner  * This function runs timers and the timer-tq in bottom half context.
24425cee9645SThomas Gleixner  */
24430766f788SEmese Revfy static __latent_entropy void run_timer_softirq(struct softirq_action *h)
24445cee9645SThomas Gleixner {
244590f5df66SRichard Cochran (linutronix GmbH) 	run_timer_base(BASE_LOCAL);
244683a665dcSAnna-Maria Behnsen 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON)) {
244790f5df66SRichard Cochran (linutronix GmbH) 		run_timer_base(BASE_GLOBAL);
244890f5df66SRichard Cochran (linutronix GmbH) 		run_timer_base(BASE_DEF);
24497ee98877SAnna-Maria Behnsen 
24507ee98877SAnna-Maria Behnsen 		if (is_timers_nohz_active())
24517ee98877SAnna-Maria Behnsen 			tmigr_handle_remote();
24525cee9645SThomas Gleixner 	}
245383a665dcSAnna-Maria Behnsen }
24545cee9645SThomas Gleixner 
24555cee9645SThomas Gleixner /*
24565cee9645SThomas Gleixner  * Called by the local, per-CPU timer interrupt on SMP.
24575cee9645SThomas Gleixner  */
2458cc947f2bSThomas Gleixner static void run_local_timers(void)
24595cee9645SThomas Gleixner {
246083a665dcSAnna-Maria Behnsen 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_LOCAL]);
24614e85876aSThomas Gleixner 
24625cee9645SThomas Gleixner 	hrtimer_run_queues();
2463af68cb3fSAnna-Maria Behnsen 
2464af68cb3fSAnna-Maria Behnsen 	for (int i = 0; i < NR_BASES; i++, base++) {
24654e85876aSThomas Gleixner 		/* Raise the softirq only if required. */
24667ee98877SAnna-Maria Behnsen 		if (time_after_eq(jiffies, base->next_expiry) ||
24677ee98877SAnna-Maria Behnsen 		    (i == BASE_DEF && tmigr_requires_handle_remote())) {
2468af68cb3fSAnna-Maria Behnsen 			raise_softirq(TIMER_SOFTIRQ);
24694e85876aSThomas Gleixner 			return;
24704e85876aSThomas Gleixner 		}
2471af68cb3fSAnna-Maria Behnsen 	}
24725cee9645SThomas Gleixner }
24735cee9645SThomas Gleixner 
247458e1177bSKees Cook /*
2475cc947f2bSThomas Gleixner  * Called from the timer interrupt handler to charge one tick to the current
2476cc947f2bSThomas Gleixner  * process.  user_tick is 1 if the tick is user time, 0 for system.
2477cc947f2bSThomas Gleixner  */
2478cc947f2bSThomas Gleixner void update_process_times(int user_tick)
2479cc947f2bSThomas Gleixner {
2480cc947f2bSThomas Gleixner 	struct task_struct *p = current;
2481cc947f2bSThomas Gleixner 
2482cc947f2bSThomas Gleixner 	/* Note: this timer irq context must be accounted for as well. */
2483cc947f2bSThomas Gleixner 	account_process_tick(p, user_tick);
2484cc947f2bSThomas Gleixner 	run_local_timers();
2485cc947f2bSThomas Gleixner 	rcu_sched_clock_irq(user_tick);
2486cc947f2bSThomas Gleixner #ifdef CONFIG_IRQ_WORK
2487cc947f2bSThomas Gleixner 	if (in_irq())
2488cc947f2bSThomas Gleixner 		irq_work_tick();
2489cc947f2bSThomas Gleixner #endif
249086dd6c04SIngo Molnar 	sched_tick();
2491cc947f2bSThomas Gleixner 	if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2492cc947f2bSThomas Gleixner 		run_posix_cpu_timers();
2493cc947f2bSThomas Gleixner }
2494cc947f2bSThomas Gleixner 
2495cc947f2bSThomas Gleixner /*
249658e1177bSKees Cook  * Since schedule_timeout()'s timer is defined on the stack, it must store
249758e1177bSKees Cook  * the target task on the stack as well.
249858e1177bSKees Cook  */
249958e1177bSKees Cook struct process_timer {
250058e1177bSKees Cook 	struct timer_list timer;
250158e1177bSKees Cook 	struct task_struct *task;
250258e1177bSKees Cook };
250358e1177bSKees Cook 
250458e1177bSKees Cook static void process_timeout(struct timer_list *t)
25055cee9645SThomas Gleixner {
250658e1177bSKees Cook 	struct process_timer *timeout = from_timer(timeout, t, timer);
250758e1177bSKees Cook 
250858e1177bSKees Cook 	wake_up_process(timeout->task);
25095cee9645SThomas Gleixner }
25105cee9645SThomas Gleixner 
25115cee9645SThomas Gleixner /**
25125cee9645SThomas Gleixner  * schedule_timeout - sleep until timeout
25135cee9645SThomas Gleixner  * @timeout: timeout value in jiffies
25145cee9645SThomas Gleixner  *
25156e317c32SAlexander Popov  * Make the current task sleep until @timeout jiffies have elapsed.
25166e317c32SAlexander Popov  * The function behavior depends on the current task state
25176e317c32SAlexander Popov  * (see also set_current_state() description):
25185cee9645SThomas Gleixner  *
25196e317c32SAlexander Popov  * %TASK_RUNNING - the scheduler is called, but the task does not sleep
25206e317c32SAlexander Popov  * at all. That happens because sched_submit_work() does nothing for
25216e317c32SAlexander Popov  * tasks in %TASK_RUNNING state.
25225cee9645SThomas Gleixner  *
25235cee9645SThomas Gleixner  * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
25244b7e9cf9SDouglas Anderson  * pass before the routine returns unless the current task is explicitly
25256e317c32SAlexander Popov  * woken up, (e.g. by wake_up_process()).
25265cee9645SThomas Gleixner  *
25275cee9645SThomas Gleixner  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
25284b7e9cf9SDouglas Anderson  * delivered to the current task or the current task is explicitly woken
25294b7e9cf9SDouglas Anderson  * up.
25305cee9645SThomas Gleixner  *
25316e317c32SAlexander Popov  * The current task state is guaranteed to be %TASK_RUNNING when this
25325cee9645SThomas Gleixner  * routine returns.
25335cee9645SThomas Gleixner  *
25345cee9645SThomas Gleixner  * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
25355cee9645SThomas Gleixner  * the CPU away without a bound on the timeout. In this case the return
25365cee9645SThomas Gleixner  * value will be %MAX_SCHEDULE_TIMEOUT.
25375cee9645SThomas Gleixner  *
25384b7e9cf9SDouglas Anderson  * Returns 0 when the timer has expired otherwise the remaining time in
25394b7e9cf9SDouglas Anderson  * jiffies will be returned. In all cases the return value is guaranteed
25404b7e9cf9SDouglas Anderson  * to be non-negative.
25415cee9645SThomas Gleixner  */
25425cee9645SThomas Gleixner signed long __sched schedule_timeout(signed long timeout)
25435cee9645SThomas Gleixner {
254458e1177bSKees Cook 	struct process_timer timer;
25455cee9645SThomas Gleixner 	unsigned long expire;
25465cee9645SThomas Gleixner 
25475cee9645SThomas Gleixner 	switch (timeout)
25485cee9645SThomas Gleixner 	{
25495cee9645SThomas Gleixner 	case MAX_SCHEDULE_TIMEOUT:
25505cee9645SThomas Gleixner 		/*
25515cee9645SThomas Gleixner 		 * These two special cases are useful to be comfortable
25525cee9645SThomas Gleixner 		 * in the caller. Nothing more. We could take
25535cee9645SThomas Gleixner 		 * MAX_SCHEDULE_TIMEOUT from one of the negative value
25545cee9645SThomas Gleixner 		 * but I' d like to return a valid offset (>=0) to allow
25555cee9645SThomas Gleixner 		 * the caller to do everything it want with the retval.
25565cee9645SThomas Gleixner 		 */
25575cee9645SThomas Gleixner 		schedule();
25585cee9645SThomas Gleixner 		goto out;
25595cee9645SThomas Gleixner 	default:
25605cee9645SThomas Gleixner 		/*
25615cee9645SThomas Gleixner 		 * Another bit of PARANOID. Note that the retval will be
25625cee9645SThomas Gleixner 		 * 0 since no piece of kernel is supposed to do a check
25635cee9645SThomas Gleixner 		 * for a negative retval of schedule_timeout() (since it
25645cee9645SThomas Gleixner 		 * should never happens anyway). You just have the printk()
25655cee9645SThomas Gleixner 		 * that will tell you if something is gone wrong and where.
25665cee9645SThomas Gleixner 		 */
25675cee9645SThomas Gleixner 		if (timeout < 0) {
25685cee9645SThomas Gleixner 			printk(KERN_ERR "schedule_timeout: wrong timeout "
25695cee9645SThomas Gleixner 				"value %lx\n", timeout);
25705cee9645SThomas Gleixner 			dump_stack();
2571600642aeSPeter Zijlstra 			__set_current_state(TASK_RUNNING);
25725cee9645SThomas Gleixner 			goto out;
25735cee9645SThomas Gleixner 		}
25745cee9645SThomas Gleixner 	}
25755cee9645SThomas Gleixner 
25765cee9645SThomas Gleixner 	expire = timeout + jiffies;
25775cee9645SThomas Gleixner 
257858e1177bSKees Cook 	timer.task = current;
257958e1177bSKees Cook 	timer_setup_on_stack(&timer.timer, process_timeout, 0);
258090c01894SEric Dumazet 	__mod_timer(&timer.timer, expire, MOD_TIMER_NOTPENDING);
25815cee9645SThomas Gleixner 	schedule();
25829a5a3056SThomas Gleixner 	del_timer_sync(&timer.timer);
25835cee9645SThomas Gleixner 
25845cee9645SThomas Gleixner 	/* Remove the timer from the object tracker */
258558e1177bSKees Cook 	destroy_timer_on_stack(&timer.timer);
25865cee9645SThomas Gleixner 
25875cee9645SThomas Gleixner 	timeout = expire - jiffies;
25885cee9645SThomas Gleixner 
25895cee9645SThomas Gleixner  out:
25905cee9645SThomas Gleixner 	return timeout < 0 ? 0 : timeout;
25915cee9645SThomas Gleixner }
25925cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout);
25935cee9645SThomas Gleixner 
25945cee9645SThomas Gleixner /*
25955cee9645SThomas Gleixner  * We can use __set_current_state() here because schedule_timeout() calls
25965cee9645SThomas Gleixner  * schedule() unconditionally.
25975cee9645SThomas Gleixner  */
25985cee9645SThomas Gleixner signed long __sched schedule_timeout_interruptible(signed long timeout)
25995cee9645SThomas Gleixner {
26005cee9645SThomas Gleixner 	__set_current_state(TASK_INTERRUPTIBLE);
26015cee9645SThomas Gleixner 	return schedule_timeout(timeout);
26025cee9645SThomas Gleixner }
26035cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout_interruptible);
26045cee9645SThomas Gleixner 
26055cee9645SThomas Gleixner signed long __sched schedule_timeout_killable(signed long timeout)
26065cee9645SThomas Gleixner {
26075cee9645SThomas Gleixner 	__set_current_state(TASK_KILLABLE);
26085cee9645SThomas Gleixner 	return schedule_timeout(timeout);
26095cee9645SThomas Gleixner }
26105cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout_killable);
26115cee9645SThomas Gleixner 
26125cee9645SThomas Gleixner signed long __sched schedule_timeout_uninterruptible(signed long timeout)
26135cee9645SThomas Gleixner {
26145cee9645SThomas Gleixner 	__set_current_state(TASK_UNINTERRUPTIBLE);
26155cee9645SThomas Gleixner 	return schedule_timeout(timeout);
26165cee9645SThomas Gleixner }
26175cee9645SThomas Gleixner EXPORT_SYMBOL(schedule_timeout_uninterruptible);
26185cee9645SThomas Gleixner 
261969b27bafSAndrew Morton /*
262069b27bafSAndrew Morton  * Like schedule_timeout_uninterruptible(), except this task will not contribute
262169b27bafSAndrew Morton  * to load average.
262269b27bafSAndrew Morton  */
262369b27bafSAndrew Morton signed long __sched schedule_timeout_idle(signed long timeout)
262469b27bafSAndrew Morton {
262569b27bafSAndrew Morton 	__set_current_state(TASK_IDLE);
262669b27bafSAndrew Morton 	return schedule_timeout(timeout);
262769b27bafSAndrew Morton }
262869b27bafSAndrew Morton EXPORT_SYMBOL(schedule_timeout_idle);
262969b27bafSAndrew Morton 
26305cee9645SThomas Gleixner #ifdef CONFIG_HOTPLUG_CPU
2631494af3edSThomas Gleixner static void migrate_timer_list(struct timer_base *new_base, struct hlist_head *head)
26325cee9645SThomas Gleixner {
26335cee9645SThomas Gleixner 	struct timer_list *timer;
26340eeda71bSThomas Gleixner 	int cpu = new_base->cpu;
26355cee9645SThomas Gleixner 
26361dabbcecSThomas Gleixner 	while (!hlist_empty(head)) {
26371dabbcecSThomas Gleixner 		timer = hlist_entry(head->first, struct timer_list, entry);
26385cee9645SThomas Gleixner 		detach_timer(timer, false);
26390eeda71bSThomas Gleixner 		timer->flags = (timer->flags & ~TIMER_BASEMASK) | cpu;
26405cee9645SThomas Gleixner 		internal_add_timer(new_base, timer);
26415cee9645SThomas Gleixner 	}
26425cee9645SThomas Gleixner }
26435cee9645SThomas Gleixner 
264426456f87SThomas Gleixner int timers_prepare_cpu(unsigned int cpu)
264526456f87SThomas Gleixner {
264626456f87SThomas Gleixner 	struct timer_base *base;
264726456f87SThomas Gleixner 	int b;
264826456f87SThomas Gleixner 
264926456f87SThomas Gleixner 	for (b = 0; b < NR_BASES; b++) {
265026456f87SThomas Gleixner 		base = per_cpu_ptr(&timer_bases[b], cpu);
265126456f87SThomas Gleixner 		base->clk = jiffies;
265226456f87SThomas Gleixner 		base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
26532731aa7dSAnna-Maria Behnsen 		base->next_expiry_recalc = false;
2654aebacb7fSNicolas Saenz Julienne 		base->timers_pending = false;
265526456f87SThomas Gleixner 		base->is_idle = false;
265626456f87SThomas Gleixner 	}
265726456f87SThomas Gleixner 	return 0;
265826456f87SThomas Gleixner }
265926456f87SThomas Gleixner 
266024f73b99SRichard Cochran int timers_dead_cpu(unsigned int cpu)
26615cee9645SThomas Gleixner {
2662494af3edSThomas Gleixner 	struct timer_base *old_base;
2663494af3edSThomas Gleixner 	struct timer_base *new_base;
2664500462a9SThomas Gleixner 	int b, i;
26655cee9645SThomas Gleixner 
2666500462a9SThomas Gleixner 	for (b = 0; b < NR_BASES; b++) {
2667500462a9SThomas Gleixner 		old_base = per_cpu_ptr(&timer_bases[b], cpu);
2668500462a9SThomas Gleixner 		new_base = get_cpu_ptr(&timer_bases[b]);
26695cee9645SThomas Gleixner 		/*
26705cee9645SThomas Gleixner 		 * The caller is globally serialized and nobody else
26715cee9645SThomas Gleixner 		 * takes two locks at once, deadlock is not possible.
26725cee9645SThomas Gleixner 		 */
26732287d866SSebastian Andrzej Siewior 		raw_spin_lock_irq(&new_base->lock);
26742287d866SSebastian Andrzej Siewior 		raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
26755cee9645SThomas Gleixner 
2676c52232a4SLingutla Chandrasekhar 		/*
2677c52232a4SLingutla Chandrasekhar 		 * The current CPUs base clock might be stale. Update it
2678c52232a4SLingutla Chandrasekhar 		 * before moving the timers over.
2679c52232a4SLingutla Chandrasekhar 		 */
2680c52232a4SLingutla Chandrasekhar 		forward_timer_base(new_base);
2681c52232a4SLingutla Chandrasekhar 
268282ed6f7eSThomas Gleixner 		WARN_ON_ONCE(old_base->running_timer);
268382ed6f7eSThomas Gleixner 		old_base->running_timer = NULL;
26845cee9645SThomas Gleixner 
2685500462a9SThomas Gleixner 		for (i = 0; i < WHEEL_SIZE; i++)
2686500462a9SThomas Gleixner 			migrate_timer_list(new_base, old_base->vectors + i);
26878def9060SViresh Kumar 
26882287d866SSebastian Andrzej Siewior 		raw_spin_unlock(&old_base->lock);
26892287d866SSebastian Andrzej Siewior 		raw_spin_unlock_irq(&new_base->lock);
2690494af3edSThomas Gleixner 		put_cpu_ptr(&timer_bases);
26915cee9645SThomas Gleixner 	}
269224f73b99SRichard Cochran 	return 0;
26935cee9645SThomas Gleixner }
26945cee9645SThomas Gleixner 
26953650b57fSPeter Zijlstra #endif /* CONFIG_HOTPLUG_CPU */
26965cee9645SThomas Gleixner 
26970eeda71bSThomas Gleixner static void __init init_timer_cpu(int cpu)
26988def9060SViresh Kumar {
2699500462a9SThomas Gleixner 	struct timer_base *base;
2700500462a9SThomas Gleixner 	int i;
27013650b57fSPeter Zijlstra 
2702500462a9SThomas Gleixner 	for (i = 0; i < NR_BASES; i++) {
2703500462a9SThomas Gleixner 		base = per_cpu_ptr(&timer_bases[i], cpu);
27048def9060SViresh Kumar 		base->cpu = cpu;
27052287d866SSebastian Andrzej Siewior 		raw_spin_lock_init(&base->lock);
2706494af3edSThomas Gleixner 		base->clk = jiffies;
2707dc2a0f1fSFrederic Weisbecker 		base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
2708030dcdd1SAnna-Maria Gleixner 		timer_base_init_expiry_lock(base);
2709500462a9SThomas Gleixner 	}
27108def9060SViresh Kumar }
27118def9060SViresh Kumar 
27128def9060SViresh Kumar static void __init init_timer_cpus(void)
27138def9060SViresh Kumar {
27148def9060SViresh Kumar 	int cpu;
27158def9060SViresh Kumar 
27160eeda71bSThomas Gleixner 	for_each_possible_cpu(cpu)
27170eeda71bSThomas Gleixner 		init_timer_cpu(cpu);
27188def9060SViresh Kumar }
27195cee9645SThomas Gleixner 
27205cee9645SThomas Gleixner void __init init_timers(void)
27215cee9645SThomas Gleixner {
27228def9060SViresh Kumar 	init_timer_cpus();
27231fb497ddSThomas Gleixner 	posix_cputimers_init_work();
27245cee9645SThomas Gleixner 	open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
27255cee9645SThomas Gleixner }
27265cee9645SThomas Gleixner 
27275cee9645SThomas Gleixner /**
27285cee9645SThomas Gleixner  * msleep - sleep safely even with waitqueue interruptions
27295cee9645SThomas Gleixner  * @msecs: Time in milliseconds to sleep for
27305cee9645SThomas Gleixner  */
27315cee9645SThomas Gleixner void msleep(unsigned int msecs)
27325cee9645SThomas Gleixner {
27335cee9645SThomas Gleixner 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
27345cee9645SThomas Gleixner 
27355cee9645SThomas Gleixner 	while (timeout)
27365cee9645SThomas Gleixner 		timeout = schedule_timeout_uninterruptible(timeout);
27375cee9645SThomas Gleixner }
27385cee9645SThomas Gleixner 
27395cee9645SThomas Gleixner EXPORT_SYMBOL(msleep);
27405cee9645SThomas Gleixner 
27415cee9645SThomas Gleixner /**
27425cee9645SThomas Gleixner  * msleep_interruptible - sleep waiting for signals
27435cee9645SThomas Gleixner  * @msecs: Time in milliseconds to sleep for
27445cee9645SThomas Gleixner  */
27455cee9645SThomas Gleixner unsigned long msleep_interruptible(unsigned int msecs)
27465cee9645SThomas Gleixner {
27475cee9645SThomas Gleixner 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
27485cee9645SThomas Gleixner 
27495cee9645SThomas Gleixner 	while (timeout && !signal_pending(current))
27505cee9645SThomas Gleixner 		timeout = schedule_timeout_interruptible(timeout);
27515cee9645SThomas Gleixner 	return jiffies_to_msecs(timeout);
27525cee9645SThomas Gleixner }
27535cee9645SThomas Gleixner 
27545cee9645SThomas Gleixner EXPORT_SYMBOL(msleep_interruptible);
27555cee9645SThomas Gleixner 
27565cee9645SThomas Gleixner /**
2757e4779015SSeongJae Park  * usleep_range_state - Sleep for an approximate time in a given state
27585cee9645SThomas Gleixner  * @min:	Minimum time in usecs to sleep
27595cee9645SThomas Gleixner  * @max:	Maximum time in usecs to sleep
2760e4779015SSeongJae Park  * @state:	State of the current task that will be while sleeping
2761b5227d03SBjorn Helgaas  *
2762b5227d03SBjorn Helgaas  * In non-atomic context where the exact wakeup time is flexible, use
2763e4779015SSeongJae Park  * usleep_range_state() instead of udelay().  The sleep improves responsiveness
2764b5227d03SBjorn Helgaas  * by avoiding the CPU-hogging busy-wait of udelay(), and the range reduces
2765b5227d03SBjorn Helgaas  * power usage by allowing hrtimers to take advantage of an already-
2766b5227d03SBjorn Helgaas  * scheduled interrupt instead of scheduling a new one just for this sleep.
27675cee9645SThomas Gleixner  */
2768e4779015SSeongJae Park void __sched usleep_range_state(unsigned long min, unsigned long max,
2769e4779015SSeongJae Park 				unsigned int state)
27705cee9645SThomas Gleixner {
27716c5e9059SDouglas Anderson 	ktime_t exp = ktime_add_us(ktime_get(), min);
27726c5e9059SDouglas Anderson 	u64 delta = (u64)(max - min) * NSEC_PER_USEC;
27736c5e9059SDouglas Anderson 
27746c5e9059SDouglas Anderson 	for (;;) {
2775e4779015SSeongJae Park 		__set_current_state(state);
27766c5e9059SDouglas Anderson 		/* Do not return before the requested sleep time has elapsed */
27776c5e9059SDouglas Anderson 		if (!schedule_hrtimeout_range(&exp, delta, HRTIMER_MODE_ABS))
27786c5e9059SDouglas Anderson 			break;
27796c5e9059SDouglas Anderson 	}
27805cee9645SThomas Gleixner }
2781e4779015SSeongJae Park EXPORT_SYMBOL(usleep_range_state);
2782