• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  *  linux/kernel/timer.c
3  *
4  *  Kernel internal timers
5  *
6  *  Copyright (C) 1991, 1992  Linus Torvalds
7  *
8  *  1997-01-28  Modified by Finn Arne Gangstad to make timers scale better.
9  *
10  *  1997-09-10  Updated NTP code according to technical memorandum Jan '96
11  *              "A Kernel Model for Precision Timekeeping" by Dave Mills
12  *  1998-12-24  Fixed a xtime SMP race (we need the xtime_lock rw spinlock to
13  *              serialize accesses to xtime/lost_ticks).
14  *                              Copyright (C) 1998  Andrea Arcangeli
15  *  1999-03-10  Improved NTP compatibility by Ulrich Windl
16  *  2002-05-31	Move sys_sysinfo here and make its locking sane, Robert Love
17  *  2000-10-05  Implemented scalable SMP per-CPU timer handling.
18  *                              Copyright (C) 2000, 2001, 2002  Ingo Molnar
19  *              Designed by David S. Miller, Alexey Kuznetsov and Ingo Molnar
20  */
21 
22 #include <linux/kernel_stat.h>
23 #include <linux/export.h>
24 #include <linux/interrupt.h>
25 #include <linux/percpu.h>
26 #include <linux/init.h>
27 #include <linux/mm.h>
28 #include <linux/swap.h>
29 #include <linux/pid_namespace.h>
30 #include <linux/notifier.h>
31 #include <linux/thread_info.h>
32 #include <linux/time.h>
33 #include <linux/jiffies.h>
34 #include <linux/posix-timers.h>
35 #include <linux/cpu.h>
36 #include <linux/syscalls.h>
37 #include <linux/delay.h>
38 #include <linux/tick.h>
39 #include <linux/kallsyms.h>
40 #include <linux/irq_work.h>
41 #include <linux/sched.h>
42 #include <linux/sched/sysctl.h>
43 #include <linux/slab.h>
44 #include <linux/compat.h>
45 
46 #include <asm/uaccess.h>
47 #include <asm/unistd.h>
48 #include <asm/div64.h>
49 #include <asm/timex.h>
50 #include <asm/io.h>
51 
52 #define CREATE_TRACE_POINTS
53 #include <trace/events/timer.h>
54 
55 __visible u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
56 
57 EXPORT_SYMBOL(jiffies_64);
58 
59 /*
60  * per-CPU timer vector definitions:
61  */
62 #define TVN_BITS (CONFIG_BASE_SMALL ? 4 : 6)
63 #define TVR_BITS (CONFIG_BASE_SMALL ? 6 : 8)
64 #define TVN_SIZE (1 << TVN_BITS)
65 #define TVR_SIZE (1 << TVR_BITS)
66 #define TVN_MASK (TVN_SIZE - 1)
67 #define TVR_MASK (TVR_SIZE - 1)
68 #define MAX_TVAL ((unsigned long)((1ULL << (TVR_BITS + 4*TVN_BITS)) - 1))
69 
70 struct tvec {
71 	struct list_head vec[TVN_SIZE];
72 };
73 
74 struct tvec_root {
75 	struct list_head vec[TVR_SIZE];
76 };
77 
78 struct tvec_base {
79 	spinlock_t lock;
80 	struct timer_list *running_timer;
81 	unsigned long timer_jiffies;
82 	unsigned long next_timer;
83 	unsigned long active_timers;
84 	unsigned long all_timers;
85 	int cpu;
86 	struct tvec_root tv1;
87 	struct tvec tv2;
88 	struct tvec tv3;
89 	struct tvec tv4;
90 	struct tvec tv5;
91 } ____cacheline_aligned;
92 
93 struct tvec_base boot_tvec_bases;
94 EXPORT_SYMBOL(boot_tvec_bases);
95 static DEFINE_PER_CPU(struct tvec_base *, tvec_bases) = &boot_tvec_bases;
96 
97 /* Functions below help us manage 'deferrable' flag */
tbase_get_deferrable(struct tvec_base * base)98 static inline unsigned int tbase_get_deferrable(struct tvec_base *base)
99 {
100 	return ((unsigned int)(unsigned long)base & TIMER_DEFERRABLE);
101 }
102 
tbase_get_irqsafe(struct tvec_base * base)103 static inline unsigned int tbase_get_irqsafe(struct tvec_base *base)
104 {
105 	return ((unsigned int)(unsigned long)base & TIMER_IRQSAFE);
106 }
107 
tbase_get_base(struct tvec_base * base)108 static inline struct tvec_base *tbase_get_base(struct tvec_base *base)
109 {
110 	return ((struct tvec_base *)((unsigned long)base & ~TIMER_FLAG_MASK));
111 }
112 
113 static inline void
timer_set_base(struct timer_list * timer,struct tvec_base * new_base)114 timer_set_base(struct timer_list *timer, struct tvec_base *new_base)
115 {
116 	unsigned long flags = (unsigned long)timer->base & TIMER_FLAG_MASK;
117 
118 	timer->base = (struct tvec_base *)((unsigned long)(new_base) | flags);
119 }
120 
round_jiffies_common(unsigned long j,int cpu,bool force_up)121 static unsigned long round_jiffies_common(unsigned long j, int cpu,
122 		bool force_up)
123 {
124 	int rem;
125 	unsigned long original = j;
126 
127 	/*
128 	 * We don't want all cpus firing their timers at once hitting the
129 	 * same lock or cachelines, so we skew each extra cpu with an extra
130 	 * 3 jiffies. This 3 jiffies came originally from the mm/ code which
131 	 * already did this.
132 	 * The skew is done by adding 3*cpunr, then round, then subtract this
133 	 * extra offset again.
134 	 */
135 	j += cpu * 3;
136 
137 	rem = j % HZ;
138 
139 	/*
140 	 * If the target jiffie is just after a whole second (which can happen
141 	 * due to delays of the timer irq, long irq off times etc etc) then
142 	 * we should round down to the whole second, not up. Use 1/4th second
143 	 * as cutoff for this rounding as an extreme upper bound for this.
144 	 * But never round down if @force_up is set.
145 	 */
146 	if (rem < HZ/4 && !force_up) /* round down */
147 		j = j - rem;
148 	else /* round up */
149 		j = j - rem + HZ;
150 
151 	/* now that we have rounded, subtract the extra skew again */
152 	j -= cpu * 3;
153 
154 	/*
155 	 * Make sure j is still in the future. Otherwise return the
156 	 * unmodified value.
157 	 */
158 	return time_is_after_jiffies(j) ? j : original;
159 }
160 
161 /**
162  * __round_jiffies - function to round jiffies to a full second
163  * @j: the time in (absolute) jiffies that should be rounded
164  * @cpu: the processor number on which the timeout will happen
165  *
166  * __round_jiffies() rounds an absolute time in the future (in jiffies)
167  * up or down to (approximately) full seconds. This is useful for timers
168  * for which the exact time they fire does not matter too much, as long as
169  * they fire approximately every X seconds.
170  *
171  * By rounding these timers to whole seconds, all such timers will fire
172  * at the same time, rather than at various times spread out. The goal
173  * of this is to have the CPU wake up less, which saves power.
174  *
175  * The exact rounding is skewed for each processor to avoid all
176  * processors firing at the exact same time, which could lead
177  * to lock contention or spurious cache line bouncing.
178  *
179  * The return value is the rounded version of the @j parameter.
180  */
__round_jiffies(unsigned long j,int cpu)181 unsigned long __round_jiffies(unsigned long j, int cpu)
182 {
183 	return round_jiffies_common(j, cpu, false);
184 }
185 EXPORT_SYMBOL_GPL(__round_jiffies);
186 
187 /**
188  * __round_jiffies_relative - function to round jiffies to a full second
189  * @j: the time in (relative) jiffies that should be rounded
190  * @cpu: the processor number on which the timeout will happen
191  *
192  * __round_jiffies_relative() rounds a time delta  in the future (in jiffies)
193  * up or down to (approximately) full seconds. This is useful for timers
194  * for which the exact time they fire does not matter too much, as long as
195  * they fire approximately every X seconds.
196  *
197  * By rounding these timers to whole seconds, all such timers will fire
198  * at the same time, rather than at various times spread out. The goal
199  * of this is to have the CPU wake up less, which saves power.
200  *
201  * The exact rounding is skewed for each processor to avoid all
202  * processors firing at the exact same time, which could lead
203  * to lock contention or spurious cache line bouncing.
204  *
205  * The return value is the rounded version of the @j parameter.
206  */
__round_jiffies_relative(unsigned long j,int cpu)207 unsigned long __round_jiffies_relative(unsigned long j, int cpu)
208 {
209 	unsigned long j0 = jiffies;
210 
211 	/* Use j0 because jiffies might change while we run */
212 	return round_jiffies_common(j + j0, cpu, false) - j0;
213 }
214 EXPORT_SYMBOL_GPL(__round_jiffies_relative);
215 
216 /**
217  * round_jiffies - function to round jiffies to a full second
218  * @j: the time in (absolute) jiffies that should be rounded
219  *
220  * round_jiffies() rounds an absolute time in the future (in jiffies)
221  * up or down to (approximately) full seconds. This is useful for timers
222  * for which the exact time they fire does not matter too much, as long as
223  * they fire approximately every X seconds.
224  *
225  * By rounding these timers to whole seconds, all such timers will fire
226  * at the same time, rather than at various times spread out. The goal
227  * of this is to have the CPU wake up less, which saves power.
228  *
229  * The return value is the rounded version of the @j parameter.
230  */
round_jiffies(unsigned long j)231 unsigned long round_jiffies(unsigned long j)
232 {
233 	return round_jiffies_common(j, raw_smp_processor_id(), false);
234 }
235 EXPORT_SYMBOL_GPL(round_jiffies);
236 
237 /**
238  * round_jiffies_relative - function to round jiffies to a full second
239  * @j: the time in (relative) jiffies that should be rounded
240  *
241  * round_jiffies_relative() rounds a time delta  in the future (in jiffies)
242  * up or down to (approximately) full seconds. This is useful for timers
243  * for which the exact time they fire does not matter too much, as long as
244  * they fire approximately every X seconds.
245  *
246  * By rounding these timers to whole seconds, all such timers will fire
247  * at the same time, rather than at various times spread out. The goal
248  * of this is to have the CPU wake up less, which saves power.
249  *
250  * The return value is the rounded version of the @j parameter.
251  */
round_jiffies_relative(unsigned long j)252 unsigned long round_jiffies_relative(unsigned long j)
253 {
254 	return __round_jiffies_relative(j, raw_smp_processor_id());
255 }
256 EXPORT_SYMBOL_GPL(round_jiffies_relative);
257 
258 /**
259  * __round_jiffies_up - function to round jiffies up to a full second
260  * @j: the time in (absolute) jiffies that should be rounded
261  * @cpu: the processor number on which the timeout will happen
262  *
263  * This is the same as __round_jiffies() except that it will never
264  * round down.  This is useful for timeouts for which the exact time
265  * of firing does not matter too much, as long as they don't fire too
266  * early.
267  */
__round_jiffies_up(unsigned long j,int cpu)268 unsigned long __round_jiffies_up(unsigned long j, int cpu)
269 {
270 	return round_jiffies_common(j, cpu, true);
271 }
272 EXPORT_SYMBOL_GPL(__round_jiffies_up);
273 
274 /**
275  * __round_jiffies_up_relative - function to round jiffies up to a full second
276  * @j: the time in (relative) jiffies that should be rounded
277  * @cpu: the processor number on which the timeout will happen
278  *
279  * This is the same as __round_jiffies_relative() except that it will never
280  * round down.  This is useful for timeouts for which the exact time
281  * of firing does not matter too much, as long as they don't fire too
282  * early.
283  */
__round_jiffies_up_relative(unsigned long j,int cpu)284 unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
285 {
286 	unsigned long j0 = jiffies;
287 
288 	/* Use j0 because jiffies might change while we run */
289 	return round_jiffies_common(j + j0, cpu, true) - j0;
290 }
291 EXPORT_SYMBOL_GPL(__round_jiffies_up_relative);
292 
293 /**
294  * round_jiffies_up - function to round jiffies up to a full second
295  * @j: the time in (absolute) jiffies that should be rounded
296  *
297  * This is the same as round_jiffies() except that it will never
298  * round down.  This is useful for timeouts for which the exact time
299  * of firing does not matter too much, as long as they don't fire too
300  * early.
301  */
round_jiffies_up(unsigned long j)302 unsigned long round_jiffies_up(unsigned long j)
303 {
304 	return round_jiffies_common(j, raw_smp_processor_id(), true);
305 }
306 EXPORT_SYMBOL_GPL(round_jiffies_up);
307 
308 /**
309  * round_jiffies_up_relative - function to round jiffies up to a full second
310  * @j: the time in (relative) jiffies that should be rounded
311  *
312  * This is the same as round_jiffies_relative() except that it will never
313  * round down.  This is useful for timeouts for which the exact time
314  * of firing does not matter too much, as long as they don't fire too
315  * early.
316  */
round_jiffies_up_relative(unsigned long j)317 unsigned long round_jiffies_up_relative(unsigned long j)
318 {
319 	return __round_jiffies_up_relative(j, raw_smp_processor_id());
320 }
321 EXPORT_SYMBOL_GPL(round_jiffies_up_relative);
322 
323 /**
324  * set_timer_slack - set the allowed slack for a timer
325  * @timer: the timer to be modified
326  * @slack_hz: the amount of time (in jiffies) allowed for rounding
327  *
328  * Set the amount of time, in jiffies, that a certain timer has
329  * in terms of slack. By setting this value, the timer subsystem
330  * will schedule the actual timer somewhere between
331  * the time mod_timer() asks for, and that time plus the slack.
332  *
333  * By setting the slack to -1, a percentage of the delay is used
334  * instead.
335  */
set_timer_slack(struct timer_list * timer,int slack_hz)336 void set_timer_slack(struct timer_list *timer, int slack_hz)
337 {
338 	timer->slack = slack_hz;
339 }
340 EXPORT_SYMBOL_GPL(set_timer_slack);
341 
342 /*
343  * If the list is empty, catch up ->timer_jiffies to the current time.
344  * The caller must hold the tvec_base lock.  Returns true if the list
345  * was empty and therefore ->timer_jiffies was updated.
346  */
catchup_timer_jiffies(struct tvec_base * base)347 static bool catchup_timer_jiffies(struct tvec_base *base)
348 {
349 	if (!base->all_timers) {
350 		base->timer_jiffies = jiffies;
351 		return true;
352 	}
353 	return false;
354 }
355 
356 static void
__internal_add_timer(struct tvec_base * base,struct timer_list * timer)357 __internal_add_timer(struct tvec_base *base, struct timer_list *timer)
358 {
359 	unsigned long expires = timer->expires;
360 	unsigned long idx = expires - base->timer_jiffies;
361 	struct list_head *vec;
362 
363 	if (idx < TVR_SIZE) {
364 		int i = expires & TVR_MASK;
365 		vec = base->tv1.vec + i;
366 	} else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
367 		int i = (expires >> TVR_BITS) & TVN_MASK;
368 		vec = base->tv2.vec + i;
369 	} else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
370 		int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
371 		vec = base->tv3.vec + i;
372 	} else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
373 		int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
374 		vec = base->tv4.vec + i;
375 	} else if ((signed long) idx < 0) {
376 		/*
377 		 * Can happen if you add a timer with expires == jiffies,
378 		 * or you set a timer to go off in the past
379 		 */
380 		vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
381 	} else {
382 		int i;
383 		/* If the timeout is larger than MAX_TVAL (on 64-bit
384 		 * architectures or with CONFIG_BASE_SMALL=1) then we
385 		 * use the maximum timeout.
386 		 */
387 		if (idx > MAX_TVAL) {
388 			idx = MAX_TVAL;
389 			expires = idx + base->timer_jiffies;
390 		}
391 		i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
392 		vec = base->tv5.vec + i;
393 	}
394 	/*
395 	 * Timers are FIFO:
396 	 */
397 	list_add_tail(&timer->entry, vec);
398 }
399 
internal_add_timer(struct tvec_base * base,struct timer_list * timer)400 static void internal_add_timer(struct tvec_base *base, struct timer_list *timer)
401 {
402 	(void)catchup_timer_jiffies(base);
403 	__internal_add_timer(base, timer);
404 	/*
405 	 * Update base->active_timers and base->next_timer
406 	 */
407 	if (!tbase_get_deferrable(timer->base)) {
408 		if (!base->active_timers++ ||
409 		    time_before(timer->expires, base->next_timer))
410 			base->next_timer = timer->expires;
411 	}
412 	base->all_timers++;
413 
414 	/*
415 	 * Check whether the other CPU is in dynticks mode and needs
416 	 * to be triggered to reevaluate the timer wheel.
417 	 * We are protected against the other CPU fiddling
418 	 * with the timer by holding the timer base lock. This also
419 	 * makes sure that a CPU on the way to stop its tick can not
420 	 * evaluate the timer wheel.
421 	 *
422 	 * Spare the IPI for deferrable timers on idle targets though.
423 	 * The next busy ticks will take care of it. Except full dynticks
424 	 * require special care against races with idle_cpu(), lets deal
425 	 * with that later.
426 	 */
427 	if (!tbase_get_deferrable(base) || tick_nohz_full_cpu(base->cpu))
428 		wake_up_nohz_cpu(base->cpu);
429 }
430 
431 #ifdef CONFIG_TIMER_STATS
__timer_stats_timer_set_start_info(struct timer_list * timer,void * addr)432 void __timer_stats_timer_set_start_info(struct timer_list *timer, void *addr)
433 {
434 	if (timer->start_site)
435 		return;
436 
437 	timer->start_site = addr;
438 	memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
439 	timer->start_pid = current->pid;
440 }
441 
timer_stats_account_timer(struct timer_list * timer)442 static void timer_stats_account_timer(struct timer_list *timer)
443 {
444 	unsigned int flag = 0;
445 
446 	if (likely(!timer->start_site))
447 		return;
448 	if (unlikely(tbase_get_deferrable(timer->base)))
449 		flag |= TIMER_STATS_FLAG_DEFERRABLE;
450 
451 	timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
452 				 timer->function, timer->start_comm, flag);
453 }
454 
455 #else
timer_stats_account_timer(struct timer_list * timer)456 static void timer_stats_account_timer(struct timer_list *timer) {}
457 #endif
458 
459 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
460 
461 static struct debug_obj_descr timer_debug_descr;
462 
timer_debug_hint(void * addr)463 static void *timer_debug_hint(void *addr)
464 {
465 	return ((struct timer_list *) addr)->function;
466 }
467 
468 /*
469  * fixup_init is called when:
470  * - an active object is initialized
471  */
timer_fixup_init(void * addr,enum debug_obj_state state)472 static int timer_fixup_init(void *addr, enum debug_obj_state state)
473 {
474 	struct timer_list *timer = addr;
475 
476 	switch (state) {
477 	case ODEBUG_STATE_ACTIVE:
478 		del_timer_sync(timer);
479 		debug_object_init(timer, &timer_debug_descr);
480 		return 1;
481 	default:
482 		return 0;
483 	}
484 }
485 
486 /* Stub timer callback for improperly used timers. */
stub_timer(unsigned long data)487 static void stub_timer(unsigned long data)
488 {
489 	WARN_ON(1);
490 }
491 
492 /*
493  * fixup_activate is called when:
494  * - an active object is activated
495  * - an unknown object is activated (might be a statically initialized object)
496  */
timer_fixup_activate(void * addr,enum debug_obj_state state)497 static int timer_fixup_activate(void *addr, enum debug_obj_state state)
498 {
499 	struct timer_list *timer = addr;
500 
501 	switch (state) {
502 
503 	case ODEBUG_STATE_NOTAVAILABLE:
504 		/*
505 		 * This is not really a fixup. The timer was
506 		 * statically initialized. We just make sure that it
507 		 * is tracked in the object tracker.
508 		 */
509 		if (timer->entry.next == NULL &&
510 		    timer->entry.prev == TIMER_ENTRY_STATIC) {
511 			debug_object_init(timer, &timer_debug_descr);
512 			debug_object_activate(timer, &timer_debug_descr);
513 			return 0;
514 		} else {
515 			setup_timer(timer, stub_timer, 0);
516 			return 1;
517 		}
518 		return 0;
519 
520 	case ODEBUG_STATE_ACTIVE:
521 		WARN_ON(1);
522 
523 	default:
524 		return 0;
525 	}
526 }
527 
528 /*
529  * fixup_free is called when:
530  * - an active object is freed
531  */
timer_fixup_free(void * addr,enum debug_obj_state state)532 static int timer_fixup_free(void *addr, enum debug_obj_state state)
533 {
534 	struct timer_list *timer = addr;
535 
536 	switch (state) {
537 	case ODEBUG_STATE_ACTIVE:
538 		del_timer_sync(timer);
539 		debug_object_free(timer, &timer_debug_descr);
540 		return 1;
541 	default:
542 		return 0;
543 	}
544 }
545 
546 /*
547  * fixup_assert_init is called when:
548  * - an untracked/uninit-ed object is found
549  */
timer_fixup_assert_init(void * addr,enum debug_obj_state state)550 static int timer_fixup_assert_init(void *addr, enum debug_obj_state state)
551 {
552 	struct timer_list *timer = addr;
553 
554 	switch (state) {
555 	case ODEBUG_STATE_NOTAVAILABLE:
556 		if (timer->entry.prev == TIMER_ENTRY_STATIC) {
557 			/*
558 			 * This is not really a fixup. The timer was
559 			 * statically initialized. We just make sure that it
560 			 * is tracked in the object tracker.
561 			 */
562 			debug_object_init(timer, &timer_debug_descr);
563 			return 0;
564 		} else {
565 			setup_timer(timer, stub_timer, 0);
566 			return 1;
567 		}
568 	default:
569 		return 0;
570 	}
571 }
572 
573 static struct debug_obj_descr timer_debug_descr = {
574 	.name			= "timer_list",
575 	.debug_hint		= timer_debug_hint,
576 	.fixup_init		= timer_fixup_init,
577 	.fixup_activate		= timer_fixup_activate,
578 	.fixup_free		= timer_fixup_free,
579 	.fixup_assert_init	= timer_fixup_assert_init,
580 };
581 
debug_timer_init(struct timer_list * timer)582 static inline void debug_timer_init(struct timer_list *timer)
583 {
584 	debug_object_init(timer, &timer_debug_descr);
585 }
586 
debug_timer_activate(struct timer_list * timer)587 static inline void debug_timer_activate(struct timer_list *timer)
588 {
589 	debug_object_activate(timer, &timer_debug_descr);
590 }
591 
debug_timer_deactivate(struct timer_list * timer)592 static inline void debug_timer_deactivate(struct timer_list *timer)
593 {
594 	debug_object_deactivate(timer, &timer_debug_descr);
595 }
596 
debug_timer_free(struct timer_list * timer)597 static inline void debug_timer_free(struct timer_list *timer)
598 {
599 	debug_object_free(timer, &timer_debug_descr);
600 }
601 
debug_timer_assert_init(struct timer_list * timer)602 static inline void debug_timer_assert_init(struct timer_list *timer)
603 {
604 	debug_object_assert_init(timer, &timer_debug_descr);
605 }
606 
607 static void do_init_timer(struct timer_list *timer, unsigned int flags,
608 			  const char *name, struct lock_class_key *key);
609 
init_timer_on_stack_key(struct timer_list * timer,unsigned int flags,const char * name,struct lock_class_key * key)610 void init_timer_on_stack_key(struct timer_list *timer, unsigned int flags,
611 			     const char *name, struct lock_class_key *key)
612 {
613 	debug_object_init_on_stack(timer, &timer_debug_descr);
614 	do_init_timer(timer, flags, name, key);
615 }
616 EXPORT_SYMBOL_GPL(init_timer_on_stack_key);
617 
destroy_timer_on_stack(struct timer_list * timer)618 void destroy_timer_on_stack(struct timer_list *timer)
619 {
620 	debug_object_free(timer, &timer_debug_descr);
621 }
622 EXPORT_SYMBOL_GPL(destroy_timer_on_stack);
623 
624 #else
debug_timer_init(struct timer_list * timer)625 static inline void debug_timer_init(struct timer_list *timer) { }
debug_timer_activate(struct timer_list * timer)626 static inline void debug_timer_activate(struct timer_list *timer) { }
debug_timer_deactivate(struct timer_list * timer)627 static inline void debug_timer_deactivate(struct timer_list *timer) { }
debug_timer_assert_init(struct timer_list * timer)628 static inline void debug_timer_assert_init(struct timer_list *timer) { }
629 #endif
630 
debug_init(struct timer_list * timer)631 static inline void debug_init(struct timer_list *timer)
632 {
633 	debug_timer_init(timer);
634 	trace_timer_init(timer);
635 }
636 
637 static inline void
debug_activate(struct timer_list * timer,unsigned long expires)638 debug_activate(struct timer_list *timer, unsigned long expires)
639 {
640 	debug_timer_activate(timer);
641 	trace_timer_start(timer, expires);
642 }
643 
debug_deactivate(struct timer_list * timer)644 static inline void debug_deactivate(struct timer_list *timer)
645 {
646 	debug_timer_deactivate(timer);
647 	trace_timer_cancel(timer);
648 }
649 
debug_assert_init(struct timer_list * timer)650 static inline void debug_assert_init(struct timer_list *timer)
651 {
652 	debug_timer_assert_init(timer);
653 }
654 
do_init_timer(struct timer_list * timer,unsigned int flags,const char * name,struct lock_class_key * key)655 static void do_init_timer(struct timer_list *timer, unsigned int flags,
656 			  const char *name, struct lock_class_key *key)
657 {
658 	struct tvec_base *base = raw_cpu_read(tvec_bases);
659 
660 	timer->entry.next = NULL;
661 	timer->base = (void *)((unsigned long)base | flags);
662 	timer->slack = -1;
663 #ifdef CONFIG_TIMER_STATS
664 	timer->start_site = NULL;
665 	timer->start_pid = -1;
666 	memset(timer->start_comm, 0, TASK_COMM_LEN);
667 #endif
668 	lockdep_init_map(&timer->lockdep_map, name, key, 0);
669 }
670 
671 /**
672  * init_timer_key - initialize a timer
673  * @timer: the timer to be initialized
674  * @flags: timer flags
675  * @name: name of the timer
676  * @key: lockdep class key of the fake lock used for tracking timer
677  *       sync lock dependencies
678  *
679  * init_timer_key() must be done to a timer prior calling *any* of the
680  * other timer functions.
681  */
init_timer_key(struct timer_list * timer,unsigned int flags,const char * name,struct lock_class_key * key)682 void init_timer_key(struct timer_list *timer, unsigned int flags,
683 		    const char *name, struct lock_class_key *key)
684 {
685 	debug_init(timer);
686 	do_init_timer(timer, flags, name, key);
687 }
688 EXPORT_SYMBOL(init_timer_key);
689 
detach_timer(struct timer_list * timer,bool clear_pending)690 static inline void detach_timer(struct timer_list *timer, bool clear_pending)
691 {
692 	struct list_head *entry = &timer->entry;
693 
694 	debug_deactivate(timer);
695 
696 	__list_del(entry->prev, entry->next);
697 	if (clear_pending)
698 		entry->next = NULL;
699 	entry->prev = LIST_POISON2;
700 }
701 
702 static inline void
detach_expired_timer(struct timer_list * timer,struct tvec_base * base)703 detach_expired_timer(struct timer_list *timer, struct tvec_base *base)
704 {
705 	detach_timer(timer, true);
706 	if (!tbase_get_deferrable(timer->base))
707 		base->active_timers--;
708 	base->all_timers--;
709 	(void)catchup_timer_jiffies(base);
710 }
711 
detach_if_pending(struct timer_list * timer,struct tvec_base * base,bool clear_pending)712 static int detach_if_pending(struct timer_list *timer, struct tvec_base *base,
713 			     bool clear_pending)
714 {
715 	if (!timer_pending(timer))
716 		return 0;
717 
718 	detach_timer(timer, clear_pending);
719 	if (!tbase_get_deferrable(timer->base)) {
720 		base->active_timers--;
721 		if (timer->expires == base->next_timer)
722 			base->next_timer = base->timer_jiffies;
723 	}
724 	base->all_timers--;
725 	(void)catchup_timer_jiffies(base);
726 	return 1;
727 }
728 
729 /*
730  * We are using hashed locking: holding per_cpu(tvec_bases).lock
731  * means that all timers which are tied to this base via timer->base are
732  * locked, and the base itself is locked too.
733  *
734  * So __run_timers/migrate_timers can safely modify all timers which could
735  * be found on ->tvX lists.
736  *
737  * When the timer's base is locked, and the timer removed from list, it is
738  * possible to set timer->base = NULL and drop the lock: the timer remains
739  * locked.
740  */
lock_timer_base(struct timer_list * timer,unsigned long * flags)741 static struct tvec_base *lock_timer_base(struct timer_list *timer,
742 					unsigned long *flags)
743 	__acquires(timer->base->lock)
744 {
745 	struct tvec_base *base;
746 
747 	for (;;) {
748 		struct tvec_base *prelock_base = timer->base;
749 		base = tbase_get_base(prelock_base);
750 		if (likely(base != NULL)) {
751 			spin_lock_irqsave(&base->lock, *flags);
752 			if (likely(prelock_base == timer->base))
753 				return base;
754 			/* The timer has migrated to another CPU */
755 			spin_unlock_irqrestore(&base->lock, *flags);
756 		}
757 		cpu_relax();
758 	}
759 }
760 
761 static inline int
__mod_timer(struct timer_list * timer,unsigned long expires,bool pending_only,int pinned)762 __mod_timer(struct timer_list *timer, unsigned long expires,
763 						bool pending_only, int pinned)
764 {
765 	struct tvec_base *base, *new_base;
766 	unsigned long flags;
767 	int ret = 0 , cpu;
768 
769 	timer_stats_timer_set_start_info(timer);
770 	BUG_ON(!timer->function);
771 
772 	base = lock_timer_base(timer, &flags);
773 
774 	ret = detach_if_pending(timer, base, false);
775 	if (!ret && pending_only)
776 		goto out_unlock;
777 
778 	debug_activate(timer, expires);
779 
780 	cpu = get_nohz_timer_target(pinned);
781 	new_base = per_cpu(tvec_bases, cpu);
782 
783 	if (base != new_base) {
784 		/*
785 		 * We are trying to schedule the timer on the local CPU.
786 		 * However we can't change timer's base while it is running,
787 		 * otherwise del_timer_sync() can't detect that the timer's
788 		 * handler yet has not finished. This also guarantees that
789 		 * the timer is serialized wrt itself.
790 		 */
791 		if (likely(base->running_timer != timer)) {
792 			/* See the comment in lock_timer_base() */
793 			timer_set_base(timer, NULL);
794 			spin_unlock(&base->lock);
795 			base = new_base;
796 			spin_lock(&base->lock);
797 			timer_set_base(timer, base);
798 		}
799 	}
800 
801 	timer->expires = expires;
802 	internal_add_timer(base, timer);
803 
804 out_unlock:
805 	spin_unlock_irqrestore(&base->lock, flags);
806 
807 	return ret;
808 }
809 
810 /**
811  * mod_timer_pending - modify a pending timer's timeout
812  * @timer: the pending timer to be modified
813  * @expires: new timeout in jiffies
814  *
815  * mod_timer_pending() is the same for pending timers as mod_timer(),
816  * but will not re-activate and modify already deleted timers.
817  *
818  * It is useful for unserialized use of timers.
819  */
mod_timer_pending(struct timer_list * timer,unsigned long expires)820 int mod_timer_pending(struct timer_list *timer, unsigned long expires)
821 {
822 	return __mod_timer(timer, expires, true, TIMER_NOT_PINNED);
823 }
824 EXPORT_SYMBOL(mod_timer_pending);
825 
826 /*
827  * Decide where to put the timer while taking the slack into account
828  *
829  * Algorithm:
830  *   1) calculate the maximum (absolute) time
831  *   2) calculate the highest bit where the expires and new max are different
832  *   3) use this bit to make a mask
833  *   4) use the bitmask to round down the maximum time, so that all last
834  *      bits are zeros
835  */
836 static inline
apply_slack(struct timer_list * timer,unsigned long expires)837 unsigned long apply_slack(struct timer_list *timer, unsigned long expires)
838 {
839 	unsigned long expires_limit, mask;
840 	int bit;
841 
842 	if (timer->slack >= 0) {
843 		expires_limit = expires + timer->slack;
844 	} else {
845 		long delta = expires - jiffies;
846 
847 		if (delta < 256)
848 			return expires;
849 
850 		expires_limit = expires + delta / 256;
851 	}
852 	mask = expires ^ expires_limit;
853 	if (mask == 0)
854 		return expires;
855 
856 	bit = find_last_bit(&mask, BITS_PER_LONG);
857 
858 	mask = (1UL << bit) - 1;
859 
860 	expires_limit = expires_limit & ~(mask);
861 
862 	return expires_limit;
863 }
864 
865 /**
866  * mod_timer - modify a timer's timeout
867  * @timer: the timer to be modified
868  * @expires: new timeout in jiffies
869  *
870  * mod_timer() is a more efficient way to update the expire field of an
871  * active timer (if the timer is inactive it will be activated)
872  *
873  * mod_timer(timer, expires) is equivalent to:
874  *
875  *     del_timer(timer); timer->expires = expires; add_timer(timer);
876  *
877  * Note that if there are multiple unserialized concurrent users of the
878  * same timer, then mod_timer() is the only safe way to modify the timeout,
879  * since add_timer() cannot modify an already running timer.
880  *
881  * The function returns whether it has modified a pending timer or not.
882  * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
883  * active timer returns 1.)
884  */
mod_timer(struct timer_list * timer,unsigned long expires)885 int mod_timer(struct timer_list *timer, unsigned long expires)
886 {
887 	expires = apply_slack(timer, expires);
888 
889 	/*
890 	 * This is a common optimization triggered by the
891 	 * networking code - if the timer is re-modified
892 	 * to be the same thing then just return:
893 	 */
894 	if (timer_pending(timer) && timer->expires == expires)
895 		return 1;
896 
897 	return __mod_timer(timer, expires, false, TIMER_NOT_PINNED);
898 }
899 EXPORT_SYMBOL(mod_timer);
900 
901 /**
902  * mod_timer_pinned - modify a timer's timeout
903  * @timer: the timer to be modified
904  * @expires: new timeout in jiffies
905  *
906  * mod_timer_pinned() is a way to update the expire field of an
907  * active timer (if the timer is inactive it will be activated)
908  * and to ensure that the timer is scheduled on the current CPU.
909  *
910  * Note that this does not prevent the timer from being migrated
911  * when the current CPU goes offline.  If this is a problem for
912  * you, use CPU-hotplug notifiers to handle it correctly, for
913  * example, cancelling the timer when the corresponding CPU goes
914  * offline.
915  *
916  * mod_timer_pinned(timer, expires) is equivalent to:
917  *
918  *     del_timer(timer); timer->expires = expires; add_timer(timer);
919  */
mod_timer_pinned(struct timer_list * timer,unsigned long expires)920 int mod_timer_pinned(struct timer_list *timer, unsigned long expires)
921 {
922 	if (timer->expires == expires && timer_pending(timer))
923 		return 1;
924 
925 	return __mod_timer(timer, expires, false, TIMER_PINNED);
926 }
927 EXPORT_SYMBOL(mod_timer_pinned);
928 
929 /**
930  * add_timer - start a timer
931  * @timer: the timer to be added
932  *
933  * The kernel will do a ->function(->data) callback from the
934  * timer interrupt at the ->expires point in the future. The
935  * current time is 'jiffies'.
936  *
937  * The timer's ->expires, ->function (and if the handler uses it, ->data)
938  * fields must be set prior calling this function.
939  *
940  * Timers with an ->expires field in the past will be executed in the next
941  * timer tick.
942  */
add_timer(struct timer_list * timer)943 void add_timer(struct timer_list *timer)
944 {
945 	BUG_ON(timer_pending(timer));
946 	mod_timer(timer, timer->expires);
947 }
948 EXPORT_SYMBOL(add_timer);
949 
950 /**
951  * add_timer_on - start a timer on a particular CPU
952  * @timer: the timer to be added
953  * @cpu: the CPU to start it on
954  *
955  * This is not very scalable on SMP. Double adds are not possible.
956  */
add_timer_on(struct timer_list * timer,int cpu)957 void add_timer_on(struct timer_list *timer, int cpu)
958 {
959 	struct tvec_base *new_base = per_cpu(tvec_bases, cpu);
960 	struct tvec_base *base;
961 	unsigned long flags;
962 
963 	timer_stats_timer_set_start_info(timer);
964 	BUG_ON(timer_pending(timer) || !timer->function);
965 
966 	/*
967 	 * If @timer was on a different CPU, it should be migrated with the
968 	 * old base locked to prevent other operations proceeding with the
969 	 * wrong base locked.  See lock_timer_base().
970 	 */
971 	base = lock_timer_base(timer, &flags);
972 	if (base != new_base) {
973 		timer_set_base(timer, NULL);
974 		spin_unlock(&base->lock);
975 		base = new_base;
976 		spin_lock(&base->lock);
977 		timer_set_base(timer, base);
978 	}
979 
980 	debug_activate(timer, timer->expires);
981 	internal_add_timer(base, timer);
982 	spin_unlock_irqrestore(&base->lock, flags);
983 }
984 EXPORT_SYMBOL_GPL(add_timer_on);
985 
986 /**
987  * del_timer - deactive a timer.
988  * @timer: the timer to be deactivated
989  *
990  * del_timer() deactivates a timer - this works on both active and inactive
991  * timers.
992  *
993  * The function returns whether it has deactivated a pending timer or not.
994  * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
995  * active timer returns 1.)
996  */
del_timer(struct timer_list * timer)997 int del_timer(struct timer_list *timer)
998 {
999 	struct tvec_base *base;
1000 	unsigned long flags;
1001 	int ret = 0;
1002 
1003 	debug_assert_init(timer);
1004 
1005 	timer_stats_timer_clear_start_info(timer);
1006 	if (timer_pending(timer)) {
1007 		base = lock_timer_base(timer, &flags);
1008 		ret = detach_if_pending(timer, base, true);
1009 		spin_unlock_irqrestore(&base->lock, flags);
1010 	}
1011 
1012 	return ret;
1013 }
1014 EXPORT_SYMBOL(del_timer);
1015 
1016 /**
1017  * try_to_del_timer_sync - Try to deactivate a timer
1018  * @timer: timer do del
1019  *
1020  * This function tries to deactivate a timer. Upon successful (ret >= 0)
1021  * exit the timer is not queued and the handler is not running on any CPU.
1022  */
try_to_del_timer_sync(struct timer_list * timer)1023 int try_to_del_timer_sync(struct timer_list *timer)
1024 {
1025 	struct tvec_base *base;
1026 	unsigned long flags;
1027 	int ret = -1;
1028 
1029 	debug_assert_init(timer);
1030 
1031 	base = lock_timer_base(timer, &flags);
1032 
1033 	if (base->running_timer != timer) {
1034 		timer_stats_timer_clear_start_info(timer);
1035 		ret = detach_if_pending(timer, base, true);
1036 	}
1037 	spin_unlock_irqrestore(&base->lock, flags);
1038 
1039 	return ret;
1040 }
1041 EXPORT_SYMBOL(try_to_del_timer_sync);
1042 
1043 #ifdef CONFIG_SMP
1044 /**
1045  * del_timer_sync - deactivate a timer and wait for the handler to finish.
1046  * @timer: the timer to be deactivated
1047  *
1048  * This function only differs from del_timer() on SMP: besides deactivating
1049  * the timer it also makes sure the handler has finished executing on other
1050  * CPUs.
1051  *
1052  * Synchronization rules: Callers must prevent restarting of the timer,
1053  * otherwise this function is meaningless. It must not be called from
1054  * interrupt contexts unless the timer is an irqsafe one. The caller must
1055  * not hold locks which would prevent completion of the timer's
1056  * handler. The timer's handler must not call add_timer_on(). Upon exit the
1057  * timer is not queued and the handler is not running on any CPU.
1058  *
1059  * Note: For !irqsafe timers, you must not hold locks that are held in
1060  *   interrupt context while calling this function. Even if the lock has
1061  *   nothing to do with the timer in question.  Here's why:
1062  *
1063  *    CPU0                             CPU1
1064  *    ----                             ----
1065  *                                   <SOFTIRQ>
1066  *                                   call_timer_fn();
1067  *                                     base->running_timer = mytimer;
1068  *  spin_lock_irq(somelock);
1069  *                                     <IRQ>
1070  *                                        spin_lock(somelock);
1071  *  del_timer_sync(mytimer);
1072  *   while (base->running_timer == mytimer);
1073  *
1074  * Now del_timer_sync() will never return and never release somelock.
1075  * The interrupt on the other CPU is waiting to grab somelock but
1076  * it has interrupted the softirq that CPU0 is waiting to finish.
1077  *
1078  * The function returns whether it has deactivated a pending timer or not.
1079  */
del_timer_sync(struct timer_list * timer)1080 int del_timer_sync(struct timer_list *timer)
1081 {
1082 #ifdef CONFIG_LOCKDEP
1083 	unsigned long flags;
1084 
1085 	/*
1086 	 * If lockdep gives a backtrace here, please reference
1087 	 * the synchronization rules above.
1088 	 */
1089 	local_irq_save(flags);
1090 	lock_map_acquire(&timer->lockdep_map);
1091 	lock_map_release(&timer->lockdep_map);
1092 	local_irq_restore(flags);
1093 #endif
1094 	/*
1095 	 * don't use it in hardirq context, because it
1096 	 * could lead to deadlock.
1097 	 */
1098 	WARN_ON(in_irq() && !tbase_get_irqsafe(timer->base));
1099 	for (;;) {
1100 		int ret = try_to_del_timer_sync(timer);
1101 		if (ret >= 0)
1102 			return ret;
1103 		cpu_relax();
1104 	}
1105 }
1106 EXPORT_SYMBOL(del_timer_sync);
1107 #endif
1108 
cascade(struct tvec_base * base,struct tvec * tv,int index)1109 static int cascade(struct tvec_base *base, struct tvec *tv, int index)
1110 {
1111 	/* cascade all the timers from tv up one level */
1112 	struct timer_list *timer, *tmp;
1113 	struct list_head tv_list;
1114 
1115 	list_replace_init(tv->vec + index, &tv_list);
1116 
1117 	/*
1118 	 * We are removing _all_ timers from the list, so we
1119 	 * don't have to detach them individually.
1120 	 */
1121 	list_for_each_entry_safe(timer, tmp, &tv_list, entry) {
1122 		BUG_ON(tbase_get_base(timer->base) != base);
1123 		/* No accounting, while moving them */
1124 		__internal_add_timer(base, timer);
1125 	}
1126 
1127 	return index;
1128 }
1129 
call_timer_fn(struct timer_list * timer,void (* fn)(unsigned long),unsigned long data)1130 static void call_timer_fn(struct timer_list *timer, void (*fn)(unsigned long),
1131 			  unsigned long data)
1132 {
1133 	int count = preempt_count();
1134 
1135 #ifdef CONFIG_LOCKDEP
1136 	/*
1137 	 * It is permissible to free the timer from inside the
1138 	 * function that is called from it, this we need to take into
1139 	 * account for lockdep too. To avoid bogus "held lock freed"
1140 	 * warnings as well as problems when looking into
1141 	 * timer->lockdep_map, make a copy and use that here.
1142 	 */
1143 	struct lockdep_map lockdep_map;
1144 
1145 	lockdep_copy_map(&lockdep_map, &timer->lockdep_map);
1146 #endif
1147 	/*
1148 	 * Couple the lock chain with the lock chain at
1149 	 * del_timer_sync() by acquiring the lock_map around the fn()
1150 	 * call here and in del_timer_sync().
1151 	 */
1152 	lock_map_acquire(&lockdep_map);
1153 
1154 	trace_timer_expire_entry(timer);
1155 	fn(data);
1156 	trace_timer_expire_exit(timer);
1157 
1158 	lock_map_release(&lockdep_map);
1159 
1160 	if (count != preempt_count()) {
1161 		WARN_ONCE(1, "timer: %pF preempt leak: %08x -> %08x\n",
1162 			  fn, count, preempt_count());
1163 		/*
1164 		 * Restore the preempt count. That gives us a decent
1165 		 * chance to survive and extract information. If the
1166 		 * callback kept a lock held, bad luck, but not worse
1167 		 * than the BUG() we had.
1168 		 */
1169 		preempt_count_set(count);
1170 	}
1171 }
1172 
1173 #define INDEX(N) ((base->timer_jiffies >> (TVR_BITS + (N) * TVN_BITS)) & TVN_MASK)
1174 
1175 /**
1176  * __run_timers - run all expired timers (if any) on this CPU.
1177  * @base: the timer vector to be processed.
1178  *
1179  * This function cascades all vectors and executes all expired timer
1180  * vectors.
1181  */
__run_timers(struct tvec_base * base)1182 static inline void __run_timers(struct tvec_base *base)
1183 {
1184 	struct timer_list *timer;
1185 
1186 	spin_lock_irq(&base->lock);
1187 	if (catchup_timer_jiffies(base)) {
1188 		spin_unlock_irq(&base->lock);
1189 		return;
1190 	}
1191 	while (time_after_eq(jiffies, base->timer_jiffies)) {
1192 		struct list_head work_list;
1193 		struct list_head *head = &work_list;
1194 		int index = base->timer_jiffies & TVR_MASK;
1195 
1196 		/*
1197 		 * Cascade timers:
1198 		 */
1199 		if (!index &&
1200 			(!cascade(base, &base->tv2, INDEX(0))) &&
1201 				(!cascade(base, &base->tv3, INDEX(1))) &&
1202 					!cascade(base, &base->tv4, INDEX(2)))
1203 			cascade(base, &base->tv5, INDEX(3));
1204 		++base->timer_jiffies;
1205 		list_replace_init(base->tv1.vec + index, head);
1206 		while (!list_empty(head)) {
1207 			void (*fn)(unsigned long);
1208 			unsigned long data;
1209 			bool irqsafe;
1210 
1211 			timer = list_first_entry(head, struct timer_list,entry);
1212 			fn = timer->function;
1213 			data = timer->data;
1214 			irqsafe = tbase_get_irqsafe(timer->base);
1215 
1216 			timer_stats_account_timer(timer);
1217 
1218 			base->running_timer = timer;
1219 			detach_expired_timer(timer, base);
1220 
1221 			if (irqsafe) {
1222 				spin_unlock(&base->lock);
1223 				call_timer_fn(timer, fn, data);
1224 				spin_lock(&base->lock);
1225 			} else {
1226 				spin_unlock_irq(&base->lock);
1227 				call_timer_fn(timer, fn, data);
1228 				spin_lock_irq(&base->lock);
1229 			}
1230 		}
1231 	}
1232 	base->running_timer = NULL;
1233 	spin_unlock_irq(&base->lock);
1234 }
1235 
1236 #ifdef CONFIG_NO_HZ_COMMON
1237 /*
1238  * Find out when the next timer event is due to happen. This
1239  * is used on S/390 to stop all activity when a CPU is idle.
1240  * This function needs to be called with interrupts disabled.
1241  */
__next_timer_interrupt(struct tvec_base * base)1242 static unsigned long __next_timer_interrupt(struct tvec_base *base)
1243 {
1244 	unsigned long timer_jiffies = base->timer_jiffies;
1245 	unsigned long expires = timer_jiffies + NEXT_TIMER_MAX_DELTA;
1246 	int index, slot, array, found = 0;
1247 	struct timer_list *nte;
1248 	struct tvec *varray[4];
1249 
1250 	/* Look for timer events in tv1. */
1251 	index = slot = timer_jiffies & TVR_MASK;
1252 	do {
1253 		list_for_each_entry(nte, base->tv1.vec + slot, entry) {
1254 			if (tbase_get_deferrable(nte->base))
1255 				continue;
1256 
1257 			found = 1;
1258 			expires = nte->expires;
1259 			/* Look at the cascade bucket(s)? */
1260 			if (!index || slot < index)
1261 				goto cascade;
1262 			return expires;
1263 		}
1264 		slot = (slot + 1) & TVR_MASK;
1265 	} while (slot != index);
1266 
1267 cascade:
1268 	/* Calculate the next cascade event */
1269 	if (index)
1270 		timer_jiffies += TVR_SIZE - index;
1271 	timer_jiffies >>= TVR_BITS;
1272 
1273 	/* Check tv2-tv5. */
1274 	varray[0] = &base->tv2;
1275 	varray[1] = &base->tv3;
1276 	varray[2] = &base->tv4;
1277 	varray[3] = &base->tv5;
1278 
1279 	for (array = 0; array < 4; array++) {
1280 		struct tvec *varp = varray[array];
1281 
1282 		index = slot = timer_jiffies & TVN_MASK;
1283 		do {
1284 			list_for_each_entry(nte, varp->vec + slot, entry) {
1285 				if (tbase_get_deferrable(nte->base))
1286 					continue;
1287 
1288 				found = 1;
1289 				if (time_before(nte->expires, expires))
1290 					expires = nte->expires;
1291 			}
1292 			/*
1293 			 * Do we still search for the first timer or are
1294 			 * we looking up the cascade buckets ?
1295 			 */
1296 			if (found) {
1297 				/* Look at the cascade bucket(s)? */
1298 				if (!index || slot < index)
1299 					break;
1300 				return expires;
1301 			}
1302 			slot = (slot + 1) & TVN_MASK;
1303 		} while (slot != index);
1304 
1305 		if (index)
1306 			timer_jiffies += TVN_SIZE - index;
1307 		timer_jiffies >>= TVN_BITS;
1308 	}
1309 	return expires;
1310 }
1311 
1312 /*
1313  * Check, if the next hrtimer event is before the next timer wheel
1314  * event:
1315  */
cmp_next_hrtimer_event(unsigned long now,unsigned long expires)1316 static unsigned long cmp_next_hrtimer_event(unsigned long now,
1317 					    unsigned long expires)
1318 {
1319 	ktime_t hr_delta = hrtimer_get_next_event();
1320 	struct timespec tsdelta;
1321 	unsigned long delta;
1322 
1323 	if (hr_delta.tv64 == KTIME_MAX)
1324 		return expires;
1325 
1326 	/*
1327 	 * Expired timer available, let it expire in the next tick
1328 	 */
1329 	if (hr_delta.tv64 <= 0)
1330 		return now + 1;
1331 
1332 	tsdelta = ktime_to_timespec(hr_delta);
1333 	delta = timespec_to_jiffies(&tsdelta);
1334 
1335 	/*
1336 	 * Limit the delta to the max value, which is checked in
1337 	 * tick_nohz_stop_sched_tick():
1338 	 */
1339 	if (delta > NEXT_TIMER_MAX_DELTA)
1340 		delta = NEXT_TIMER_MAX_DELTA;
1341 
1342 	/*
1343 	 * Take rounding errors in to account and make sure, that it
1344 	 * expires in the next tick. Otherwise we go into an endless
1345 	 * ping pong due to tick_nohz_stop_sched_tick() retriggering
1346 	 * the timer softirq
1347 	 */
1348 	if (delta < 1)
1349 		delta = 1;
1350 	now += delta;
1351 	if (time_before(now, expires))
1352 		return now;
1353 	return expires;
1354 }
1355 
1356 /**
1357  * get_next_timer_interrupt - return the jiffy of the next pending timer
1358  * @now: current time (in jiffies)
1359  */
get_next_timer_interrupt(unsigned long now)1360 unsigned long get_next_timer_interrupt(unsigned long now)
1361 {
1362 	struct tvec_base *base = __this_cpu_read(tvec_bases);
1363 	unsigned long expires = now + NEXT_TIMER_MAX_DELTA;
1364 
1365 	/*
1366 	 * Pretend that there is no timer pending if the cpu is offline.
1367 	 * Possible pending timers will be migrated later to an active cpu.
1368 	 */
1369 	if (cpu_is_offline(smp_processor_id()))
1370 		return expires;
1371 
1372 	spin_lock(&base->lock);
1373 	if (base->active_timers) {
1374 		if (time_before_eq(base->next_timer, base->timer_jiffies))
1375 			base->next_timer = __next_timer_interrupt(base);
1376 		expires = base->next_timer;
1377 	}
1378 	spin_unlock(&base->lock);
1379 
1380 	if (time_before_eq(expires, now))
1381 		return now;
1382 
1383 	return cmp_next_hrtimer_event(now, expires);
1384 }
1385 #endif
1386 
1387 /*
1388  * Called from the timer interrupt handler to charge one tick to the current
1389  * process.  user_tick is 1 if the tick is user time, 0 for system.
1390  */
update_process_times(int user_tick)1391 void update_process_times(int user_tick)
1392 {
1393 	struct task_struct *p = current;
1394 	int cpu = smp_processor_id();
1395 
1396 	/* Note: this timer irq context must be accounted for as well. */
1397 	account_process_tick(p, user_tick);
1398 	run_local_timers();
1399 	rcu_check_callbacks(cpu, user_tick);
1400 #ifdef CONFIG_IRQ_WORK
1401 	if (in_irq())
1402 		irq_work_tick();
1403 #endif
1404 	scheduler_tick();
1405 	run_posix_cpu_timers(p);
1406 }
1407 
1408 /*
1409  * This function runs timers and the timer-tq in bottom half context.
1410  */
run_timer_softirq(struct softirq_action * h)1411 static void run_timer_softirq(struct softirq_action *h)
1412 {
1413 	struct tvec_base *base = __this_cpu_read(tvec_bases);
1414 
1415 	hrtimer_run_pending();
1416 
1417 	if (time_after_eq(jiffies, base->timer_jiffies))
1418 		__run_timers(base);
1419 }
1420 
1421 /*
1422  * Called by the local, per-CPU timer interrupt on SMP.
1423  */
run_local_timers(void)1424 void run_local_timers(void)
1425 {
1426 	hrtimer_run_queues();
1427 	raise_softirq(TIMER_SOFTIRQ);
1428 }
1429 
1430 #ifdef __ARCH_WANT_SYS_ALARM
1431 
1432 /*
1433  * For backwards compatibility?  This can be done in libc so Alpha
1434  * and all newer ports shouldn't need it.
1435  */
SYSCALL_DEFINE1(alarm,unsigned int,seconds)1436 SYSCALL_DEFINE1(alarm, unsigned int, seconds)
1437 {
1438 	return alarm_setitimer(seconds);
1439 }
1440 
1441 #endif
1442 
process_timeout(unsigned long __data)1443 static void process_timeout(unsigned long __data)
1444 {
1445 	wake_up_process((struct task_struct *)__data);
1446 }
1447 
1448 /**
1449  * schedule_timeout - sleep until timeout
1450  * @timeout: timeout value in jiffies
1451  *
1452  * Make the current task sleep until @timeout jiffies have
1453  * elapsed. The routine will return immediately unless
1454  * the current task state has been set (see set_current_state()).
1455  *
1456  * You can set the task state as follows -
1457  *
1458  * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1459  * pass before the routine returns. The routine will return 0
1460  *
1461  * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1462  * delivered to the current task. In this case the remaining time
1463  * in jiffies will be returned, or 0 if the timer expired in time
1464  *
1465  * The current task state is guaranteed to be TASK_RUNNING when this
1466  * routine returns.
1467  *
1468  * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1469  * the CPU away without a bound on the timeout. In this case the return
1470  * value will be %MAX_SCHEDULE_TIMEOUT.
1471  *
1472  * In all cases the return value is guaranteed to be non-negative.
1473  */
schedule_timeout(signed long timeout)1474 signed long __sched schedule_timeout(signed long timeout)
1475 {
1476 	struct timer_list timer;
1477 	unsigned long expire;
1478 
1479 	switch (timeout)
1480 	{
1481 	case MAX_SCHEDULE_TIMEOUT:
1482 		/*
1483 		 * These two special cases are useful to be comfortable
1484 		 * in the caller. Nothing more. We could take
1485 		 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1486 		 * but I' d like to return a valid offset (>=0) to allow
1487 		 * the caller to do everything it want with the retval.
1488 		 */
1489 		schedule();
1490 		goto out;
1491 	default:
1492 		/*
1493 		 * Another bit of PARANOID. Note that the retval will be
1494 		 * 0 since no piece of kernel is supposed to do a check
1495 		 * for a negative retval of schedule_timeout() (since it
1496 		 * should never happens anyway). You just have the printk()
1497 		 * that will tell you if something is gone wrong and where.
1498 		 */
1499 		if (timeout < 0) {
1500 			printk(KERN_ERR "schedule_timeout: wrong timeout "
1501 				"value %lx\n", timeout);
1502 			dump_stack();
1503 			current->state = TASK_RUNNING;
1504 			goto out;
1505 		}
1506 	}
1507 
1508 	expire = timeout + jiffies;
1509 
1510 	setup_timer_on_stack(&timer, process_timeout, (unsigned long)current);
1511 	__mod_timer(&timer, expire, false, TIMER_NOT_PINNED);
1512 	schedule();
1513 	del_singleshot_timer_sync(&timer);
1514 
1515 	/* Remove the timer from the object tracker */
1516 	destroy_timer_on_stack(&timer);
1517 
1518 	timeout = expire - jiffies;
1519 
1520  out:
1521 	return timeout < 0 ? 0 : timeout;
1522 }
1523 EXPORT_SYMBOL(schedule_timeout);
1524 
1525 /*
1526  * We can use __set_current_state() here because schedule_timeout() calls
1527  * schedule() unconditionally.
1528  */
schedule_timeout_interruptible(signed long timeout)1529 signed long __sched schedule_timeout_interruptible(signed long timeout)
1530 {
1531 	__set_current_state(TASK_INTERRUPTIBLE);
1532 	return schedule_timeout(timeout);
1533 }
1534 EXPORT_SYMBOL(schedule_timeout_interruptible);
1535 
schedule_timeout_killable(signed long timeout)1536 signed long __sched schedule_timeout_killable(signed long timeout)
1537 {
1538 	__set_current_state(TASK_KILLABLE);
1539 	return schedule_timeout(timeout);
1540 }
1541 EXPORT_SYMBOL(schedule_timeout_killable);
1542 
schedule_timeout_uninterruptible(signed long timeout)1543 signed long __sched schedule_timeout_uninterruptible(signed long timeout)
1544 {
1545 	__set_current_state(TASK_UNINTERRUPTIBLE);
1546 	return schedule_timeout(timeout);
1547 }
1548 EXPORT_SYMBOL(schedule_timeout_uninterruptible);
1549 
init_timers_cpu(int cpu)1550 static int init_timers_cpu(int cpu)
1551 {
1552 	int j;
1553 	struct tvec_base *base;
1554 	static char tvec_base_done[NR_CPUS];
1555 
1556 	if (!tvec_base_done[cpu]) {
1557 		static char boot_done;
1558 
1559 		if (boot_done) {
1560 			/*
1561 			 * The APs use this path later in boot
1562 			 */
1563 			base = kzalloc_node(sizeof(*base), GFP_KERNEL,
1564 					    cpu_to_node(cpu));
1565 			if (!base)
1566 				return -ENOMEM;
1567 
1568 			/* Make sure tvec_base has TIMER_FLAG_MASK bits free */
1569 			if (WARN_ON(base != tbase_get_base(base))) {
1570 				kfree(base);
1571 				return -ENOMEM;
1572 			}
1573 			per_cpu(tvec_bases, cpu) = base;
1574 		} else {
1575 			/*
1576 			 * This is for the boot CPU - we use compile-time
1577 			 * static initialisation because per-cpu memory isn't
1578 			 * ready yet and because the memory allocators are not
1579 			 * initialised either.
1580 			 */
1581 			boot_done = 1;
1582 			base = &boot_tvec_bases;
1583 		}
1584 		spin_lock_init(&base->lock);
1585 		tvec_base_done[cpu] = 1;
1586 		base->cpu = cpu;
1587 	} else {
1588 		base = per_cpu(tvec_bases, cpu);
1589 	}
1590 
1591 
1592 	for (j = 0; j < TVN_SIZE; j++) {
1593 		INIT_LIST_HEAD(base->tv5.vec + j);
1594 		INIT_LIST_HEAD(base->tv4.vec + j);
1595 		INIT_LIST_HEAD(base->tv3.vec + j);
1596 		INIT_LIST_HEAD(base->tv2.vec + j);
1597 	}
1598 	for (j = 0; j < TVR_SIZE; j++)
1599 		INIT_LIST_HEAD(base->tv1.vec + j);
1600 
1601 	base->timer_jiffies = jiffies;
1602 	base->next_timer = base->timer_jiffies;
1603 	base->active_timers = 0;
1604 	base->all_timers = 0;
1605 	return 0;
1606 }
1607 
1608 #ifdef CONFIG_HOTPLUG_CPU
migrate_timer_list(struct tvec_base * new_base,struct list_head * head)1609 static void migrate_timer_list(struct tvec_base *new_base, struct list_head *head)
1610 {
1611 	struct timer_list *timer;
1612 
1613 	while (!list_empty(head)) {
1614 		timer = list_first_entry(head, struct timer_list, entry);
1615 		/* We ignore the accounting on the dying cpu */
1616 		detach_timer(timer, false);
1617 		timer_set_base(timer, new_base);
1618 		internal_add_timer(new_base, timer);
1619 	}
1620 }
1621 
migrate_timers(int cpu)1622 static void migrate_timers(int cpu)
1623 {
1624 	struct tvec_base *old_base;
1625 	struct tvec_base *new_base;
1626 	int i;
1627 
1628 	BUG_ON(cpu_online(cpu));
1629 	old_base = per_cpu(tvec_bases, cpu);
1630 	new_base = get_cpu_var(tvec_bases);
1631 	/*
1632 	 * The caller is globally serialized and nobody else
1633 	 * takes two locks at once, deadlock is not possible.
1634 	 */
1635 	spin_lock_irq(&new_base->lock);
1636 	spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1637 
1638 	BUG_ON(old_base->running_timer);
1639 
1640 	for (i = 0; i < TVR_SIZE; i++)
1641 		migrate_timer_list(new_base, old_base->tv1.vec + i);
1642 	for (i = 0; i < TVN_SIZE; i++) {
1643 		migrate_timer_list(new_base, old_base->tv2.vec + i);
1644 		migrate_timer_list(new_base, old_base->tv3.vec + i);
1645 		migrate_timer_list(new_base, old_base->tv4.vec + i);
1646 		migrate_timer_list(new_base, old_base->tv5.vec + i);
1647 	}
1648 
1649 	spin_unlock(&old_base->lock);
1650 	spin_unlock_irq(&new_base->lock);
1651 	put_cpu_var(tvec_bases);
1652 }
1653 #endif /* CONFIG_HOTPLUG_CPU */
1654 
timer_cpu_notify(struct notifier_block * self,unsigned long action,void * hcpu)1655 static int timer_cpu_notify(struct notifier_block *self,
1656 				unsigned long action, void *hcpu)
1657 {
1658 	long cpu = (long)hcpu;
1659 	int err;
1660 
1661 	switch(action) {
1662 	case CPU_UP_PREPARE:
1663 	case CPU_UP_PREPARE_FROZEN:
1664 		err = init_timers_cpu(cpu);
1665 		if (err < 0)
1666 			return notifier_from_errno(err);
1667 		break;
1668 #ifdef CONFIG_HOTPLUG_CPU
1669 	case CPU_DEAD:
1670 	case CPU_DEAD_FROZEN:
1671 		migrate_timers(cpu);
1672 		break;
1673 #endif
1674 	default:
1675 		break;
1676 	}
1677 	return NOTIFY_OK;
1678 }
1679 
1680 static struct notifier_block timers_nb = {
1681 	.notifier_call	= timer_cpu_notify,
1682 };
1683 
1684 
init_timers(void)1685 void __init init_timers(void)
1686 {
1687 	int err;
1688 
1689 	/* ensure there are enough low bits for flags in timer->base pointer */
1690 	BUILD_BUG_ON(__alignof__(struct tvec_base) & TIMER_FLAG_MASK);
1691 
1692 	err = timer_cpu_notify(&timers_nb, (unsigned long)CPU_UP_PREPARE,
1693 			       (void *)(long)smp_processor_id());
1694 	BUG_ON(err != NOTIFY_OK);
1695 
1696 	init_timer_stats();
1697 	register_cpu_notifier(&timers_nb);
1698 	open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
1699 }
1700 
1701 /**
1702  * msleep - sleep safely even with waitqueue interruptions
1703  * @msecs: Time in milliseconds to sleep for
1704  */
msleep(unsigned int msecs)1705 void msleep(unsigned int msecs)
1706 {
1707 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1708 
1709 	while (timeout)
1710 		timeout = schedule_timeout_uninterruptible(timeout);
1711 }
1712 
1713 EXPORT_SYMBOL(msleep);
1714 
1715 /**
1716  * msleep_interruptible - sleep waiting for signals
1717  * @msecs: Time in milliseconds to sleep for
1718  */
msleep_interruptible(unsigned int msecs)1719 unsigned long msleep_interruptible(unsigned int msecs)
1720 {
1721 	unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1722 
1723 	while (timeout && !signal_pending(current))
1724 		timeout = schedule_timeout_interruptible(timeout);
1725 	return jiffies_to_msecs(timeout);
1726 }
1727 
1728 EXPORT_SYMBOL(msleep_interruptible);
1729 
do_usleep_range(unsigned long min,unsigned long max)1730 static int __sched do_usleep_range(unsigned long min, unsigned long max)
1731 {
1732 	ktime_t kmin;
1733 	unsigned long delta;
1734 
1735 	kmin = ktime_set(0, min * NSEC_PER_USEC);
1736 	delta = (max - min) * NSEC_PER_USEC;
1737 	return schedule_hrtimeout_range(&kmin, delta, HRTIMER_MODE_REL);
1738 }
1739 
1740 /**
1741  * usleep_range - Drop in replacement for udelay where wakeup is flexible
1742  * @min: Minimum time in usecs to sleep
1743  * @max: Maximum time in usecs to sleep
1744  */
usleep_range(unsigned long min,unsigned long max)1745 void usleep_range(unsigned long min, unsigned long max)
1746 {
1747 	__set_current_state(TASK_UNINTERRUPTIBLE);
1748 	do_usleep_range(min, max);
1749 }
1750 EXPORT_SYMBOL(usleep_range);
1751