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 jiffies.
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 reacquire 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 | TIMER_IRQSAFE))) {
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 /*
1381 * Must be able to sleep on PREEMPT_RT because of the slowpath in
1382 * del_timer_wait_running().
1383 */
1384 if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(timer->flags & TIMER_IRQSAFE))
1385 lockdep_assert_preemption_enabled();
1386
1387 do {
1388 ret = try_to_del_timer_sync(timer);
1389
1390 if (unlikely(ret < 0)) {
1391 del_timer_wait_running(timer);
1392 cpu_relax();
1393 }
1394 } while (ret < 0);
1395
1396 return ret;
1397 }
1398 EXPORT_SYMBOL(del_timer_sync);
1399 #endif
1400
call_timer_fn(struct timer_list * timer,void (* fn)(struct timer_list *),unsigned long baseclk)1401 static void call_timer_fn(struct timer_list *timer,
1402 void (*fn)(struct timer_list *),
1403 unsigned long baseclk)
1404 {
1405 int count = preempt_count();
1406
1407 #ifdef CONFIG_LOCKDEP
1408 /*
1409 * It is permissible to free the timer from inside the
1410 * function that is called from it, this we need to take into
1411 * account for lockdep too. To avoid bogus "held lock freed"
1412 * warnings as well as problems when looking into
1413 * timer->lockdep_map, make a copy and use that here.
1414 */
1415 struct lockdep_map lockdep_map;
1416
1417 lockdep_copy_map(&lockdep_map, &timer->lockdep_map);
1418 #endif
1419 /*
1420 * Couple the lock chain with the lock chain at
1421 * del_timer_sync() by acquiring the lock_map around the fn()
1422 * call here and in del_timer_sync().
1423 */
1424 lock_map_acquire(&lockdep_map);
1425
1426 trace_timer_expire_entry(timer, baseclk);
1427 fn(timer);
1428 trace_timer_expire_exit(timer);
1429
1430 lock_map_release(&lockdep_map);
1431
1432 if (count != preempt_count()) {
1433 WARN_ONCE(1, "timer: %pS preempt leak: %08x -> %08x\n",
1434 fn, count, preempt_count());
1435 /*
1436 * Restore the preempt count. That gives us a decent
1437 * chance to survive and extract information. If the
1438 * callback kept a lock held, bad luck, but not worse
1439 * than the BUG() we had.
1440 */
1441 preempt_count_set(count);
1442 }
1443 }
1444
expire_timers(struct timer_base * base,struct hlist_head * head)1445 static void expire_timers(struct timer_base *base, struct hlist_head *head)
1446 {
1447 /*
1448 * This value is required only for tracing. base->clk was
1449 * incremented directly before expire_timers was called. But expiry
1450 * is related to the old base->clk value.
1451 */
1452 unsigned long baseclk = base->clk - 1;
1453
1454 while (!hlist_empty(head)) {
1455 struct timer_list *timer;
1456 void (*fn)(struct timer_list *);
1457
1458 timer = hlist_entry(head->first, struct timer_list, entry);
1459
1460 base->running_timer = timer;
1461 detach_timer(timer, true);
1462
1463 fn = timer->function;
1464
1465 if (timer->flags & TIMER_IRQSAFE) {
1466 raw_spin_unlock(&base->lock);
1467 call_timer_fn(timer, fn, baseclk);
1468 raw_spin_lock(&base->lock);
1469 base->running_timer = NULL;
1470 } else {
1471 raw_spin_unlock_irq(&base->lock);
1472 call_timer_fn(timer, fn, baseclk);
1473 raw_spin_lock_irq(&base->lock);
1474 base->running_timer = NULL;
1475 timer_sync_wait_running(base);
1476 }
1477 }
1478 }
1479
collect_expired_timers(struct timer_base * base,struct hlist_head * heads)1480 static int collect_expired_timers(struct timer_base *base,
1481 struct hlist_head *heads)
1482 {
1483 unsigned long clk = base->clk = base->next_expiry;
1484 struct hlist_head *vec;
1485 int i, levels = 0;
1486 unsigned int idx;
1487
1488 for (i = 0; i < LVL_DEPTH; i++) {
1489 idx = (clk & LVL_MASK) + i * LVL_SIZE;
1490
1491 if (__test_and_clear_bit(idx, base->pending_map)) {
1492 vec = base->vectors + idx;
1493 hlist_move_list(vec, heads++);
1494 levels++;
1495 }
1496 /* Is it time to look at the next level? */
1497 if (clk & LVL_CLK_MASK)
1498 break;
1499 /* Shift clock for the next level granularity */
1500 clk >>= LVL_CLK_SHIFT;
1501 }
1502 return levels;
1503 }
1504
1505 /*
1506 * Find the next pending bucket of a level. Search from level start (@offset)
1507 * + @clk upwards and if nothing there, search from start of the level
1508 * (@offset) up to @offset + clk.
1509 */
next_pending_bucket(struct timer_base * base,unsigned offset,unsigned clk)1510 static int next_pending_bucket(struct timer_base *base, unsigned offset,
1511 unsigned clk)
1512 {
1513 unsigned pos, start = offset + clk;
1514 unsigned end = offset + LVL_SIZE;
1515
1516 pos = find_next_bit(base->pending_map, end, start);
1517 if (pos < end)
1518 return pos - start;
1519
1520 pos = find_next_bit(base->pending_map, start, offset);
1521 return pos < start ? pos + LVL_SIZE - start : -1;
1522 }
1523
1524 /*
1525 * Search the first expiring timer in the various clock levels. Caller must
1526 * hold base->lock.
1527 */
__next_timer_interrupt(struct timer_base * base)1528 static unsigned long __next_timer_interrupt(struct timer_base *base)
1529 {
1530 unsigned long clk, next, adj;
1531 unsigned lvl, offset = 0;
1532
1533 next = base->clk + NEXT_TIMER_MAX_DELTA;
1534 clk = base->clk;
1535 for (lvl = 0; lvl < LVL_DEPTH; lvl++, offset += LVL_SIZE) {
1536 int pos = next_pending_bucket(base, offset, clk & LVL_MASK);
1537 unsigned long lvl_clk = clk & LVL_CLK_MASK;
1538
1539 if (pos >= 0) {
1540 unsigned long tmp = clk + (unsigned long) pos;
1541
1542 tmp <<= LVL_SHIFT(lvl);
1543 if (time_before(tmp, next))
1544 next = tmp;
1545
1546 /*
1547 * If the next expiration happens before we reach
1548 * the next level, no need to check further.
1549 */
1550 if (pos <= ((LVL_CLK_DIV - lvl_clk) & LVL_CLK_MASK))
1551 break;
1552 }
1553 /*
1554 * Clock for the next level. If the current level clock lower
1555 * bits are zero, we look at the next level as is. If not we
1556 * need to advance it by one because that's going to be the
1557 * next expiring bucket in that level. base->clk is the next
1558 * expiring jiffie. So in case of:
1559 *
1560 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1561 * 0 0 0 0 0 0
1562 *
1563 * we have to look at all levels @index 0. With
1564 *
1565 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1566 * 0 0 0 0 0 2
1567 *
1568 * LVL0 has the next expiring bucket @index 2. The upper
1569 * levels have the next expiring bucket @index 1.
1570 *
1571 * In case that the propagation wraps the next level the same
1572 * rules apply:
1573 *
1574 * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0
1575 * 0 0 0 0 F 2
1576 *
1577 * So after looking at LVL0 we get:
1578 *
1579 * LVL5 LVL4 LVL3 LVL2 LVL1
1580 * 0 0 0 1 0
1581 *
1582 * So no propagation from LVL1 to LVL2 because that happened
1583 * with the add already, but then we need to propagate further
1584 * from LVL2 to LVL3.
1585 *
1586 * So the simple check whether the lower bits of the current
1587 * level are 0 or not is sufficient for all cases.
1588 */
1589 adj = lvl_clk ? 1 : 0;
1590 clk >>= LVL_CLK_SHIFT;
1591 clk += adj;
1592 }
1593
1594 base->next_expiry_recalc = false;
1595 base->timers_pending = !(next == base->clk + NEXT_TIMER_MAX_DELTA);
1596
1597 return next;
1598 }
1599
1600 #ifdef CONFIG_NO_HZ_COMMON
1601 /*
1602 * Check, if the next hrtimer event is before the next timer wheel
1603 * event:
1604 */
cmp_next_hrtimer_event(u64 basem,u64 expires)1605 static u64 cmp_next_hrtimer_event(u64 basem, u64 expires)
1606 {
1607 u64 nextevt = hrtimer_get_next_event();
1608
1609 /*
1610 * If high resolution timers are enabled
1611 * hrtimer_get_next_event() returns KTIME_MAX.
1612 */
1613 if (expires <= nextevt)
1614 return expires;
1615
1616 /*
1617 * If the next timer is already expired, return the tick base
1618 * time so the tick is fired immediately.
1619 */
1620 if (nextevt <= basem)
1621 return basem;
1622
1623 /*
1624 * Round up to the next jiffie. High resolution timers are
1625 * off, so the hrtimers are expired in the tick and we need to
1626 * make sure that this tick really expires the timer to avoid
1627 * a ping pong of the nohz stop code.
1628 *
1629 * Use DIV_ROUND_UP_ULL to prevent gcc calling __divdi3
1630 */
1631 return DIV_ROUND_UP_ULL(nextevt, TICK_NSEC) * TICK_NSEC;
1632 }
1633
1634 /**
1635 * get_next_timer_interrupt - return the time (clock mono) of the next timer
1636 * @basej: base time jiffies
1637 * @basem: base time clock monotonic
1638 *
1639 * Returns the tick aligned clock monotonic time of the next pending
1640 * timer or KTIME_MAX if no timer is pending.
1641 */
get_next_timer_interrupt(unsigned long basej,u64 basem)1642 u64 get_next_timer_interrupt(unsigned long basej, u64 basem)
1643 {
1644 struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1645 u64 expires = KTIME_MAX;
1646 unsigned long nextevt;
1647
1648 /*
1649 * Pretend that there is no timer pending if the cpu is offline.
1650 * Possible pending timers will be migrated later to an active cpu.
1651 */
1652 if (cpu_is_offline(smp_processor_id()))
1653 return expires;
1654
1655 raw_spin_lock(&base->lock);
1656 if (base->next_expiry_recalc)
1657 base->next_expiry = __next_timer_interrupt(base);
1658 nextevt = base->next_expiry;
1659
1660 /*
1661 * We have a fresh next event. Check whether we can forward the
1662 * base. We can only do that when @basej is past base->clk
1663 * otherwise we might rewind base->clk.
1664 */
1665 if (time_after(basej, base->clk)) {
1666 if (time_after(nextevt, basej))
1667 base->clk = basej;
1668 else if (time_after(nextevt, base->clk))
1669 base->clk = nextevt;
1670 }
1671
1672 if (time_before_eq(nextevt, basej)) {
1673 expires = basem;
1674 base->is_idle = false;
1675 } else {
1676 if (base->timers_pending)
1677 expires = basem + (u64)(nextevt - basej) * TICK_NSEC;
1678 /*
1679 * If we expect to sleep more than a tick, mark the base idle.
1680 * Also the tick is stopped so any added timer must forward
1681 * the base clk itself to keep granularity small. This idle
1682 * logic is only maintained for the BASE_STD base, deferrable
1683 * timers may still see large granularity skew (by design).
1684 */
1685 if ((expires - basem) > TICK_NSEC)
1686 base->is_idle = true;
1687 }
1688 raw_spin_unlock(&base->lock);
1689
1690 return cmp_next_hrtimer_event(basem, expires);
1691 }
1692
1693 /**
1694 * timer_clear_idle - Clear the idle state of the timer base
1695 *
1696 * Called with interrupts disabled
1697 */
timer_clear_idle(void)1698 void timer_clear_idle(void)
1699 {
1700 struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1701
1702 /*
1703 * We do this unlocked. The worst outcome is a remote enqueue sending
1704 * a pointless IPI, but taking the lock would just make the window for
1705 * sending the IPI a few instructions smaller for the cost of taking
1706 * the lock in the exit from idle path.
1707 */
1708 base->is_idle = false;
1709 }
1710 #endif
1711
1712 /**
1713 * __run_timers - run all expired timers (if any) on this CPU.
1714 * @base: the timer vector to be processed.
1715 */
__run_timers(struct timer_base * base)1716 static inline void __run_timers(struct timer_base *base)
1717 {
1718 struct hlist_head heads[LVL_DEPTH];
1719 int levels;
1720
1721 if (time_before(jiffies, base->next_expiry))
1722 return;
1723
1724 timer_base_lock_expiry(base);
1725 raw_spin_lock_irq(&base->lock);
1726
1727 while (time_after_eq(jiffies, base->clk) &&
1728 time_after_eq(jiffies, base->next_expiry)) {
1729 levels = collect_expired_timers(base, heads);
1730 /*
1731 * The two possible reasons for not finding any expired
1732 * timer at this clk are that all matching timers have been
1733 * dequeued or no timer has been queued since
1734 * base::next_expiry was set to base::clk +
1735 * NEXT_TIMER_MAX_DELTA.
1736 */
1737 WARN_ON_ONCE(!levels && !base->next_expiry_recalc
1738 && base->timers_pending);
1739 base->clk++;
1740 base->next_expiry = __next_timer_interrupt(base);
1741
1742 while (levels--)
1743 expire_timers(base, heads + levels);
1744 }
1745 raw_spin_unlock_irq(&base->lock);
1746 timer_base_unlock_expiry(base);
1747 }
1748
1749 /*
1750 * This function runs timers and the timer-tq in bottom half context.
1751 */
run_timer_softirq(struct softirq_action * h)1752 static __latent_entropy void run_timer_softirq(struct softirq_action *h)
1753 {
1754 struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1755
1756 __run_timers(base);
1757 if (IS_ENABLED(CONFIG_NO_HZ_COMMON))
1758 __run_timers(this_cpu_ptr(&timer_bases[BASE_DEF]));
1759 }
1760
1761 /*
1762 * Called by the local, per-CPU timer interrupt on SMP.
1763 */
run_local_timers(void)1764 static void run_local_timers(void)
1765 {
1766 struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]);
1767
1768 hrtimer_run_queues();
1769 /* Raise the softirq only if required. */
1770 if (time_before(jiffies, base->next_expiry)) {
1771 if (!IS_ENABLED(CONFIG_NO_HZ_COMMON))
1772 return;
1773 /* CPU is awake, so check the deferrable base. */
1774 base++;
1775 if (time_before(jiffies, base->next_expiry))
1776 return;
1777 }
1778 raise_softirq(TIMER_SOFTIRQ);
1779 }
1780
1781 /*
1782 * Called from the timer interrupt handler to charge one tick to the current
1783 * process. user_tick is 1 if the tick is user time, 0 for system.
1784 */
update_process_times(int user_tick)1785 void update_process_times(int user_tick)
1786 {
1787 struct task_struct *p = current;
1788
1789 PRANDOM_ADD_NOISE(jiffies, user_tick, p, 0);
1790
1791 /* Note: this timer irq context must be accounted for as well. */
1792 account_process_tick(p, user_tick);
1793 run_local_timers();
1794 rcu_sched_clock_irq(user_tick);
1795 #ifdef CONFIG_IRQ_WORK
1796 if (in_irq())
1797 irq_work_tick();
1798 #endif
1799 scheduler_tick();
1800 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
1801 run_posix_cpu_timers();
1802 }
1803
1804 /*
1805 * Since schedule_timeout()'s timer is defined on the stack, it must store
1806 * the target task on the stack as well.
1807 */
1808 struct process_timer {
1809 struct timer_list timer;
1810 struct task_struct *task;
1811 };
1812
process_timeout(struct timer_list * t)1813 static void process_timeout(struct timer_list *t)
1814 {
1815 struct process_timer *timeout = from_timer(timeout, t, timer);
1816
1817 wake_up_process(timeout->task);
1818 }
1819
1820 /**
1821 * schedule_timeout - sleep until timeout
1822 * @timeout: timeout value in jiffies
1823 *
1824 * Make the current task sleep until @timeout jiffies have elapsed.
1825 * The function behavior depends on the current task state
1826 * (see also set_current_state() description):
1827 *
1828 * %TASK_RUNNING - the scheduler is called, but the task does not sleep
1829 * at all. That happens because sched_submit_work() does nothing for
1830 * tasks in %TASK_RUNNING state.
1831 *
1832 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1833 * pass before the routine returns unless the current task is explicitly
1834 * woken up, (e.g. by wake_up_process()).
1835 *
1836 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1837 * delivered to the current task or the current task is explicitly woken
1838 * up.
1839 *
1840 * The current task state is guaranteed to be %TASK_RUNNING when this
1841 * routine returns.
1842 *
1843 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1844 * the CPU away without a bound on the timeout. In this case the return
1845 * value will be %MAX_SCHEDULE_TIMEOUT.
1846 *
1847 * Returns 0 when the timer has expired otherwise the remaining time in
1848 * jiffies will be returned. In all cases the return value is guaranteed
1849 * to be non-negative.
1850 */
schedule_timeout(signed long timeout)1851 signed long __sched schedule_timeout(signed long timeout)
1852 {
1853 struct process_timer timer;
1854 unsigned long expire;
1855
1856 switch (timeout)
1857 {
1858 case MAX_SCHEDULE_TIMEOUT:
1859 /*
1860 * These two special cases are useful to be comfortable
1861 * in the caller. Nothing more. We could take
1862 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1863 * but I' d like to return a valid offset (>=0) to allow
1864 * the caller to do everything it want with the retval.
1865 */
1866 schedule();
1867 goto out;
1868 default:
1869 /*
1870 * Another bit of PARANOID. Note that the retval will be
1871 * 0 since no piece of kernel is supposed to do a check
1872 * for a negative retval of schedule_timeout() (since it
1873 * should never happens anyway). You just have the printk()
1874 * that will tell you if something is gone wrong and where.
1875 */
1876 if (timeout < 0) {
1877 printk(KERN_ERR "schedule_timeout: wrong timeout "
1878 "value %lx\n", timeout);
1879 dump_stack();
1880 __set_current_state(TASK_RUNNING);
1881 goto out;
1882 }
1883 }
1884
1885 expire = timeout + jiffies;
1886
1887 timer.task = current;
1888 timer_setup_on_stack(&timer.timer, process_timeout, 0);
1889 __mod_timer(&timer.timer, expire, MOD_TIMER_NOTPENDING);
1890 schedule();
1891 del_singleshot_timer_sync(&timer.timer);
1892
1893 /* Remove the timer from the object tracker */
1894 destroy_timer_on_stack(&timer.timer);
1895
1896 timeout = expire - jiffies;
1897
1898 out:
1899 return timeout < 0 ? 0 : timeout;
1900 }
1901 EXPORT_SYMBOL(schedule_timeout);
1902
1903 /*
1904 * We can use __set_current_state() here because schedule_timeout() calls
1905 * schedule() unconditionally.
1906 */
schedule_timeout_interruptible(signed long timeout)1907 signed long __sched schedule_timeout_interruptible(signed long timeout)
1908 {
1909 __set_current_state(TASK_INTERRUPTIBLE);
1910 return schedule_timeout(timeout);
1911 }
1912 EXPORT_SYMBOL(schedule_timeout_interruptible);
1913
schedule_timeout_killable(signed long timeout)1914 signed long __sched schedule_timeout_killable(signed long timeout)
1915 {
1916 __set_current_state(TASK_KILLABLE);
1917 return schedule_timeout(timeout);
1918 }
1919 EXPORT_SYMBOL(schedule_timeout_killable);
1920
schedule_timeout_uninterruptible(signed long timeout)1921 signed long __sched schedule_timeout_uninterruptible(signed long timeout)
1922 {
1923 __set_current_state(TASK_UNINTERRUPTIBLE);
1924 return schedule_timeout(timeout);
1925 }
1926 EXPORT_SYMBOL(schedule_timeout_uninterruptible);
1927
1928 /*
1929 * Like schedule_timeout_uninterruptible(), except this task will not contribute
1930 * to load average.
1931 */
schedule_timeout_idle(signed long timeout)1932 signed long __sched schedule_timeout_idle(signed long timeout)
1933 {
1934 __set_current_state(TASK_IDLE);
1935 return schedule_timeout(timeout);
1936 }
1937 EXPORT_SYMBOL(schedule_timeout_idle);
1938
1939 #ifdef CONFIG_HOTPLUG_CPU
migrate_timer_list(struct timer_base * new_base,struct hlist_head * head)1940 static void migrate_timer_list(struct timer_base *new_base, struct hlist_head *head)
1941 {
1942 struct timer_list *timer;
1943 int cpu = new_base->cpu;
1944
1945 while (!hlist_empty(head)) {
1946 timer = hlist_entry(head->first, struct timer_list, entry);
1947 detach_timer(timer, false);
1948 timer->flags = (timer->flags & ~TIMER_BASEMASK) | cpu;
1949 internal_add_timer(new_base, timer);
1950 }
1951 }
1952
timers_prepare_cpu(unsigned int cpu)1953 int timers_prepare_cpu(unsigned int cpu)
1954 {
1955 struct timer_base *base;
1956 int b;
1957
1958 for (b = 0; b < NR_BASES; b++) {
1959 base = per_cpu_ptr(&timer_bases[b], cpu);
1960 base->clk = jiffies;
1961 base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
1962 base->timers_pending = false;
1963 base->is_idle = false;
1964 }
1965 return 0;
1966 }
1967
timers_dead_cpu(unsigned int cpu)1968 int timers_dead_cpu(unsigned int cpu)
1969 {
1970 struct timer_base *old_base;
1971 struct timer_base *new_base;
1972 int b, i;
1973
1974 BUG_ON(cpu_online(cpu));
1975
1976 for (b = 0; b < NR_BASES; b++) {
1977 old_base = per_cpu_ptr(&timer_bases[b], cpu);
1978 new_base = get_cpu_ptr(&timer_bases[b]);
1979 /*
1980 * The caller is globally serialized and nobody else
1981 * takes two locks at once, deadlock is not possible.
1982 */
1983 raw_spin_lock_irq(&new_base->lock);
1984 raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1985
1986 /*
1987 * The current CPUs base clock might be stale. Update it
1988 * before moving the timers over.
1989 */
1990 forward_timer_base(new_base);
1991
1992 BUG_ON(old_base->running_timer);
1993
1994 for (i = 0; i < WHEEL_SIZE; i++)
1995 migrate_timer_list(new_base, old_base->vectors + i);
1996
1997 raw_spin_unlock(&old_base->lock);
1998 raw_spin_unlock_irq(&new_base->lock);
1999 put_cpu_ptr(&timer_bases);
2000 }
2001 return 0;
2002 }
2003
2004 #endif /* CONFIG_HOTPLUG_CPU */
2005
init_timer_cpu(int cpu)2006 static void __init init_timer_cpu(int cpu)
2007 {
2008 struct timer_base *base;
2009 int i;
2010
2011 for (i = 0; i < NR_BASES; i++) {
2012 base = per_cpu_ptr(&timer_bases[i], cpu);
2013 base->cpu = cpu;
2014 raw_spin_lock_init(&base->lock);
2015 base->clk = jiffies;
2016 base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA;
2017 timer_base_init_expiry_lock(base);
2018 }
2019 }
2020
init_timer_cpus(void)2021 static void __init init_timer_cpus(void)
2022 {
2023 int cpu;
2024
2025 for_each_possible_cpu(cpu)
2026 init_timer_cpu(cpu);
2027 }
2028
init_timers(void)2029 void __init init_timers(void)
2030 {
2031 init_timer_cpus();
2032 posix_cputimers_init_work();
2033 open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
2034 }
2035
2036 /**
2037 * msleep - sleep safely even with waitqueue interruptions
2038 * @msecs: Time in milliseconds to sleep for
2039 */
msleep(unsigned int msecs)2040 void msleep(unsigned int msecs)
2041 {
2042 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
2043
2044 while (timeout)
2045 timeout = schedule_timeout_uninterruptible(timeout);
2046 }
2047
2048 EXPORT_SYMBOL(msleep);
2049
2050 /**
2051 * msleep_interruptible - sleep waiting for signals
2052 * @msecs: Time in milliseconds to sleep for
2053 */
msleep_interruptible(unsigned int msecs)2054 unsigned long msleep_interruptible(unsigned int msecs)
2055 {
2056 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
2057
2058 while (timeout && !signal_pending(current))
2059 timeout = schedule_timeout_interruptible(timeout);
2060 return jiffies_to_msecs(timeout);
2061 }
2062
2063 EXPORT_SYMBOL(msleep_interruptible);
2064
2065 /**
2066 * usleep_range_state - Sleep for an approximate time in a given state
2067 * @min: Minimum time in usecs to sleep
2068 * @max: Maximum time in usecs to sleep
2069 * @state: State of the current task that will be while sleeping
2070 *
2071 * In non-atomic context where the exact wakeup time is flexible, use
2072 * usleep_range_state() instead of udelay(). The sleep improves responsiveness
2073 * by avoiding the CPU-hogging busy-wait of udelay(), and the range reduces
2074 * power usage by allowing hrtimers to take advantage of an already-
2075 * scheduled interrupt instead of scheduling a new one just for this sleep.
2076 */
usleep_range_state(unsigned long min,unsigned long max,unsigned int state)2077 void __sched usleep_range_state(unsigned long min, unsigned long max,
2078 unsigned int state)
2079 {
2080 ktime_t exp = ktime_add_us(ktime_get(), min);
2081 u64 delta = (u64)(max - min) * NSEC_PER_USEC;
2082
2083 for (;;) {
2084 __set_current_state(state);
2085 /* Do not return before the requested sleep time has elapsed */
2086 if (!schedule_hrtimeout_range(&exp, delta, HRTIMER_MODE_ABS))
2087 break;
2088 }
2089 }
2090 EXPORT_SYMBOL(usleep_range_state);
2091