• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  Kernel internal timers
4  *
5  *  Copyright (C) 1991, 1992  Linus Torvalds
6  *
7  *  1997-01-28  Modified by Finn Arne Gangstad to make timers scale better.
8  *
9  *  1997-09-10  Updated NTP code according to technical memorandum Jan '96
10  *              "A Kernel Model for Precision Timekeeping" by Dave Mills
11  *  1998-12-24  Fixed a xtime SMP race (we need the xtime_lock rw spinlock to
12  *              serialize accesses to xtime/lost_ticks).
13  *                              Copyright (C) 1998  Andrea Arcangeli
14  *  1999-03-10  Improved NTP compatibility by Ulrich Windl
15  *  2002-05-31	Move sys_sysinfo here and make its locking sane, Robert Love
16  *  2000-10-05  Implemented scalable SMP per-CPU timer handling.
17  *                              Copyright (C) 2000, 2001, 2002  Ingo Molnar
18  *              Designed by David S. Miller, Alexey Kuznetsov and Ingo Molnar
19  */
20 
21 #include <linux/kernel_stat.h>
22 #include <linux/export.h>
23 #include <linux/interrupt.h>
24 #include <linux/percpu.h>
25 #include <linux/init.h>
26 #include <linux/mm.h>
27 #include <linux/swap.h>
28 #include <linux/pid_namespace.h>
29 #include <linux/notifier.h>
30 #include <linux/thread_info.h>
31 #include <linux/time.h>
32 #include <linux/jiffies.h>
33 #include <linux/posix-timers.h>
34 #include <linux/cpu.h>
35 #include <linux/syscalls.h>
36 #include <linux/delay.h>
37 #include <linux/tick.h>
38 #include <linux/kallsyms.h>
39 #include <linux/irq_work.h>
40 #include <linux/sched/signal.h>
41 #include <linux/sched/sysctl.h>
42 #include <linux/sched/nohz.h>
43 #include <linux/sched/debug.h>
44 #include <linux/slab.h>
45 #include <linux/compat.h>
46 #include <linux/random.h>
47 #include <linux/sysctl.h>
48 
49 #include <linux/uaccess.h>
50 #include <asm/unistd.h>
51 #include <asm/div64.h>
52 #include <asm/timex.h>
53 #include <asm/io.h>
54 
55 #include "tick-internal.h"
56 
57 #define CREATE_TRACE_POINTS
58 #include <trace/events/timer.h>
59 #undef CREATE_TRACE_POINTS
60 #include <trace/hooks/timer.h>
61 
62 __visible u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
63 
64 EXPORT_SYMBOL(jiffies_64);
65 
66 /*
67  * The timer wheel has LVL_DEPTH array levels. Each level provides an array of
68  * LVL_SIZE buckets. Each level is driven by its own clock and therefor each
69  * level has a different granularity.
70  *
71  * The level granularity is:		LVL_CLK_DIV ^ lvl
72  * The level clock frequency is:	HZ / (LVL_CLK_DIV ^ level)
73  *
74  * The array level of a newly armed timer depends on the relative expiry
75  * time. The farther the expiry time is away the higher the array level and
76  * therefor the granularity becomes.
77  *
78  * Contrary to the original timer wheel implementation, which aims for 'exact'
79  * expiry of the timers, this implementation removes the need for recascading
80  * the timers into the lower array levels. The previous 'classic' timer wheel
81  * implementation of the kernel already violated the 'exact' expiry by adding
82  * slack to the expiry time to provide batched expiration. The granularity
83  * levels provide implicit batching.
84  *
85  * This is an optimization of the original timer wheel implementation for the
86  * majority of the timer wheel use cases: timeouts. The vast majority of
87  * timeout timers (networking, disk I/O ...) are canceled before expiry. If
88  * the timeout expires it indicates that normal operation is disturbed, so it
89  * does not matter much whether the timeout comes with a slight delay.
90  *
91  * The only exception to this are networking timers with a small expiry
92  * time. They rely on the granularity. Those fit into the first wheel level,
93  * which has HZ granularity.
94  *
95  * We don't have cascading anymore. timers with a expiry time above the
96  * capacity of the last wheel level are force expired at the maximum timeout
97  * value of the last wheel level. From data sampling we know that the maximum
98  * value observed is 5 days (network connection tracking), so this should not
99  * be an issue.
100  *
101  * The currently chosen array constants values are a good compromise between
102  * array size and granularity.
103  *
104  * This results in the following granularity and range levels:
105  *
106  * HZ 1000 steps
107  * Level Offset  Granularity            Range
108  *  0      0         1 ms                0 ms -         63 ms
109  *  1     64         8 ms               64 ms -        511 ms
110  *  2    128        64 ms              512 ms -       4095 ms (512ms - ~4s)
111  *  3    192       512 ms             4096 ms -      32767 ms (~4s - ~32s)
112  *  4    256      4096 ms (~4s)      32768 ms -     262143 ms (~32s - ~4m)
113  *  5    320     32768 ms (~32s)    262144 ms -    2097151 ms (~4m - ~34m)
114  *  6    384    262144 ms (~4m)    2097152 ms -   16777215 ms (~34m - ~4h)
115  *  7    448   2097152 ms (~34m)  16777216 ms -  134217727 ms (~4h - ~1d)
116  *  8    512  16777216 ms (~4h)  134217728 ms - 1073741822 ms (~1d - ~12d)
117  *
118  * HZ  300
119  * Level Offset  Granularity            Range
120  *  0	   0         3 ms                0 ms -        210 ms
121  *  1	  64        26 ms              213 ms -       1703 ms (213ms - ~1s)
122  *  2	 128       213 ms             1706 ms -      13650 ms (~1s - ~13s)
123  *  3	 192      1706 ms (~1s)      13653 ms -     109223 ms (~13s - ~1m)
124  *  4	 256     13653 ms (~13s)    109226 ms -     873810 ms (~1m - ~14m)
125  *  5	 320    109226 ms (~1m)     873813 ms -    6990503 ms (~14m - ~1h)
126  *  6	 384    873813 ms (~14m)   6990506 ms -   55924050 ms (~1h - ~15h)
127  *  7	 448   6990506 ms (~1h)   55924053 ms -  447392423 ms (~15h - ~5d)
128  *  8    512  55924053 ms (~15h) 447392426 ms - 3579139406 ms (~5d - ~41d)
129  *
130  * HZ  250
131  * Level Offset  Granularity            Range
132  *  0	   0         4 ms                0 ms -        255 ms
133  *  1	  64        32 ms              256 ms -       2047 ms (256ms - ~2s)
134  *  2	 128       256 ms             2048 ms -      16383 ms (~2s - ~16s)
135  *  3	 192      2048 ms (~2s)      16384 ms -     131071 ms (~16s - ~2m)
136  *  4	 256     16384 ms (~16s)    131072 ms -    1048575 ms (~2m - ~17m)
137  *  5	 320    131072 ms (~2m)    1048576 ms -    8388607 ms (~17m - ~2h)
138  *  6	 384   1048576 ms (~17m)   8388608 ms -   67108863 ms (~2h - ~18h)
139  *  7	 448   8388608 ms (~2h)   67108864 ms -  536870911 ms (~18h - ~6d)
140  *  8    512  67108864 ms (~18h) 536870912 ms - 4294967288 ms (~6d - ~49d)
141  *
142  * HZ  100
143  * Level Offset  Granularity            Range
144  *  0	   0         10 ms               0 ms -        630 ms
145  *  1	  64         80 ms             640 ms -       5110 ms (640ms - ~5s)
146  *  2	 128        640 ms            5120 ms -      40950 ms (~5s - ~40s)
147  *  3	 192       5120 ms (~5s)     40960 ms -     327670 ms (~40s - ~5m)
148  *  4	 256      40960 ms (~40s)   327680 ms -    2621430 ms (~5m - ~43m)
149  *  5	 320     327680 ms (~5m)   2621440 ms -   20971510 ms (~43m - ~5h)
150  *  6	 384    2621440 ms (~43m) 20971520 ms -  167772150 ms (~5h - ~1d)
151  *  7	 448   20971520 ms (~5h) 167772160 ms - 1342177270 ms (~1d - ~15d)
152  */
153 
154 /* Clock divisor for the next level */
155 #define LVL_CLK_SHIFT	3
156 #define LVL_CLK_DIV	(1UL << LVL_CLK_SHIFT)
157 #define LVL_CLK_MASK	(LVL_CLK_DIV - 1)
158 #define LVL_SHIFT(n)	((n) * LVL_CLK_SHIFT)
159 #define LVL_GRAN(n)	(1UL << LVL_SHIFT(n))
160 
161 /*
162  * The time start value for each level to select the bucket at enqueue
163  * time. We start from the last possible delta of the previous level
164  * so that we can later add an extra LVL_GRAN(n) to n (see calc_index()).
165  */
166 #define LVL_START(n)	((LVL_SIZE - 1) << (((n) - 1) * LVL_CLK_SHIFT))
167 
168 /* Size of each clock level */
169 #define LVL_BITS	6
170 #define LVL_SIZE	(1UL << LVL_BITS)
171 #define LVL_MASK	(LVL_SIZE - 1)
172 #define LVL_OFFS(n)	((n) * LVL_SIZE)
173 
174 /* Level depth */
175 #if HZ > 100
176 # define LVL_DEPTH	9
177 # else
178 # define LVL_DEPTH	8
179 #endif
180 
181 /* The cutoff (max. capacity of the wheel) */
182 #define WHEEL_TIMEOUT_CUTOFF	(LVL_START(LVL_DEPTH))
183 #define WHEEL_TIMEOUT_MAX	(WHEEL_TIMEOUT_CUTOFF - LVL_GRAN(LVL_DEPTH - 1))
184 
185 /*
186  * The resulting wheel size. If NOHZ is configured we allocate two
187  * wheels so we have a separate storage for the deferrable timers.
188  */
189 #define WHEEL_SIZE	(LVL_SIZE * LVL_DEPTH)
190 
191 #ifdef CONFIG_NO_HZ_COMMON
192 # define NR_BASES	2
193 # define BASE_STD	0
194 # define BASE_DEF	1
195 #else
196 # define NR_BASES	1
197 # define BASE_STD	0
198 # define BASE_DEF	0
199 #endif
200 
201 struct timer_base {
202 	raw_spinlock_t		lock;
203 	struct timer_list	*running_timer;
204 #ifdef CONFIG_PREEMPT_RT
205 	spinlock_t		expiry_lock;
206 	atomic_t		timer_waiters;
207 #endif
208 	unsigned long		clk;
209 	unsigned long		next_expiry;
210 	unsigned int		cpu;
211 	bool			next_expiry_recalc;
212 	bool			is_idle;
213 	bool			timers_pending;
214 	DECLARE_BITMAP(pending_map, WHEEL_SIZE);
215 	struct hlist_head	vectors[WHEEL_SIZE];
216 } ____cacheline_aligned;
217 
218 static DEFINE_PER_CPU(struct timer_base, timer_bases[NR_BASES]);
219 
220 #ifdef CONFIG_NO_HZ_COMMON
221 
222 static DEFINE_STATIC_KEY_FALSE(timers_nohz_active);
223 static DEFINE_MUTEX(timer_keys_mutex);
224 
225 static void timer_update_keys(struct work_struct *work);
226 static DECLARE_WORK(timer_update_work, timer_update_keys);
227 
228 #ifdef CONFIG_SMP
229 static unsigned int sysctl_timer_migration = 1;
230 
231 DEFINE_STATIC_KEY_FALSE(timers_migration_enabled);
232 
timers_update_migration(void)233 static void timers_update_migration(void)
234 {
235 	if (sysctl_timer_migration && tick_nohz_active)
236 		static_branch_enable(&timers_migration_enabled);
237 	else
238 		static_branch_disable(&timers_migration_enabled);
239 }
240 
241 #ifdef CONFIG_SYSCTL
timer_migration_handler(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)242 static int timer_migration_handler(struct ctl_table *table, int write,
243 			    void *buffer, size_t *lenp, loff_t *ppos)
244 {
245 	int ret;
246 
247 	mutex_lock(&timer_keys_mutex);
248 	ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos);
249 	if (!ret && write)
250 		timers_update_migration();
251 	mutex_unlock(&timer_keys_mutex);
252 	return ret;
253 }
254 
255 static struct ctl_table timer_sysctl[] = {
256 	{
257 		.procname	= "timer_migration",
258 		.data		= &sysctl_timer_migration,
259 		.maxlen		= sizeof(unsigned int),
260 		.mode		= 0644,
261 		.proc_handler	= timer_migration_handler,
262 		.extra1		= SYSCTL_ZERO,
263 		.extra2		= SYSCTL_ONE,
264 	},
265 	{}
266 };
267 
timer_sysctl_init(void)268 static int __init timer_sysctl_init(void)
269 {
270 	register_sysctl("kernel", timer_sysctl);
271 	return 0;
272 }
273 device_initcall(timer_sysctl_init);
274 #endif /* CONFIG_SYSCTL */
275 #else /* CONFIG_SMP */
timers_update_migration(void)276 static inline void timers_update_migration(void) { }
277 #endif /* !CONFIG_SMP */
278 
timer_update_keys(struct work_struct * work)279 static void timer_update_keys(struct work_struct *work)
280 {
281 	mutex_lock(&timer_keys_mutex);
282 	timers_update_migration();
283 	static_branch_enable(&timers_nohz_active);
284 	mutex_unlock(&timer_keys_mutex);
285 }
286 
timers_update_nohz(void)287 void timers_update_nohz(void)
288 {
289 	schedule_work(&timer_update_work);
290 }
291 
is_timers_nohz_active(void)292 static inline bool is_timers_nohz_active(void)
293 {
294 	return static_branch_unlikely(&timers_nohz_active);
295 }
296 #else
is_timers_nohz_active(void)297 static inline bool is_timers_nohz_active(void) { return false; }
298 #endif /* NO_HZ_COMMON */
299 
round_jiffies_common(unsigned long j,int cpu,bool force_up)300 static unsigned long round_jiffies_common(unsigned long j, int cpu,
301 		bool force_up)
302 {
303 	int rem;
304 	unsigned long original = j;
305 
306 	/*
307 	 * We don't want all cpus firing their timers at once hitting the
308 	 * same lock or cachelines, so we skew each extra cpu with an extra
309 	 * 3 jiffies. This 3 jiffies came originally from the mm/ code which
310 	 * already did this.
311 	 * The skew is done by adding 3*cpunr, then round, then subtract this
312 	 * extra offset again.
313 	 */
314 	j += cpu * 3;
315 
316 	rem = j % HZ;
317 
318 	/*
319 	 * If the target jiffie is just after a whole second (which can happen
320 	 * due to delays of the timer irq, long irq off times etc etc) then
321 	 * we should round down to the whole second, not up. Use 1/4th second
322 	 * as cutoff for this rounding as an extreme upper bound for this.
323 	 * But never round down if @force_up is set.
324 	 */
325 	if (rem < HZ/4 && !force_up) /* round down */
326 		j = j - rem;
327 	else /* round up */
328 		j = j - rem + HZ;
329 
330 	/* now that we have rounded, subtract the extra skew again */
331 	j -= cpu * 3;
332 
333 	/*
334 	 * Make sure j is still in the future. Otherwise return the
335 	 * unmodified value.
336 	 */
337 	return time_is_after_jiffies(j) ? j : original;
338 }
339 
340 /**
341  * __round_jiffies - function to round jiffies to a full second
342  * @j: the time in (absolute) jiffies that should be rounded
343  * @cpu: the processor number on which the timeout will happen
344  *
345  * __round_jiffies() rounds an absolute time in the future (in jiffies)
346  * up or down to (approximately) full seconds. This is useful for timers
347  * for which the exact time they fire does not matter too much, as long as
348  * they fire approximately every X seconds.
349  *
350  * By rounding these timers to whole seconds, all such timers will fire
351  * at the same time, rather than at various times spread out. The goal
352  * of this is to have the CPU wake up less, which saves power.
353  *
354  * The exact rounding is skewed for each processor to avoid all
355  * processors firing at the exact same time, which could lead
356  * to lock contention or spurious cache line bouncing.
357  *
358  * The return value is the rounded version of the @j parameter.
359  */
__round_jiffies(unsigned long j,int cpu)360 unsigned long __round_jiffies(unsigned long j, int cpu)
361 {
362 	return round_jiffies_common(j, cpu, false);
363 }
364 EXPORT_SYMBOL_GPL(__round_jiffies);
365 
366 /**
367  * __round_jiffies_relative - function to round jiffies to a full second
368  * @j: the time in (relative) jiffies that should be rounded
369  * @cpu: the processor number on which the timeout will happen
370  *
371  * __round_jiffies_relative() rounds a time delta  in the future (in jiffies)
372  * up or down to (approximately) full seconds. This is useful for timers
373  * for which the exact time they fire does not matter too much, as long as
374  * they fire approximately every X seconds.
375  *
376  * By rounding these timers to whole seconds, all such timers will fire
377  * at the same time, rather than at various times spread out. The goal
378  * of this is to have the CPU wake up less, which saves power.
379  *
380  * The exact rounding is skewed for each processor to avoid all
381  * processors firing at the exact same time, which could lead
382  * to lock contention or spurious cache line bouncing.
383  *
384  * The return value is the rounded version of the @j parameter.
385  */
__round_jiffies_relative(unsigned long j,int cpu)386 unsigned long __round_jiffies_relative(unsigned long j, int cpu)
387 {
388 	unsigned long j0 = jiffies;
389 
390 	/* Use j0 because jiffies might change while we run */
391 	return round_jiffies_common(j + j0, cpu, false) - j0;
392 }
393 EXPORT_SYMBOL_GPL(__round_jiffies_relative);
394 
395 /**
396  * round_jiffies - function to round jiffies to a full second
397  * @j: the time in (absolute) jiffies that should be rounded
398  *
399  * round_jiffies() rounds an absolute time in the future (in jiffies)
400  * up or down to (approximately) full seconds. This is useful for timers
401  * for which the exact time they fire does not matter too much, as long as
402  * they fire approximately every X seconds.
403  *
404  * By rounding these timers to whole seconds, all such timers will fire
405  * at the same time, rather than at various times spread out. The goal
406  * of this is to have the CPU wake up less, which saves power.
407  *
408  * The return value is the rounded version of the @j parameter.
409  */
round_jiffies(unsigned long j)410 unsigned long round_jiffies(unsigned long j)
411 {
412 	return round_jiffies_common(j, raw_smp_processor_id(), false);
413 }
414 EXPORT_SYMBOL_GPL(round_jiffies);
415 
416 /**
417  * round_jiffies_relative - function to round jiffies to a full second
418  * @j: the time in (relative) jiffies that should be rounded
419  *
420  * round_jiffies_relative() rounds a time delta  in the future (in jiffies)
421  * up or down to (approximately) full seconds. This is useful for timers
422  * for which the exact time they fire does not matter too much, as long as
423  * they fire approximately every X seconds.
424  *
425  * By rounding these timers to whole seconds, all such timers will fire
426  * at the same time, rather than at various times spread out. The goal
427  * of this is to have the CPU wake up less, which saves power.
428  *
429  * The return value is the rounded version of the @j parameter.
430  */
round_jiffies_relative(unsigned long j)431 unsigned long round_jiffies_relative(unsigned long j)
432 {
433 	return __round_jiffies_relative(j, raw_smp_processor_id());
434 }
435 EXPORT_SYMBOL_GPL(round_jiffies_relative);
436 
437 /**
438  * __round_jiffies_up - function to round jiffies up to a full second
439  * @j: the time in (absolute) jiffies that should be rounded
440  * @cpu: the processor number on which the timeout will happen
441  *
442  * This is the same as __round_jiffies() except that it will never
443  * round down.  This is useful for timeouts for which the exact time
444  * of firing does not matter too much, as long as they don't fire too
445  * early.
446  */
__round_jiffies_up(unsigned long j,int cpu)447 unsigned long __round_jiffies_up(unsigned long j, int cpu)
448 {
449 	return round_jiffies_common(j, cpu, true);
450 }
451 EXPORT_SYMBOL_GPL(__round_jiffies_up);
452 
453 /**
454  * __round_jiffies_up_relative - function to round jiffies up to a full second
455  * @j: the time in (relative) jiffies that should be rounded
456  * @cpu: the processor number on which the timeout will happen
457  *
458  * This is the same as __round_jiffies_relative() except that it will never
459  * round down.  This is useful for timeouts for which the exact time
460  * of firing does not matter too much, as long as they don't fire too
461  * early.
462  */
__round_jiffies_up_relative(unsigned long j,int cpu)463 unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
464 {
465 	unsigned long j0 = jiffies;
466 
467 	/* Use j0 because jiffies might change while we run */
468 	return round_jiffies_common(j + j0, cpu, true) - j0;
469 }
470 EXPORT_SYMBOL_GPL(__round_jiffies_up_relative);
471 
472 /**
473  * round_jiffies_up - function to round jiffies up to a full second
474  * @j: the time in (absolute) jiffies that should be rounded
475  *
476  * This is the same as round_jiffies() except that it will never
477  * round down.  This is useful for timeouts for which the exact time
478  * of firing does not matter too much, as long as they don't fire too
479  * early.
480  */
round_jiffies_up(unsigned long j)481 unsigned long round_jiffies_up(unsigned long j)
482 {
483 	return round_jiffies_common(j, raw_smp_processor_id(), true);
484 }
485 EXPORT_SYMBOL_GPL(round_jiffies_up);
486 
487 /**
488  * round_jiffies_up_relative - function to round jiffies up to a full second
489  * @j: the time in (relative) jiffies that should be rounded
490  *
491  * This is the same as round_jiffies_relative() except that it will never
492  * round down.  This is useful for timeouts for which the exact time
493  * of firing does not matter too much, as long as they don't fire too
494  * early.
495  */
round_jiffies_up_relative(unsigned long j)496 unsigned long round_jiffies_up_relative(unsigned long j)
497 {
498 	return __round_jiffies_up_relative(j, raw_smp_processor_id());
499 }
500 EXPORT_SYMBOL_GPL(round_jiffies_up_relative);
501 
502 
timer_get_idx(struct timer_list * timer)503 static inline unsigned int timer_get_idx(struct timer_list *timer)
504 {
505 	return (timer->flags & TIMER_ARRAYMASK) >> TIMER_ARRAYSHIFT;
506 }
507 
timer_set_idx(struct timer_list * timer,unsigned int idx)508 static inline void timer_set_idx(struct timer_list *timer, unsigned int idx)
509 {
510 	timer->flags = (timer->flags & ~TIMER_ARRAYMASK) |
511 			idx << TIMER_ARRAYSHIFT;
512 }
513 
514 /*
515  * Helper function to calculate the array index for a given expiry
516  * time.
517  */
calc_index(unsigned long expires,unsigned lvl,unsigned long * bucket_expiry)518 static inline unsigned calc_index(unsigned long expires, unsigned lvl,
519 				  unsigned long *bucket_expiry)
520 {
521 
522 	/*
523 	 * The timer wheel has to guarantee that a timer does not fire
524 	 * early. Early expiry can happen due to:
525 	 * - Timer is armed at the edge of a tick
526 	 * - Truncation of the expiry time in the outer wheel levels
527 	 *
528 	 * Round up with level granularity to prevent this.
529 	 */
530 	trace_android_vh_timer_calc_index(lvl, &expires);
531 	expires = (expires >> LVL_SHIFT(lvl)) + 1;
532 	*bucket_expiry = expires << LVL_SHIFT(lvl);
533 	return LVL_OFFS(lvl) + (expires & LVL_MASK);
534 }
535 
calc_wheel_index(unsigned long expires,unsigned long clk,unsigned long * bucket_expiry)536 static int calc_wheel_index(unsigned long expires, unsigned long clk,
537 			    unsigned long *bucket_expiry)
538 {
539 	unsigned long delta = expires - clk;
540 	unsigned int idx;
541 
542 	if (delta < LVL_START(1)) {
543 		idx = calc_index(expires, 0, bucket_expiry);
544 	} else if (delta < LVL_START(2)) {
545 		idx = calc_index(expires, 1, bucket_expiry);
546 	} else if (delta < LVL_START(3)) {
547 		idx = calc_index(expires, 2, bucket_expiry);
548 	} else if (delta < LVL_START(4)) {
549 		idx = calc_index(expires, 3, bucket_expiry);
550 	} else if (delta < LVL_START(5)) {
551 		idx = calc_index(expires, 4, bucket_expiry);
552 	} else if (delta < LVL_START(6)) {
553 		idx = calc_index(expires, 5, bucket_expiry);
554 	} else if (delta < LVL_START(7)) {
555 		idx = calc_index(expires, 6, bucket_expiry);
556 	} else if (LVL_DEPTH > 8 && delta < LVL_START(8)) {
557 		idx = calc_index(expires, 7, bucket_expiry);
558 	} else if ((long) delta < 0) {
559 		idx = clk & LVL_MASK;
560 		*bucket_expiry = clk;
561 	} else {
562 		/*
563 		 * Force expire obscene large timeouts to expire at the
564 		 * capacity limit of the wheel.
565 		 */
566 		if (delta >= WHEEL_TIMEOUT_CUTOFF)
567 			expires = clk + WHEEL_TIMEOUT_MAX;
568 
569 		idx = calc_index(expires, LVL_DEPTH - 1, bucket_expiry);
570 	}
571 	return idx;
572 }
573 
574 static void
trigger_dyntick_cpu(struct timer_base * base,struct timer_list * timer)575 trigger_dyntick_cpu(struct timer_base *base, struct timer_list *timer)
576 {
577 	if (!is_timers_nohz_active())
578 		return;
579 
580 	/*
581 	 * TODO: This wants some optimizing similar to the code below, but we
582 	 * will do that when we switch from push to pull for deferrable timers.
583 	 */
584 	if (timer->flags & TIMER_DEFERRABLE) {
585 		if (tick_nohz_full_cpu(base->cpu))
586 			wake_up_nohz_cpu(base->cpu);
587 		return;
588 	}
589 
590 	/*
591 	 * We might have to IPI the remote CPU if the base is idle and the
592 	 * timer is not deferrable. If the other CPU is on the way to idle
593 	 * then it can't set base->is_idle as we hold the base lock:
594 	 */
595 	if (base->is_idle)
596 		wake_up_nohz_cpu(base->cpu);
597 }
598 
599 /*
600  * Enqueue the timer into the hash bucket, mark it pending in
601  * the bitmap, store the index in the timer flags then wake up
602  * the target CPU if needed.
603  */
enqueue_timer(struct timer_base * base,struct timer_list * timer,unsigned int idx,unsigned long bucket_expiry)604 static void enqueue_timer(struct timer_base *base, struct timer_list *timer,
605 			  unsigned int idx, unsigned long bucket_expiry)
606 {
607 
608 	hlist_add_head(&timer->entry, base->vectors + idx);
609 	__set_bit(idx, base->pending_map);
610 	timer_set_idx(timer, idx);
611 
612 	trace_timer_start(timer, timer->expires, timer->flags);
613 
614 	/*
615 	 * Check whether this is the new first expiring timer. The
616 	 * effective expiry time of the timer is required here
617 	 * (bucket_expiry) instead of timer->expires.
618 	 */
619 	if (time_before(bucket_expiry, base->next_expiry)) {
620 		/*
621 		 * Set the next expiry time and kick the CPU so it
622 		 * can reevaluate the wheel:
623 		 */
624 		base->next_expiry = bucket_expiry;
625 		base->timers_pending = true;
626 		base->next_expiry_recalc = false;
627 		trigger_dyntick_cpu(base, timer);
628 	}
629 }
630 
internal_add_timer(struct timer_base * base,struct timer_list * timer)631 static void internal_add_timer(struct timer_base *base, struct timer_list *timer)
632 {
633 	unsigned long bucket_expiry;
634 	unsigned int idx;
635 
636 	idx = calc_wheel_index(timer->expires, base->clk, &bucket_expiry);
637 	enqueue_timer(base, timer, idx, bucket_expiry);
638 }
639 
640 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
641 
642 static const struct debug_obj_descr timer_debug_descr;
643 
644 struct timer_hint {
645 	void	(*function)(struct timer_list *t);
646 	long	offset;
647 };
648 
649 #define TIMER_HINT(fn, container, timr, hintfn)			\
650 	{							\
651 		.function = fn,					\
652 		.offset	  = offsetof(container, hintfn) -	\
653 			    offsetof(container, timr)		\
654 	}
655 
656 static const struct timer_hint timer_hints[] = {
657 	TIMER_HINT(delayed_work_timer_fn,
658 		   struct delayed_work, timer, work.func),
659 	TIMER_HINT(kthread_delayed_work_timer_fn,
660 		   struct kthread_delayed_work, timer, work.func),
661 };
662 
timer_debug_hint(void * addr)663 static void *timer_debug_hint(void *addr)
664 {
665 	struct timer_list *timer = addr;
666 	int i;
667 
668 	for (i = 0; i < ARRAY_SIZE(timer_hints); i++) {
669 		if (timer_hints[i].function == timer->function) {
670 			void (**fn)(void) = addr + timer_hints[i].offset;
671 
672 			return *fn;
673 		}
674 	}
675 
676 	return timer->function;
677 }
678 
timer_is_static_object(void * addr)679 static bool timer_is_static_object(void *addr)
680 {
681 	struct timer_list *timer = addr;
682 
683 	return (timer->entry.pprev == NULL &&
684 		timer->entry.next == TIMER_ENTRY_STATIC);
685 }
686 
687 /*
688  * fixup_init is called when:
689  * - an active object is initialized
690  */
timer_fixup_init(void * addr,enum debug_obj_state state)691 static bool timer_fixup_init(void *addr, enum debug_obj_state state)
692 {
693 	struct timer_list *timer = addr;
694 
695 	switch (state) {
696 	case ODEBUG_STATE_ACTIVE:
697 		del_timer_sync(timer);
698 		debug_object_init(timer, &timer_debug_descr);
699 		return true;
700 	default:
701 		return false;
702 	}
703 }
704 
705 /* Stub timer callback for improperly used timers. */
stub_timer(struct timer_list * unused)706 static void stub_timer(struct timer_list *unused)
707 {
708 	WARN_ON(1);
709 }
710 
711 /*
712  * fixup_activate is called when:
713  * - an active object is activated
714  * - an unknown non-static object is activated
715  */
timer_fixup_activate(void * addr,enum debug_obj_state state)716 static bool timer_fixup_activate(void *addr, enum debug_obj_state state)
717 {
718 	struct timer_list *timer = addr;
719 
720 	switch (state) {
721 	case ODEBUG_STATE_NOTAVAILABLE:
722 		timer_setup(timer, stub_timer, 0);
723 		return true;
724 
725 	case ODEBUG_STATE_ACTIVE:
726 		WARN_ON(1);
727 		fallthrough;
728 	default:
729 		return false;
730 	}
731 }
732 
733 /*
734  * fixup_free is called when:
735  * - an active object is freed
736  */
timer_fixup_free(void * addr,enum debug_obj_state state)737 static bool timer_fixup_free(void *addr, enum debug_obj_state state)
738 {
739 	struct timer_list *timer = addr;
740 
741 	switch (state) {
742 	case ODEBUG_STATE_ACTIVE:
743 		del_timer_sync(timer);
744 		debug_object_free(timer, &timer_debug_descr);
745 		return true;
746 	default:
747 		return false;
748 	}
749 }
750 
751 /*
752  * fixup_assert_init is called when:
753  * - an untracked/uninit-ed object is found
754  */
timer_fixup_assert_init(void * addr,enum debug_obj_state state)755 static bool timer_fixup_assert_init(void *addr, enum debug_obj_state state)
756 {
757 	struct timer_list *timer = addr;
758 
759 	switch (state) {
760 	case ODEBUG_STATE_NOTAVAILABLE:
761 		timer_setup(timer, stub_timer, 0);
762 		return true;
763 	default:
764 		return false;
765 	}
766 }
767 
768 static const struct debug_obj_descr timer_debug_descr = {
769 	.name			= "timer_list",
770 	.debug_hint		= timer_debug_hint,
771 	.is_static_object	= timer_is_static_object,
772 	.fixup_init		= timer_fixup_init,
773 	.fixup_activate		= timer_fixup_activate,
774 	.fixup_free		= timer_fixup_free,
775 	.fixup_assert_init	= timer_fixup_assert_init,
776 };
777 
debug_timer_init(struct timer_list * timer)778 static inline void debug_timer_init(struct timer_list *timer)
779 {
780 	debug_object_init(timer, &timer_debug_descr);
781 }
782 
debug_timer_activate(struct timer_list * timer)783 static inline void debug_timer_activate(struct timer_list *timer)
784 {
785 	debug_object_activate(timer, &timer_debug_descr);
786 }
787 
debug_timer_deactivate(struct timer_list * timer)788 static inline void debug_timer_deactivate(struct timer_list *timer)
789 {
790 	debug_object_deactivate(timer, &timer_debug_descr);
791 }
792 
debug_timer_assert_init(struct timer_list * timer)793 static inline void debug_timer_assert_init(struct timer_list *timer)
794 {
795 	debug_object_assert_init(timer, &timer_debug_descr);
796 }
797 
798 static void do_init_timer(struct timer_list *timer,
799 			  void (*func)(struct timer_list *),
800 			  unsigned int flags,
801 			  const char *name, struct lock_class_key *key);
802 
init_timer_on_stack_key(struct timer_list * timer,void (* func)(struct timer_list *),unsigned int flags,const char * name,struct lock_class_key * key)803 void init_timer_on_stack_key(struct timer_list *timer,
804 			     void (*func)(struct timer_list *),
805 			     unsigned int flags,
806 			     const char *name, struct lock_class_key *key)
807 {
808 	debug_object_init_on_stack(timer, &timer_debug_descr);
809 	do_init_timer(timer, func, flags, name, key);
810 }
811 EXPORT_SYMBOL_GPL(init_timer_on_stack_key);
812 
destroy_timer_on_stack(struct timer_list * timer)813 void destroy_timer_on_stack(struct timer_list *timer)
814 {
815 	debug_object_free(timer, &timer_debug_descr);
816 }
817 EXPORT_SYMBOL_GPL(destroy_timer_on_stack);
818 
819 #else
debug_timer_init(struct timer_list * timer)820 static inline void debug_timer_init(struct timer_list *timer) { }
debug_timer_activate(struct timer_list * timer)821 static inline void debug_timer_activate(struct timer_list *timer) { }
debug_timer_deactivate(struct timer_list * timer)822 static inline void debug_timer_deactivate(struct timer_list *timer) { }
debug_timer_assert_init(struct timer_list * timer)823 static inline void debug_timer_assert_init(struct timer_list *timer) { }
824 #endif
825 
debug_init(struct timer_list * timer)826 static inline void debug_init(struct timer_list *timer)
827 {
828 	debug_timer_init(timer);
829 	trace_timer_init(timer);
830 }
831 
debug_deactivate(struct timer_list * timer)832 static inline void debug_deactivate(struct timer_list *timer)
833 {
834 	debug_timer_deactivate(timer);
835 	trace_timer_cancel(timer);
836 }
837 
debug_assert_init(struct timer_list * timer)838 static inline void debug_assert_init(struct timer_list *timer)
839 {
840 	debug_timer_assert_init(timer);
841 }
842 
do_init_timer(struct timer_list * timer,void (* func)(struct timer_list *),unsigned int flags,const char * name,struct lock_class_key * key)843 static void do_init_timer(struct timer_list *timer,
844 			  void (*func)(struct timer_list *),
845 			  unsigned int flags,
846 			  const char *name, struct lock_class_key *key)
847 {
848 	timer->entry.pprev = NULL;
849 	timer->function = func;
850 	if (WARN_ON_ONCE(flags & ~TIMER_INIT_FLAGS))
851 		flags &= TIMER_INIT_FLAGS;
852 	timer->flags = flags | raw_smp_processor_id();
853 	lockdep_init_map(&timer->lockdep_map, name, key, 0);
854 }
855 
856 /**
857  * init_timer_key - initialize a timer
858  * @timer: the timer to be initialized
859  * @func: timer callback function
860  * @flags: timer flags
861  * @name: name of the timer
862  * @key: lockdep class key of the fake lock used for tracking timer
863  *       sync lock dependencies
864  *
865  * init_timer_key() must be done to a timer prior calling *any* of the
866  * other timer functions.
867  */
init_timer_key(struct timer_list * timer,void (* func)(struct timer_list *),unsigned int flags,const char * name,struct lock_class_key * key)868 void init_timer_key(struct timer_list *timer,
869 		    void (*func)(struct timer_list *), unsigned int flags,
870 		    const char *name, struct lock_class_key *key)
871 {
872 	debug_init(timer);
873 	do_init_timer(timer, func, flags, name, key);
874 }
875 EXPORT_SYMBOL(init_timer_key);
876 
detach_timer(struct timer_list * timer,bool clear_pending)877 static inline void detach_timer(struct timer_list *timer, bool clear_pending)
878 {
879 	struct hlist_node *entry = &timer->entry;
880 
881 	debug_deactivate(timer);
882 
883 	__hlist_del(entry);
884 	if (clear_pending)
885 		entry->pprev = NULL;
886 	entry->next = LIST_POISON2;
887 }
888 
detach_if_pending(struct timer_list * timer,struct timer_base * base,bool clear_pending)889 static int detach_if_pending(struct timer_list *timer, struct timer_base *base,
890 			     bool clear_pending)
891 {
892 	unsigned idx = timer_get_idx(timer);
893 
894 	if (!timer_pending(timer))
895 		return 0;
896 
897 	if (hlist_is_singular_node(&timer->entry, base->vectors + idx)) {
898 		__clear_bit(idx, base->pending_map);
899 		base->next_expiry_recalc = true;
900 	}
901 
902 	detach_timer(timer, clear_pending);
903 	return 1;
904 }
905 
get_timer_cpu_base(u32 tflags,u32 cpu)906 static inline struct timer_base *get_timer_cpu_base(u32 tflags, u32 cpu)
907 {
908 	struct timer_base *base = per_cpu_ptr(&timer_bases[BASE_STD], cpu);
909 
910 	/*
911 	 * If the timer is deferrable and NO_HZ_COMMON is set then we need
912 	 * to use the deferrable base.
913 	 */
914 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
915 		base = per_cpu_ptr(&timer_bases[BASE_DEF], cpu);
916 	return base;
917 }
918 
get_timer_this_cpu_base(u32 tflags)919 static inline struct timer_base *get_timer_this_cpu_base(u32 tflags)
920 {
921 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
922 
923 	/*
924 	 * If the timer is deferrable and NO_HZ_COMMON is set then we need
925 	 * to use the deferrable base.
926 	 */
927 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE))
928 		base = this_cpu_ptr(&timer_bases[BASE_DEF]);
929 	return base;
930 }
931 
get_timer_base(u32 tflags)932 static inline struct timer_base *get_timer_base(u32 tflags)
933 {
934 	return get_timer_cpu_base(tflags, tflags & TIMER_CPUMASK);
935 }
936 
937 static inline struct timer_base *
get_target_base(struct timer_base * base,unsigned tflags)938 get_target_base(struct timer_base *base, unsigned tflags)
939 {
940 #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
941 	if (static_branch_likely(&timers_migration_enabled) &&
942 	    !(tflags & TIMER_PINNED))
943 		return get_timer_cpu_base(tflags, get_nohz_timer_target());
944 #endif
945 	return get_timer_this_cpu_base(tflags);
946 }
947 
forward_timer_base(struct timer_base * base)948 static inline void forward_timer_base(struct timer_base *base)
949 {
950 	unsigned long jnow = READ_ONCE(jiffies);
951 
952 	/*
953 	 * No need to forward if we are close enough below jiffies.
954 	 * Also while executing timers, base->clk is 1 offset ahead
955 	 * of jiffies to avoid endless requeuing to current jiffies.
956 	 */
957 	if ((long)(jnow - base->clk) < 1)
958 		return;
959 
960 	/*
961 	 * If the next expiry value is > jiffies, then we fast forward to
962 	 * jiffies otherwise we forward to the next expiry value.
963 	 */
964 	if (time_after(base->next_expiry, jnow)) {
965 		base->clk = jnow;
966 	} else {
967 		if (WARN_ON_ONCE(time_before(base->next_expiry, base->clk)))
968 			return;
969 		base->clk = base->next_expiry;
970 	}
971 }
972 
973 
974 /*
975  * We are using hashed locking: Holding per_cpu(timer_bases[x]).lock means
976  * that all timers which are tied to this base are locked, and the base itself
977  * is locked too.
978  *
979  * So __run_timers/migrate_timers can safely modify all timers which could
980  * be found in the base->vectors array.
981  *
982  * When a timer is migrating then the TIMER_MIGRATING flag is set and we need
983  * to wait until the migration is done.
984  */
lock_timer_base(struct timer_list * timer,unsigned long * flags)985 static struct timer_base *lock_timer_base(struct timer_list *timer,
986 					  unsigned long *flags)
987 	__acquires(timer->base->lock)
988 {
989 	for (;;) {
990 		struct timer_base *base;
991 		u32 tf;
992 
993 		/*
994 		 * We need to use READ_ONCE() here, otherwise the compiler
995 		 * might re-read @tf between the check for TIMER_MIGRATING
996 		 * and spin_lock().
997 		 */
998 		tf = READ_ONCE(timer->flags);
999 
1000 		if (!(tf & TIMER_MIGRATING)) {
1001 			base = get_timer_base(tf);
1002 			raw_spin_lock_irqsave(&base->lock, *flags);
1003 			if (timer->flags == tf)
1004 				return base;
1005 			raw_spin_unlock_irqrestore(&base->lock, *flags);
1006 		}
1007 		cpu_relax();
1008 	}
1009 }
1010 
1011 #define MOD_TIMER_PENDING_ONLY		0x01
1012 #define MOD_TIMER_REDUCE		0x02
1013 #define MOD_TIMER_NOTPENDING		0x04
1014 
1015 static inline int
__mod_timer(struct timer_list * timer,unsigned long expires,unsigned int options)1016 __mod_timer(struct timer_list *timer, unsigned long expires, unsigned int options)
1017 {
1018 	unsigned long clk = 0, flags, bucket_expiry;
1019 	struct timer_base *base, *new_base;
1020 	unsigned int idx = UINT_MAX;
1021 	int ret = 0;
1022 
1023 	debug_assert_init(timer);
1024 
1025 	/*
1026 	 * This is a common optimization triggered by the networking code - if
1027 	 * the timer is re-modified to have the same timeout or ends up in the
1028 	 * same array bucket then just return:
1029 	 */
1030 	if (!(options & MOD_TIMER_NOTPENDING) && timer_pending(timer)) {
1031 		/*
1032 		 * The downside of this optimization is that it can result in
1033 		 * larger granularity than you would get from adding a new
1034 		 * timer with this expiry.
1035 		 */
1036 		long diff = timer->expires - expires;
1037 
1038 		if (!diff)
1039 			return 1;
1040 		if (options & MOD_TIMER_REDUCE && diff <= 0)
1041 			return 1;
1042 
1043 		/*
1044 		 * We lock timer base and calculate the bucket index right
1045 		 * here. If the timer ends up in the same bucket, then we
1046 		 * just update the expiry time and avoid the whole
1047 		 * dequeue/enqueue dance.
1048 		 */
1049 		base = lock_timer_base(timer, &flags);
1050 		/*
1051 		 * Has @timer been shutdown? This needs to be evaluated
1052 		 * while holding base lock to prevent a race against the
1053 		 * shutdown code.
1054 		 */
1055 		if (!timer->function)
1056 			goto out_unlock;
1057 
1058 		forward_timer_base(base);
1059 
1060 		if (timer_pending(timer) && (options & MOD_TIMER_REDUCE) &&
1061 		    time_before_eq(timer->expires, expires)) {
1062 			ret = 1;
1063 			goto out_unlock;
1064 		}
1065 
1066 		clk = base->clk;
1067 		idx = calc_wheel_index(expires, clk, &bucket_expiry);
1068 
1069 		/*
1070 		 * Retrieve and compare the array index of the pending
1071 		 * timer. If it matches set the expiry to the new value so a
1072 		 * subsequent call will exit in the expires check above.
1073 		 */
1074 		if (idx == timer_get_idx(timer)) {
1075 			if (!(options & MOD_TIMER_REDUCE))
1076 				timer->expires = expires;
1077 			else if (time_after(timer->expires, expires))
1078 				timer->expires = expires;
1079 			ret = 1;
1080 			goto out_unlock;
1081 		}
1082 	} else {
1083 		base = lock_timer_base(timer, &flags);
1084 		/*
1085 		 * Has @timer been shutdown? This needs to be evaluated
1086 		 * while holding base lock to prevent a race against the
1087 		 * shutdown code.
1088 		 */
1089 		if (!timer->function)
1090 			goto out_unlock;
1091 
1092 		forward_timer_base(base);
1093 	}
1094 
1095 	ret = detach_if_pending(timer, base, false);
1096 	if (!ret && (options & MOD_TIMER_PENDING_ONLY))
1097 		goto out_unlock;
1098 
1099 	new_base = get_target_base(base, timer->flags);
1100 
1101 	if (base != new_base) {
1102 		/*
1103 		 * We are trying to schedule the timer on the new base.
1104 		 * However we can't change timer's base while it is running,
1105 		 * otherwise timer_delete_sync() can't detect that the timer's
1106 		 * handler yet has not finished. This also guarantees that the
1107 		 * timer is serialized wrt itself.
1108 		 */
1109 		if (likely(base->running_timer != timer)) {
1110 			/* See the comment in lock_timer_base() */
1111 			timer->flags |= TIMER_MIGRATING;
1112 
1113 			raw_spin_unlock(&base->lock);
1114 			base = new_base;
1115 			raw_spin_lock(&base->lock);
1116 			WRITE_ONCE(timer->flags,
1117 				   (timer->flags & ~TIMER_BASEMASK) | base->cpu);
1118 			forward_timer_base(base);
1119 		}
1120 	}
1121 
1122 	debug_timer_activate(timer);
1123 
1124 	timer->expires = expires;
1125 	/*
1126 	 * If 'idx' was calculated above and the base time did not advance
1127 	 * between calculating 'idx' and possibly switching the base, only
1128 	 * enqueue_timer() is required. Otherwise we need to (re)calculate
1129 	 * the wheel index via internal_add_timer().
1130 	 */
1131 	if (idx != UINT_MAX && clk == base->clk)
1132 		enqueue_timer(base, timer, idx, bucket_expiry);
1133 	else
1134 		internal_add_timer(base, timer);
1135 
1136 out_unlock:
1137 	raw_spin_unlock_irqrestore(&base->lock, flags);
1138 
1139 	return ret;
1140 }
1141 
1142 /**
1143  * mod_timer_pending - Modify a pending timer's timeout
1144  * @timer:	The pending timer to be modified
1145  * @expires:	New absolute timeout in jiffies
1146  *
1147  * mod_timer_pending() is the same for pending timers as mod_timer(), but
1148  * will not activate inactive timers.
1149  *
1150  * If @timer->function == NULL then the start operation is silently
1151  * discarded.
1152  *
1153  * Return:
1154  * * %0 - The timer was inactive and not modified or was in
1155  *	  shutdown state and the operation was discarded
1156  * * %1 - The timer was active and requeued to expire at @expires
1157  */
mod_timer_pending(struct timer_list * timer,unsigned long expires)1158 int mod_timer_pending(struct timer_list *timer, unsigned long expires)
1159 {
1160 	return __mod_timer(timer, expires, MOD_TIMER_PENDING_ONLY);
1161 }
1162 EXPORT_SYMBOL(mod_timer_pending);
1163 
1164 /**
1165  * mod_timer - Modify a timer's timeout
1166  * @timer:	The timer to be modified
1167  * @expires:	New absolute timeout in jiffies
1168  *
1169  * mod_timer(timer, expires) is equivalent to:
1170  *
1171  *     del_timer(timer); timer->expires = expires; add_timer(timer);
1172  *
1173  * mod_timer() is more efficient than the above open coded sequence. In
1174  * case that the timer is inactive, the del_timer() part is a NOP. The
1175  * timer is in any case activated with the new expiry time @expires.
1176  *
1177  * Note that if there are multiple unserialized concurrent users of the
1178  * same timer, then mod_timer() is the only safe way to modify the timeout,
1179  * since add_timer() cannot modify an already running timer.
1180  *
1181  * If @timer->function == NULL then the start operation is silently
1182  * discarded. In this case the return value is 0 and meaningless.
1183  *
1184  * Return:
1185  * * %0 - The timer was inactive and started or was in shutdown
1186  *	  state and the operation was discarded
1187  * * %1 - The timer was active and requeued to expire at @expires or
1188  *	  the timer was active and not modified because @expires did
1189  *	  not change the effective expiry time
1190  */
mod_timer(struct timer_list * timer,unsigned long expires)1191 int mod_timer(struct timer_list *timer, unsigned long expires)
1192 {
1193 	return __mod_timer(timer, expires, 0);
1194 }
1195 EXPORT_SYMBOL(mod_timer);
1196 
1197 /**
1198  * timer_reduce - Modify a timer's timeout if it would reduce the timeout
1199  * @timer:	The timer to be modified
1200  * @expires:	New absolute timeout in jiffies
1201  *
1202  * timer_reduce() is very similar to mod_timer(), except that it will only
1203  * modify an enqueued timer if that would reduce the expiration time. If
1204  * @timer is not enqueued it starts the timer.
1205  *
1206  * If @timer->function == NULL then the start operation is silently
1207  * discarded.
1208  *
1209  * Return:
1210  * * %0 - The timer was inactive and started or was in shutdown
1211  *	  state and the operation was discarded
1212  * * %1 - The timer was active and requeued to expire at @expires or
1213  *	  the timer was active and not modified because @expires
1214  *	  did not change the effective expiry time such that the
1215  *	  timer would expire earlier than already scheduled
1216  */
timer_reduce(struct timer_list * timer,unsigned long expires)1217 int timer_reduce(struct timer_list *timer, unsigned long expires)
1218 {
1219 	return __mod_timer(timer, expires, MOD_TIMER_REDUCE);
1220 }
1221 EXPORT_SYMBOL(timer_reduce);
1222 
1223 /**
1224  * add_timer - Start a timer
1225  * @timer:	The timer to be started
1226  *
1227  * Start @timer to expire at @timer->expires in the future. @timer->expires
1228  * is the absolute expiry time measured in 'jiffies'. When the timer expires
1229  * timer->function(timer) will be invoked from soft interrupt context.
1230  *
1231  * The @timer->expires and @timer->function fields must be set prior
1232  * to calling this function.
1233  *
1234  * If @timer->function == NULL then the start operation is silently
1235  * discarded.
1236  *
1237  * If @timer->expires is already in the past @timer will be queued to
1238  * expire at the next timer tick.
1239  *
1240  * This can only operate on an inactive timer. Attempts to invoke this on
1241  * an active timer are rejected with a warning.
1242  */
add_timer(struct timer_list * timer)1243 void add_timer(struct timer_list *timer)
1244 {
1245 	if (WARN_ON_ONCE(timer_pending(timer)))
1246 		return;
1247 	__mod_timer(timer, timer->expires, MOD_TIMER_NOTPENDING);
1248 }
1249 EXPORT_SYMBOL(add_timer);
1250 
1251 /**
1252  * add_timer_on - Start a timer on a particular CPU
1253  * @timer:	The timer to be started
1254  * @cpu:	The CPU to start it on
1255  *
1256  * Same as add_timer() except that it starts the timer on the given CPU.
1257  *
1258  * See add_timer() for further details.
1259  */
add_timer_on(struct timer_list * timer,int cpu)1260 void add_timer_on(struct timer_list *timer, int cpu)
1261 {
1262 	struct timer_base *new_base, *base;
1263 	unsigned long flags;
1264 
1265 	debug_assert_init(timer);
1266 
1267 	if (WARN_ON_ONCE(timer_pending(timer)))
1268 		return;
1269 
1270 	new_base = get_timer_cpu_base(timer->flags, cpu);
1271 
1272 	/*
1273 	 * If @timer was on a different CPU, it should be migrated with the
1274 	 * old base locked to prevent other operations proceeding with the
1275 	 * wrong base locked.  See lock_timer_base().
1276 	 */
1277 	base = lock_timer_base(timer, &flags);
1278 	/*
1279 	 * Has @timer been shutdown? This needs to be evaluated while
1280 	 * holding base lock to prevent a race against the shutdown code.
1281 	 */
1282 	if (!timer->function)
1283 		goto out_unlock;
1284 
1285 	if (base != new_base) {
1286 		timer->flags |= TIMER_MIGRATING;
1287 
1288 		raw_spin_unlock(&base->lock);
1289 		base = new_base;
1290 		raw_spin_lock(&base->lock);
1291 		WRITE_ONCE(timer->flags,
1292 			   (timer->flags & ~TIMER_BASEMASK) | cpu);
1293 	}
1294 	forward_timer_base(base);
1295 
1296 	debug_timer_activate(timer);
1297 	internal_add_timer(base, timer);
1298 out_unlock:
1299 	raw_spin_unlock_irqrestore(&base->lock, flags);
1300 }
1301 EXPORT_SYMBOL_GPL(add_timer_on);
1302 
1303 /**
1304  * __timer_delete - Internal function: Deactivate a timer
1305  * @timer:	The timer to be deactivated
1306  * @shutdown:	If true, this indicates that the timer is about to be
1307  *		shutdown permanently.
1308  *
1309  * If @shutdown is true then @timer->function is set to NULL under the
1310  * timer base lock which prevents further rearming of the time. In that
1311  * case any attempt to rearm @timer after this function returns will be
1312  * silently ignored.
1313  *
1314  * Return:
1315  * * %0 - The timer was not pending
1316  * * %1 - The timer was pending and deactivated
1317  */
__timer_delete(struct timer_list * timer,bool shutdown)1318 static int __timer_delete(struct timer_list *timer, bool shutdown)
1319 {
1320 	struct timer_base *base;
1321 	unsigned long flags;
1322 	int ret = 0;
1323 
1324 	debug_assert_init(timer);
1325 
1326 	/*
1327 	 * If @shutdown is set then the lock has to be taken whether the
1328 	 * timer is pending or not to protect against a concurrent rearm
1329 	 * which might hit between the lockless pending check and the lock
1330 	 * aquisition. By taking the lock it is ensured that such a newly
1331 	 * enqueued timer is dequeued and cannot end up with
1332 	 * timer->function == NULL in the expiry code.
1333 	 *
1334 	 * If timer->function is currently executed, then this makes sure
1335 	 * that the callback cannot requeue the timer.
1336 	 */
1337 	if (timer_pending(timer) || shutdown) {
1338 		base = lock_timer_base(timer, &flags);
1339 		ret = detach_if_pending(timer, base, true);
1340 		if (shutdown)
1341 			timer->function = NULL;
1342 		raw_spin_unlock_irqrestore(&base->lock, flags);
1343 	}
1344 
1345 	return ret;
1346 }
1347 
1348 /**
1349  * timer_delete - Deactivate a timer
1350  * @timer:	The timer to be deactivated
1351  *
1352  * The function only deactivates a pending timer, but contrary to
1353  * timer_delete_sync() it does not take into account whether the timer's
1354  * callback function is concurrently executed on a different CPU or not.
1355  * It neither prevents rearming of the timer.  If @timer can be rearmed
1356  * concurrently then the return value of this function is meaningless.
1357  *
1358  * Return:
1359  * * %0 - The timer was not pending
1360  * * %1 - The timer was pending and deactivated
1361  */
timer_delete(struct timer_list * timer)1362 int timer_delete(struct timer_list *timer)
1363 {
1364 	return __timer_delete(timer, false);
1365 }
1366 EXPORT_SYMBOL(timer_delete);
1367 
1368 /**
1369  * timer_shutdown - Deactivate a timer and prevent rearming
1370  * @timer:	The timer to be deactivated
1371  *
1372  * The function does not wait for an eventually running timer callback on a
1373  * different CPU but it prevents rearming of the timer. Any attempt to arm
1374  * @timer after this function returns will be silently ignored.
1375  *
1376  * This function is useful for teardown code and should only be used when
1377  * timer_shutdown_sync() cannot be invoked due to locking or context constraints.
1378  *
1379  * Return:
1380  * * %0 - The timer was not pending
1381  * * %1 - The timer was pending
1382  */
timer_shutdown(struct timer_list * timer)1383 int timer_shutdown(struct timer_list *timer)
1384 {
1385 	return __timer_delete(timer, true);
1386 }
1387 EXPORT_SYMBOL_GPL(timer_shutdown);
1388 
1389 /**
1390  * __try_to_del_timer_sync - Internal function: Try to deactivate a timer
1391  * @timer:	Timer to deactivate
1392  * @shutdown:	If true, this indicates that the timer is about to be
1393  *		shutdown permanently.
1394  *
1395  * If @shutdown is true then @timer->function is set to NULL under the
1396  * timer base lock which prevents further rearming of the timer. Any
1397  * attempt to rearm @timer after this function returns will be silently
1398  * ignored.
1399  *
1400  * This function cannot guarantee that the timer cannot be rearmed
1401  * right after dropping the base lock if @shutdown is false. That
1402  * needs to be prevented by the calling code if necessary.
1403  *
1404  * Return:
1405  * * %0  - The timer was not pending
1406  * * %1  - The timer was pending and deactivated
1407  * * %-1 - The timer callback function is running on a different CPU
1408  */
__try_to_del_timer_sync(struct timer_list * timer,bool shutdown)1409 static int __try_to_del_timer_sync(struct timer_list *timer, bool shutdown)
1410 {
1411 	struct timer_base *base;
1412 	unsigned long flags;
1413 	int ret = -1;
1414 
1415 	debug_assert_init(timer);
1416 
1417 	base = lock_timer_base(timer, &flags);
1418 
1419 	if (base->running_timer != timer)
1420 		ret = detach_if_pending(timer, base, true);
1421 	if (shutdown)
1422 		timer->function = NULL;
1423 
1424 	raw_spin_unlock_irqrestore(&base->lock, flags);
1425 
1426 	return ret;
1427 }
1428 
1429 /**
1430  * try_to_del_timer_sync - Try to deactivate a timer
1431  * @timer:	Timer to deactivate
1432  *
1433  * This function tries to deactivate a timer. On success the timer is not
1434  * queued and the timer callback function is not running on any CPU.
1435  *
1436  * This function does not guarantee that the timer cannot be rearmed right
1437  * after dropping the base lock. That needs to be prevented by the calling
1438  * code if necessary.
1439  *
1440  * Return:
1441  * * %0  - The timer was not pending
1442  * * %1  - The timer was pending and deactivated
1443  * * %-1 - The timer callback function is running on a different CPU
1444  */
try_to_del_timer_sync(struct timer_list * timer)1445 int try_to_del_timer_sync(struct timer_list *timer)
1446 {
1447 	return __try_to_del_timer_sync(timer, false);
1448 }
1449 EXPORT_SYMBOL(try_to_del_timer_sync);
1450 
1451 #ifdef CONFIG_PREEMPT_RT
timer_base_init_expiry_lock(struct timer_base * base)1452 static __init void timer_base_init_expiry_lock(struct timer_base *base)
1453 {
1454 	spin_lock_init(&base->expiry_lock);
1455 }
1456 
timer_base_lock_expiry(struct timer_base * base)1457 static inline void timer_base_lock_expiry(struct timer_base *base)
1458 {
1459 	spin_lock(&base->expiry_lock);
1460 }
1461 
timer_base_unlock_expiry(struct timer_base * base)1462 static inline void timer_base_unlock_expiry(struct timer_base *base)
1463 {
1464 	spin_unlock(&base->expiry_lock);
1465 }
1466 
1467 /*
1468  * The counterpart to del_timer_wait_running().
1469  *
1470  * If there is a waiter for base->expiry_lock, then it was waiting for the
1471  * timer callback to finish. Drop expiry_lock and reacquire it. That allows
1472  * the waiter to acquire the lock and make progress.
1473  */
timer_sync_wait_running(struct timer_base * base)1474 static void timer_sync_wait_running(struct timer_base *base)
1475 {
1476 	if (atomic_read(&base->timer_waiters)) {
1477 		raw_spin_unlock_irq(&base->lock);
1478 		spin_unlock(&base->expiry_lock);
1479 		spin_lock(&base->expiry_lock);
1480 		raw_spin_lock_irq(&base->lock);
1481 	}
1482 }
1483 
1484 /*
1485  * This function is called on PREEMPT_RT kernels when the fast path
1486  * deletion of a timer failed because the timer callback function was
1487  * running.
1488  *
1489  * This prevents priority inversion, if the softirq thread on a remote CPU
1490  * got preempted, and it prevents a life lock when the task which tries to
1491  * delete a timer preempted the softirq thread running the timer callback
1492  * function.
1493  */
del_timer_wait_running(struct timer_list * timer)1494 static void del_timer_wait_running(struct timer_list *timer)
1495 {
1496 	u32 tf;
1497 
1498 	tf = READ_ONCE(timer->flags);
1499 	if (!(tf & (TIMER_MIGRATING | TIMER_IRQSAFE))) {
1500 		struct timer_base *base = get_timer_base(tf);
1501 
1502 		/*
1503 		 * Mark the base as contended and grab the expiry lock,
1504 		 * which is held by the softirq across the timer
1505 		 * callback. Drop the lock immediately so the softirq can
1506 		 * expire the next timer. In theory the timer could already
1507 		 * be running again, but that's more than unlikely and just
1508 		 * causes another wait loop.
1509 		 */
1510 		atomic_inc(&base->timer_waiters);
1511 		spin_lock_bh(&base->expiry_lock);
1512 		atomic_dec(&base->timer_waiters);
1513 		spin_unlock_bh(&base->expiry_lock);
1514 	}
1515 }
1516 #else
timer_base_init_expiry_lock(struct timer_base * base)1517 static inline void timer_base_init_expiry_lock(struct timer_base *base) { }
timer_base_lock_expiry(struct timer_base * base)1518 static inline void timer_base_lock_expiry(struct timer_base *base) { }
timer_base_unlock_expiry(struct timer_base * base)1519 static inline void timer_base_unlock_expiry(struct timer_base *base) { }
timer_sync_wait_running(struct timer_base * base)1520 static inline void timer_sync_wait_running(struct timer_base *base) { }
del_timer_wait_running(struct timer_list * timer)1521 static inline void del_timer_wait_running(struct timer_list *timer) { }
1522 #endif
1523 
1524 /**
1525  * __timer_delete_sync - Internal function: Deactivate a timer and wait
1526  *			 for the handler to finish.
1527  * @timer:	The timer to be deactivated
1528  * @shutdown:	If true, @timer->function will be set to NULL under the
1529  *		timer base lock which prevents rearming of @timer
1530  *
1531  * If @shutdown is not set the timer can be rearmed later. If the timer can
1532  * be rearmed concurrently, i.e. after dropping the base lock then the
1533  * return value is meaningless.
1534  *
1535  * If @shutdown is set then @timer->function is set to NULL under timer
1536  * base lock which prevents rearming of the timer. Any attempt to rearm
1537  * a shutdown timer is silently ignored.
1538  *
1539  * If the timer should be reused after shutdown it has to be initialized
1540  * again.
1541  *
1542  * Return:
1543  * * %0	- The timer was not pending
1544  * * %1	- The timer was pending and deactivated
1545  */
__timer_delete_sync(struct timer_list * timer,bool shutdown)1546 static int __timer_delete_sync(struct timer_list *timer, bool shutdown)
1547 {
1548 	int ret;
1549 
1550 #ifdef CONFIG_LOCKDEP
1551 	unsigned long flags;
1552 
1553 	/*
1554 	 * If lockdep gives a backtrace here, please reference
1555 	 * the synchronization rules above.
1556 	 */
1557 	local_irq_save(flags);
1558 	lock_map_acquire(&timer->lockdep_map);
1559 	lock_map_release(&timer->lockdep_map);
1560 	local_irq_restore(flags);
1561 #endif
1562 	/*
1563 	 * don't use it in hardirq context, because it
1564 	 * could lead to deadlock.
1565 	 */
1566 	WARN_ON(in_hardirq() && !(timer->flags & TIMER_IRQSAFE));
1567 
1568 	/*
1569 	 * Must be able to sleep on PREEMPT_RT because of the slowpath in
1570 	 * del_timer_wait_running().
1571 	 */
1572 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(timer->flags & TIMER_IRQSAFE))
1573 		lockdep_assert_preemption_enabled();
1574 
1575 	do {
1576 		ret = __try_to_del_timer_sync(timer, shutdown);
1577 
1578 		if (unlikely(ret < 0)) {
1579 			del_timer_wait_running(timer);
1580 			cpu_relax();
1581 		}
1582 	} while (ret < 0);
1583 
1584 	return ret;
1585 }
1586 
1587 /**
1588  * timer_delete_sync - Deactivate a timer and wait for the handler to finish.
1589  * @timer:	The timer to be deactivated
1590  *
1591  * Synchronization rules: Callers must prevent restarting of the timer,
1592  * otherwise this function is meaningless. It must not be called from
1593  * interrupt contexts unless the timer is an irqsafe one. The caller must
1594  * not hold locks which would prevent completion of the timer's callback
1595  * function. The timer's handler must not call add_timer_on(). Upon exit
1596  * the timer is not queued and the handler is not running on any CPU.
1597  *
1598  * For !irqsafe timers, the caller must not hold locks that are held in
1599  * interrupt context. Even if the lock has nothing to do with the timer in
1600  * question.  Here's why::
1601  *
1602  *    CPU0                             CPU1
1603  *    ----                             ----
1604  *                                     <SOFTIRQ>
1605  *                                       call_timer_fn();
1606  *                                       base->running_timer = mytimer;
1607  *    spin_lock_irq(somelock);
1608  *                                     <IRQ>
1609  *                                        spin_lock(somelock);
1610  *    timer_delete_sync(mytimer);
1611  *    while (base->running_timer == mytimer);
1612  *
1613  * Now timer_delete_sync() will never return and never release somelock.
1614  * The interrupt on the other CPU is waiting to grab somelock but it has
1615  * interrupted the softirq that CPU0 is waiting to finish.
1616  *
1617  * This function cannot guarantee that the timer is not rearmed again by
1618  * some concurrent or preempting code, right after it dropped the base
1619  * lock. If there is the possibility of a concurrent rearm then the return
1620  * value of the function is meaningless.
1621  *
1622  * If such a guarantee is needed, e.g. for teardown situations then use
1623  * timer_shutdown_sync() instead.
1624  *
1625  * Return:
1626  * * %0	- The timer was not pending
1627  * * %1	- The timer was pending and deactivated
1628  */
timer_delete_sync(struct timer_list * timer)1629 int timer_delete_sync(struct timer_list *timer)
1630 {
1631 	return __timer_delete_sync(timer, false);
1632 }
1633 EXPORT_SYMBOL(timer_delete_sync);
1634 
1635 /**
1636  * timer_shutdown_sync - Shutdown a timer and prevent rearming
1637  * @timer: The timer to be shutdown
1638  *
1639  * When the function returns it is guaranteed that:
1640  *   - @timer is not queued
1641  *   - The callback function of @timer is not running
1642  *   - @timer cannot be enqueued again. Any attempt to rearm
1643  *     @timer is silently ignored.
1644  *
1645  * See timer_delete_sync() for synchronization rules.
1646  *
1647  * This function is useful for final teardown of an infrastructure where
1648  * the timer is subject to a circular dependency problem.
1649  *
1650  * A common pattern for this is a timer and a workqueue where the timer can
1651  * schedule work and work can arm the timer. On shutdown the workqueue must
1652  * be destroyed and the timer must be prevented from rearming. Unless the
1653  * code has conditionals like 'if (mything->in_shutdown)' to prevent that
1654  * there is no way to get this correct with timer_delete_sync().
1655  *
1656  * timer_shutdown_sync() is solving the problem. The correct ordering of
1657  * calls in this case is:
1658  *
1659  *	timer_shutdown_sync(&mything->timer);
1660  *	workqueue_destroy(&mything->workqueue);
1661  *
1662  * After this 'mything' can be safely freed.
1663  *
1664  * This obviously implies that the timer is not required to be functional
1665  * for the rest of the shutdown operation.
1666  *
1667  * Return:
1668  * * %0 - The timer was not pending
1669  * * %1 - The timer was pending
1670  */
timer_shutdown_sync(struct timer_list * timer)1671 int timer_shutdown_sync(struct timer_list *timer)
1672 {
1673 	return __timer_delete_sync(timer, true);
1674 }
1675 EXPORT_SYMBOL_GPL(timer_shutdown_sync);
1676 
call_timer_fn(struct timer_list * timer,void (* fn)(struct timer_list *),unsigned long baseclk)1677 static void call_timer_fn(struct timer_list *timer,
1678 			  void (*fn)(struct timer_list *),
1679 			  unsigned long baseclk)
1680 {
1681 	int count = preempt_count();
1682 
1683 #ifdef CONFIG_LOCKDEP
1684 	/*
1685 	 * It is permissible to free the timer from inside the
1686 	 * function that is called from it, this we need to take into
1687 	 * account for lockdep too. To avoid bogus "held lock freed"
1688 	 * warnings as well as problems when looking into
1689 	 * timer->lockdep_map, make a copy and use that here.
1690 	 */
1691 	struct lockdep_map lockdep_map;
1692 
1693 	lockdep_copy_map(&lockdep_map, &timer->lockdep_map);
1694 #endif
1695 	/*
1696 	 * Couple the lock chain with the lock chain at
1697 	 * timer_delete_sync() by acquiring the lock_map around the fn()
1698 	 * call here and in timer_delete_sync().
1699 	 */
1700 	lock_map_acquire(&lockdep_map);
1701 
1702 	trace_timer_expire_entry(timer, baseclk);
1703 	fn(timer);
1704 	trace_timer_expire_exit(timer);
1705 
1706 	lock_map_release(&lockdep_map);
1707 
1708 	if (count != preempt_count()) {
1709 		WARN_ONCE(1, "timer: %pS preempt leak: %08x -> %08x\n",
1710 			  fn, count, preempt_count());
1711 		/*
1712 		 * Restore the preempt count. That gives us a decent
1713 		 * chance to survive and extract information. If the
1714 		 * callback kept a lock held, bad luck, but not worse
1715 		 * than the BUG() we had.
1716 		 */
1717 		preempt_count_set(count);
1718 	}
1719 }
1720 
expire_timers(struct timer_base * base,struct hlist_head * head)1721 static void expire_timers(struct timer_base *base, struct hlist_head *head)
1722 {
1723 	/*
1724 	 * This value is required only for tracing. base->clk was
1725 	 * incremented directly before expire_timers was called. But expiry
1726 	 * is related to the old base->clk value.
1727 	 */
1728 	unsigned long baseclk = base->clk - 1;
1729 
1730 	while (!hlist_empty(head)) {
1731 		struct timer_list *timer;
1732 		void (*fn)(struct timer_list *);
1733 
1734 		timer = hlist_entry(head->first, struct timer_list, entry);
1735 
1736 		base->running_timer = timer;
1737 		detach_timer(timer, true);
1738 
1739 		fn = timer->function;
1740 
1741 		if (WARN_ON_ONCE(!fn)) {
1742 			/* Should never happen. Emphasis on should! */
1743 			base->running_timer = NULL;
1744 			continue;
1745 		}
1746 
1747 		if (timer->flags & TIMER_IRQSAFE) {
1748 			raw_spin_unlock(&base->lock);
1749 			call_timer_fn(timer, fn, baseclk);
1750 			raw_spin_lock(&base->lock);
1751 			base->running_timer = NULL;
1752 		} else {
1753 			raw_spin_unlock_irq(&base->lock);
1754 			call_timer_fn(timer, fn, baseclk);
1755 			raw_spin_lock_irq(&base->lock);
1756 			base->running_timer = NULL;
1757 			timer_sync_wait_running(base);
1758 		}
1759 	}
1760 }
1761 
collect_expired_timers(struct timer_base * base,struct hlist_head * heads)1762 static int collect_expired_timers(struct timer_base *base,
1763 				  struct hlist_head *heads)
1764 {
1765 	unsigned long clk = base->clk = base->next_expiry;
1766 	struct hlist_head *vec;
1767 	int i, levels = 0;
1768 	unsigned int idx;
1769 
1770 	for (i = 0; i < LVL_DEPTH; i++) {
1771 		idx = (clk & LVL_MASK) + i * LVL_SIZE;
1772 
1773 		if (__test_and_clear_bit(idx, base->pending_map)) {
1774 			vec = base->vectors + idx;
1775 			hlist_move_list(vec, heads++);
1776 			levels++;
1777 		}
1778 		/* Is it time to look at the next level? */
1779 		if (clk & LVL_CLK_MASK)
1780 			break;
1781 		/* Shift clock for the next level granularity */
1782 		clk >>= LVL_CLK_SHIFT;
1783 	}
1784 	return levels;
1785 }
1786 
1787 /*
1788  * Find the next pending bucket of a level. Search from level start (@offset)
1789  * + @clk upwards and if nothing there, search from start of the level
1790  * (@offset) up to @offset + clk.
1791  */
next_pending_bucket(struct timer_base * base,unsigned offset,unsigned clk)1792 static int next_pending_bucket(struct timer_base *base, unsigned offset,
1793 			       unsigned clk)
1794 {
1795 	unsigned pos, start = offset + clk;
1796 	unsigned end = offset + LVL_SIZE;
1797 
1798 	pos = find_next_bit(base->pending_map, end, start);
1799 	if (pos < end)
1800 		return pos - start;
1801 
1802 	pos = find_next_bit(base->pending_map, start, offset);
1803 	return pos < start ? pos + LVL_SIZE - start : -1;
1804 }
1805 
1806 /*
1807  * Search the first expiring timer in the various clock levels. Caller must
1808  * hold base->lock.
1809  */
__next_timer_interrupt(struct timer_base * base)1810 static unsigned long __next_timer_interrupt(struct timer_base *base)
1811 {
1812 	unsigned long clk, next, adj;
1813 	unsigned lvl, offset = 0;
1814 
1815 	next = base->clk + NEXT_TIMER_MAX_DELTA;
1816 	clk = base->clk;
1817 	for (lvl = 0; lvl < LVL_DEPTH; lvl++, offset += LVL_SIZE) {
1818 		int pos = next_pending_bucket(base, offset, clk & LVL_MASK);
1819 		unsigned long lvl_clk = clk & LVL_CLK_MASK;
1820 
1821 		if (pos >= 0) {
1822 			unsigned long tmp = clk + (unsigned long) pos;
1823 
1824 			tmp <<= LVL_SHIFT(lvl);
1825 			if (time_before(tmp, next))
1826 				next = tmp;
1827 
1828 			/*
1829 			 * If the next expiration happens before we reach
1830 			 * the next level, no need to check further.
1831 			 */
1832 			if (pos <= ((LVL_CLK_DIV - lvl_clk) & LVL_CLK_MASK))
1833 				break;
1834 		}
1835 		/*
1836 		 * Clock for the next level. If the current level clock lower
1837 		 * bits are zero, we look at the next level as is. If not we
1838 		 * need to advance it by one because that's going to be the
1839 		 * next expiring bucket in that level. base->clk is the next
1840 		 * expiring jiffie. So in case of:
1841 		 *
1842 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1843 		 *  0    0    0    0    0    0
1844 		 *
1845 		 * we have to look at all levels @index 0. With
1846 		 *
1847 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1848 		 *  0    0    0    0    0    2
1849 		 *
1850 		 * LVL0 has the next expiring bucket @index 2. The upper
1851 		 * levels have the next expiring bucket @index 1.
1852 		 *
1853 		 * In case that the propagation wraps the next level the same
1854 		 * rules apply:
1855 		 *
1856 		 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1857 		 *  0    0    0    0    F    2
1858 		 *
1859 		 * So after looking at LVL0 we get:
1860 		 *
1861 		 * LVL5 LVL4 LVL3 LVL2 LVL1
1862 		 *  0    0    0    1    0
1863 		 *
1864 		 * So no propagation from LVL1 to LVL2 because that happened
1865 		 * with the add already, but then we need to propagate further
1866 		 * from LVL2 to LVL3.
1867 		 *
1868 		 * So the simple check whether the lower bits of the current
1869 		 * level are 0 or not is sufficient for all cases.
1870 		 */
1871 		adj = lvl_clk ? 1 : 0;
1872 		clk >>= LVL_CLK_SHIFT;
1873 		clk += adj;
1874 	}
1875 
1876 	base->next_expiry_recalc = false;
1877 	base->timers_pending = !(next == base->clk + NEXT_TIMER_MAX_DELTA);
1878 
1879 	return next;
1880 }
1881 
1882 #ifdef CONFIG_NO_HZ_COMMON
1883 /*
1884  * Check, if the next hrtimer event is before the next timer wheel
1885  * event:
1886  */
cmp_next_hrtimer_event(u64 basem,u64 expires)1887 static u64 cmp_next_hrtimer_event(u64 basem, u64 expires)
1888 {
1889 	u64 nextevt = hrtimer_get_next_event();
1890 
1891 	/*
1892 	 * If high resolution timers are enabled
1893 	 * hrtimer_get_next_event() returns KTIME_MAX.
1894 	 */
1895 	if (expires <= nextevt)
1896 		return expires;
1897 
1898 	/*
1899 	 * If the next timer is already expired, return the tick base
1900 	 * time so the tick is fired immediately.
1901 	 */
1902 	if (nextevt <= basem)
1903 		return basem;
1904 
1905 	/*
1906 	 * Round up to the next jiffie. High resolution timers are
1907 	 * off, so the hrtimers are expired in the tick and we need to
1908 	 * make sure that this tick really expires the timer to avoid
1909 	 * a ping pong of the nohz stop code.
1910 	 *
1911 	 * Use DIV_ROUND_UP_ULL to prevent gcc calling __divdi3
1912 	 */
1913 	return DIV_ROUND_UP_ULL(nextevt, TICK_NSEC) * TICK_NSEC;
1914 }
1915 
1916 /**
1917  * get_next_timer_interrupt - return the time (clock mono) of the next timer
1918  * @basej:	base time jiffies
1919  * @basem:	base time clock monotonic
1920  *
1921  * Returns the tick aligned clock monotonic time of the next pending
1922  * timer or KTIME_MAX if no timer is pending.
1923  */
get_next_timer_interrupt(unsigned long basej,u64 basem)1924 u64 get_next_timer_interrupt(unsigned long basej, u64 basem)
1925 {
1926 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1927 	u64 expires = KTIME_MAX;
1928 	unsigned long nextevt;
1929 
1930 	/*
1931 	 * Pretend that there is no timer pending if the cpu is offline.
1932 	 * Possible pending timers will be migrated later to an active cpu.
1933 	 */
1934 	if (cpu_is_offline(smp_processor_id()))
1935 		return expires;
1936 
1937 	raw_spin_lock(&base->lock);
1938 	if (base->next_expiry_recalc)
1939 		base->next_expiry = __next_timer_interrupt(base);
1940 	nextevt = base->next_expiry;
1941 
1942 	/*
1943 	 * We have a fresh next event. Check whether we can forward the
1944 	 * base. We can only do that when @basej is past base->clk
1945 	 * otherwise we might rewind base->clk.
1946 	 */
1947 	if (time_after(basej, base->clk)) {
1948 		if (time_after(nextevt, basej))
1949 			base->clk = basej;
1950 		else if (time_after(nextevt, base->clk))
1951 			base->clk = nextevt;
1952 	}
1953 
1954 	if (time_before_eq(nextevt, basej)) {
1955 		expires = basem;
1956 		base->is_idle = false;
1957 	} else {
1958 		if (base->timers_pending)
1959 			expires = basem + (u64)(nextevt - basej) * TICK_NSEC;
1960 		/*
1961 		 * If we expect to sleep more than a tick, mark the base idle.
1962 		 * Also the tick is stopped so any added timer must forward
1963 		 * the base clk itself to keep granularity small. This idle
1964 		 * logic is only maintained for the BASE_STD base, deferrable
1965 		 * timers may still see large granularity skew (by design).
1966 		 */
1967 		if ((expires - basem) > TICK_NSEC)
1968 			base->is_idle = true;
1969 	}
1970 	raw_spin_unlock(&base->lock);
1971 
1972 	return cmp_next_hrtimer_event(basem, expires);
1973 }
1974 
1975 /**
1976  * timer_clear_idle - Clear the idle state of the timer base
1977  *
1978  * Called with interrupts disabled
1979  */
timer_clear_idle(void)1980 void timer_clear_idle(void)
1981 {
1982 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1983 
1984 	/*
1985 	 * We do this unlocked. The worst outcome is a remote enqueue sending
1986 	 * a pointless IPI, but taking the lock would just make the window for
1987 	 * sending the IPI a few instructions smaller for the cost of taking
1988 	 * the lock in the exit from idle path.
1989 	 */
1990 	base->is_idle = false;
1991 }
1992 #endif
1993 
1994 /**
1995  * __run_timers - run all expired timers (if any) on this CPU.
1996  * @base: the timer vector to be processed.
1997  */
__run_timers(struct timer_base * base)1998 static inline void __run_timers(struct timer_base *base)
1999 {
2000 	struct hlist_head heads[LVL_DEPTH];
2001 	int levels;
2002 
2003 	if (time_before(jiffies, base->next_expiry))
2004 		return;
2005 
2006 	timer_base_lock_expiry(base);
2007 	raw_spin_lock_irq(&base->lock);
2008 
2009 	while (time_after_eq(jiffies, base->clk) &&
2010 	       time_after_eq(jiffies, base->next_expiry)) {
2011 		levels = collect_expired_timers(base, heads);
2012 		/*
2013 		 * The two possible reasons for not finding any expired
2014 		 * timer at this clk are that all matching timers have been
2015 		 * dequeued or no timer has been queued since
2016 		 * base::next_expiry was set to base::clk +
2017 		 * NEXT_TIMER_MAX_DELTA.
2018 		 */
2019 		WARN_ON_ONCE(!levels && !base->next_expiry_recalc
2020 			     && base->timers_pending);
2021 		base->clk++;
2022 		base->next_expiry = __next_timer_interrupt(base);
2023 
2024 		while (levels--)
2025 			expire_timers(base, heads + levels);
2026 	}
2027 	raw_spin_unlock_irq(&base->lock);
2028 	timer_base_unlock_expiry(base);
2029 }
2030 
2031 /*
2032  * This function runs timers and the timer-tq in bottom half context.
2033  */
run_timer_softirq(struct softirq_action * h)2034 static __latent_entropy void run_timer_softirq(struct softirq_action *h)
2035 {
2036 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
2037 
2038 	__run_timers(base);
2039 	if (IS_ENABLED(CONFIG_NO_HZ_COMMON))
2040 		__run_timers(this_cpu_ptr(&timer_bases[BASE_DEF]));
2041 }
2042 
2043 /*
2044  * Called by the local, per-CPU timer interrupt on SMP.
2045  */
run_local_timers(void)2046 static void run_local_timers(void)
2047 {
2048 	struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
2049 
2050 	hrtimer_run_queues();
2051 	/* Raise the softirq only if required. */
2052 	if (time_before(jiffies, base->next_expiry)) {
2053 		if (!IS_ENABLED(CONFIG_NO_HZ_COMMON))
2054 			return;
2055 		/* CPU is awake, so check the deferrable base. */
2056 		base++;
2057 		if (time_before(jiffies, base->next_expiry))
2058 			return;
2059 	}
2060 	raise_softirq(TIMER_SOFTIRQ);
2061 }
2062 
2063 /*
2064  * Called from the timer interrupt handler to charge one tick to the current
2065  * process.  user_tick is 1 if the tick is user time, 0 for system.
2066  */
update_process_times(int user_tick)2067 void update_process_times(int user_tick)
2068 {
2069 	struct task_struct *p = current;
2070 
2071 	/* Note: this timer irq context must be accounted for as well. */
2072 	account_process_tick(p, user_tick);
2073 	run_local_timers();
2074 	rcu_sched_clock_irq(user_tick);
2075 #ifdef CONFIG_IRQ_WORK
2076 	if (in_irq())
2077 		irq_work_tick();
2078 #endif
2079 	scheduler_tick();
2080 	if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2081 		run_posix_cpu_timers();
2082 }
2083 
2084 /*
2085  * Since schedule_timeout()'s timer is defined on the stack, it must store
2086  * the target task on the stack as well.
2087  */
2088 struct process_timer {
2089 	struct timer_list timer;
2090 	struct task_struct *task;
2091 };
2092 
process_timeout(struct timer_list * t)2093 static void process_timeout(struct timer_list *t)
2094 {
2095 	struct process_timer *timeout = from_timer(timeout, t, timer);
2096 
2097 	wake_up_process(timeout->task);
2098 }
2099 
2100 /**
2101  * schedule_timeout - sleep until timeout
2102  * @timeout: timeout value in jiffies
2103  *
2104  * Make the current task sleep until @timeout jiffies have elapsed.
2105  * The function behavior depends on the current task state
2106  * (see also set_current_state() description):
2107  *
2108  * %TASK_RUNNING - the scheduler is called, but the task does not sleep
2109  * at all. That happens because sched_submit_work() does nothing for
2110  * tasks in %TASK_RUNNING state.
2111  *
2112  * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
2113  * pass before the routine returns unless the current task is explicitly
2114  * woken up, (e.g. by wake_up_process()).
2115  *
2116  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
2117  * delivered to the current task or the current task is explicitly woken
2118  * up.
2119  *
2120  * The current task state is guaranteed to be %TASK_RUNNING when this
2121  * routine returns.
2122  *
2123  * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
2124  * the CPU away without a bound on the timeout. In this case the return
2125  * value will be %MAX_SCHEDULE_TIMEOUT.
2126  *
2127  * Returns 0 when the timer has expired otherwise the remaining time in
2128  * jiffies will be returned. In all cases the return value is guaranteed
2129  * to be non-negative.
2130  */
schedule_timeout(signed long timeout)2131 signed long __sched schedule_timeout(signed long timeout)
2132 {
2133 	struct process_timer timer;
2134 	unsigned long expire;
2135 
2136 	switch (timeout)
2137 	{
2138 	case MAX_SCHEDULE_TIMEOUT:
2139 		/*
2140 		 * These two special cases are useful to be comfortable
2141 		 * in the caller. Nothing more. We could take
2142 		 * MAX_SCHEDULE_TIMEOUT from one of the negative value
2143 		 * but I' d like to return a valid offset (>=0) to allow
2144 		 * the caller to do everything it want with the retval.
2145 		 */
2146 		schedule();
2147 		goto out;
2148 	default:
2149 		/*
2150 		 * Another bit of PARANOID. Note that the retval will be
2151 		 * 0 since no piece of kernel is supposed to do a check
2152 		 * for a negative retval of schedule_timeout() (since it
2153 		 * should never happens anyway). You just have the printk()
2154 		 * that will tell you if something is gone wrong and where.
2155 		 */
2156 		if (timeout < 0) {
2157 			printk(KERN_ERR "schedule_timeout: wrong timeout "
2158 				"value %lx\n", timeout);
2159 			dump_stack();
2160 			__set_current_state(TASK_RUNNING);
2161 			goto out;
2162 		}
2163 	}
2164 
2165 	expire = timeout + jiffies;
2166 
2167 	timer.task = current;
2168 	timer_setup_on_stack(&timer.timer, process_timeout, 0);
2169 	__mod_timer(&timer.timer, expire, MOD_TIMER_NOTPENDING);
2170 	schedule();
2171 	del_timer_sync(&timer.timer);
2172 
2173 	/* Remove the timer from the object tracker */
2174 	destroy_timer_on_stack(&timer.timer);
2175 
2176 	timeout = expire - jiffies;
2177 
2178  out:
2179 	return timeout < 0 ? 0 : timeout;
2180 }
2181 EXPORT_SYMBOL(schedule_timeout);
2182 
2183 /*
2184  * We can use __set_current_state() here because schedule_timeout() calls
2185  * schedule() unconditionally.
2186  */
schedule_timeout_interruptible(signed long timeout)2187 signed long __sched schedule_timeout_interruptible(signed long timeout)
2188 {
2189 	__set_current_state(TASK_INTERRUPTIBLE);
2190 	return schedule_timeout(timeout);
2191 }
2192 EXPORT_SYMBOL(schedule_timeout_interruptible);
2193 
schedule_timeout_killable(signed long timeout)2194 signed long __sched schedule_timeout_killable(signed long timeout)
2195 {
2196 	__set_current_state(TASK_KILLABLE);
2197 	return schedule_timeout(timeout);
2198 }
2199 EXPORT_SYMBOL(schedule_timeout_killable);
2200 
schedule_timeout_uninterruptible(signed long timeout)2201 signed long __sched schedule_timeout_uninterruptible(signed long timeout)
2202 {
2203 	__set_current_state(TASK_UNINTERRUPTIBLE);
2204 	return schedule_timeout(timeout);
2205 }
2206 EXPORT_SYMBOL(schedule_timeout_uninterruptible);
2207 
2208 /*
2209  * Like schedule_timeout_uninterruptible(), except this task will not contribute
2210  * to load average.
2211  */
schedule_timeout_idle(signed long timeout)2212 signed long __sched schedule_timeout_idle(signed long timeout)
2213 {
2214 	__set_current_state(TASK_IDLE);
2215 	return schedule_timeout(timeout);
2216 }
2217 EXPORT_SYMBOL(schedule_timeout_idle);
2218 
2219 #ifdef CONFIG_HOTPLUG_CPU
migrate_timer_list(struct timer_base * new_base,struct hlist_head * head)2220 static void migrate_timer_list(struct timer_base *new_base, struct hlist_head *head)
2221 {
2222 	struct timer_list *timer;
2223 	int cpu = new_base->cpu;
2224 
2225 	while (!hlist_empty(head)) {
2226 		timer = hlist_entry(head->first, struct timer_list, entry);
2227 		detach_timer(timer, false);
2228 		timer->flags = (timer->flags & ~TIMER_BASEMASK) | cpu;
2229 		internal_add_timer(new_base, timer);
2230 	}
2231 }
2232 
timers_prepare_cpu(unsigned int cpu)2233 int timers_prepare_cpu(unsigned int cpu)
2234 {
2235 	struct timer_base *base;
2236 	int b;
2237 
2238 	for (b = 0; b < NR_BASES; b++) {
2239 		base = per_cpu_ptr(&timer_bases[b], cpu);
2240 		base->clk = jiffies;
2241 		base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
2242 		base->next_expiry_recalc = false;
2243 		base->timers_pending = false;
2244 		base->is_idle = false;
2245 	}
2246 	return 0;
2247 }
2248 
timers_dead_cpu(unsigned int cpu)2249 int timers_dead_cpu(unsigned int cpu)
2250 {
2251 	struct timer_base *old_base;
2252 	struct timer_base *new_base;
2253 	int b, i;
2254 
2255 	for (b = 0; b < NR_BASES; b++) {
2256 		old_base = per_cpu_ptr(&timer_bases[b], cpu);
2257 		new_base = get_cpu_ptr(&timer_bases[b]);
2258 		/*
2259 		 * The caller is globally serialized and nobody else
2260 		 * takes two locks at once, deadlock is not possible.
2261 		 */
2262 		raw_spin_lock_irq(&new_base->lock);
2263 		raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
2264 
2265 		/*
2266 		 * The current CPUs base clock might be stale. Update it
2267 		 * before moving the timers over.
2268 		 */
2269 		forward_timer_base(new_base);
2270 
2271 		WARN_ON_ONCE(old_base->running_timer);
2272 		old_base->running_timer = NULL;
2273 
2274 		for (i = 0; i < WHEEL_SIZE; i++)
2275 			migrate_timer_list(new_base, old_base->vectors + i);
2276 
2277 		raw_spin_unlock(&old_base->lock);
2278 		raw_spin_unlock_irq(&new_base->lock);
2279 		put_cpu_ptr(&timer_bases);
2280 	}
2281 	return 0;
2282 }
2283 
2284 #endif /* CONFIG_HOTPLUG_CPU */
2285 
init_timer_cpu(int cpu)2286 static void __init init_timer_cpu(int cpu)
2287 {
2288 	struct timer_base *base;
2289 	int i;
2290 
2291 	for (i = 0; i < NR_BASES; i++) {
2292 		base = per_cpu_ptr(&timer_bases[i], cpu);
2293 		base->cpu = cpu;
2294 		raw_spin_lock_init(&base->lock);
2295 		base->clk = jiffies;
2296 		base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
2297 		timer_base_init_expiry_lock(base);
2298 	}
2299 }
2300 
init_timer_cpus(void)2301 static void __init init_timer_cpus(void)
2302 {
2303 	int cpu;
2304 
2305 	for_each_possible_cpu(cpu)
2306 		init_timer_cpu(cpu);
2307 }
2308 
init_timers(void)2309 void __init init_timers(void)
2310 {
2311 	init_timer_cpus();
2312 	posix_cputimers_init_work();
2313 	open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
2314 }
2315 
2316 /**
2317  * msleep - sleep safely even with waitqueue interruptions
2318  * @msecs: Time in milliseconds to sleep for
2319  */
msleep(unsigned int msecs)2320 void msleep(unsigned int msecs)
2321 {
2322 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
2323 
2324 	while (timeout)
2325 		timeout = schedule_timeout_uninterruptible(timeout);
2326 }
2327 
2328 EXPORT_SYMBOL(msleep);
2329 
2330 /**
2331  * msleep_interruptible - sleep waiting for signals
2332  * @msecs: Time in milliseconds to sleep for
2333  */
msleep_interruptible(unsigned int msecs)2334 unsigned long msleep_interruptible(unsigned int msecs)
2335 {
2336 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
2337 
2338 	while (timeout && !signal_pending(current))
2339 		timeout = schedule_timeout_interruptible(timeout);
2340 	return jiffies_to_msecs(timeout);
2341 }
2342 
2343 EXPORT_SYMBOL(msleep_interruptible);
2344 
2345 /**
2346  * usleep_range_state - Sleep for an approximate time in a given state
2347  * @min:	Minimum time in usecs to sleep
2348  * @max:	Maximum time in usecs to sleep
2349  * @state:	State of the current task that will be while sleeping
2350  *
2351  * In non-atomic context where the exact wakeup time is flexible, use
2352  * usleep_range_state() instead of udelay().  The sleep improves responsiveness
2353  * by avoiding the CPU-hogging busy-wait of udelay(), and the range reduces
2354  * power usage by allowing hrtimers to take advantage of an already-
2355  * scheduled interrupt instead of scheduling a new one just for this sleep.
2356  */
usleep_range_state(unsigned long min,unsigned long max,unsigned int state)2357 void __sched usleep_range_state(unsigned long min, unsigned long max,
2358 				unsigned int state)
2359 {
2360 	ktime_t exp = ktime_add_us(ktime_get(), min);
2361 	u64 delta = (u64)(max - min) * NSEC_PER_USEC;
2362 
2363 	for (;;) {
2364 		__set_current_state(state);
2365 		/* Do not return before the requested sleep time has elapsed */
2366 		if (!schedule_hrtimeout_range(&exp, delta, HRTIMER_MODE_ABS))
2367 			break;
2368 	}
2369 }
2370 EXPORT_SYMBOL(usleep_range_state);
2371