xref: /linux/kernel/time/hrtimer.c (revision f49040c7aaa5532a1f94355ef5073c49e6b32349)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  Copyright(C) 2005-2006, Thomas Gleixner <tglx@linutronix.de>
4  *  Copyright(C) 2005-2007, Red Hat, Inc., Ingo Molnar
5  *  Copyright(C) 2006-2007  Timesys Corp., Thomas Gleixner
6  *
7  *  High-resolution kernel timers
8  *
9  *  In contrast to the low-resolution timeout API, aka timer wheel,
10  *  hrtimers provide finer resolution and accuracy depending on system
11  *  configuration and capabilities.
12  *
13  *  Started by: Thomas Gleixner and Ingo Molnar
14  *
15  *  Credits:
16  *	Based on the original timer wheel code
17  *
18  *	Help, testing, suggestions, bugfixes, improvements were
19  *	provided by:
20  *
21  *	George Anzinger, Andrew Morton, Steven Rostedt, Roman Zippel
22  *	et. al.
23  */
24 
25 #include <linux/cpu.h>
26 #include <linux/export.h>
27 #include <linux/percpu.h>
28 #include <linux/hrtimer.h>
29 #include <linux/notifier.h>
30 #include <linux/syscalls.h>
31 #include <linux/interrupt.h>
32 #include <linux/tick.h>
33 #include <linux/err.h>
34 #include <linux/debugobjects.h>
35 #include <linux/sched/signal.h>
36 #include <linux/sched/sysctl.h>
37 #include <linux/sched/rt.h>
38 #include <linux/sched/deadline.h>
39 #include <linux/sched/nohz.h>
40 #include <linux/sched/debug.h>
41 #include <linux/sched/isolation.h>
42 #include <linux/timer.h>
43 #include <linux/freezer.h>
44 #include <linux/compat.h>
45 
46 #include <linux/uaccess.h>
47 
48 #include <trace/events/timer.h>
49 
50 #include "tick-internal.h"
51 
52 /*
53  * Masks for selecting the soft and hard context timers from
54  * cpu_base->active
55  */
56 #define MASK_SHIFT		(HRTIMER_BASE_MONOTONIC_SOFT)
57 #define HRTIMER_ACTIVE_HARD	((1U << MASK_SHIFT) - 1)
58 #define HRTIMER_ACTIVE_SOFT	(HRTIMER_ACTIVE_HARD << MASK_SHIFT)
59 #define HRTIMER_ACTIVE_ALL	(HRTIMER_ACTIVE_SOFT | HRTIMER_ACTIVE_HARD)
60 
61 static void retrigger_next_event(void *arg);
62 
63 /*
64  * The timer bases:
65  *
66  * There are more clockids than hrtimer bases. Thus, we index
67  * into the timer bases by the hrtimer_base_type enum. When trying
68  * to reach a base using a clockid, hrtimer_clockid_to_base()
69  * is used to convert from clockid to the proper hrtimer_base_type.
70  */
71 DEFINE_PER_CPU(struct hrtimer_cpu_base, hrtimer_bases) =
72 {
73 	.lock = __RAW_SPIN_LOCK_UNLOCKED(hrtimer_bases.lock),
74 	.clock_base =
75 	{
76 		{
77 			.index = HRTIMER_BASE_MONOTONIC,
78 			.clockid = CLOCK_MONOTONIC,
79 			.get_time = &ktime_get,
80 		},
81 		{
82 			.index = HRTIMER_BASE_REALTIME,
83 			.clockid = CLOCK_REALTIME,
84 			.get_time = &ktime_get_real,
85 		},
86 		{
87 			.index = HRTIMER_BASE_BOOTTIME,
88 			.clockid = CLOCK_BOOTTIME,
89 			.get_time = &ktime_get_boottime,
90 		},
91 		{
92 			.index = HRTIMER_BASE_TAI,
93 			.clockid = CLOCK_TAI,
94 			.get_time = &ktime_get_clocktai,
95 		},
96 		{
97 			.index = HRTIMER_BASE_MONOTONIC_SOFT,
98 			.clockid = CLOCK_MONOTONIC,
99 			.get_time = &ktime_get,
100 		},
101 		{
102 			.index = HRTIMER_BASE_REALTIME_SOFT,
103 			.clockid = CLOCK_REALTIME,
104 			.get_time = &ktime_get_real,
105 		},
106 		{
107 			.index = HRTIMER_BASE_BOOTTIME_SOFT,
108 			.clockid = CLOCK_BOOTTIME,
109 			.get_time = &ktime_get_boottime,
110 		},
111 		{
112 			.index = HRTIMER_BASE_TAI_SOFT,
113 			.clockid = CLOCK_TAI,
114 			.get_time = &ktime_get_clocktai,
115 		},
116 	},
117 	.csd = CSD_INIT(retrigger_next_event, NULL)
118 };
119 
hrtimer_base_is_online(struct hrtimer_cpu_base * base)120 static inline bool hrtimer_base_is_online(struct hrtimer_cpu_base *base)
121 {
122 	if (!IS_ENABLED(CONFIG_HOTPLUG_CPU))
123 		return true;
124 	else
125 		return likely(base->online);
126 }
127 
128 /*
129  * Functions and macros which are different for UP/SMP systems are kept in a
130  * single place
131  */
132 #ifdef CONFIG_SMP
133 
134 /*
135  * We require the migration_base for lock_hrtimer_base()/switch_hrtimer_base()
136  * such that hrtimer_callback_running() can unconditionally dereference
137  * timer->base->cpu_base
138  */
139 static struct hrtimer_cpu_base migration_cpu_base = {
140 	.clock_base = { {
141 		.cpu_base = &migration_cpu_base,
142 		.seq      = SEQCNT_RAW_SPINLOCK_ZERO(migration_cpu_base.seq,
143 						     &migration_cpu_base.lock),
144 	}, },
145 };
146 
147 #define migration_base	migration_cpu_base.clock_base[0]
148 
149 /*
150  * We are using hashed locking: holding per_cpu(hrtimer_bases)[n].lock
151  * means that all timers which are tied to this base via timer->base are
152  * locked, and the base itself is locked too.
153  *
154  * So __run_timers/migrate_timers can safely modify all timers which could
155  * be found on the lists/queues.
156  *
157  * When the timer's base is locked, and the timer removed from list, it is
158  * possible to set timer->base = &migration_base and drop the lock: the timer
159  * remains locked.
160  */
161 static
lock_hrtimer_base(const struct hrtimer * timer,unsigned long * flags)162 struct hrtimer_clock_base *lock_hrtimer_base(const struct hrtimer *timer,
163 					     unsigned long *flags)
164 	__acquires(&timer->base->lock)
165 {
166 	struct hrtimer_clock_base *base;
167 
168 	for (;;) {
169 		base = READ_ONCE(timer->base);
170 		if (likely(base != &migration_base)) {
171 			raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
172 			if (likely(base == timer->base))
173 				return base;
174 			/* The timer has migrated to another CPU: */
175 			raw_spin_unlock_irqrestore(&base->cpu_base->lock, *flags);
176 		}
177 		cpu_relax();
178 	}
179 }
180 
181 /*
182  * Check if the elected target is suitable considering its next
183  * event and the hotplug state of the current CPU.
184  *
185  * If the elected target is remote and its next event is after the timer
186  * to queue, then a remote reprogram is necessary. However there is no
187  * guarantee the IPI handling the operation would arrive in time to meet
188  * the high resolution deadline. In this case the local CPU becomes a
189  * preferred target, unless it is offline.
190  *
191  * High and low resolution modes are handled the same way for simplicity.
192  *
193  * Called with cpu_base->lock of target cpu held.
194  */
hrtimer_suitable_target(struct hrtimer * timer,struct hrtimer_clock_base * new_base,struct hrtimer_cpu_base * new_cpu_base,struct hrtimer_cpu_base * this_cpu_base)195 static bool hrtimer_suitable_target(struct hrtimer *timer, struct hrtimer_clock_base *new_base,
196 				    struct hrtimer_cpu_base *new_cpu_base,
197 				    struct hrtimer_cpu_base *this_cpu_base)
198 {
199 	ktime_t expires;
200 
201 	/*
202 	 * The local CPU clockevent can be reprogrammed. Also get_target_base()
203 	 * guarantees it is online.
204 	 */
205 	if (new_cpu_base == this_cpu_base)
206 		return true;
207 
208 	/*
209 	 * The offline local CPU can't be the default target if the
210 	 * next remote target event is after this timer. Keep the
211 	 * elected new base. An IPI will we issued to reprogram
212 	 * it as a last resort.
213 	 */
214 	if (!hrtimer_base_is_online(this_cpu_base))
215 		return true;
216 
217 	expires = ktime_sub(hrtimer_get_expires(timer), new_base->offset);
218 
219 	return expires >= new_base->cpu_base->expires_next;
220 }
221 
get_target_base(struct hrtimer_cpu_base * base,int pinned)222 static inline struct hrtimer_cpu_base *get_target_base(struct hrtimer_cpu_base *base, int pinned)
223 {
224 	if (!hrtimer_base_is_online(base)) {
225 		int cpu = cpumask_any_and(cpu_online_mask, housekeeping_cpumask(HK_TYPE_TIMER));
226 
227 		return &per_cpu(hrtimer_bases, cpu);
228 	}
229 
230 #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
231 	if (static_branch_likely(&timers_migration_enabled) && !pinned)
232 		return &per_cpu(hrtimer_bases, get_nohz_timer_target());
233 #endif
234 	return base;
235 }
236 
237 /*
238  * We switch the timer base to a power-optimized selected CPU target,
239  * if:
240  *	- NO_HZ_COMMON is enabled
241  *	- timer migration is enabled
242  *	- the timer callback is not running
243  *	- the timer is not the first expiring timer on the new target
244  *
245  * If one of the above requirements is not fulfilled we move the timer
246  * to the current CPU or leave it on the previously assigned CPU if
247  * the timer callback is currently running.
248  */
249 static inline struct hrtimer_clock_base *
switch_hrtimer_base(struct hrtimer * timer,struct hrtimer_clock_base * base,int pinned)250 switch_hrtimer_base(struct hrtimer *timer, struct hrtimer_clock_base *base,
251 		    int pinned)
252 {
253 	struct hrtimer_cpu_base *new_cpu_base, *this_cpu_base;
254 	struct hrtimer_clock_base *new_base;
255 	int basenum = base->index;
256 
257 	this_cpu_base = this_cpu_ptr(&hrtimer_bases);
258 	new_cpu_base = get_target_base(this_cpu_base, pinned);
259 again:
260 	new_base = &new_cpu_base->clock_base[basenum];
261 
262 	if (base != new_base) {
263 		/*
264 		 * We are trying to move timer to new_base.
265 		 * However we can't change timer's base while it is running,
266 		 * so we keep it on the same CPU. No hassle vs. reprogramming
267 		 * the event source in the high resolution case. The softirq
268 		 * code will take care of this when the timer function has
269 		 * completed. There is no conflict as we hold the lock until
270 		 * the timer is enqueued.
271 		 */
272 		if (unlikely(hrtimer_callback_running(timer)))
273 			return base;
274 
275 		/* See the comment in lock_hrtimer_base() */
276 		WRITE_ONCE(timer->base, &migration_base);
277 		raw_spin_unlock(&base->cpu_base->lock);
278 		raw_spin_lock(&new_base->cpu_base->lock);
279 
280 		if (!hrtimer_suitable_target(timer, new_base, new_cpu_base,
281 					     this_cpu_base)) {
282 			raw_spin_unlock(&new_base->cpu_base->lock);
283 			raw_spin_lock(&base->cpu_base->lock);
284 			new_cpu_base = this_cpu_base;
285 			WRITE_ONCE(timer->base, base);
286 			goto again;
287 		}
288 		WRITE_ONCE(timer->base, new_base);
289 	} else {
290 		if (!hrtimer_suitable_target(timer, new_base,  new_cpu_base, this_cpu_base)) {
291 			new_cpu_base = this_cpu_base;
292 			goto again;
293 		}
294 	}
295 	return new_base;
296 }
297 
298 #else /* CONFIG_SMP */
299 
300 static inline struct hrtimer_clock_base *
lock_hrtimer_base(const struct hrtimer * timer,unsigned long * flags)301 lock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
302 	__acquires(&timer->base->cpu_base->lock)
303 {
304 	struct hrtimer_clock_base *base = timer->base;
305 
306 	raw_spin_lock_irqsave(&base->cpu_base->lock, *flags);
307 
308 	return base;
309 }
310 
311 # define switch_hrtimer_base(t, b, p)	(b)
312 
313 #endif	/* !CONFIG_SMP */
314 
315 /*
316  * Functions for the union type storage format of ktime_t which are
317  * too large for inlining:
318  */
319 #if BITS_PER_LONG < 64
320 /*
321  * Divide a ktime value by a nanosecond value
322  */
__ktime_divns(const ktime_t kt,s64 div)323 s64 __ktime_divns(const ktime_t kt, s64 div)
324 {
325 	int sft = 0;
326 	s64 dclc;
327 	u64 tmp;
328 
329 	dclc = ktime_to_ns(kt);
330 	tmp = dclc < 0 ? -dclc : dclc;
331 
332 	/* Make sure the divisor is less than 2^32: */
333 	while (div >> 32) {
334 		sft++;
335 		div >>= 1;
336 	}
337 	tmp >>= sft;
338 	do_div(tmp, (u32) div);
339 	return dclc < 0 ? -tmp : tmp;
340 }
341 EXPORT_SYMBOL_GPL(__ktime_divns);
342 #endif /* BITS_PER_LONG >= 64 */
343 
344 /*
345  * Add two ktime values and do a safety check for overflow:
346  */
ktime_add_safe(const ktime_t lhs,const ktime_t rhs)347 ktime_t ktime_add_safe(const ktime_t lhs, const ktime_t rhs)
348 {
349 	ktime_t res = ktime_add_unsafe(lhs, rhs);
350 
351 	/*
352 	 * We use KTIME_SEC_MAX here, the maximum timeout which we can
353 	 * return to user space in a timespec:
354 	 */
355 	if (res < 0 || res < lhs || res < rhs)
356 		res = ktime_set(KTIME_SEC_MAX, 0);
357 
358 	return res;
359 }
360 
361 EXPORT_SYMBOL_GPL(ktime_add_safe);
362 
363 #ifdef CONFIG_DEBUG_OBJECTS_TIMERS
364 
365 static const struct debug_obj_descr hrtimer_debug_descr;
366 
hrtimer_debug_hint(void * addr)367 static void *hrtimer_debug_hint(void *addr)
368 {
369 	return ((struct hrtimer *) addr)->function;
370 }
371 
372 /*
373  * fixup_init is called when:
374  * - an active object is initialized
375  */
hrtimer_fixup_init(void * addr,enum debug_obj_state state)376 static bool hrtimer_fixup_init(void *addr, enum debug_obj_state state)
377 {
378 	struct hrtimer *timer = addr;
379 
380 	switch (state) {
381 	case ODEBUG_STATE_ACTIVE:
382 		hrtimer_cancel(timer);
383 		debug_object_init(timer, &hrtimer_debug_descr);
384 		return true;
385 	default:
386 		return false;
387 	}
388 }
389 
390 /*
391  * fixup_activate is called when:
392  * - an active object is activated
393  * - an unknown non-static object is activated
394  */
hrtimer_fixup_activate(void * addr,enum debug_obj_state state)395 static bool hrtimer_fixup_activate(void *addr, enum debug_obj_state state)
396 {
397 	switch (state) {
398 	case ODEBUG_STATE_ACTIVE:
399 		WARN_ON(1);
400 		fallthrough;
401 	default:
402 		return false;
403 	}
404 }
405 
406 /*
407  * fixup_free is called when:
408  * - an active object is freed
409  */
hrtimer_fixup_free(void * addr,enum debug_obj_state state)410 static bool hrtimer_fixup_free(void *addr, enum debug_obj_state state)
411 {
412 	struct hrtimer *timer = addr;
413 
414 	switch (state) {
415 	case ODEBUG_STATE_ACTIVE:
416 		hrtimer_cancel(timer);
417 		debug_object_free(timer, &hrtimer_debug_descr);
418 		return true;
419 	default:
420 		return false;
421 	}
422 }
423 
424 static const struct debug_obj_descr hrtimer_debug_descr = {
425 	.name		= "hrtimer",
426 	.debug_hint	= hrtimer_debug_hint,
427 	.fixup_init	= hrtimer_fixup_init,
428 	.fixup_activate	= hrtimer_fixup_activate,
429 	.fixup_free	= hrtimer_fixup_free,
430 };
431 
debug_hrtimer_init(struct hrtimer * timer)432 static inline void debug_hrtimer_init(struct hrtimer *timer)
433 {
434 	debug_object_init(timer, &hrtimer_debug_descr);
435 }
436 
debug_hrtimer_init_on_stack(struct hrtimer * timer)437 static inline void debug_hrtimer_init_on_stack(struct hrtimer *timer)
438 {
439 	debug_object_init_on_stack(timer, &hrtimer_debug_descr);
440 }
441 
debug_hrtimer_activate(struct hrtimer * timer,enum hrtimer_mode mode)442 static inline void debug_hrtimer_activate(struct hrtimer *timer,
443 					  enum hrtimer_mode mode)
444 {
445 	debug_object_activate(timer, &hrtimer_debug_descr);
446 }
447 
debug_hrtimer_deactivate(struct hrtimer * timer)448 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
449 {
450 	debug_object_deactivate(timer, &hrtimer_debug_descr);
451 }
452 
destroy_hrtimer_on_stack(struct hrtimer * timer)453 void destroy_hrtimer_on_stack(struct hrtimer *timer)
454 {
455 	debug_object_free(timer, &hrtimer_debug_descr);
456 }
457 EXPORT_SYMBOL_GPL(destroy_hrtimer_on_stack);
458 
459 #else
460 
debug_hrtimer_init(struct hrtimer * timer)461 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
debug_hrtimer_init_on_stack(struct hrtimer * timer)462 static inline void debug_hrtimer_init_on_stack(struct hrtimer *timer) { }
debug_hrtimer_activate(struct hrtimer * timer,enum hrtimer_mode mode)463 static inline void debug_hrtimer_activate(struct hrtimer *timer,
464 					  enum hrtimer_mode mode) { }
debug_hrtimer_deactivate(struct hrtimer * timer)465 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
466 #endif
467 
468 static inline void
debug_init(struct hrtimer * timer,clockid_t clockid,enum hrtimer_mode mode)469 debug_init(struct hrtimer *timer, clockid_t clockid,
470 	   enum hrtimer_mode mode)
471 {
472 	debug_hrtimer_init(timer);
473 	trace_hrtimer_init(timer, clockid, mode);
474 }
475 
debug_init_on_stack(struct hrtimer * timer,clockid_t clockid,enum hrtimer_mode mode)476 static inline void debug_init_on_stack(struct hrtimer *timer, clockid_t clockid,
477 				       enum hrtimer_mode mode)
478 {
479 	debug_hrtimer_init_on_stack(timer);
480 	trace_hrtimer_init(timer, clockid, mode);
481 }
482 
debug_activate(struct hrtimer * timer,enum hrtimer_mode mode)483 static inline void debug_activate(struct hrtimer *timer,
484 				  enum hrtimer_mode mode)
485 {
486 	debug_hrtimer_activate(timer, mode);
487 	trace_hrtimer_start(timer, mode);
488 }
489 
debug_deactivate(struct hrtimer * timer)490 static inline void debug_deactivate(struct hrtimer *timer)
491 {
492 	debug_hrtimer_deactivate(timer);
493 	trace_hrtimer_cancel(timer);
494 }
495 
496 static struct hrtimer_clock_base *
__next_base(struct hrtimer_cpu_base * cpu_base,unsigned int * active)497 __next_base(struct hrtimer_cpu_base *cpu_base, unsigned int *active)
498 {
499 	unsigned int idx;
500 
501 	if (!*active)
502 		return NULL;
503 
504 	idx = __ffs(*active);
505 	*active &= ~(1U << idx);
506 
507 	return &cpu_base->clock_base[idx];
508 }
509 
510 #define for_each_active_base(base, cpu_base, active)	\
511 	while ((base = __next_base((cpu_base), &(active))))
512 
__hrtimer_next_event_base(struct hrtimer_cpu_base * cpu_base,const struct hrtimer * exclude,unsigned int active,ktime_t expires_next)513 static ktime_t __hrtimer_next_event_base(struct hrtimer_cpu_base *cpu_base,
514 					 const struct hrtimer *exclude,
515 					 unsigned int active,
516 					 ktime_t expires_next)
517 {
518 	struct hrtimer_clock_base *base;
519 	ktime_t expires;
520 
521 	for_each_active_base(base, cpu_base, active) {
522 		struct timerqueue_node *next;
523 		struct hrtimer *timer;
524 
525 		next = timerqueue_getnext(&base->active);
526 		timer = container_of(next, struct hrtimer, node);
527 		if (timer == exclude) {
528 			/* Get to the next timer in the queue. */
529 			next = timerqueue_iterate_next(next);
530 			if (!next)
531 				continue;
532 
533 			timer = container_of(next, struct hrtimer, node);
534 		}
535 		expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
536 		if (expires < expires_next) {
537 			expires_next = expires;
538 
539 			/* Skip cpu_base update if a timer is being excluded. */
540 			if (exclude)
541 				continue;
542 
543 			if (timer->is_soft)
544 				cpu_base->softirq_next_timer = timer;
545 			else
546 				cpu_base->next_timer = timer;
547 		}
548 	}
549 	/*
550 	 * clock_was_set() might have changed base->offset of any of
551 	 * the clock bases so the result might be negative. Fix it up
552 	 * to prevent a false positive in clockevents_program_event().
553 	 */
554 	if (expires_next < 0)
555 		expires_next = 0;
556 	return expires_next;
557 }
558 
559 /*
560  * Recomputes cpu_base::*next_timer and returns the earliest expires_next
561  * but does not set cpu_base::*expires_next, that is done by
562  * hrtimer[_force]_reprogram and hrtimer_interrupt only. When updating
563  * cpu_base::*expires_next right away, reprogramming logic would no longer
564  * work.
565  *
566  * When a softirq is pending, we can ignore the HRTIMER_ACTIVE_SOFT bases,
567  * those timers will get run whenever the softirq gets handled, at the end of
568  * hrtimer_run_softirq(), hrtimer_update_softirq_timer() will re-add these bases.
569  *
570  * Therefore softirq values are those from the HRTIMER_ACTIVE_SOFT clock bases.
571  * The !softirq values are the minima across HRTIMER_ACTIVE_ALL, unless an actual
572  * softirq is pending, in which case they're the minima of HRTIMER_ACTIVE_HARD.
573  *
574  * @active_mask must be one of:
575  *  - HRTIMER_ACTIVE_ALL,
576  *  - HRTIMER_ACTIVE_SOFT, or
577  *  - HRTIMER_ACTIVE_HARD.
578  */
579 static ktime_t
__hrtimer_get_next_event(struct hrtimer_cpu_base * cpu_base,unsigned int active_mask)580 __hrtimer_get_next_event(struct hrtimer_cpu_base *cpu_base, unsigned int active_mask)
581 {
582 	unsigned int active;
583 	struct hrtimer *next_timer = NULL;
584 	ktime_t expires_next = KTIME_MAX;
585 
586 	if (!cpu_base->softirq_activated && (active_mask & HRTIMER_ACTIVE_SOFT)) {
587 		active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT;
588 		cpu_base->softirq_next_timer = NULL;
589 		expires_next = __hrtimer_next_event_base(cpu_base, NULL,
590 							 active, KTIME_MAX);
591 
592 		next_timer = cpu_base->softirq_next_timer;
593 	}
594 
595 	if (active_mask & HRTIMER_ACTIVE_HARD) {
596 		active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD;
597 		cpu_base->next_timer = next_timer;
598 		expires_next = __hrtimer_next_event_base(cpu_base, NULL, active,
599 							 expires_next);
600 	}
601 
602 	return expires_next;
603 }
604 
hrtimer_update_next_event(struct hrtimer_cpu_base * cpu_base)605 static ktime_t hrtimer_update_next_event(struct hrtimer_cpu_base *cpu_base)
606 {
607 	ktime_t expires_next, soft = KTIME_MAX;
608 
609 	/*
610 	 * If the soft interrupt has already been activated, ignore the
611 	 * soft bases. They will be handled in the already raised soft
612 	 * interrupt.
613 	 */
614 	if (!cpu_base->softirq_activated) {
615 		soft = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_SOFT);
616 		/*
617 		 * Update the soft expiry time. clock_settime() might have
618 		 * affected it.
619 		 */
620 		cpu_base->softirq_expires_next = soft;
621 	}
622 
623 	expires_next = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_HARD);
624 	/*
625 	 * If a softirq timer is expiring first, update cpu_base->next_timer
626 	 * and program the hardware with the soft expiry time.
627 	 */
628 	if (expires_next > soft) {
629 		cpu_base->next_timer = cpu_base->softirq_next_timer;
630 		expires_next = soft;
631 	}
632 
633 	return expires_next;
634 }
635 
hrtimer_update_base(struct hrtimer_cpu_base * base)636 static inline ktime_t hrtimer_update_base(struct hrtimer_cpu_base *base)
637 {
638 	ktime_t *offs_real = &base->clock_base[HRTIMER_BASE_REALTIME].offset;
639 	ktime_t *offs_boot = &base->clock_base[HRTIMER_BASE_BOOTTIME].offset;
640 	ktime_t *offs_tai = &base->clock_base[HRTIMER_BASE_TAI].offset;
641 
642 	ktime_t now = ktime_get_update_offsets_now(&base->clock_was_set_seq,
643 					    offs_real, offs_boot, offs_tai);
644 
645 	base->clock_base[HRTIMER_BASE_REALTIME_SOFT].offset = *offs_real;
646 	base->clock_base[HRTIMER_BASE_BOOTTIME_SOFT].offset = *offs_boot;
647 	base->clock_base[HRTIMER_BASE_TAI_SOFT].offset = *offs_tai;
648 
649 	return now;
650 }
651 
652 /*
653  * Is the high resolution mode active ?
654  */
hrtimer_hres_active(struct hrtimer_cpu_base * cpu_base)655 static inline int hrtimer_hres_active(struct hrtimer_cpu_base *cpu_base)
656 {
657 	return IS_ENABLED(CONFIG_HIGH_RES_TIMERS) ?
658 		cpu_base->hres_active : 0;
659 }
660 
__hrtimer_reprogram(struct hrtimer_cpu_base * cpu_base,struct hrtimer * next_timer,ktime_t expires_next)661 static void __hrtimer_reprogram(struct hrtimer_cpu_base *cpu_base,
662 				struct hrtimer *next_timer,
663 				ktime_t expires_next)
664 {
665 	cpu_base->expires_next = expires_next;
666 
667 	/*
668 	 * If hres is not active, hardware does not have to be
669 	 * reprogrammed yet.
670 	 *
671 	 * If a hang was detected in the last timer interrupt then we
672 	 * leave the hang delay active in the hardware. We want the
673 	 * system to make progress. That also prevents the following
674 	 * scenario:
675 	 * T1 expires 50ms from now
676 	 * T2 expires 5s from now
677 	 *
678 	 * T1 is removed, so this code is called and would reprogram
679 	 * the hardware to 5s from now. Any hrtimer_start after that
680 	 * will not reprogram the hardware due to hang_detected being
681 	 * set. So we'd effectively block all timers until the T2 event
682 	 * fires.
683 	 */
684 	if (!hrtimer_hres_active(cpu_base) || cpu_base->hang_detected)
685 		return;
686 
687 	tick_program_event(expires_next, 1);
688 }
689 
690 /*
691  * Reprogram the event source with checking both queues for the
692  * next event
693  * Called with interrupts disabled and base->lock held
694  */
695 static void
hrtimer_force_reprogram(struct hrtimer_cpu_base * cpu_base,int skip_equal)696 hrtimer_force_reprogram(struct hrtimer_cpu_base *cpu_base, int skip_equal)
697 {
698 	ktime_t expires_next;
699 
700 	expires_next = hrtimer_update_next_event(cpu_base);
701 
702 	if (skip_equal && expires_next == cpu_base->expires_next)
703 		return;
704 
705 	__hrtimer_reprogram(cpu_base, cpu_base->next_timer, expires_next);
706 }
707 
708 /* High resolution timer related functions */
709 #ifdef CONFIG_HIGH_RES_TIMERS
710 
711 /*
712  * High resolution timer enabled ?
713  */
714 static bool hrtimer_hres_enabled __read_mostly  = true;
715 unsigned int hrtimer_resolution __read_mostly = LOW_RES_NSEC;
716 EXPORT_SYMBOL_GPL(hrtimer_resolution);
717 
718 /*
719  * Enable / Disable high resolution mode
720  */
setup_hrtimer_hres(char * str)721 static int __init setup_hrtimer_hres(char *str)
722 {
723 	return (kstrtobool(str, &hrtimer_hres_enabled) == 0);
724 }
725 
726 __setup("highres=", setup_hrtimer_hres);
727 
728 /*
729  * hrtimer_high_res_enabled - query, if the highres mode is enabled
730  */
hrtimer_is_hres_enabled(void)731 static inline int hrtimer_is_hres_enabled(void)
732 {
733 	return hrtimer_hres_enabled;
734 }
735 
736 /*
737  * Switch to high resolution mode
738  */
hrtimer_switch_to_hres(void)739 static void hrtimer_switch_to_hres(void)
740 {
741 	struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
742 
743 	if (tick_init_highres()) {
744 		pr_warn("Could not switch to high resolution mode on CPU %u\n",
745 			base->cpu);
746 		return;
747 	}
748 	base->hres_active = 1;
749 	hrtimer_resolution = HIGH_RES_NSEC;
750 
751 	tick_setup_sched_timer(true);
752 	/* "Retrigger" the interrupt to get things going */
753 	retrigger_next_event(NULL);
754 }
755 
756 #else
757 
hrtimer_is_hres_enabled(void)758 static inline int hrtimer_is_hres_enabled(void) { return 0; }
hrtimer_switch_to_hres(void)759 static inline void hrtimer_switch_to_hres(void) { }
760 
761 #endif /* CONFIG_HIGH_RES_TIMERS */
762 /*
763  * Retrigger next event is called after clock was set with interrupts
764  * disabled through an SMP function call or directly from low level
765  * resume code.
766  *
767  * This is only invoked when:
768  *	- CONFIG_HIGH_RES_TIMERS is enabled.
769  *	- CONFIG_NOHZ_COMMON is enabled
770  *
771  * For the other cases this function is empty and because the call sites
772  * are optimized out it vanishes as well, i.e. no need for lots of
773  * #ifdeffery.
774  */
retrigger_next_event(void * arg)775 static void retrigger_next_event(void *arg)
776 {
777 	struct hrtimer_cpu_base *base = this_cpu_ptr(&hrtimer_bases);
778 
779 	/*
780 	 * When high resolution mode or nohz is active, then the offsets of
781 	 * CLOCK_REALTIME/TAI/BOOTTIME have to be updated. Otherwise the
782 	 * next tick will take care of that.
783 	 *
784 	 * If high resolution mode is active then the next expiring timer
785 	 * must be reevaluated and the clock event device reprogrammed if
786 	 * necessary.
787 	 *
788 	 * In the NOHZ case the update of the offset and the reevaluation
789 	 * of the next expiring timer is enough. The return from the SMP
790 	 * function call will take care of the reprogramming in case the
791 	 * CPU was in a NOHZ idle sleep.
792 	 */
793 	if (!hrtimer_hres_active(base) && !tick_nohz_active)
794 		return;
795 
796 	raw_spin_lock(&base->lock);
797 	hrtimer_update_base(base);
798 	if (hrtimer_hres_active(base))
799 		hrtimer_force_reprogram(base, 0);
800 	else
801 		hrtimer_update_next_event(base);
802 	raw_spin_unlock(&base->lock);
803 }
804 
805 /*
806  * When a timer is enqueued and expires earlier than the already enqueued
807  * timers, we have to check, whether it expires earlier than the timer for
808  * which the clock event device was armed.
809  *
810  * Called with interrupts disabled and base->cpu_base.lock held
811  */
hrtimer_reprogram(struct hrtimer * timer,bool reprogram)812 static void hrtimer_reprogram(struct hrtimer *timer, bool reprogram)
813 {
814 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
815 	struct hrtimer_clock_base *base = timer->base;
816 	ktime_t expires = ktime_sub(hrtimer_get_expires(timer), base->offset);
817 
818 	WARN_ON_ONCE(hrtimer_get_expires_tv64(timer) < 0);
819 
820 	/*
821 	 * CLOCK_REALTIME timer might be requested with an absolute
822 	 * expiry time which is less than base->offset. Set it to 0.
823 	 */
824 	if (expires < 0)
825 		expires = 0;
826 
827 	if (timer->is_soft) {
828 		/*
829 		 * soft hrtimer could be started on a remote CPU. In this
830 		 * case softirq_expires_next needs to be updated on the
831 		 * remote CPU. The soft hrtimer will not expire before the
832 		 * first hard hrtimer on the remote CPU -
833 		 * hrtimer_check_target() prevents this case.
834 		 */
835 		struct hrtimer_cpu_base *timer_cpu_base = base->cpu_base;
836 
837 		if (timer_cpu_base->softirq_activated)
838 			return;
839 
840 		if (!ktime_before(expires, timer_cpu_base->softirq_expires_next))
841 			return;
842 
843 		timer_cpu_base->softirq_next_timer = timer;
844 		timer_cpu_base->softirq_expires_next = expires;
845 
846 		if (!ktime_before(expires, timer_cpu_base->expires_next) ||
847 		    !reprogram)
848 			return;
849 	}
850 
851 	/*
852 	 * If the timer is not on the current cpu, we cannot reprogram
853 	 * the other cpus clock event device.
854 	 */
855 	if (base->cpu_base != cpu_base)
856 		return;
857 
858 	if (expires >= cpu_base->expires_next)
859 		return;
860 
861 	/*
862 	 * If the hrtimer interrupt is running, then it will reevaluate the
863 	 * clock bases and reprogram the clock event device.
864 	 */
865 	if (cpu_base->in_hrtirq)
866 		return;
867 
868 	cpu_base->next_timer = timer;
869 
870 	__hrtimer_reprogram(cpu_base, timer, expires);
871 }
872 
update_needs_ipi(struct hrtimer_cpu_base * cpu_base,unsigned int active)873 static bool update_needs_ipi(struct hrtimer_cpu_base *cpu_base,
874 			     unsigned int active)
875 {
876 	struct hrtimer_clock_base *base;
877 	unsigned int seq;
878 	ktime_t expires;
879 
880 	/*
881 	 * Update the base offsets unconditionally so the following
882 	 * checks whether the SMP function call is required works.
883 	 *
884 	 * The update is safe even when the remote CPU is in the hrtimer
885 	 * interrupt or the hrtimer soft interrupt and expiring affected
886 	 * bases. Either it will see the update before handling a base or
887 	 * it will see it when it finishes the processing and reevaluates
888 	 * the next expiring timer.
889 	 */
890 	seq = cpu_base->clock_was_set_seq;
891 	hrtimer_update_base(cpu_base);
892 
893 	/*
894 	 * If the sequence did not change over the update then the
895 	 * remote CPU already handled it.
896 	 */
897 	if (seq == cpu_base->clock_was_set_seq)
898 		return false;
899 
900 	/*
901 	 * If the remote CPU is currently handling an hrtimer interrupt, it
902 	 * will reevaluate the first expiring timer of all clock bases
903 	 * before reprogramming. Nothing to do here.
904 	 */
905 	if (cpu_base->in_hrtirq)
906 		return false;
907 
908 	/*
909 	 * Walk the affected clock bases and check whether the first expiring
910 	 * timer in a clock base is moving ahead of the first expiring timer of
911 	 * @cpu_base. If so, the IPI must be invoked because per CPU clock
912 	 * event devices cannot be remotely reprogrammed.
913 	 */
914 	active &= cpu_base->active_bases;
915 
916 	for_each_active_base(base, cpu_base, active) {
917 		struct timerqueue_node *next;
918 
919 		next = timerqueue_getnext(&base->active);
920 		expires = ktime_sub(next->expires, base->offset);
921 		if (expires < cpu_base->expires_next)
922 			return true;
923 
924 		/* Extra check for softirq clock bases */
925 		if (base->clockid < HRTIMER_BASE_MONOTONIC_SOFT)
926 			continue;
927 		if (cpu_base->softirq_activated)
928 			continue;
929 		if (expires < cpu_base->softirq_expires_next)
930 			return true;
931 	}
932 	return false;
933 }
934 
935 /*
936  * Clock was set. This might affect CLOCK_REALTIME, CLOCK_TAI and
937  * CLOCK_BOOTTIME (for late sleep time injection).
938  *
939  * This requires to update the offsets for these clocks
940  * vs. CLOCK_MONOTONIC. When high resolution timers are enabled, then this
941  * also requires to eventually reprogram the per CPU clock event devices
942  * when the change moves an affected timer ahead of the first expiring
943  * timer on that CPU. Obviously remote per CPU clock event devices cannot
944  * be reprogrammed. The other reason why an IPI has to be sent is when the
945  * system is in !HIGH_RES and NOHZ mode. The NOHZ mode updates the offsets
946  * in the tick, which obviously might be stopped, so this has to bring out
947  * the remote CPU which might sleep in idle to get this sorted.
948  */
clock_was_set(unsigned int bases)949 void clock_was_set(unsigned int bases)
950 {
951 	struct hrtimer_cpu_base *cpu_base = raw_cpu_ptr(&hrtimer_bases);
952 	cpumask_var_t mask;
953 	int cpu;
954 
955 	if (!hrtimer_hres_active(cpu_base) && !tick_nohz_active)
956 		goto out_timerfd;
957 
958 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL)) {
959 		on_each_cpu(retrigger_next_event, NULL, 1);
960 		goto out_timerfd;
961 	}
962 
963 	/* Avoid interrupting CPUs if possible */
964 	cpus_read_lock();
965 	for_each_online_cpu(cpu) {
966 		unsigned long flags;
967 
968 		cpu_base = &per_cpu(hrtimer_bases, cpu);
969 		raw_spin_lock_irqsave(&cpu_base->lock, flags);
970 
971 		if (update_needs_ipi(cpu_base, bases))
972 			cpumask_set_cpu(cpu, mask);
973 
974 		raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
975 	}
976 
977 	preempt_disable();
978 	smp_call_function_many(mask, retrigger_next_event, NULL, 1);
979 	preempt_enable();
980 	cpus_read_unlock();
981 	free_cpumask_var(mask);
982 
983 out_timerfd:
984 	timerfd_clock_was_set();
985 }
986 
clock_was_set_work(struct work_struct * work)987 static void clock_was_set_work(struct work_struct *work)
988 {
989 	clock_was_set(CLOCK_SET_WALL);
990 }
991 
992 static DECLARE_WORK(hrtimer_work, clock_was_set_work);
993 
994 /*
995  * Called from timekeeping code to reprogram the hrtimer interrupt device
996  * on all cpus and to notify timerfd.
997  */
clock_was_set_delayed(void)998 void clock_was_set_delayed(void)
999 {
1000 	schedule_work(&hrtimer_work);
1001 }
1002 
1003 /*
1004  * Called during resume either directly from via timekeeping_resume()
1005  * or in the case of s2idle from tick_unfreeze() to ensure that the
1006  * hrtimers are up to date.
1007  */
hrtimers_resume_local(void)1008 void hrtimers_resume_local(void)
1009 {
1010 	lockdep_assert_irqs_disabled();
1011 	/* Retrigger on the local CPU */
1012 	retrigger_next_event(NULL);
1013 }
1014 
1015 /*
1016  * Counterpart to lock_hrtimer_base above:
1017  */
1018 static inline
unlock_hrtimer_base(const struct hrtimer * timer,unsigned long * flags)1019 void unlock_hrtimer_base(const struct hrtimer *timer, unsigned long *flags)
1020 	__releases(&timer->base->cpu_base->lock)
1021 {
1022 	raw_spin_unlock_irqrestore(&timer->base->cpu_base->lock, *flags);
1023 }
1024 
1025 /**
1026  * hrtimer_forward() - forward the timer expiry
1027  * @timer:	hrtimer to forward
1028  * @now:	forward past this time
1029  * @interval:	the interval to forward
1030  *
1031  * Forward the timer expiry so it will expire in the future.
1032  *
1033  * .. note::
1034  *  This only updates the timer expiry value and does not requeue the timer.
1035  *
1036  * There is also a variant of the function hrtimer_forward_now().
1037  *
1038  * Context: Can be safely called from the callback function of @timer. If called
1039  *          from other contexts @timer must neither be enqueued nor running the
1040  *          callback and the caller needs to take care of serialization.
1041  *
1042  * Return: The number of overruns are returned.
1043  */
hrtimer_forward(struct hrtimer * timer,ktime_t now,ktime_t interval)1044 u64 hrtimer_forward(struct hrtimer *timer, ktime_t now, ktime_t interval)
1045 {
1046 	u64 orun = 1;
1047 	ktime_t delta;
1048 
1049 	delta = ktime_sub(now, hrtimer_get_expires(timer));
1050 
1051 	if (delta < 0)
1052 		return 0;
1053 
1054 	if (WARN_ON(timer->state & HRTIMER_STATE_ENQUEUED))
1055 		return 0;
1056 
1057 	if (interval < hrtimer_resolution)
1058 		interval = hrtimer_resolution;
1059 
1060 	if (unlikely(delta >= interval)) {
1061 		s64 incr = ktime_to_ns(interval);
1062 
1063 		orun = ktime_divns(delta, incr);
1064 		hrtimer_add_expires_ns(timer, incr * orun);
1065 		if (hrtimer_get_expires_tv64(timer) > now)
1066 			return orun;
1067 		/*
1068 		 * This (and the ktime_add() below) is the
1069 		 * correction for exact:
1070 		 */
1071 		orun++;
1072 	}
1073 	hrtimer_add_expires(timer, interval);
1074 
1075 	return orun;
1076 }
1077 EXPORT_SYMBOL_GPL(hrtimer_forward);
1078 
1079 /*
1080  * enqueue_hrtimer - internal function to (re)start a timer
1081  *
1082  * The timer is inserted in expiry order. Insertion into the
1083  * red black tree is O(log(n)). Must hold the base lock.
1084  *
1085  * Returns true when the new timer is the leftmost timer in the tree.
1086  */
enqueue_hrtimer(struct hrtimer * timer,struct hrtimer_clock_base * base,enum hrtimer_mode mode)1087 static bool enqueue_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base,
1088 			    enum hrtimer_mode mode)
1089 {
1090 	debug_activate(timer, mode);
1091 	WARN_ON_ONCE(!base->cpu_base->online);
1092 
1093 	base->cpu_base->active_bases |= 1 << base->index;
1094 
1095 	/* Pairs with the lockless read in hrtimer_is_queued() */
1096 	WRITE_ONCE(timer->state, HRTIMER_STATE_ENQUEUED);
1097 
1098 	return timerqueue_add(&base->active, &timer->node);
1099 }
1100 
1101 /*
1102  * __remove_hrtimer - internal function to remove a timer
1103  *
1104  * Caller must hold the base lock.
1105  *
1106  * High resolution timer mode reprograms the clock event device when the
1107  * timer is the one which expires next. The caller can disable this by setting
1108  * reprogram to zero. This is useful, when the context does a reprogramming
1109  * anyway (e.g. timer interrupt)
1110  */
__remove_hrtimer(struct hrtimer * timer,struct hrtimer_clock_base * base,u8 newstate,int reprogram)1111 static void __remove_hrtimer(struct hrtimer *timer,
1112 			     struct hrtimer_clock_base *base,
1113 			     u8 newstate, int reprogram)
1114 {
1115 	struct hrtimer_cpu_base *cpu_base = base->cpu_base;
1116 	u8 state = timer->state;
1117 
1118 	/* Pairs with the lockless read in hrtimer_is_queued() */
1119 	WRITE_ONCE(timer->state, newstate);
1120 	if (!(state & HRTIMER_STATE_ENQUEUED))
1121 		return;
1122 
1123 	if (!timerqueue_del(&base->active, &timer->node))
1124 		cpu_base->active_bases &= ~(1 << base->index);
1125 
1126 	/*
1127 	 * Note: If reprogram is false we do not update
1128 	 * cpu_base->next_timer. This happens when we remove the first
1129 	 * timer on a remote cpu. No harm as we never dereference
1130 	 * cpu_base->next_timer. So the worst thing what can happen is
1131 	 * an superfluous call to hrtimer_force_reprogram() on the
1132 	 * remote cpu later on if the same timer gets enqueued again.
1133 	 */
1134 	if (reprogram && timer == cpu_base->next_timer)
1135 		hrtimer_force_reprogram(cpu_base, 1);
1136 }
1137 
1138 /*
1139  * remove hrtimer, called with base lock held
1140  */
1141 static inline int
remove_hrtimer(struct hrtimer * timer,struct hrtimer_clock_base * base,bool restart,bool keep_local)1142 remove_hrtimer(struct hrtimer *timer, struct hrtimer_clock_base *base,
1143 	       bool restart, bool keep_local)
1144 {
1145 	u8 state = timer->state;
1146 
1147 	if (state & HRTIMER_STATE_ENQUEUED) {
1148 		bool reprogram;
1149 
1150 		/*
1151 		 * Remove the timer and force reprogramming when high
1152 		 * resolution mode is active and the timer is on the current
1153 		 * CPU. If we remove a timer on another CPU, reprogramming is
1154 		 * skipped. The interrupt event on this CPU is fired and
1155 		 * reprogramming happens in the interrupt handler. This is a
1156 		 * rare case and less expensive than a smp call.
1157 		 */
1158 		debug_deactivate(timer);
1159 		reprogram = base->cpu_base == this_cpu_ptr(&hrtimer_bases);
1160 
1161 		/*
1162 		 * If the timer is not restarted then reprogramming is
1163 		 * required if the timer is local. If it is local and about
1164 		 * to be restarted, avoid programming it twice (on removal
1165 		 * and a moment later when it's requeued).
1166 		 */
1167 		if (!restart)
1168 			state = HRTIMER_STATE_INACTIVE;
1169 		else
1170 			reprogram &= !keep_local;
1171 
1172 		__remove_hrtimer(timer, base, state, reprogram);
1173 		return 1;
1174 	}
1175 	return 0;
1176 }
1177 
hrtimer_update_lowres(struct hrtimer * timer,ktime_t tim,const enum hrtimer_mode mode)1178 static inline ktime_t hrtimer_update_lowres(struct hrtimer *timer, ktime_t tim,
1179 					    const enum hrtimer_mode mode)
1180 {
1181 #ifdef CONFIG_TIME_LOW_RES
1182 	/*
1183 	 * CONFIG_TIME_LOW_RES indicates that the system has no way to return
1184 	 * granular time values. For relative timers we add hrtimer_resolution
1185 	 * (i.e. one jiffy) to prevent short timeouts.
1186 	 */
1187 	timer->is_rel = mode & HRTIMER_MODE_REL;
1188 	if (timer->is_rel)
1189 		tim = ktime_add_safe(tim, hrtimer_resolution);
1190 #endif
1191 	return tim;
1192 }
1193 
1194 static void
hrtimer_update_softirq_timer(struct hrtimer_cpu_base * cpu_base,bool reprogram)1195 hrtimer_update_softirq_timer(struct hrtimer_cpu_base *cpu_base, bool reprogram)
1196 {
1197 	ktime_t expires;
1198 
1199 	/*
1200 	 * Find the next SOFT expiration.
1201 	 */
1202 	expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_SOFT);
1203 
1204 	/*
1205 	 * reprogramming needs to be triggered, even if the next soft
1206 	 * hrtimer expires at the same time than the next hard
1207 	 * hrtimer. cpu_base->softirq_expires_next needs to be updated!
1208 	 */
1209 	if (expires == KTIME_MAX)
1210 		return;
1211 
1212 	/*
1213 	 * cpu_base->*next_timer is recomputed by __hrtimer_get_next_event()
1214 	 * cpu_base->*expires_next is only set by hrtimer_reprogram()
1215 	 */
1216 	hrtimer_reprogram(cpu_base->softirq_next_timer, reprogram);
1217 }
1218 
__hrtimer_start_range_ns(struct hrtimer * timer,ktime_t tim,u64 delta_ns,const enum hrtimer_mode mode,struct hrtimer_clock_base * base)1219 static int __hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1220 				    u64 delta_ns, const enum hrtimer_mode mode,
1221 				    struct hrtimer_clock_base *base)
1222 {
1223 	struct hrtimer_cpu_base *this_cpu_base = this_cpu_ptr(&hrtimer_bases);
1224 	struct hrtimer_clock_base *new_base;
1225 	bool force_local, first;
1226 
1227 	/*
1228 	 * If the timer is on the local cpu base and is the first expiring
1229 	 * timer then this might end up reprogramming the hardware twice
1230 	 * (on removal and on enqueue). To avoid that by prevent the
1231 	 * reprogram on removal, keep the timer local to the current CPU
1232 	 * and enforce reprogramming after it is queued no matter whether
1233 	 * it is the new first expiring timer again or not.
1234 	 */
1235 	force_local = base->cpu_base == this_cpu_base;
1236 	force_local &= base->cpu_base->next_timer == timer;
1237 
1238 	/*
1239 	 * Don't force local queuing if this enqueue happens on a unplugged
1240 	 * CPU after hrtimer_cpu_dying() has been invoked.
1241 	 */
1242 	force_local &= this_cpu_base->online;
1243 
1244 	/*
1245 	 * Remove an active timer from the queue. In case it is not queued
1246 	 * on the current CPU, make sure that remove_hrtimer() updates the
1247 	 * remote data correctly.
1248 	 *
1249 	 * If it's on the current CPU and the first expiring timer, then
1250 	 * skip reprogramming, keep the timer local and enforce
1251 	 * reprogramming later if it was the first expiring timer.  This
1252 	 * avoids programming the underlying clock event twice (once at
1253 	 * removal and once after enqueue).
1254 	 */
1255 	remove_hrtimer(timer, base, true, force_local);
1256 
1257 	if (mode & HRTIMER_MODE_REL)
1258 		tim = ktime_add_safe(tim, base->get_time());
1259 
1260 	tim = hrtimer_update_lowres(timer, tim, mode);
1261 
1262 	hrtimer_set_expires_range_ns(timer, tim, delta_ns);
1263 
1264 	/* Switch the timer base, if necessary: */
1265 	if (!force_local) {
1266 		new_base = switch_hrtimer_base(timer, base,
1267 					       mode & HRTIMER_MODE_PINNED);
1268 	} else {
1269 		new_base = base;
1270 	}
1271 
1272 	first = enqueue_hrtimer(timer, new_base, mode);
1273 	if (!force_local) {
1274 		/*
1275 		 * If the current CPU base is online, then the timer is
1276 		 * never queued on a remote CPU if it would be the first
1277 		 * expiring timer there.
1278 		 */
1279 		if (hrtimer_base_is_online(this_cpu_base))
1280 			return first;
1281 
1282 		/*
1283 		 * Timer was enqueued remote because the current base is
1284 		 * already offline. If the timer is the first to expire,
1285 		 * kick the remote CPU to reprogram the clock event.
1286 		 */
1287 		if (first) {
1288 			struct hrtimer_cpu_base *new_cpu_base = new_base->cpu_base;
1289 
1290 			smp_call_function_single_async(new_cpu_base->cpu, &new_cpu_base->csd);
1291 		}
1292 		return 0;
1293 	}
1294 
1295 	/*
1296 	 * Timer was forced to stay on the current CPU to avoid
1297 	 * reprogramming on removal and enqueue. Force reprogram the
1298 	 * hardware by evaluating the new first expiring timer.
1299 	 */
1300 	hrtimer_force_reprogram(new_base->cpu_base, 1);
1301 	return 0;
1302 }
1303 
1304 /**
1305  * hrtimer_start_range_ns - (re)start an hrtimer
1306  * @timer:	the timer to be added
1307  * @tim:	expiry time
1308  * @delta_ns:	"slack" range for the timer
1309  * @mode:	timer mode: absolute (HRTIMER_MODE_ABS) or
1310  *		relative (HRTIMER_MODE_REL), and pinned (HRTIMER_MODE_PINNED);
1311  *		softirq based mode is considered for debug purpose only!
1312  */
hrtimer_start_range_ns(struct hrtimer * timer,ktime_t tim,u64 delta_ns,const enum hrtimer_mode mode)1313 void hrtimer_start_range_ns(struct hrtimer *timer, ktime_t tim,
1314 			    u64 delta_ns, const enum hrtimer_mode mode)
1315 {
1316 	struct hrtimer_clock_base *base;
1317 	unsigned long flags;
1318 
1319 	if (WARN_ON_ONCE(!timer->function))
1320 		return;
1321 	/*
1322 	 * Check whether the HRTIMER_MODE_SOFT bit and hrtimer.is_soft
1323 	 * match on CONFIG_PREEMPT_RT = n. With PREEMPT_RT check the hard
1324 	 * expiry mode because unmarked timers are moved to softirq expiry.
1325 	 */
1326 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
1327 		WARN_ON_ONCE(!(mode & HRTIMER_MODE_SOFT) ^ !timer->is_soft);
1328 	else
1329 		WARN_ON_ONCE(!(mode & HRTIMER_MODE_HARD) ^ !timer->is_hard);
1330 
1331 	base = lock_hrtimer_base(timer, &flags);
1332 
1333 	if (__hrtimer_start_range_ns(timer, tim, delta_ns, mode, base))
1334 		hrtimer_reprogram(timer, true);
1335 
1336 	unlock_hrtimer_base(timer, &flags);
1337 }
1338 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1339 
1340 /**
1341  * hrtimer_try_to_cancel - try to deactivate a timer
1342  * @timer:	hrtimer to stop
1343  *
1344  * Returns:
1345  *
1346  *  *  0 when the timer was not active
1347  *  *  1 when the timer was active
1348  *  * -1 when the timer is currently executing the callback function and
1349  *    cannot be stopped
1350  */
hrtimer_try_to_cancel(struct hrtimer * timer)1351 int hrtimer_try_to_cancel(struct hrtimer *timer)
1352 {
1353 	struct hrtimer_clock_base *base;
1354 	unsigned long flags;
1355 	int ret = -1;
1356 
1357 	/*
1358 	 * Check lockless first. If the timer is not active (neither
1359 	 * enqueued nor running the callback, nothing to do here.  The
1360 	 * base lock does not serialize against a concurrent enqueue,
1361 	 * so we can avoid taking it.
1362 	 */
1363 	if (!hrtimer_active(timer))
1364 		return 0;
1365 
1366 	base = lock_hrtimer_base(timer, &flags);
1367 
1368 	if (!hrtimer_callback_running(timer))
1369 		ret = remove_hrtimer(timer, base, false, false);
1370 
1371 	unlock_hrtimer_base(timer, &flags);
1372 
1373 	return ret;
1374 
1375 }
1376 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1377 
1378 #ifdef CONFIG_PREEMPT_RT
hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base * base)1379 static void hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base)
1380 {
1381 	spin_lock_init(&base->softirq_expiry_lock);
1382 }
1383 
hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base * base)1384 static void hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base)
1385 	__acquires(&base->softirq_expiry_lock)
1386 {
1387 	spin_lock(&base->softirq_expiry_lock);
1388 }
1389 
hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base * base)1390 static void hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base)
1391 	__releases(&base->softirq_expiry_lock)
1392 {
1393 	spin_unlock(&base->softirq_expiry_lock);
1394 }
1395 
1396 /*
1397  * The counterpart to hrtimer_cancel_wait_running().
1398  *
1399  * If there is a waiter for cpu_base->expiry_lock, then it was waiting for
1400  * the timer callback to finish. Drop expiry_lock and reacquire it. That
1401  * allows the waiter to acquire the lock and make progress.
1402  */
hrtimer_sync_wait_running(struct hrtimer_cpu_base * cpu_base,unsigned long flags)1403 static void hrtimer_sync_wait_running(struct hrtimer_cpu_base *cpu_base,
1404 				      unsigned long flags)
1405 {
1406 	if (atomic_read(&cpu_base->timer_waiters)) {
1407 		raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1408 		spin_unlock(&cpu_base->softirq_expiry_lock);
1409 		spin_lock(&cpu_base->softirq_expiry_lock);
1410 		raw_spin_lock_irq(&cpu_base->lock);
1411 	}
1412 }
1413 
1414 #ifdef CONFIG_SMP
is_migration_base(struct hrtimer_clock_base * base)1415 static __always_inline bool is_migration_base(struct hrtimer_clock_base *base)
1416 {
1417 	return base == &migration_base;
1418 }
1419 #else
is_migration_base(struct hrtimer_clock_base * base)1420 static __always_inline bool is_migration_base(struct hrtimer_clock_base *base)
1421 {
1422 	return false;
1423 }
1424 #endif
1425 
1426 /*
1427  * This function is called on PREEMPT_RT kernels when the fast path
1428  * deletion of a timer failed because the timer callback function was
1429  * running.
1430  *
1431  * This prevents priority inversion: if the soft irq thread is preempted
1432  * in the middle of a timer callback, then calling del_timer_sync() can
1433  * lead to two issues:
1434  *
1435  *  - If the caller is on a remote CPU then it has to spin wait for the timer
1436  *    handler to complete. This can result in unbound priority inversion.
1437  *
1438  *  - If the caller originates from the task which preempted the timer
1439  *    handler on the same CPU, then spin waiting for the timer handler to
1440  *    complete is never going to end.
1441  */
hrtimer_cancel_wait_running(const struct hrtimer * timer)1442 void hrtimer_cancel_wait_running(const struct hrtimer *timer)
1443 {
1444 	/* Lockless read. Prevent the compiler from reloading it below */
1445 	struct hrtimer_clock_base *base = READ_ONCE(timer->base);
1446 
1447 	/*
1448 	 * Just relax if the timer expires in hard interrupt context or if
1449 	 * it is currently on the migration base.
1450 	 */
1451 	if (!timer->is_soft || is_migration_base(base)) {
1452 		cpu_relax();
1453 		return;
1454 	}
1455 
1456 	/*
1457 	 * Mark the base as contended and grab the expiry lock, which is
1458 	 * held by the softirq across the timer callback. Drop the lock
1459 	 * immediately so the softirq can expire the next timer. In theory
1460 	 * the timer could already be running again, but that's more than
1461 	 * unlikely and just causes another wait loop.
1462 	 */
1463 	atomic_inc(&base->cpu_base->timer_waiters);
1464 	spin_lock_bh(&base->cpu_base->softirq_expiry_lock);
1465 	atomic_dec(&base->cpu_base->timer_waiters);
1466 	spin_unlock_bh(&base->cpu_base->softirq_expiry_lock);
1467 }
1468 #else
1469 static inline void
hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base * base)1470 hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base) { }
1471 static inline void
hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base * base)1472 hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base) { }
1473 static inline void
hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base * base)1474 hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base) { }
hrtimer_sync_wait_running(struct hrtimer_cpu_base * base,unsigned long flags)1475 static inline void hrtimer_sync_wait_running(struct hrtimer_cpu_base *base,
1476 					     unsigned long flags) { }
1477 #endif
1478 
1479 /**
1480  * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1481  * @timer:	the timer to be cancelled
1482  *
1483  * Returns:
1484  *  0 when the timer was not active
1485  *  1 when the timer was active
1486  */
hrtimer_cancel(struct hrtimer * timer)1487 int hrtimer_cancel(struct hrtimer *timer)
1488 {
1489 	int ret;
1490 
1491 	do {
1492 		ret = hrtimer_try_to_cancel(timer);
1493 
1494 		if (ret < 0)
1495 			hrtimer_cancel_wait_running(timer);
1496 	} while (ret < 0);
1497 	return ret;
1498 }
1499 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1500 
1501 /**
1502  * __hrtimer_get_remaining - get remaining time for the timer
1503  * @timer:	the timer to read
1504  * @adjust:	adjust relative timers when CONFIG_TIME_LOW_RES=y
1505  */
__hrtimer_get_remaining(const struct hrtimer * timer,bool adjust)1506 ktime_t __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust)
1507 {
1508 	unsigned long flags;
1509 	ktime_t rem;
1510 
1511 	lock_hrtimer_base(timer, &flags);
1512 	if (IS_ENABLED(CONFIG_TIME_LOW_RES) && adjust)
1513 		rem = hrtimer_expires_remaining_adjusted(timer);
1514 	else
1515 		rem = hrtimer_expires_remaining(timer);
1516 	unlock_hrtimer_base(timer, &flags);
1517 
1518 	return rem;
1519 }
1520 EXPORT_SYMBOL_GPL(__hrtimer_get_remaining);
1521 
1522 #ifdef CONFIG_NO_HZ_COMMON
1523 /**
1524  * hrtimer_get_next_event - get the time until next expiry event
1525  *
1526  * Returns the next expiry time or KTIME_MAX if no timer is pending.
1527  */
hrtimer_get_next_event(void)1528 u64 hrtimer_get_next_event(void)
1529 {
1530 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1531 	u64 expires = KTIME_MAX;
1532 	unsigned long flags;
1533 
1534 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1535 
1536 	if (!hrtimer_hres_active(cpu_base))
1537 		expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_ALL);
1538 
1539 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1540 
1541 	return expires;
1542 }
1543 
1544 /**
1545  * hrtimer_next_event_without - time until next expiry event w/o one timer
1546  * @exclude:	timer to exclude
1547  *
1548  * Returns the next expiry time over all timers except for the @exclude one or
1549  * KTIME_MAX if none of them is pending.
1550  */
hrtimer_next_event_without(const struct hrtimer * exclude)1551 u64 hrtimer_next_event_without(const struct hrtimer *exclude)
1552 {
1553 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1554 	u64 expires = KTIME_MAX;
1555 	unsigned long flags;
1556 
1557 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1558 
1559 	if (hrtimer_hres_active(cpu_base)) {
1560 		unsigned int active;
1561 
1562 		if (!cpu_base->softirq_activated) {
1563 			active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT;
1564 			expires = __hrtimer_next_event_base(cpu_base, exclude,
1565 							    active, KTIME_MAX);
1566 		}
1567 		active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD;
1568 		expires = __hrtimer_next_event_base(cpu_base, exclude, active,
1569 						    expires);
1570 	}
1571 
1572 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1573 
1574 	return expires;
1575 }
1576 #endif
1577 
hrtimer_clockid_to_base(clockid_t clock_id)1578 static inline int hrtimer_clockid_to_base(clockid_t clock_id)
1579 {
1580 	switch (clock_id) {
1581 	case CLOCK_REALTIME:
1582 		return HRTIMER_BASE_REALTIME;
1583 	case CLOCK_MONOTONIC:
1584 		return HRTIMER_BASE_MONOTONIC;
1585 	case CLOCK_BOOTTIME:
1586 		return HRTIMER_BASE_BOOTTIME;
1587 	case CLOCK_TAI:
1588 		return HRTIMER_BASE_TAI;
1589 	default:
1590 		WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id);
1591 		return HRTIMER_BASE_MONOTONIC;
1592 	}
1593 }
1594 
__hrtimer_init(struct hrtimer * timer,clockid_t clock_id,enum hrtimer_mode mode)1595 static void __hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1596 			   enum hrtimer_mode mode)
1597 {
1598 	bool softtimer = !!(mode & HRTIMER_MODE_SOFT);
1599 	struct hrtimer_cpu_base *cpu_base;
1600 	int base;
1601 
1602 	/*
1603 	 * On PREEMPT_RT enabled kernels hrtimers which are not explicitly
1604 	 * marked for hard interrupt expiry mode are moved into soft
1605 	 * interrupt context for latency reasons and because the callbacks
1606 	 * can invoke functions which might sleep on RT, e.g. spin_lock().
1607 	 */
1608 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(mode & HRTIMER_MODE_HARD))
1609 		softtimer = true;
1610 
1611 	memset(timer, 0, sizeof(struct hrtimer));
1612 
1613 	cpu_base = raw_cpu_ptr(&hrtimer_bases);
1614 
1615 	/*
1616 	 * POSIX magic: Relative CLOCK_REALTIME timers are not affected by
1617 	 * clock modifications, so they needs to become CLOCK_MONOTONIC to
1618 	 * ensure POSIX compliance.
1619 	 */
1620 	if (clock_id == CLOCK_REALTIME && mode & HRTIMER_MODE_REL)
1621 		clock_id = CLOCK_MONOTONIC;
1622 
1623 	base = softtimer ? HRTIMER_MAX_CLOCK_BASES / 2 : 0;
1624 	base += hrtimer_clockid_to_base(clock_id);
1625 	timer->is_soft = softtimer;
1626 	timer->is_hard = !!(mode & HRTIMER_MODE_HARD);
1627 	timer->base = &cpu_base->clock_base[base];
1628 	timerqueue_init(&timer->node);
1629 }
1630 
__hrtimer_setup(struct hrtimer * timer,enum hrtimer_restart (* function)(struct hrtimer *),clockid_t clock_id,enum hrtimer_mode mode)1631 static void __hrtimer_setup(struct hrtimer *timer,
1632 			    enum hrtimer_restart (*function)(struct hrtimer *),
1633 			    clockid_t clock_id, enum hrtimer_mode mode)
1634 {
1635 	__hrtimer_init(timer, clock_id, mode);
1636 
1637 	if (WARN_ON_ONCE(!function))
1638 		timer->function = hrtimer_dummy_timeout;
1639 	else
1640 		timer->function = function;
1641 }
1642 
1643 /**
1644  * hrtimer_init - initialize a timer to the given clock
1645  * @timer:	the timer to be initialized
1646  * @clock_id:	the clock to be used
1647  * @mode:       The modes which are relevant for initialization:
1648  *              HRTIMER_MODE_ABS, HRTIMER_MODE_REL, HRTIMER_MODE_ABS_SOFT,
1649  *              HRTIMER_MODE_REL_SOFT
1650  *
1651  *              The PINNED variants of the above can be handed in,
1652  *              but the PINNED bit is ignored as pinning happens
1653  *              when the hrtimer is started
1654  */
hrtimer_init(struct hrtimer * timer,clockid_t clock_id,enum hrtimer_mode mode)1655 void hrtimer_init(struct hrtimer *timer, clockid_t clock_id,
1656 		  enum hrtimer_mode mode)
1657 {
1658 	debug_init(timer, clock_id, mode);
1659 	__hrtimer_init(timer, clock_id, mode);
1660 }
1661 EXPORT_SYMBOL_GPL(hrtimer_init);
1662 
1663 /**
1664  * hrtimer_setup - initialize a timer to the given clock
1665  * @timer:	the timer to be initialized
1666  * @function:	the callback function
1667  * @clock_id:	the clock to be used
1668  * @mode:       The modes which are relevant for initialization:
1669  *              HRTIMER_MODE_ABS, HRTIMER_MODE_REL, HRTIMER_MODE_ABS_SOFT,
1670  *              HRTIMER_MODE_REL_SOFT
1671  *
1672  *              The PINNED variants of the above can be handed in,
1673  *              but the PINNED bit is ignored as pinning happens
1674  *              when the hrtimer is started
1675  */
hrtimer_setup(struct hrtimer * timer,enum hrtimer_restart (* function)(struct hrtimer *),clockid_t clock_id,enum hrtimer_mode mode)1676 void hrtimer_setup(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *),
1677 		   clockid_t clock_id, enum hrtimer_mode mode)
1678 {
1679 	debug_init(timer, clock_id, mode);
1680 	__hrtimer_setup(timer, function, clock_id, mode);
1681 }
1682 EXPORT_SYMBOL_GPL(hrtimer_setup);
1683 
1684 /**
1685  * hrtimer_setup_on_stack - initialize a timer on stack memory
1686  * @timer:	The timer to be initialized
1687  * @function:	the callback function
1688  * @clock_id:	The clock to be used
1689  * @mode:       The timer mode
1690  *
1691  * Similar to hrtimer_setup(), except that this one must be used if struct hrtimer is in stack
1692  * memory.
1693  */
hrtimer_setup_on_stack(struct hrtimer * timer,enum hrtimer_restart (* function)(struct hrtimer *),clockid_t clock_id,enum hrtimer_mode mode)1694 void hrtimer_setup_on_stack(struct hrtimer *timer,
1695 			    enum hrtimer_restart (*function)(struct hrtimer *),
1696 			    clockid_t clock_id, enum hrtimer_mode mode)
1697 {
1698 	debug_init_on_stack(timer, clock_id, mode);
1699 	__hrtimer_setup(timer, function, clock_id, mode);
1700 }
1701 EXPORT_SYMBOL_GPL(hrtimer_setup_on_stack);
1702 
1703 /*
1704  * A timer is active, when it is enqueued into the rbtree or the
1705  * callback function is running or it's in the state of being migrated
1706  * to another cpu.
1707  *
1708  * It is important for this function to not return a false negative.
1709  */
hrtimer_active(const struct hrtimer * timer)1710 bool hrtimer_active(const struct hrtimer *timer)
1711 {
1712 	struct hrtimer_clock_base *base;
1713 	unsigned int seq;
1714 
1715 	do {
1716 		base = READ_ONCE(timer->base);
1717 		seq = raw_read_seqcount_begin(&base->seq);
1718 
1719 		if (timer->state != HRTIMER_STATE_INACTIVE ||
1720 		    base->running == timer)
1721 			return true;
1722 
1723 	} while (read_seqcount_retry(&base->seq, seq) ||
1724 		 base != READ_ONCE(timer->base));
1725 
1726 	return false;
1727 }
1728 EXPORT_SYMBOL_GPL(hrtimer_active);
1729 
1730 /*
1731  * The write_seqcount_barrier()s in __run_hrtimer() split the thing into 3
1732  * distinct sections:
1733  *
1734  *  - queued:	the timer is queued
1735  *  - callback:	the timer is being ran
1736  *  - post:	the timer is inactive or (re)queued
1737  *
1738  * On the read side we ensure we observe timer->state and cpu_base->running
1739  * from the same section, if anything changed while we looked at it, we retry.
1740  * This includes timer->base changing because sequence numbers alone are
1741  * insufficient for that.
1742  *
1743  * The sequence numbers are required because otherwise we could still observe
1744  * a false negative if the read side got smeared over multiple consecutive
1745  * __run_hrtimer() invocations.
1746  */
1747 
__run_hrtimer(struct hrtimer_cpu_base * cpu_base,struct hrtimer_clock_base * base,struct hrtimer * timer,ktime_t * now,unsigned long flags)1748 static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base,
1749 			  struct hrtimer_clock_base *base,
1750 			  struct hrtimer *timer, ktime_t *now,
1751 			  unsigned long flags) __must_hold(&cpu_base->lock)
1752 {
1753 	enum hrtimer_restart (*fn)(struct hrtimer *);
1754 	bool expires_in_hardirq;
1755 	int restart;
1756 
1757 	lockdep_assert_held(&cpu_base->lock);
1758 
1759 	debug_deactivate(timer);
1760 	base->running = timer;
1761 
1762 	/*
1763 	 * Separate the ->running assignment from the ->state assignment.
1764 	 *
1765 	 * As with a regular write barrier, this ensures the read side in
1766 	 * hrtimer_active() cannot observe base->running == NULL &&
1767 	 * timer->state == INACTIVE.
1768 	 */
1769 	raw_write_seqcount_barrier(&base->seq);
1770 
1771 	__remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE, 0);
1772 	fn = timer->function;
1773 
1774 	/*
1775 	 * Clear the 'is relative' flag for the TIME_LOW_RES case. If the
1776 	 * timer is restarted with a period then it becomes an absolute
1777 	 * timer. If its not restarted it does not matter.
1778 	 */
1779 	if (IS_ENABLED(CONFIG_TIME_LOW_RES))
1780 		timer->is_rel = false;
1781 
1782 	/*
1783 	 * The timer is marked as running in the CPU base, so it is
1784 	 * protected against migration to a different CPU even if the lock
1785 	 * is dropped.
1786 	 */
1787 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1788 	trace_hrtimer_expire_entry(timer, now);
1789 	expires_in_hardirq = lockdep_hrtimer_enter(timer);
1790 
1791 	restart = fn(timer);
1792 
1793 	lockdep_hrtimer_exit(expires_in_hardirq);
1794 	trace_hrtimer_expire_exit(timer);
1795 	raw_spin_lock_irq(&cpu_base->lock);
1796 
1797 	/*
1798 	 * Note: We clear the running state after enqueue_hrtimer and
1799 	 * we do not reprogram the event hardware. Happens either in
1800 	 * hrtimer_start_range_ns() or in hrtimer_interrupt()
1801 	 *
1802 	 * Note: Because we dropped the cpu_base->lock above,
1803 	 * hrtimer_start_range_ns() can have popped in and enqueued the timer
1804 	 * for us already.
1805 	 */
1806 	if (restart != HRTIMER_NORESTART &&
1807 	    !(timer->state & HRTIMER_STATE_ENQUEUED))
1808 		enqueue_hrtimer(timer, base, HRTIMER_MODE_ABS);
1809 
1810 	/*
1811 	 * Separate the ->running assignment from the ->state assignment.
1812 	 *
1813 	 * As with a regular write barrier, this ensures the read side in
1814 	 * hrtimer_active() cannot observe base->running.timer == NULL &&
1815 	 * timer->state == INACTIVE.
1816 	 */
1817 	raw_write_seqcount_barrier(&base->seq);
1818 
1819 	WARN_ON_ONCE(base->running != timer);
1820 	base->running = NULL;
1821 }
1822 
__hrtimer_run_queues(struct hrtimer_cpu_base * cpu_base,ktime_t now,unsigned long flags,unsigned int active_mask)1823 static void __hrtimer_run_queues(struct hrtimer_cpu_base *cpu_base, ktime_t now,
1824 				 unsigned long flags, unsigned int active_mask)
1825 {
1826 	struct hrtimer_clock_base *base;
1827 	unsigned int active = cpu_base->active_bases & active_mask;
1828 
1829 	for_each_active_base(base, cpu_base, active) {
1830 		struct timerqueue_node *node;
1831 		ktime_t basenow;
1832 
1833 		basenow = ktime_add(now, base->offset);
1834 
1835 		while ((node = timerqueue_getnext(&base->active))) {
1836 			struct hrtimer *timer;
1837 
1838 			timer = container_of(node, struct hrtimer, node);
1839 
1840 			/*
1841 			 * The immediate goal for using the softexpires is
1842 			 * minimizing wakeups, not running timers at the
1843 			 * earliest interrupt after their soft expiration.
1844 			 * This allows us to avoid using a Priority Search
1845 			 * Tree, which can answer a stabbing query for
1846 			 * overlapping intervals and instead use the simple
1847 			 * BST we already have.
1848 			 * We don't add extra wakeups by delaying timers that
1849 			 * are right-of a not yet expired timer, because that
1850 			 * timer will have to trigger a wakeup anyway.
1851 			 */
1852 			if (basenow < hrtimer_get_softexpires_tv64(timer))
1853 				break;
1854 
1855 			__run_hrtimer(cpu_base, base, timer, &basenow, flags);
1856 			if (active_mask == HRTIMER_ACTIVE_SOFT)
1857 				hrtimer_sync_wait_running(cpu_base, flags);
1858 		}
1859 	}
1860 }
1861 
hrtimer_run_softirq(void)1862 static __latent_entropy void hrtimer_run_softirq(void)
1863 {
1864 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1865 	unsigned long flags;
1866 	ktime_t now;
1867 
1868 	hrtimer_cpu_base_lock_expiry(cpu_base);
1869 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1870 
1871 	now = hrtimer_update_base(cpu_base);
1872 	__hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_SOFT);
1873 
1874 	cpu_base->softirq_activated = 0;
1875 	hrtimer_update_softirq_timer(cpu_base, true);
1876 
1877 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1878 	hrtimer_cpu_base_unlock_expiry(cpu_base);
1879 }
1880 
1881 #ifdef CONFIG_HIGH_RES_TIMERS
1882 
1883 /*
1884  * High resolution timer interrupt
1885  * Called with interrupts disabled
1886  */
hrtimer_interrupt(struct clock_event_device * dev)1887 void hrtimer_interrupt(struct clock_event_device *dev)
1888 {
1889 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1890 	ktime_t expires_next, now, entry_time, delta;
1891 	unsigned long flags;
1892 	int retries = 0;
1893 
1894 	BUG_ON(!cpu_base->hres_active);
1895 	cpu_base->nr_events++;
1896 	dev->next_event = KTIME_MAX;
1897 
1898 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1899 	entry_time = now = hrtimer_update_base(cpu_base);
1900 retry:
1901 	cpu_base->in_hrtirq = 1;
1902 	/*
1903 	 * We set expires_next to KTIME_MAX here with cpu_base->lock
1904 	 * held to prevent that a timer is enqueued in our queue via
1905 	 * the migration code. This does not affect enqueueing of
1906 	 * timers which run their callback and need to be requeued on
1907 	 * this CPU.
1908 	 */
1909 	cpu_base->expires_next = KTIME_MAX;
1910 
1911 	if (!ktime_before(now, cpu_base->softirq_expires_next)) {
1912 		cpu_base->softirq_expires_next = KTIME_MAX;
1913 		cpu_base->softirq_activated = 1;
1914 		raise_timer_softirq(HRTIMER_SOFTIRQ);
1915 	}
1916 
1917 	__hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
1918 
1919 	/* Reevaluate the clock bases for the [soft] next expiry */
1920 	expires_next = hrtimer_update_next_event(cpu_base);
1921 	/*
1922 	 * Store the new expiry value so the migration code can verify
1923 	 * against it.
1924 	 */
1925 	cpu_base->expires_next = expires_next;
1926 	cpu_base->in_hrtirq = 0;
1927 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1928 
1929 	/* Reprogramming necessary ? */
1930 	if (!tick_program_event(expires_next, 0)) {
1931 		cpu_base->hang_detected = 0;
1932 		return;
1933 	}
1934 
1935 	/*
1936 	 * The next timer was already expired due to:
1937 	 * - tracing
1938 	 * - long lasting callbacks
1939 	 * - being scheduled away when running in a VM
1940 	 *
1941 	 * We need to prevent that we loop forever in the hrtimer
1942 	 * interrupt routine. We give it 3 attempts to avoid
1943 	 * overreacting on some spurious event.
1944 	 *
1945 	 * Acquire base lock for updating the offsets and retrieving
1946 	 * the current time.
1947 	 */
1948 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1949 	now = hrtimer_update_base(cpu_base);
1950 	cpu_base->nr_retries++;
1951 	if (++retries < 3)
1952 		goto retry;
1953 	/*
1954 	 * Give the system a chance to do something else than looping
1955 	 * here. We stored the entry time, so we know exactly how long
1956 	 * we spent here. We schedule the next event this amount of
1957 	 * time away.
1958 	 */
1959 	cpu_base->nr_hangs++;
1960 	cpu_base->hang_detected = 1;
1961 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1962 
1963 	delta = ktime_sub(now, entry_time);
1964 	if ((unsigned int)delta > cpu_base->max_hang_time)
1965 		cpu_base->max_hang_time = (unsigned int) delta;
1966 	/*
1967 	 * Limit it to a sensible value as we enforce a longer
1968 	 * delay. Give the CPU at least 100ms to catch up.
1969 	 */
1970 	if (delta > 100 * NSEC_PER_MSEC)
1971 		expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1972 	else
1973 		expires_next = ktime_add(now, delta);
1974 	tick_program_event(expires_next, 1);
1975 	pr_warn_once("hrtimer: interrupt took %llu ns\n", ktime_to_ns(delta));
1976 }
1977 #endif /* !CONFIG_HIGH_RES_TIMERS */
1978 
1979 /*
1980  * Called from run_local_timers in hardirq context every jiffy
1981  */
hrtimer_run_queues(void)1982 void hrtimer_run_queues(void)
1983 {
1984 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1985 	unsigned long flags;
1986 	ktime_t now;
1987 
1988 	if (hrtimer_hres_active(cpu_base))
1989 		return;
1990 
1991 	/*
1992 	 * This _is_ ugly: We have to check periodically, whether we
1993 	 * can switch to highres and / or nohz mode. The clocksource
1994 	 * switch happens with xtime_lock held. Notification from
1995 	 * there only sets the check bit in the tick_oneshot code,
1996 	 * otherwise we might deadlock vs. xtime_lock.
1997 	 */
1998 	if (tick_check_oneshot_change(!hrtimer_is_hres_enabled())) {
1999 		hrtimer_switch_to_hres();
2000 		return;
2001 	}
2002 
2003 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
2004 	now = hrtimer_update_base(cpu_base);
2005 
2006 	if (!ktime_before(now, cpu_base->softirq_expires_next)) {
2007 		cpu_base->softirq_expires_next = KTIME_MAX;
2008 		cpu_base->softirq_activated = 1;
2009 		raise_timer_softirq(HRTIMER_SOFTIRQ);
2010 	}
2011 
2012 	__hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
2013 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
2014 }
2015 
2016 /*
2017  * Sleep related functions:
2018  */
hrtimer_wakeup(struct hrtimer * timer)2019 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
2020 {
2021 	struct hrtimer_sleeper *t =
2022 		container_of(timer, struct hrtimer_sleeper, timer);
2023 	struct task_struct *task = t->task;
2024 
2025 	t->task = NULL;
2026 	if (task)
2027 		wake_up_process(task);
2028 
2029 	return HRTIMER_NORESTART;
2030 }
2031 
2032 /**
2033  * hrtimer_sleeper_start_expires - Start a hrtimer sleeper timer
2034  * @sl:		sleeper to be started
2035  * @mode:	timer mode abs/rel
2036  *
2037  * Wrapper around hrtimer_start_expires() for hrtimer_sleeper based timers
2038  * to allow PREEMPT_RT to tweak the delivery mode (soft/hardirq context)
2039  */
hrtimer_sleeper_start_expires(struct hrtimer_sleeper * sl,enum hrtimer_mode mode)2040 void hrtimer_sleeper_start_expires(struct hrtimer_sleeper *sl,
2041 				   enum hrtimer_mode mode)
2042 {
2043 	/*
2044 	 * Make the enqueue delivery mode check work on RT. If the sleeper
2045 	 * was initialized for hard interrupt delivery, force the mode bit.
2046 	 * This is a special case for hrtimer_sleepers because
2047 	 * __hrtimer_init_sleeper() determines the delivery mode on RT so the
2048 	 * fiddling with this decision is avoided at the call sites.
2049 	 */
2050 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && sl->timer.is_hard)
2051 		mode |= HRTIMER_MODE_HARD;
2052 
2053 	hrtimer_start_expires(&sl->timer, mode);
2054 }
2055 EXPORT_SYMBOL_GPL(hrtimer_sleeper_start_expires);
2056 
__hrtimer_init_sleeper(struct hrtimer_sleeper * sl,clockid_t clock_id,enum hrtimer_mode mode)2057 static void __hrtimer_init_sleeper(struct hrtimer_sleeper *sl,
2058 				   clockid_t clock_id, enum hrtimer_mode mode)
2059 {
2060 	/*
2061 	 * On PREEMPT_RT enabled kernels hrtimers which are not explicitly
2062 	 * marked for hard interrupt expiry mode are moved into soft
2063 	 * interrupt context either for latency reasons or because the
2064 	 * hrtimer callback takes regular spinlocks or invokes other
2065 	 * functions which are not suitable for hard interrupt context on
2066 	 * PREEMPT_RT.
2067 	 *
2068 	 * The hrtimer_sleeper callback is RT compatible in hard interrupt
2069 	 * context, but there is a latency concern: Untrusted userspace can
2070 	 * spawn many threads which arm timers for the same expiry time on
2071 	 * the same CPU. That causes a latency spike due to the wakeup of
2072 	 * a gazillion threads.
2073 	 *
2074 	 * OTOH, privileged real-time user space applications rely on the
2075 	 * low latency of hard interrupt wakeups. If the current task is in
2076 	 * a real-time scheduling class, mark the mode for hard interrupt
2077 	 * expiry.
2078 	 */
2079 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
2080 		if (rt_or_dl_task_policy(current) && !(mode & HRTIMER_MODE_SOFT))
2081 			mode |= HRTIMER_MODE_HARD;
2082 	}
2083 
2084 	__hrtimer_init(&sl->timer, clock_id, mode);
2085 	sl->timer.function = hrtimer_wakeup;
2086 	sl->task = current;
2087 }
2088 
2089 /**
2090  * hrtimer_setup_sleeper_on_stack - initialize a sleeper in stack memory
2091  * @sl:		sleeper to be initialized
2092  * @clock_id:	the clock to be used
2093  * @mode:	timer mode abs/rel
2094  */
hrtimer_setup_sleeper_on_stack(struct hrtimer_sleeper * sl,clockid_t clock_id,enum hrtimer_mode mode)2095 void hrtimer_setup_sleeper_on_stack(struct hrtimer_sleeper *sl,
2096 				    clockid_t clock_id, enum hrtimer_mode mode)
2097 {
2098 	debug_init_on_stack(&sl->timer, clock_id, mode);
2099 	__hrtimer_init_sleeper(sl, clock_id, mode);
2100 }
2101 EXPORT_SYMBOL_GPL(hrtimer_setup_sleeper_on_stack);
2102 
nanosleep_copyout(struct restart_block * restart,struct timespec64 * ts)2103 int nanosleep_copyout(struct restart_block *restart, struct timespec64 *ts)
2104 {
2105 	switch(restart->nanosleep.type) {
2106 #ifdef CONFIG_COMPAT_32BIT_TIME
2107 	case TT_COMPAT:
2108 		if (put_old_timespec32(ts, restart->nanosleep.compat_rmtp))
2109 			return -EFAULT;
2110 		break;
2111 #endif
2112 	case TT_NATIVE:
2113 		if (put_timespec64(ts, restart->nanosleep.rmtp))
2114 			return -EFAULT;
2115 		break;
2116 	default:
2117 		BUG();
2118 	}
2119 	return -ERESTART_RESTARTBLOCK;
2120 }
2121 
do_nanosleep(struct hrtimer_sleeper * t,enum hrtimer_mode mode)2122 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
2123 {
2124 	struct restart_block *restart;
2125 
2126 	do {
2127 		set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
2128 		hrtimer_sleeper_start_expires(t, mode);
2129 
2130 		if (likely(t->task))
2131 			schedule();
2132 
2133 		hrtimer_cancel(&t->timer);
2134 		mode = HRTIMER_MODE_ABS;
2135 
2136 	} while (t->task && !signal_pending(current));
2137 
2138 	__set_current_state(TASK_RUNNING);
2139 
2140 	if (!t->task)
2141 		return 0;
2142 
2143 	restart = &current->restart_block;
2144 	if (restart->nanosleep.type != TT_NONE) {
2145 		ktime_t rem = hrtimer_expires_remaining(&t->timer);
2146 		struct timespec64 rmt;
2147 
2148 		if (rem <= 0)
2149 			return 0;
2150 		rmt = ktime_to_timespec64(rem);
2151 
2152 		return nanosleep_copyout(restart, &rmt);
2153 	}
2154 	return -ERESTART_RESTARTBLOCK;
2155 }
2156 
hrtimer_nanosleep_restart(struct restart_block * restart)2157 static long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
2158 {
2159 	struct hrtimer_sleeper t;
2160 	int ret;
2161 
2162 	hrtimer_setup_sleeper_on_stack(&t, restart->nanosleep.clockid, HRTIMER_MODE_ABS);
2163 	hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
2164 	ret = do_nanosleep(&t, HRTIMER_MODE_ABS);
2165 	destroy_hrtimer_on_stack(&t.timer);
2166 	return ret;
2167 }
2168 
hrtimer_nanosleep(ktime_t rqtp,const enum hrtimer_mode mode,const clockid_t clockid)2169 long hrtimer_nanosleep(ktime_t rqtp, const enum hrtimer_mode mode,
2170 		       const clockid_t clockid)
2171 {
2172 	struct restart_block *restart;
2173 	struct hrtimer_sleeper t;
2174 	int ret = 0;
2175 
2176 	hrtimer_setup_sleeper_on_stack(&t, clockid, mode);
2177 	hrtimer_set_expires_range_ns(&t.timer, rqtp, current->timer_slack_ns);
2178 	ret = do_nanosleep(&t, mode);
2179 	if (ret != -ERESTART_RESTARTBLOCK)
2180 		goto out;
2181 
2182 	/* Absolute timers do not update the rmtp value and restart: */
2183 	if (mode == HRTIMER_MODE_ABS) {
2184 		ret = -ERESTARTNOHAND;
2185 		goto out;
2186 	}
2187 
2188 	restart = &current->restart_block;
2189 	restart->nanosleep.clockid = t.timer.base->clockid;
2190 	restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
2191 	set_restart_fn(restart, hrtimer_nanosleep_restart);
2192 out:
2193 	destroy_hrtimer_on_stack(&t.timer);
2194 	return ret;
2195 }
2196 
2197 #ifdef CONFIG_64BIT
2198 
SYSCALL_DEFINE2(nanosleep,struct __kernel_timespec __user *,rqtp,struct __kernel_timespec __user *,rmtp)2199 SYSCALL_DEFINE2(nanosleep, struct __kernel_timespec __user *, rqtp,
2200 		struct __kernel_timespec __user *, rmtp)
2201 {
2202 	struct timespec64 tu;
2203 
2204 	if (get_timespec64(&tu, rqtp))
2205 		return -EFAULT;
2206 
2207 	if (!timespec64_valid(&tu))
2208 		return -EINVAL;
2209 
2210 	current->restart_block.fn = do_no_restart_syscall;
2211 	current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE;
2212 	current->restart_block.nanosleep.rmtp = rmtp;
2213 	return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL,
2214 				 CLOCK_MONOTONIC);
2215 }
2216 
2217 #endif
2218 
2219 #ifdef CONFIG_COMPAT_32BIT_TIME
2220 
SYSCALL_DEFINE2(nanosleep_time32,struct old_timespec32 __user *,rqtp,struct old_timespec32 __user *,rmtp)2221 SYSCALL_DEFINE2(nanosleep_time32, struct old_timespec32 __user *, rqtp,
2222 		       struct old_timespec32 __user *, rmtp)
2223 {
2224 	struct timespec64 tu;
2225 
2226 	if (get_old_timespec32(&tu, rqtp))
2227 		return -EFAULT;
2228 
2229 	if (!timespec64_valid(&tu))
2230 		return -EINVAL;
2231 
2232 	current->restart_block.fn = do_no_restart_syscall;
2233 	current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE;
2234 	current->restart_block.nanosleep.compat_rmtp = rmtp;
2235 	return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL,
2236 				 CLOCK_MONOTONIC);
2237 }
2238 #endif
2239 
2240 /*
2241  * Functions related to boot-time initialization:
2242  */
hrtimers_prepare_cpu(unsigned int cpu)2243 int hrtimers_prepare_cpu(unsigned int cpu)
2244 {
2245 	struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
2246 	int i;
2247 
2248 	for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
2249 		struct hrtimer_clock_base *clock_b = &cpu_base->clock_base[i];
2250 
2251 		clock_b->cpu_base = cpu_base;
2252 		seqcount_raw_spinlock_init(&clock_b->seq, &cpu_base->lock);
2253 		timerqueue_init_head(&clock_b->active);
2254 	}
2255 
2256 	cpu_base->cpu = cpu;
2257 	hrtimer_cpu_base_init_expiry_lock(cpu_base);
2258 	return 0;
2259 }
2260 
hrtimers_cpu_starting(unsigned int cpu)2261 int hrtimers_cpu_starting(unsigned int cpu)
2262 {
2263 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
2264 
2265 	/* Clear out any left over state from a CPU down operation */
2266 	cpu_base->active_bases = 0;
2267 	cpu_base->hres_active = 0;
2268 	cpu_base->hang_detected = 0;
2269 	cpu_base->next_timer = NULL;
2270 	cpu_base->softirq_next_timer = NULL;
2271 	cpu_base->expires_next = KTIME_MAX;
2272 	cpu_base->softirq_expires_next = KTIME_MAX;
2273 	cpu_base->online = 1;
2274 	return 0;
2275 }
2276 
2277 #ifdef CONFIG_HOTPLUG_CPU
2278 
migrate_hrtimer_list(struct hrtimer_clock_base * old_base,struct hrtimer_clock_base * new_base)2279 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
2280 				struct hrtimer_clock_base *new_base)
2281 {
2282 	struct hrtimer *timer;
2283 	struct timerqueue_node *node;
2284 
2285 	while ((node = timerqueue_getnext(&old_base->active))) {
2286 		timer = container_of(node, struct hrtimer, node);
2287 		BUG_ON(hrtimer_callback_running(timer));
2288 		debug_deactivate(timer);
2289 
2290 		/*
2291 		 * Mark it as ENQUEUED not INACTIVE otherwise the
2292 		 * timer could be seen as !active and just vanish away
2293 		 * under us on another CPU
2294 		 */
2295 		__remove_hrtimer(timer, old_base, HRTIMER_STATE_ENQUEUED, 0);
2296 		timer->base = new_base;
2297 		/*
2298 		 * Enqueue the timers on the new cpu. This does not
2299 		 * reprogram the event device in case the timer
2300 		 * expires before the earliest on this CPU, but we run
2301 		 * hrtimer_interrupt after we migrated everything to
2302 		 * sort out already expired timers and reprogram the
2303 		 * event device.
2304 		 */
2305 		enqueue_hrtimer(timer, new_base, HRTIMER_MODE_ABS);
2306 	}
2307 }
2308 
hrtimers_cpu_dying(unsigned int dying_cpu)2309 int hrtimers_cpu_dying(unsigned int dying_cpu)
2310 {
2311 	int i, ncpu = cpumask_any_and(cpu_active_mask, housekeeping_cpumask(HK_TYPE_TIMER));
2312 	struct hrtimer_cpu_base *old_base, *new_base;
2313 
2314 	old_base = this_cpu_ptr(&hrtimer_bases);
2315 	new_base = &per_cpu(hrtimer_bases, ncpu);
2316 
2317 	/*
2318 	 * The caller is globally serialized and nobody else
2319 	 * takes two locks at once, deadlock is not possible.
2320 	 */
2321 	raw_spin_lock(&old_base->lock);
2322 	raw_spin_lock_nested(&new_base->lock, SINGLE_DEPTH_NESTING);
2323 
2324 	for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
2325 		migrate_hrtimer_list(&old_base->clock_base[i],
2326 				     &new_base->clock_base[i]);
2327 	}
2328 
2329 	/*
2330 	 * The migration might have changed the first expiring softirq
2331 	 * timer on this CPU. Update it.
2332 	 */
2333 	__hrtimer_get_next_event(new_base, HRTIMER_ACTIVE_SOFT);
2334 	/* Tell the other CPU to retrigger the next event */
2335 	smp_call_function_single(ncpu, retrigger_next_event, NULL, 0);
2336 
2337 	raw_spin_unlock(&new_base->lock);
2338 	old_base->online = 0;
2339 	raw_spin_unlock(&old_base->lock);
2340 
2341 	return 0;
2342 }
2343 
2344 #endif /* CONFIG_HOTPLUG_CPU */
2345 
hrtimers_init(void)2346 void __init hrtimers_init(void)
2347 {
2348 	hrtimers_prepare_cpu(smp_processor_id());
2349 	hrtimers_cpu_starting(smp_processor_id());
2350 	open_softirq(HRTIMER_SOFTIRQ, hrtimer_run_softirq);
2351 }
2352