4 * Kernel internal timers
6 * Copyright (C) 1991, 1992 Linus Torvalds
8 * 1997-01-28 Modified by Finn Arne Gangstad to make timers scale better.
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
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>
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>
46 #include <asm/uaccess.h>
47 #include <asm/unistd.h>
48 #include <asm/div64.h>
49 #include <asm/timex.h>
52 #include "tick-internal.h"
54 #define CREATE_TRACE_POINTS
55 #include <trace/events/timer.h>
57 __visible u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES;
59 EXPORT_SYMBOL(jiffies_64);
62 * per-CPU timer vector definitions:
64 #define TVN_BITS (CONFIG_BASE_SMALL ? 4 : 6)
65 #define TVR_BITS (CONFIG_BASE_SMALL ? 6 : 8)
66 #define TVN_SIZE (1 << TVN_BITS)
67 #define TVR_SIZE (1 << TVR_BITS)
68 #define TVN_MASK (TVN_SIZE - 1)
69 #define TVR_MASK (TVR_SIZE - 1)
70 #define MAX_TVAL ((unsigned long)((1ULL << (TVR_BITS + 4*TVN_BITS)) - 1))
73 struct hlist_head vec[TVN_SIZE];
77 struct hlist_head vec[TVR_SIZE];
82 struct timer_list *running_timer;
83 unsigned long timer_jiffies;
84 unsigned long next_timer;
85 unsigned long active_timers;
86 unsigned long all_timers;
88 bool migration_enabled;
94 } ____cacheline_aligned;
97 static DEFINE_PER_CPU(struct tvec_base, tvec_bases);
99 #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
100 unsigned int sysctl_timer_migration = 1;
102 void timers_update_migration(void)
104 bool on = sysctl_timer_migration && tick_nohz_active;
107 /* Avoid the loop, if nothing to update */
108 if (this_cpu_read(tvec_bases.migration_enabled) == on)
111 for_each_possible_cpu(cpu) {
112 per_cpu(tvec_bases.migration_enabled, cpu) = on;
113 per_cpu(hrtimer_bases.migration_enabled, cpu) = on;
117 int timer_migration_handler(struct ctl_table *table, int write,
118 void __user *buffer, size_t *lenp,
121 static DEFINE_MUTEX(mutex);
125 ret = proc_dointvec(table, write, buffer, lenp, ppos);
127 timers_update_migration();
128 mutex_unlock(&mutex);
132 static inline struct tvec_base *get_target_base(struct tvec_base *base,
135 if (pinned || !base->migration_enabled)
136 return this_cpu_ptr(&tvec_bases);
137 return per_cpu_ptr(&tvec_bases, get_nohz_timer_target());
140 static inline struct tvec_base *get_target_base(struct tvec_base *base,
143 return this_cpu_ptr(&tvec_bases);
147 static unsigned long round_jiffies_common(unsigned long j, int cpu,
151 unsigned long original = j;
154 * We don't want all cpus firing their timers at once hitting the
155 * same lock or cachelines, so we skew each extra cpu with an extra
156 * 3 jiffies. This 3 jiffies came originally from the mm/ code which
158 * The skew is done by adding 3*cpunr, then round, then subtract this
159 * extra offset again.
166 * If the target jiffie is just after a whole second (which can happen
167 * due to delays of the timer irq, long irq off times etc etc) then
168 * we should round down to the whole second, not up. Use 1/4th second
169 * as cutoff for this rounding as an extreme upper bound for this.
170 * But never round down if @force_up is set.
172 if (rem < HZ/4 && !force_up) /* round down */
177 /* now that we have rounded, subtract the extra skew again */
181 * Make sure j is still in the future. Otherwise return the
184 return time_is_after_jiffies(j) ? j : original;
188 * __round_jiffies - function to round jiffies to a full second
189 * @j: the time in (absolute) jiffies that should be rounded
190 * @cpu: the processor number on which the timeout will happen
192 * __round_jiffies() rounds an absolute time 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.
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.
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.
205 * The return value is the rounded version of the @j parameter.
207 unsigned long __round_jiffies(unsigned long j, int cpu)
209 return round_jiffies_common(j, cpu, false);
211 EXPORT_SYMBOL_GPL(__round_jiffies);
214 * __round_jiffies_relative - function to round jiffies to a full second
215 * @j: the time in (relative) jiffies that should be rounded
216 * @cpu: the processor number on which the timeout will happen
218 * __round_jiffies_relative() rounds a time delta in the future (in jiffies)
219 * up or down to (approximately) full seconds. This is useful for timers
220 * for which the exact time they fire does not matter too much, as long as
221 * they fire approximately every X seconds.
223 * By rounding these timers to whole seconds, all such timers will fire
224 * at the same time, rather than at various times spread out. The goal
225 * of this is to have the CPU wake up less, which saves power.
227 * The exact rounding is skewed for each processor to avoid all
228 * processors firing at the exact same time, which could lead
229 * to lock contention or spurious cache line bouncing.
231 * The return value is the rounded version of the @j parameter.
233 unsigned long __round_jiffies_relative(unsigned long j, int cpu)
235 unsigned long j0 = jiffies;
237 /* Use j0 because jiffies might change while we run */
238 return round_jiffies_common(j + j0, cpu, false) - j0;
240 EXPORT_SYMBOL_GPL(__round_jiffies_relative);
243 * round_jiffies - function to round jiffies to a full second
244 * @j: the time in (absolute) jiffies that should be rounded
246 * round_jiffies() rounds an absolute time in the future (in jiffies)
247 * up or down to (approximately) full seconds. This is useful for timers
248 * for which the exact time they fire does not matter too much, as long as
249 * they fire approximately every X seconds.
251 * By rounding these timers to whole seconds, all such timers will fire
252 * at the same time, rather than at various times spread out. The goal
253 * of this is to have the CPU wake up less, which saves power.
255 * The return value is the rounded version of the @j parameter.
257 unsigned long round_jiffies(unsigned long j)
259 return round_jiffies_common(j, raw_smp_processor_id(), false);
261 EXPORT_SYMBOL_GPL(round_jiffies);
264 * round_jiffies_relative - function to round jiffies to a full second
265 * @j: the time in (relative) jiffies that should be rounded
267 * round_jiffies_relative() rounds a time delta in the future (in jiffies)
268 * up or down to (approximately) full seconds. This is useful for timers
269 * for which the exact time they fire does not matter too much, as long as
270 * they fire approximately every X seconds.
272 * By rounding these timers to whole seconds, all such timers will fire
273 * at the same time, rather than at various times spread out. The goal
274 * of this is to have the CPU wake up less, which saves power.
276 * The return value is the rounded version of the @j parameter.
278 unsigned long round_jiffies_relative(unsigned long j)
280 return __round_jiffies_relative(j, raw_smp_processor_id());
282 EXPORT_SYMBOL_GPL(round_jiffies_relative);
285 * __round_jiffies_up - function to round jiffies up to a full second
286 * @j: the time in (absolute) jiffies that should be rounded
287 * @cpu: the processor number on which the timeout will happen
289 * This is the same as __round_jiffies() except that it will never
290 * round down. This is useful for timeouts for which the exact time
291 * of firing does not matter too much, as long as they don't fire too
294 unsigned long __round_jiffies_up(unsigned long j, int cpu)
296 return round_jiffies_common(j, cpu, true);
298 EXPORT_SYMBOL_GPL(__round_jiffies_up);
301 * __round_jiffies_up_relative - function to round jiffies up to a full second
302 * @j: the time in (relative) jiffies that should be rounded
303 * @cpu: the processor number on which the timeout will happen
305 * This is the same as __round_jiffies_relative() except that it will never
306 * round down. This is useful for timeouts for which the exact time
307 * of firing does not matter too much, as long as they don't fire too
310 unsigned long __round_jiffies_up_relative(unsigned long j, int cpu)
312 unsigned long j0 = jiffies;
314 /* Use j0 because jiffies might change while we run */
315 return round_jiffies_common(j + j0, cpu, true) - j0;
317 EXPORT_SYMBOL_GPL(__round_jiffies_up_relative);
320 * round_jiffies_up - function to round jiffies up to a full second
321 * @j: the time in (absolute) jiffies that should be rounded
323 * This is the same as round_jiffies() except that it will never
324 * round down. This is useful for timeouts for which the exact time
325 * of firing does not matter too much, as long as they don't fire too
328 unsigned long round_jiffies_up(unsigned long j)
330 return round_jiffies_common(j, raw_smp_processor_id(), true);
332 EXPORT_SYMBOL_GPL(round_jiffies_up);
335 * round_jiffies_up_relative - function to round jiffies up to a full second
336 * @j: the time in (relative) jiffies that should be rounded
338 * This is the same as round_jiffies_relative() except that it will never
339 * round down. This is useful for timeouts for which the exact time
340 * of firing does not matter too much, as long as they don't fire too
343 unsigned long round_jiffies_up_relative(unsigned long j)
345 return __round_jiffies_up_relative(j, raw_smp_processor_id());
347 EXPORT_SYMBOL_GPL(round_jiffies_up_relative);
350 * set_timer_slack - set the allowed slack for a timer
351 * @timer: the timer to be modified
352 * @slack_hz: the amount of time (in jiffies) allowed for rounding
354 * Set the amount of time, in jiffies, that a certain timer has
355 * in terms of slack. By setting this value, the timer subsystem
356 * will schedule the actual timer somewhere between
357 * the time mod_timer() asks for, and that time plus the slack.
359 * By setting the slack to -1, a percentage of the delay is used
362 void set_timer_slack(struct timer_list *timer, int slack_hz)
364 timer->slack = slack_hz;
366 EXPORT_SYMBOL_GPL(set_timer_slack);
369 __internal_add_timer(struct tvec_base *base, struct timer_list *timer)
371 unsigned long expires = timer->expires;
372 unsigned long idx = expires - base->timer_jiffies;
373 struct hlist_head *vec;
375 if (idx < TVR_SIZE) {
376 int i = expires & TVR_MASK;
377 vec = base->tv1.vec + i;
378 } else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
379 int i = (expires >> TVR_BITS) & TVN_MASK;
380 vec = base->tv2.vec + i;
381 } else if (idx < 1 << (TVR_BITS + 2 * TVN_BITS)) {
382 int i = (expires >> (TVR_BITS + TVN_BITS)) & TVN_MASK;
383 vec = base->tv3.vec + i;
384 } else if (idx < 1 << (TVR_BITS + 3 * TVN_BITS)) {
385 int i = (expires >> (TVR_BITS + 2 * TVN_BITS)) & TVN_MASK;
386 vec = base->tv4.vec + i;
387 } else if ((signed long) idx < 0) {
389 * Can happen if you add a timer with expires == jiffies,
390 * or you set a timer to go off in the past
392 vec = base->tv1.vec + (base->timer_jiffies & TVR_MASK);
395 /* If the timeout is larger than MAX_TVAL (on 64-bit
396 * architectures or with CONFIG_BASE_SMALL=1) then we
397 * use the maximum timeout.
399 if (idx > MAX_TVAL) {
401 expires = idx + base->timer_jiffies;
403 i = (expires >> (TVR_BITS + 3 * TVN_BITS)) & TVN_MASK;
404 vec = base->tv5.vec + i;
407 hlist_add_head(&timer->entry, vec);
410 static void internal_add_timer(struct tvec_base *base, struct timer_list *timer)
412 /* Advance base->jiffies, if the base is empty */
413 if (!base->all_timers++)
414 base->timer_jiffies = jiffies;
416 __internal_add_timer(base, timer);
418 * Update base->active_timers and base->next_timer
420 if (!(timer->flags & TIMER_DEFERRABLE)) {
421 if (!base->active_timers++ ||
422 time_before(timer->expires, base->next_timer))
423 base->next_timer = timer->expires;
427 * Check whether the other CPU is in dynticks mode and needs
428 * to be triggered to reevaluate the timer wheel.
429 * We are protected against the other CPU fiddling
430 * with the timer by holding the timer base lock. This also
431 * makes sure that a CPU on the way to stop its tick can not
432 * evaluate the timer wheel.
434 * Spare the IPI for deferrable timers on idle targets though.
435 * The next busy ticks will take care of it. Except full dynticks
436 * require special care against races with idle_cpu(), lets deal
439 if (!(timer->flags & TIMER_DEFERRABLE) || tick_nohz_full_cpu(base->cpu))
440 wake_up_nohz_cpu(base->cpu);
443 #ifdef CONFIG_TIMER_STATS
444 void __timer_stats_timer_set_start_info(struct timer_list *timer, void *addr)
446 if (timer->start_site)
449 timer->start_site = addr;
450 memcpy(timer->start_comm, current->comm, TASK_COMM_LEN);
451 timer->start_pid = current->pid;
454 static void timer_stats_account_timer(struct timer_list *timer)
456 if (likely(!timer->start_site))
459 timer_stats_update_stats(timer, timer->start_pid, timer->start_site,
460 timer->function, timer->start_comm,
465 static void timer_stats_account_timer(struct timer_list *timer) {}
468 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
470 static struct debug_obj_descr timer_debug_descr;
472 static void *timer_debug_hint(void *addr)
474 return ((struct timer_list *) addr)->function;
478 * fixup_init is called when:
479 * - an active object is initialized
481 static int timer_fixup_init(void *addr, enum debug_obj_state state)
483 struct timer_list *timer = addr;
486 case ODEBUG_STATE_ACTIVE:
487 del_timer_sync(timer);
488 debug_object_init(timer, &timer_debug_descr);
495 /* Stub timer callback for improperly used timers. */
496 static void stub_timer(unsigned long data)
502 * fixup_activate is called when:
503 * - an active object is activated
504 * - an unknown object is activated (might be a statically initialized object)
506 static int timer_fixup_activate(void *addr, enum debug_obj_state state)
508 struct timer_list *timer = addr;
512 case ODEBUG_STATE_NOTAVAILABLE:
514 * This is not really a fixup. The timer was
515 * statically initialized. We just make sure that it
516 * is tracked in the object tracker.
518 if (timer->entry.pprev == NULL &&
519 timer->entry.next == TIMER_ENTRY_STATIC) {
520 debug_object_init(timer, &timer_debug_descr);
521 debug_object_activate(timer, &timer_debug_descr);
524 setup_timer(timer, stub_timer, 0);
529 case ODEBUG_STATE_ACTIVE:
538 * fixup_free is called when:
539 * - an active object is freed
541 static int timer_fixup_free(void *addr, enum debug_obj_state state)
543 struct timer_list *timer = addr;
546 case ODEBUG_STATE_ACTIVE:
547 del_timer_sync(timer);
548 debug_object_free(timer, &timer_debug_descr);
556 * fixup_assert_init is called when:
557 * - an untracked/uninit-ed object is found
559 static int timer_fixup_assert_init(void *addr, enum debug_obj_state state)
561 struct timer_list *timer = addr;
564 case ODEBUG_STATE_NOTAVAILABLE:
565 if (timer->entry.next == TIMER_ENTRY_STATIC) {
567 * This is not really a fixup. The timer was
568 * statically initialized. We just make sure that it
569 * is tracked in the object tracker.
571 debug_object_init(timer, &timer_debug_descr);
574 setup_timer(timer, stub_timer, 0);
582 static struct debug_obj_descr timer_debug_descr = {
583 .name = "timer_list",
584 .debug_hint = timer_debug_hint,
585 .fixup_init = timer_fixup_init,
586 .fixup_activate = timer_fixup_activate,
587 .fixup_free = timer_fixup_free,
588 .fixup_assert_init = timer_fixup_assert_init,
591 static inline void debug_timer_init(struct timer_list *timer)
593 debug_object_init(timer, &timer_debug_descr);
596 static inline void debug_timer_activate(struct timer_list *timer)
598 debug_object_activate(timer, &timer_debug_descr);
601 static inline void debug_timer_deactivate(struct timer_list *timer)
603 debug_object_deactivate(timer, &timer_debug_descr);
606 static inline void debug_timer_free(struct timer_list *timer)
608 debug_object_free(timer, &timer_debug_descr);
611 static inline void debug_timer_assert_init(struct timer_list *timer)
613 debug_object_assert_init(timer, &timer_debug_descr);
616 static void do_init_timer(struct timer_list *timer, unsigned int flags,
617 const char *name, struct lock_class_key *key);
619 void init_timer_on_stack_key(struct timer_list *timer, unsigned int flags,
620 const char *name, struct lock_class_key *key)
622 debug_object_init_on_stack(timer, &timer_debug_descr);
623 do_init_timer(timer, flags, name, key);
625 EXPORT_SYMBOL_GPL(init_timer_on_stack_key);
627 void destroy_timer_on_stack(struct timer_list *timer)
629 debug_object_free(timer, &timer_debug_descr);
631 EXPORT_SYMBOL_GPL(destroy_timer_on_stack);
634 static inline void debug_timer_init(struct timer_list *timer) { }
635 static inline void debug_timer_activate(struct timer_list *timer) { }
636 static inline void debug_timer_deactivate(struct timer_list *timer) { }
637 static inline void debug_timer_assert_init(struct timer_list *timer) { }
640 static inline void debug_init(struct timer_list *timer)
642 debug_timer_init(timer);
643 trace_timer_init(timer);
647 debug_activate(struct timer_list *timer, unsigned long expires)
649 debug_timer_activate(timer);
650 trace_timer_start(timer, expires, timer->flags);
653 static inline void debug_deactivate(struct timer_list *timer)
655 debug_timer_deactivate(timer);
656 trace_timer_cancel(timer);
659 static inline void debug_assert_init(struct timer_list *timer)
661 debug_timer_assert_init(timer);
664 static void do_init_timer(struct timer_list *timer, unsigned int flags,
665 const char *name, struct lock_class_key *key)
667 timer->entry.pprev = NULL;
668 timer->flags = flags | raw_smp_processor_id();
670 #ifdef CONFIG_TIMER_STATS
671 timer->start_site = NULL;
672 timer->start_pid = -1;
673 memset(timer->start_comm, 0, TASK_COMM_LEN);
675 lockdep_init_map(&timer->lockdep_map, name, key, 0);
679 * init_timer_key - initialize a timer
680 * @timer: the timer to be initialized
681 * @flags: timer flags
682 * @name: name of the timer
683 * @key: lockdep class key of the fake lock used for tracking timer
684 * sync lock dependencies
686 * init_timer_key() must be done to a timer prior calling *any* of the
687 * other timer functions.
689 void init_timer_key(struct timer_list *timer, unsigned int flags,
690 const char *name, struct lock_class_key *key)
693 do_init_timer(timer, flags, name, key);
695 EXPORT_SYMBOL(init_timer_key);
697 static inline void detach_timer(struct timer_list *timer, bool clear_pending)
699 struct hlist_node *entry = &timer->entry;
701 debug_deactivate(timer);
706 entry->next = LIST_POISON2;
710 detach_expired_timer(struct timer_list *timer, struct tvec_base *base)
712 detach_timer(timer, true);
713 if (!(timer->flags & TIMER_DEFERRABLE))
714 base->active_timers--;
718 static int detach_if_pending(struct timer_list *timer, struct tvec_base *base,
721 if (!timer_pending(timer))
724 detach_timer(timer, clear_pending);
725 if (!(timer->flags & TIMER_DEFERRABLE)) {
726 base->active_timers--;
727 if (timer->expires == base->next_timer)
728 base->next_timer = base->timer_jiffies;
730 /* If this was the last timer, advance base->jiffies */
731 if (!--base->all_timers)
732 base->timer_jiffies = jiffies;
737 * We are using hashed locking: holding per_cpu(tvec_bases).lock
738 * means that all timers which are tied to this base via timer->base are
739 * locked, and the base itself is locked too.
741 * So __run_timers/migrate_timers can safely modify all timers which could
742 * be found on ->tvX lists.
744 * When the timer's base is locked and removed from the list, the
745 * TIMER_MIGRATING flag is set, FIXME
747 static struct tvec_base *lock_timer_base(struct timer_list *timer,
748 unsigned long *flags)
749 __acquires(timer->base->lock)
752 u32 tf = timer->flags;
753 struct tvec_base *base;
755 if (!(tf & TIMER_MIGRATING)) {
756 base = per_cpu_ptr(&tvec_bases, tf & TIMER_CPUMASK);
757 spin_lock_irqsave(&base->lock, *flags);
758 if (timer->flags == tf)
760 spin_unlock_irqrestore(&base->lock, *flags);
767 __mod_timer(struct timer_list *timer, unsigned long expires,
768 bool pending_only, int pinned)
770 struct tvec_base *base, *new_base;
774 timer_stats_timer_set_start_info(timer);
775 BUG_ON(!timer->function);
777 base = lock_timer_base(timer, &flags);
779 ret = detach_if_pending(timer, base, false);
780 if (!ret && pending_only)
783 debug_activate(timer, expires);
785 new_base = get_target_base(base, pinned);
787 if (base != new_base) {
789 * We are trying to schedule the timer on the local CPU.
790 * However we can't change timer's base while it is running,
791 * otherwise del_timer_sync() can't detect that the timer's
792 * handler yet has not finished. This also guarantees that
793 * the timer is serialized wrt itself.
795 if (likely(base->running_timer != timer)) {
796 /* See the comment in lock_timer_base() */
797 timer->flags |= TIMER_MIGRATING;
799 spin_unlock(&base->lock);
801 spin_lock(&base->lock);
802 timer->flags &= ~TIMER_BASEMASK;
803 timer->flags |= base->cpu;
807 timer->expires = expires;
808 internal_add_timer(base, timer);
811 spin_unlock_irqrestore(&base->lock, flags);
817 * mod_timer_pending - modify a pending timer's timeout
818 * @timer: the pending timer to be modified
819 * @expires: new timeout in jiffies
821 * mod_timer_pending() is the same for pending timers as mod_timer(),
822 * but will not re-activate and modify already deleted timers.
824 * It is useful for unserialized use of timers.
826 int mod_timer_pending(struct timer_list *timer, unsigned long expires)
828 return __mod_timer(timer, expires, true, TIMER_NOT_PINNED);
830 EXPORT_SYMBOL(mod_timer_pending);
833 * Decide where to put the timer while taking the slack into account
836 * 1) calculate the maximum (absolute) time
837 * 2) calculate the highest bit where the expires and new max are different
838 * 3) use this bit to make a mask
839 * 4) use the bitmask to round down the maximum time, so that all last
843 unsigned long apply_slack(struct timer_list *timer, unsigned long expires)
845 unsigned long expires_limit, mask;
848 if (timer->slack >= 0) {
849 expires_limit = expires + timer->slack;
851 long delta = expires - jiffies;
856 expires_limit = expires + delta / 256;
858 mask = expires ^ expires_limit;
862 bit = find_last_bit(&mask, BITS_PER_LONG);
864 mask = (1UL << bit) - 1;
866 expires_limit = expires_limit & ~(mask);
868 return expires_limit;
872 * mod_timer - modify a timer's timeout
873 * @timer: the timer to be modified
874 * @expires: new timeout in jiffies
876 * mod_timer() is a more efficient way to update the expire field of an
877 * active timer (if the timer is inactive it will be activated)
879 * mod_timer(timer, expires) is equivalent to:
881 * del_timer(timer); timer->expires = expires; add_timer(timer);
883 * Note that if there are multiple unserialized concurrent users of the
884 * same timer, then mod_timer() is the only safe way to modify the timeout,
885 * since add_timer() cannot modify an already running timer.
887 * The function returns whether it has modified a pending timer or not.
888 * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an
889 * active timer returns 1.)
891 int mod_timer(struct timer_list *timer, unsigned long expires)
893 expires = apply_slack(timer, expires);
896 * This is a common optimization triggered by the
897 * networking code - if the timer is re-modified
898 * to be the same thing then just return:
900 if (timer_pending(timer) && timer->expires == expires)
903 return __mod_timer(timer, expires, false, TIMER_NOT_PINNED);
905 EXPORT_SYMBOL(mod_timer);
908 * mod_timer_pinned - modify a timer's timeout
909 * @timer: the timer to be modified
910 * @expires: new timeout in jiffies
912 * mod_timer_pinned() is a way to update the expire field of an
913 * active timer (if the timer is inactive it will be activated)
914 * and to ensure that the timer is scheduled on the current CPU.
916 * Note that this does not prevent the timer from being migrated
917 * when the current CPU goes offline. If this is a problem for
918 * you, use CPU-hotplug notifiers to handle it correctly, for
919 * example, cancelling the timer when the corresponding CPU goes
922 * mod_timer_pinned(timer, expires) is equivalent to:
924 * del_timer(timer); timer->expires = expires; add_timer(timer);
926 int mod_timer_pinned(struct timer_list *timer, unsigned long expires)
928 if (timer->expires == expires && timer_pending(timer))
931 return __mod_timer(timer, expires, false, TIMER_PINNED);
933 EXPORT_SYMBOL(mod_timer_pinned);
936 * add_timer - start a timer
937 * @timer: the timer to be added
939 * The kernel will do a ->function(->data) callback from the
940 * timer interrupt at the ->expires point in the future. The
941 * current time is 'jiffies'.
943 * The timer's ->expires, ->function (and if the handler uses it, ->data)
944 * fields must be set prior calling this function.
946 * Timers with an ->expires field in the past will be executed in the next
949 void add_timer(struct timer_list *timer)
951 BUG_ON(timer_pending(timer));
952 mod_timer(timer, timer->expires);
954 EXPORT_SYMBOL(add_timer);
957 * add_timer_on - start a timer on a particular CPU
958 * @timer: the timer to be added
959 * @cpu: the CPU to start it on
961 * This is not very scalable on SMP. Double adds are not possible.
963 void add_timer_on(struct timer_list *timer, int cpu)
965 struct tvec_base *base = per_cpu_ptr(&tvec_bases, cpu);
968 timer_stats_timer_set_start_info(timer);
969 BUG_ON(timer_pending(timer) || !timer->function);
970 spin_lock_irqsave(&base->lock, flags);
971 timer->flags = (timer->flags & ~TIMER_BASEMASK) | cpu;
972 debug_activate(timer, timer->expires);
973 internal_add_timer(base, timer);
974 spin_unlock_irqrestore(&base->lock, flags);
976 EXPORT_SYMBOL_GPL(add_timer_on);
979 * del_timer - deactive a timer.
980 * @timer: the timer to be deactivated
982 * del_timer() deactivates a timer - this works on both active and inactive
985 * The function returns whether it has deactivated a pending timer or not.
986 * (ie. del_timer() of an inactive timer returns 0, del_timer() of an
987 * active timer returns 1.)
989 int del_timer(struct timer_list *timer)
991 struct tvec_base *base;
995 debug_assert_init(timer);
997 timer_stats_timer_clear_start_info(timer);
998 if (timer_pending(timer)) {
999 base = lock_timer_base(timer, &flags);
1000 ret = detach_if_pending(timer, base, true);
1001 spin_unlock_irqrestore(&base->lock, flags);
1006 EXPORT_SYMBOL(del_timer);
1009 * try_to_del_timer_sync - Try to deactivate a timer
1010 * @timer: timer do del
1012 * This function tries to deactivate a timer. Upon successful (ret >= 0)
1013 * exit the timer is not queued and the handler is not running on any CPU.
1015 int try_to_del_timer_sync(struct timer_list *timer)
1017 struct tvec_base *base;
1018 unsigned long flags;
1021 debug_assert_init(timer);
1023 base = lock_timer_base(timer, &flags);
1025 if (base->running_timer != timer) {
1026 timer_stats_timer_clear_start_info(timer);
1027 ret = detach_if_pending(timer, base, true);
1029 spin_unlock_irqrestore(&base->lock, flags);
1033 EXPORT_SYMBOL(try_to_del_timer_sync);
1037 * del_timer_sync - deactivate a timer and wait for the handler to finish.
1038 * @timer: the timer to be deactivated
1040 * This function only differs from del_timer() on SMP: besides deactivating
1041 * the timer it also makes sure the handler has finished executing on other
1044 * Synchronization rules: Callers must prevent restarting of the timer,
1045 * otherwise this function is meaningless. It must not be called from
1046 * interrupt contexts unless the timer is an irqsafe one. The caller must
1047 * not hold locks which would prevent completion of the timer's
1048 * handler. The timer's handler must not call add_timer_on(). Upon exit the
1049 * timer is not queued and the handler is not running on any CPU.
1051 * Note: For !irqsafe timers, you must not hold locks that are held in
1052 * interrupt context while calling this function. Even if the lock has
1053 * nothing to do with the timer in question. Here's why:
1059 * base->running_timer = mytimer;
1060 * spin_lock_irq(somelock);
1062 * spin_lock(somelock);
1063 * del_timer_sync(mytimer);
1064 * while (base->running_timer == mytimer);
1066 * Now del_timer_sync() will never return and never release somelock.
1067 * The interrupt on the other CPU is waiting to grab somelock but
1068 * it has interrupted the softirq that CPU0 is waiting to finish.
1070 * The function returns whether it has deactivated a pending timer or not.
1072 int del_timer_sync(struct timer_list *timer)
1074 #ifdef CONFIG_LOCKDEP
1075 unsigned long flags;
1078 * If lockdep gives a backtrace here, please reference
1079 * the synchronization rules above.
1081 local_irq_save(flags);
1082 lock_map_acquire(&timer->lockdep_map);
1083 lock_map_release(&timer->lockdep_map);
1084 local_irq_restore(flags);
1087 * don't use it in hardirq context, because it
1088 * could lead to deadlock.
1090 WARN_ON(in_irq() && !(timer->flags & TIMER_IRQSAFE));
1092 int ret = try_to_del_timer_sync(timer);
1098 EXPORT_SYMBOL(del_timer_sync);
1101 static int cascade(struct tvec_base *base, struct tvec *tv, int index)
1103 /* cascade all the timers from tv up one level */
1104 struct timer_list *timer;
1105 struct hlist_node *tmp;
1106 struct hlist_head tv_list;
1108 hlist_move_list(tv->vec + index, &tv_list);
1111 * We are removing _all_ timers from the list, so we
1112 * don't have to detach them individually.
1114 hlist_for_each_entry_safe(timer, tmp, &tv_list, entry) {
1115 /* No accounting, while moving them */
1116 __internal_add_timer(base, timer);
1122 static void call_timer_fn(struct timer_list *timer, void (*fn)(unsigned long),
1125 int count = preempt_count();
1127 #ifdef CONFIG_LOCKDEP
1129 * It is permissible to free the timer from inside the
1130 * function that is called from it, this we need to take into
1131 * account for lockdep too. To avoid bogus "held lock freed"
1132 * warnings as well as problems when looking into
1133 * timer->lockdep_map, make a copy and use that here.
1135 struct lockdep_map lockdep_map;
1137 lockdep_copy_map(&lockdep_map, &timer->lockdep_map);
1140 * Couple the lock chain with the lock chain at
1141 * del_timer_sync() by acquiring the lock_map around the fn()
1142 * call here and in del_timer_sync().
1144 lock_map_acquire(&lockdep_map);
1146 trace_timer_expire_entry(timer);
1148 trace_timer_expire_exit(timer);
1150 lock_map_release(&lockdep_map);
1152 if (count != preempt_count()) {
1153 WARN_ONCE(1, "timer: %pF preempt leak: %08x -> %08x\n",
1154 fn, count, preempt_count());
1156 * Restore the preempt count. That gives us a decent
1157 * chance to survive and extract information. If the
1158 * callback kept a lock held, bad luck, but not worse
1159 * than the BUG() we had.
1161 preempt_count_set(count);
1165 #define INDEX(N) ((base->timer_jiffies >> (TVR_BITS + (N) * TVN_BITS)) & TVN_MASK)
1168 * __run_timers - run all expired timers (if any) on this CPU.
1169 * @base: the timer vector to be processed.
1171 * This function cascades all vectors and executes all expired timer
1174 static inline void __run_timers(struct tvec_base *base)
1176 struct timer_list *timer;
1178 spin_lock_irq(&base->lock);
1180 while (time_after_eq(jiffies, base->timer_jiffies)) {
1181 struct hlist_head work_list;
1182 struct hlist_head *head = &work_list;
1185 if (!base->all_timers) {
1186 base->timer_jiffies = jiffies;
1190 index = base->timer_jiffies & TVR_MASK;
1196 (!cascade(base, &base->tv2, INDEX(0))) &&
1197 (!cascade(base, &base->tv3, INDEX(1))) &&
1198 !cascade(base, &base->tv4, INDEX(2)))
1199 cascade(base, &base->tv5, INDEX(3));
1200 ++base->timer_jiffies;
1201 hlist_move_list(base->tv1.vec + index, head);
1202 while (!hlist_empty(head)) {
1203 void (*fn)(unsigned long);
1207 timer = hlist_entry(head->first, struct timer_list, entry);
1208 fn = timer->function;
1210 irqsafe = timer->flags & TIMER_IRQSAFE;
1212 timer_stats_account_timer(timer);
1214 base->running_timer = timer;
1215 detach_expired_timer(timer, base);
1218 spin_unlock(&base->lock);
1219 call_timer_fn(timer, fn, data);
1220 spin_lock(&base->lock);
1222 spin_unlock_irq(&base->lock);
1223 call_timer_fn(timer, fn, data);
1224 spin_lock_irq(&base->lock);
1228 base->running_timer = NULL;
1229 spin_unlock_irq(&base->lock);
1232 #ifdef CONFIG_NO_HZ_COMMON
1234 * Find out when the next timer event is due to happen. This
1235 * is used on S/390 to stop all activity when a CPU is idle.
1236 * This function needs to be called with interrupts disabled.
1238 static unsigned long __next_timer_interrupt(struct tvec_base *base)
1240 unsigned long timer_jiffies = base->timer_jiffies;
1241 unsigned long expires = timer_jiffies + NEXT_TIMER_MAX_DELTA;
1242 int index, slot, array, found = 0;
1243 struct timer_list *nte;
1244 struct tvec *varray[4];
1246 /* Look for timer events in tv1. */
1247 index = slot = timer_jiffies & TVR_MASK;
1249 hlist_for_each_entry(nte, base->tv1.vec + slot, entry) {
1250 if (nte->flags & TIMER_DEFERRABLE)
1254 expires = nte->expires;
1255 /* Look at the cascade bucket(s)? */
1256 if (!index || slot < index)
1260 slot = (slot + 1) & TVR_MASK;
1261 } while (slot != index);
1264 /* Calculate the next cascade event */
1266 timer_jiffies += TVR_SIZE - index;
1267 timer_jiffies >>= TVR_BITS;
1269 /* Check tv2-tv5. */
1270 varray[0] = &base->tv2;
1271 varray[1] = &base->tv3;
1272 varray[2] = &base->tv4;
1273 varray[3] = &base->tv5;
1275 for (array = 0; array < 4; array++) {
1276 struct tvec *varp = varray[array];
1278 index = slot = timer_jiffies & TVN_MASK;
1280 hlist_for_each_entry(nte, varp->vec + slot, entry) {
1281 if (nte->flags & TIMER_DEFERRABLE)
1285 if (time_before(nte->expires, expires))
1286 expires = nte->expires;
1289 * Do we still search for the first timer or are
1290 * we looking up the cascade buckets ?
1293 /* Look at the cascade bucket(s)? */
1294 if (!index || slot < index)
1298 slot = (slot + 1) & TVN_MASK;
1299 } while (slot != index);
1302 timer_jiffies += TVN_SIZE - index;
1303 timer_jiffies >>= TVN_BITS;
1309 * Check, if the next hrtimer event is before the next timer wheel
1312 static u64 cmp_next_hrtimer_event(u64 basem, u64 expires)
1314 u64 nextevt = hrtimer_get_next_event();
1317 * If high resolution timers are enabled
1318 * hrtimer_get_next_event() returns KTIME_MAX.
1320 if (expires <= nextevt)
1324 * If the next timer is already expired, return the tick base
1325 * time so the tick is fired immediately.
1327 if (nextevt <= basem)
1331 * Round up to the next jiffie. High resolution timers are
1332 * off, so the hrtimers are expired in the tick and we need to
1333 * make sure that this tick really expires the timer to avoid
1334 * a ping pong of the nohz stop code.
1336 * Use DIV_ROUND_UP_ULL to prevent gcc calling __divdi3
1338 return DIV_ROUND_UP_ULL(nextevt, TICK_NSEC) * TICK_NSEC;
1342 * get_next_timer_interrupt - return the time (clock mono) of the next timer
1343 * @basej: base time jiffies
1344 * @basem: base time clock monotonic
1346 * Returns the tick aligned clock monotonic time of the next pending
1347 * timer or KTIME_MAX if no timer is pending.
1349 u64 get_next_timer_interrupt(unsigned long basej, u64 basem)
1351 struct tvec_base *base = this_cpu_ptr(&tvec_bases);
1352 u64 expires = KTIME_MAX;
1353 unsigned long nextevt;
1356 * Pretend that there is no timer pending if the cpu is offline.
1357 * Possible pending timers will be migrated later to an active cpu.
1359 if (cpu_is_offline(smp_processor_id()))
1362 spin_lock(&base->lock);
1363 if (base->active_timers) {
1364 if (time_before_eq(base->next_timer, base->timer_jiffies))
1365 base->next_timer = __next_timer_interrupt(base);
1366 nextevt = base->next_timer;
1367 if (time_before_eq(nextevt, basej))
1370 expires = basem + (nextevt - basej) * TICK_NSEC;
1372 spin_unlock(&base->lock);
1374 return cmp_next_hrtimer_event(basem, expires);
1379 * Called from the timer interrupt handler to charge one tick to the current
1380 * process. user_tick is 1 if the tick is user time, 0 for system.
1382 void update_process_times(int user_tick)
1384 struct task_struct *p = current;
1386 /* Note: this timer irq context must be accounted for as well. */
1387 account_process_tick(p, user_tick);
1389 rcu_check_callbacks(user_tick);
1390 #ifdef CONFIG_IRQ_WORK
1395 run_posix_cpu_timers(p);
1399 * This function runs timers and the timer-tq in bottom half context.
1401 static void run_timer_softirq(struct softirq_action *h)
1403 struct tvec_base *base = this_cpu_ptr(&tvec_bases);
1405 if (time_after_eq(jiffies, base->timer_jiffies))
1410 * Called by the local, per-CPU timer interrupt on SMP.
1412 void run_local_timers(void)
1414 hrtimer_run_queues();
1415 raise_softirq(TIMER_SOFTIRQ);
1418 #ifdef __ARCH_WANT_SYS_ALARM
1421 * For backwards compatibility? This can be done in libc so Alpha
1422 * and all newer ports shouldn't need it.
1424 SYSCALL_DEFINE1(alarm, unsigned int, seconds)
1426 return alarm_setitimer(seconds);
1431 static void process_timeout(unsigned long __data)
1433 wake_up_process((struct task_struct *)__data);
1437 * schedule_timeout - sleep until timeout
1438 * @timeout: timeout value in jiffies
1440 * Make the current task sleep until @timeout jiffies have
1441 * elapsed. The routine will return immediately unless
1442 * the current task state has been set (see set_current_state()).
1444 * You can set the task state as follows -
1446 * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to
1447 * pass before the routine returns. The routine will return 0
1449 * %TASK_INTERRUPTIBLE - the routine may return early if a signal is
1450 * delivered to the current task. In this case the remaining time
1451 * in jiffies will be returned, or 0 if the timer expired in time
1453 * The current task state is guaranteed to be TASK_RUNNING when this
1456 * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule
1457 * the CPU away without a bound on the timeout. In this case the return
1458 * value will be %MAX_SCHEDULE_TIMEOUT.
1460 * In all cases the return value is guaranteed to be non-negative.
1462 signed long __sched schedule_timeout(signed long timeout)
1464 struct timer_list timer;
1465 unsigned long expire;
1469 case MAX_SCHEDULE_TIMEOUT:
1471 * These two special cases are useful to be comfortable
1472 * in the caller. Nothing more. We could take
1473 * MAX_SCHEDULE_TIMEOUT from one of the negative value
1474 * but I' d like to return a valid offset (>=0) to allow
1475 * the caller to do everything it want with the retval.
1481 * Another bit of PARANOID. Note that the retval will be
1482 * 0 since no piece of kernel is supposed to do a check
1483 * for a negative retval of schedule_timeout() (since it
1484 * should never happens anyway). You just have the printk()
1485 * that will tell you if something is gone wrong and where.
1488 printk(KERN_ERR "schedule_timeout: wrong timeout "
1489 "value %lx\n", timeout);
1491 current->state = TASK_RUNNING;
1496 expire = timeout + jiffies;
1498 setup_timer_on_stack(&timer, process_timeout, (unsigned long)current);
1499 __mod_timer(&timer, expire, false, TIMER_NOT_PINNED);
1501 del_singleshot_timer_sync(&timer);
1503 /* Remove the timer from the object tracker */
1504 destroy_timer_on_stack(&timer);
1506 timeout = expire - jiffies;
1509 return timeout < 0 ? 0 : timeout;
1511 EXPORT_SYMBOL(schedule_timeout);
1514 * We can use __set_current_state() here because schedule_timeout() calls
1515 * schedule() unconditionally.
1517 signed long __sched schedule_timeout_interruptible(signed long timeout)
1519 __set_current_state(TASK_INTERRUPTIBLE);
1520 return schedule_timeout(timeout);
1522 EXPORT_SYMBOL(schedule_timeout_interruptible);
1524 signed long __sched schedule_timeout_killable(signed long timeout)
1526 __set_current_state(TASK_KILLABLE);
1527 return schedule_timeout(timeout);
1529 EXPORT_SYMBOL(schedule_timeout_killable);
1531 signed long __sched schedule_timeout_uninterruptible(signed long timeout)
1533 __set_current_state(TASK_UNINTERRUPTIBLE);
1534 return schedule_timeout(timeout);
1536 EXPORT_SYMBOL(schedule_timeout_uninterruptible);
1538 #ifdef CONFIG_HOTPLUG_CPU
1539 static void migrate_timer_list(struct tvec_base *new_base, struct hlist_head *head)
1541 struct timer_list *timer;
1542 int cpu = new_base->cpu;
1544 while (!hlist_empty(head)) {
1545 timer = hlist_entry(head->first, struct timer_list, entry);
1546 /* We ignore the accounting on the dying cpu */
1547 detach_timer(timer, false);
1548 timer->flags = (timer->flags & ~TIMER_BASEMASK) | cpu;
1549 internal_add_timer(new_base, timer);
1553 static void migrate_timers(int cpu)
1555 struct tvec_base *old_base;
1556 struct tvec_base *new_base;
1559 BUG_ON(cpu_online(cpu));
1560 old_base = per_cpu_ptr(&tvec_bases, cpu);
1561 new_base = this_cpu_ptr(&tvec_bases);
1563 * The caller is globally serialized and nobody else
1564 * takes two locks at once, deadlock is not possible.
1566 spin_lock_irq(&new_base->lock);
1567 spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING);
1569 BUG_ON(old_base->running_timer);
1571 for (i = 0; i < TVR_SIZE; i++)
1572 migrate_timer_list(new_base, old_base->tv1.vec + i);
1573 for (i = 0; i < TVN_SIZE; i++) {
1574 migrate_timer_list(new_base, old_base->tv2.vec + i);
1575 migrate_timer_list(new_base, old_base->tv3.vec + i);
1576 migrate_timer_list(new_base, old_base->tv4.vec + i);
1577 migrate_timer_list(new_base, old_base->tv5.vec + i);
1580 old_base->active_timers = 0;
1581 old_base->all_timers = 0;
1583 spin_unlock(&old_base->lock);
1584 spin_unlock_irq(&new_base->lock);
1587 static int timer_cpu_notify(struct notifier_block *self,
1588 unsigned long action, void *hcpu)
1592 case CPU_DEAD_FROZEN:
1593 migrate_timers((long)hcpu);
1602 static inline void timer_register_cpu_notifier(void)
1604 cpu_notifier(timer_cpu_notify, 0);
1607 static inline void timer_register_cpu_notifier(void) { }
1608 #endif /* CONFIG_HOTPLUG_CPU */
1610 static void __init init_timer_cpu(int cpu)
1612 struct tvec_base *base = per_cpu_ptr(&tvec_bases, cpu);
1615 spin_lock_init(&base->lock);
1617 base->timer_jiffies = jiffies;
1618 base->next_timer = base->timer_jiffies;
1621 static void __init init_timer_cpus(void)
1625 for_each_possible_cpu(cpu)
1626 init_timer_cpu(cpu);
1629 void __init init_timers(void)
1633 timer_register_cpu_notifier();
1634 open_softirq(TIMER_SOFTIRQ, run_timer_softirq);
1638 * msleep - sleep safely even with waitqueue interruptions
1639 * @msecs: Time in milliseconds to sleep for
1641 void msleep(unsigned int msecs)
1643 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1646 timeout = schedule_timeout_uninterruptible(timeout);
1649 EXPORT_SYMBOL(msleep);
1652 * msleep_interruptible - sleep waiting for signals
1653 * @msecs: Time in milliseconds to sleep for
1655 unsigned long msleep_interruptible(unsigned int msecs)
1657 unsigned long timeout = msecs_to_jiffies(msecs) + 1;
1659 while (timeout && !signal_pending(current))
1660 timeout = schedule_timeout_interruptible(timeout);
1661 return jiffies_to_msecs(timeout);
1664 EXPORT_SYMBOL(msleep_interruptible);
1666 static void __sched do_usleep_range(unsigned long min, unsigned long max)
1669 unsigned long delta;
1671 kmin = ktime_set(0, min * NSEC_PER_USEC);
1672 delta = (max - min) * NSEC_PER_USEC;
1673 schedule_hrtimeout_range(&kmin, delta, HRTIMER_MODE_REL);
1677 * usleep_range - Drop in replacement for udelay where wakeup is flexible
1678 * @min: Minimum time in usecs to sleep
1679 * @max: Maximum time in usecs to sleep
1681 void __sched usleep_range(unsigned long min, unsigned long max)
1683 __set_current_state(TASK_UNINTERRUPTIBLE);
1684 do_usleep_range(min, max);
1686 EXPORT_SYMBOL(usleep_range);