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