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