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