xref: /linux-6.15/kernel/time/hrtimer.c (revision fcea1ccf)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  *  Copyright(C) 2005-2006, Thomas Gleixner <[email protected]>
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 
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
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  */
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 
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 *
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 *
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  */
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  */
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 
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  */
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  */
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  */
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 
432 static inline void debug_hrtimer_init(struct hrtimer *timer)
433 {
434 	debug_object_init(timer, &hrtimer_debug_descr);
435 }
436 
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 
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 
448 static inline void debug_hrtimer_deactivate(struct hrtimer *timer)
449 {
450 	debug_object_deactivate(timer, &hrtimer_debug_descr);
451 }
452 
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 
461 static inline void debug_hrtimer_init(struct hrtimer *timer) { }
462 static inline void debug_hrtimer_init_on_stack(struct hrtimer *timer) { }
463 static inline void debug_hrtimer_activate(struct hrtimer *timer,
464 					  enum hrtimer_mode mode) { }
465 static inline void debug_hrtimer_deactivate(struct hrtimer *timer) { }
466 #endif
467 
468 static inline void
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 
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 
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 
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 *
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 
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
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 
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 
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  */
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 
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
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  */
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  */
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  */
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 
758 static inline int hrtimer_is_hres_enabled(void) { return 0; }
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  */
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  */
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 
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  */
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 
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  */
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  */
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
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  */
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  */
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  */
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
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 
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
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 
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  */
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 	/*
1320 	 * Check whether the HRTIMER_MODE_SOFT bit and hrtimer.is_soft
1321 	 * match on CONFIG_PREEMPT_RT = n. With PREEMPT_RT check the hard
1322 	 * expiry mode because unmarked timers are moved to softirq expiry.
1323 	 */
1324 	if (!IS_ENABLED(CONFIG_PREEMPT_RT))
1325 		WARN_ON_ONCE(!(mode & HRTIMER_MODE_SOFT) ^ !timer->is_soft);
1326 	else
1327 		WARN_ON_ONCE(!(mode & HRTIMER_MODE_HARD) ^ !timer->is_hard);
1328 
1329 	base = lock_hrtimer_base(timer, &flags);
1330 
1331 	if (__hrtimer_start_range_ns(timer, tim, delta_ns, mode, base))
1332 		hrtimer_reprogram(timer, true);
1333 
1334 	unlock_hrtimer_base(timer, &flags);
1335 }
1336 EXPORT_SYMBOL_GPL(hrtimer_start_range_ns);
1337 
1338 /**
1339  * hrtimer_try_to_cancel - try to deactivate a timer
1340  * @timer:	hrtimer to stop
1341  *
1342  * Returns:
1343  *
1344  *  *  0 when the timer was not active
1345  *  *  1 when the timer was active
1346  *  * -1 when the timer is currently executing the callback function and
1347  *    cannot be stopped
1348  */
1349 int hrtimer_try_to_cancel(struct hrtimer *timer)
1350 {
1351 	struct hrtimer_clock_base *base;
1352 	unsigned long flags;
1353 	int ret = -1;
1354 
1355 	/*
1356 	 * Check lockless first. If the timer is not active (neither
1357 	 * enqueued nor running the callback, nothing to do here.  The
1358 	 * base lock does not serialize against a concurrent enqueue,
1359 	 * so we can avoid taking it.
1360 	 */
1361 	if (!hrtimer_active(timer))
1362 		return 0;
1363 
1364 	base = lock_hrtimer_base(timer, &flags);
1365 
1366 	if (!hrtimer_callback_running(timer))
1367 		ret = remove_hrtimer(timer, base, false, false);
1368 
1369 	unlock_hrtimer_base(timer, &flags);
1370 
1371 	return ret;
1372 
1373 }
1374 EXPORT_SYMBOL_GPL(hrtimer_try_to_cancel);
1375 
1376 #ifdef CONFIG_PREEMPT_RT
1377 static void hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base)
1378 {
1379 	spin_lock_init(&base->softirq_expiry_lock);
1380 }
1381 
1382 static void hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base)
1383 	__acquires(&base->softirq_expiry_lock)
1384 {
1385 	spin_lock(&base->softirq_expiry_lock);
1386 }
1387 
1388 static void hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base)
1389 	__releases(&base->softirq_expiry_lock)
1390 {
1391 	spin_unlock(&base->softirq_expiry_lock);
1392 }
1393 
1394 /*
1395  * The counterpart to hrtimer_cancel_wait_running().
1396  *
1397  * If there is a waiter for cpu_base->expiry_lock, then it was waiting for
1398  * the timer callback to finish. Drop expiry_lock and reacquire it. That
1399  * allows the waiter to acquire the lock and make progress.
1400  */
1401 static void hrtimer_sync_wait_running(struct hrtimer_cpu_base *cpu_base,
1402 				      unsigned long flags)
1403 {
1404 	if (atomic_read(&cpu_base->timer_waiters)) {
1405 		raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1406 		spin_unlock(&cpu_base->softirq_expiry_lock);
1407 		spin_lock(&cpu_base->softirq_expiry_lock);
1408 		raw_spin_lock_irq(&cpu_base->lock);
1409 	}
1410 }
1411 
1412 #ifdef CONFIG_SMP
1413 static __always_inline bool is_migration_base(struct hrtimer_clock_base *base)
1414 {
1415 	return base == &migration_base;
1416 }
1417 #else
1418 static __always_inline bool is_migration_base(struct hrtimer_clock_base *base)
1419 {
1420 	return false;
1421 }
1422 #endif
1423 
1424 /*
1425  * This function is called on PREEMPT_RT kernels when the fast path
1426  * deletion of a timer failed because the timer callback function was
1427  * running.
1428  *
1429  * This prevents priority inversion: if the soft irq thread is preempted
1430  * in the middle of a timer callback, then calling hrtimer_cancel() can
1431  * lead to two issues:
1432  *
1433  *  - If the caller is on a remote CPU then it has to spin wait for the timer
1434  *    handler to complete. This can result in unbound priority inversion.
1435  *
1436  *  - If the caller originates from the task which preempted the timer
1437  *    handler on the same CPU, then spin waiting for the timer handler to
1438  *    complete is never going to end.
1439  */
1440 void hrtimer_cancel_wait_running(const struct hrtimer *timer)
1441 {
1442 	/* Lockless read. Prevent the compiler from reloading it below */
1443 	struct hrtimer_clock_base *base = READ_ONCE(timer->base);
1444 
1445 	/*
1446 	 * Just relax if the timer expires in hard interrupt context or if
1447 	 * it is currently on the migration base.
1448 	 */
1449 	if (!timer->is_soft || is_migration_base(base)) {
1450 		cpu_relax();
1451 		return;
1452 	}
1453 
1454 	/*
1455 	 * Mark the base as contended and grab the expiry lock, which is
1456 	 * held by the softirq across the timer callback. Drop the lock
1457 	 * immediately so the softirq can expire the next timer. In theory
1458 	 * the timer could already be running again, but that's more than
1459 	 * unlikely and just causes another wait loop.
1460 	 */
1461 	atomic_inc(&base->cpu_base->timer_waiters);
1462 	spin_lock_bh(&base->cpu_base->softirq_expiry_lock);
1463 	atomic_dec(&base->cpu_base->timer_waiters);
1464 	spin_unlock_bh(&base->cpu_base->softirq_expiry_lock);
1465 }
1466 #else
1467 static inline void
1468 hrtimer_cpu_base_init_expiry_lock(struct hrtimer_cpu_base *base) { }
1469 static inline void
1470 hrtimer_cpu_base_lock_expiry(struct hrtimer_cpu_base *base) { }
1471 static inline void
1472 hrtimer_cpu_base_unlock_expiry(struct hrtimer_cpu_base *base) { }
1473 static inline void hrtimer_sync_wait_running(struct hrtimer_cpu_base *base,
1474 					     unsigned long flags) { }
1475 #endif
1476 
1477 /**
1478  * hrtimer_cancel - cancel a timer and wait for the handler to finish.
1479  * @timer:	the timer to be cancelled
1480  *
1481  * Returns:
1482  *  0 when the timer was not active
1483  *  1 when the timer was active
1484  */
1485 int hrtimer_cancel(struct hrtimer *timer)
1486 {
1487 	int ret;
1488 
1489 	do {
1490 		ret = hrtimer_try_to_cancel(timer);
1491 
1492 		if (ret < 0)
1493 			hrtimer_cancel_wait_running(timer);
1494 	} while (ret < 0);
1495 	return ret;
1496 }
1497 EXPORT_SYMBOL_GPL(hrtimer_cancel);
1498 
1499 /**
1500  * __hrtimer_get_remaining - get remaining time for the timer
1501  * @timer:	the timer to read
1502  * @adjust:	adjust relative timers when CONFIG_TIME_LOW_RES=y
1503  */
1504 ktime_t __hrtimer_get_remaining(const struct hrtimer *timer, bool adjust)
1505 {
1506 	unsigned long flags;
1507 	ktime_t rem;
1508 
1509 	lock_hrtimer_base(timer, &flags);
1510 	if (IS_ENABLED(CONFIG_TIME_LOW_RES) && adjust)
1511 		rem = hrtimer_expires_remaining_adjusted(timer);
1512 	else
1513 		rem = hrtimer_expires_remaining(timer);
1514 	unlock_hrtimer_base(timer, &flags);
1515 
1516 	return rem;
1517 }
1518 EXPORT_SYMBOL_GPL(__hrtimer_get_remaining);
1519 
1520 #ifdef CONFIG_NO_HZ_COMMON
1521 /**
1522  * hrtimer_get_next_event - get the time until next expiry event
1523  *
1524  * Returns the next expiry time or KTIME_MAX if no timer is pending.
1525  */
1526 u64 hrtimer_get_next_event(void)
1527 {
1528 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1529 	u64 expires = KTIME_MAX;
1530 	unsigned long flags;
1531 
1532 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1533 
1534 	if (!hrtimer_hres_active(cpu_base))
1535 		expires = __hrtimer_get_next_event(cpu_base, HRTIMER_ACTIVE_ALL);
1536 
1537 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1538 
1539 	return expires;
1540 }
1541 
1542 /**
1543  * hrtimer_next_event_without - time until next expiry event w/o one timer
1544  * @exclude:	timer to exclude
1545  *
1546  * Returns the next expiry time over all timers except for the @exclude one or
1547  * KTIME_MAX if none of them is pending.
1548  */
1549 u64 hrtimer_next_event_without(const struct hrtimer *exclude)
1550 {
1551 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1552 	u64 expires = KTIME_MAX;
1553 	unsigned long flags;
1554 
1555 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1556 
1557 	if (hrtimer_hres_active(cpu_base)) {
1558 		unsigned int active;
1559 
1560 		if (!cpu_base->softirq_activated) {
1561 			active = cpu_base->active_bases & HRTIMER_ACTIVE_SOFT;
1562 			expires = __hrtimer_next_event_base(cpu_base, exclude,
1563 							    active, KTIME_MAX);
1564 		}
1565 		active = cpu_base->active_bases & HRTIMER_ACTIVE_HARD;
1566 		expires = __hrtimer_next_event_base(cpu_base, exclude, active,
1567 						    expires);
1568 	}
1569 
1570 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1571 
1572 	return expires;
1573 }
1574 #endif
1575 
1576 static inline int hrtimer_clockid_to_base(clockid_t clock_id)
1577 {
1578 	switch (clock_id) {
1579 	case CLOCK_REALTIME:
1580 		return HRTIMER_BASE_REALTIME;
1581 	case CLOCK_MONOTONIC:
1582 		return HRTIMER_BASE_MONOTONIC;
1583 	case CLOCK_BOOTTIME:
1584 		return HRTIMER_BASE_BOOTTIME;
1585 	case CLOCK_TAI:
1586 		return HRTIMER_BASE_TAI;
1587 	default:
1588 		WARN(1, "Invalid clockid %d. Using MONOTONIC\n", clock_id);
1589 		return HRTIMER_BASE_MONOTONIC;
1590 	}
1591 }
1592 
1593 static void __hrtimer_setup(struct hrtimer *timer,
1594 			    enum hrtimer_restart (*function)(struct hrtimer *),
1595 			    clockid_t clock_id, enum hrtimer_mode mode)
1596 {
1597 	bool softtimer = !!(mode & HRTIMER_MODE_SOFT);
1598 	struct hrtimer_cpu_base *cpu_base;
1599 	int base;
1600 
1601 	/*
1602 	 * On PREEMPT_RT enabled kernels hrtimers which are not explicitly
1603 	 * marked for hard interrupt expiry mode are moved into soft
1604 	 * interrupt context for latency reasons and because the callbacks
1605 	 * can invoke functions which might sleep on RT, e.g. spin_lock().
1606 	 */
1607 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && !(mode & HRTIMER_MODE_HARD))
1608 		softtimer = true;
1609 
1610 	memset(timer, 0, sizeof(struct hrtimer));
1611 
1612 	cpu_base = raw_cpu_ptr(&hrtimer_bases);
1613 
1614 	/*
1615 	 * POSIX magic: Relative CLOCK_REALTIME timers are not affected by
1616 	 * clock modifications, so they needs to become CLOCK_MONOTONIC to
1617 	 * ensure POSIX compliance.
1618 	 */
1619 	if (clock_id == CLOCK_REALTIME && mode & HRTIMER_MODE_REL)
1620 		clock_id = CLOCK_MONOTONIC;
1621 
1622 	base = softtimer ? HRTIMER_MAX_CLOCK_BASES / 2 : 0;
1623 	base += hrtimer_clockid_to_base(clock_id);
1624 	timer->is_soft = softtimer;
1625 	timer->is_hard = !!(mode & HRTIMER_MODE_HARD);
1626 	timer->base = &cpu_base->clock_base[base];
1627 	timerqueue_init(&timer->node);
1628 
1629 	if (WARN_ON_ONCE(!function))
1630 		ACCESS_PRIVATE(timer, function) = hrtimer_dummy_timeout;
1631 	else
1632 		ACCESS_PRIVATE(timer, function) = function;
1633 }
1634 
1635 /**
1636  * hrtimer_setup - initialize a timer to the given clock
1637  * @timer:	the timer to be initialized
1638  * @function:	the callback function
1639  * @clock_id:	the clock to be used
1640  * @mode:       The modes which are relevant for initialization:
1641  *              HRTIMER_MODE_ABS, HRTIMER_MODE_REL, HRTIMER_MODE_ABS_SOFT,
1642  *              HRTIMER_MODE_REL_SOFT
1643  *
1644  *              The PINNED variants of the above can be handed in,
1645  *              but the PINNED bit is ignored as pinning happens
1646  *              when the hrtimer is started
1647  */
1648 void hrtimer_setup(struct hrtimer *timer, enum hrtimer_restart (*function)(struct hrtimer *),
1649 		   clockid_t clock_id, enum hrtimer_mode mode)
1650 {
1651 	debug_init(timer, clock_id, mode);
1652 	__hrtimer_setup(timer, function, clock_id, mode);
1653 }
1654 EXPORT_SYMBOL_GPL(hrtimer_setup);
1655 
1656 /**
1657  * hrtimer_setup_on_stack - initialize a timer on stack memory
1658  * @timer:	The timer to be initialized
1659  * @function:	the callback function
1660  * @clock_id:	The clock to be used
1661  * @mode:       The timer mode
1662  *
1663  * Similar to hrtimer_setup(), except that this one must be used if struct hrtimer is in stack
1664  * memory.
1665  */
1666 void hrtimer_setup_on_stack(struct hrtimer *timer,
1667 			    enum hrtimer_restart (*function)(struct hrtimer *),
1668 			    clockid_t clock_id, enum hrtimer_mode mode)
1669 {
1670 	debug_init_on_stack(timer, clock_id, mode);
1671 	__hrtimer_setup(timer, function, clock_id, mode);
1672 }
1673 EXPORT_SYMBOL_GPL(hrtimer_setup_on_stack);
1674 
1675 /*
1676  * A timer is active, when it is enqueued into the rbtree or the
1677  * callback function is running or it's in the state of being migrated
1678  * to another cpu.
1679  *
1680  * It is important for this function to not return a false negative.
1681  */
1682 bool hrtimer_active(const struct hrtimer *timer)
1683 {
1684 	struct hrtimer_clock_base *base;
1685 	unsigned int seq;
1686 
1687 	do {
1688 		base = READ_ONCE(timer->base);
1689 		seq = raw_read_seqcount_begin(&base->seq);
1690 
1691 		if (timer->state != HRTIMER_STATE_INACTIVE ||
1692 		    base->running == timer)
1693 			return true;
1694 
1695 	} while (read_seqcount_retry(&base->seq, seq) ||
1696 		 base != READ_ONCE(timer->base));
1697 
1698 	return false;
1699 }
1700 EXPORT_SYMBOL_GPL(hrtimer_active);
1701 
1702 /*
1703  * The write_seqcount_barrier()s in __run_hrtimer() split the thing into 3
1704  * distinct sections:
1705  *
1706  *  - queued:	the timer is queued
1707  *  - callback:	the timer is being ran
1708  *  - post:	the timer is inactive or (re)queued
1709  *
1710  * On the read side we ensure we observe timer->state and cpu_base->running
1711  * from the same section, if anything changed while we looked at it, we retry.
1712  * This includes timer->base changing because sequence numbers alone are
1713  * insufficient for that.
1714  *
1715  * The sequence numbers are required because otherwise we could still observe
1716  * a false negative if the read side got smeared over multiple consecutive
1717  * __run_hrtimer() invocations.
1718  */
1719 
1720 static void __run_hrtimer(struct hrtimer_cpu_base *cpu_base,
1721 			  struct hrtimer_clock_base *base,
1722 			  struct hrtimer *timer, ktime_t *now,
1723 			  unsigned long flags) __must_hold(&cpu_base->lock)
1724 {
1725 	enum hrtimer_restart (*fn)(struct hrtimer *);
1726 	bool expires_in_hardirq;
1727 	int restart;
1728 
1729 	lockdep_assert_held(&cpu_base->lock);
1730 
1731 	debug_deactivate(timer);
1732 	base->running = timer;
1733 
1734 	/*
1735 	 * Separate the ->running assignment from the ->state assignment.
1736 	 *
1737 	 * As with a regular write barrier, this ensures the read side in
1738 	 * hrtimer_active() cannot observe base->running == NULL &&
1739 	 * timer->state == INACTIVE.
1740 	 */
1741 	raw_write_seqcount_barrier(&base->seq);
1742 
1743 	__remove_hrtimer(timer, base, HRTIMER_STATE_INACTIVE, 0);
1744 	fn = ACCESS_PRIVATE(timer, function);
1745 
1746 	/*
1747 	 * Clear the 'is relative' flag for the TIME_LOW_RES case. If the
1748 	 * timer is restarted with a period then it becomes an absolute
1749 	 * timer. If its not restarted it does not matter.
1750 	 */
1751 	if (IS_ENABLED(CONFIG_TIME_LOW_RES))
1752 		timer->is_rel = false;
1753 
1754 	/*
1755 	 * The timer is marked as running in the CPU base, so it is
1756 	 * protected against migration to a different CPU even if the lock
1757 	 * is dropped.
1758 	 */
1759 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1760 	trace_hrtimer_expire_entry(timer, now);
1761 	expires_in_hardirq = lockdep_hrtimer_enter(timer);
1762 
1763 	restart = fn(timer);
1764 
1765 	lockdep_hrtimer_exit(expires_in_hardirq);
1766 	trace_hrtimer_expire_exit(timer);
1767 	raw_spin_lock_irq(&cpu_base->lock);
1768 
1769 	/*
1770 	 * Note: We clear the running state after enqueue_hrtimer and
1771 	 * we do not reprogram the event hardware. Happens either in
1772 	 * hrtimer_start_range_ns() or in hrtimer_interrupt()
1773 	 *
1774 	 * Note: Because we dropped the cpu_base->lock above,
1775 	 * hrtimer_start_range_ns() can have popped in and enqueued the timer
1776 	 * for us already.
1777 	 */
1778 	if (restart != HRTIMER_NORESTART &&
1779 	    !(timer->state & HRTIMER_STATE_ENQUEUED))
1780 		enqueue_hrtimer(timer, base, HRTIMER_MODE_ABS);
1781 
1782 	/*
1783 	 * Separate the ->running assignment from the ->state assignment.
1784 	 *
1785 	 * As with a regular write barrier, this ensures the read side in
1786 	 * hrtimer_active() cannot observe base->running.timer == NULL &&
1787 	 * timer->state == INACTIVE.
1788 	 */
1789 	raw_write_seqcount_barrier(&base->seq);
1790 
1791 	WARN_ON_ONCE(base->running != timer);
1792 	base->running = NULL;
1793 }
1794 
1795 static void __hrtimer_run_queues(struct hrtimer_cpu_base *cpu_base, ktime_t now,
1796 				 unsigned long flags, unsigned int active_mask)
1797 {
1798 	struct hrtimer_clock_base *base;
1799 	unsigned int active = cpu_base->active_bases & active_mask;
1800 
1801 	for_each_active_base(base, cpu_base, active) {
1802 		struct timerqueue_node *node;
1803 		ktime_t basenow;
1804 
1805 		basenow = ktime_add(now, base->offset);
1806 
1807 		while ((node = timerqueue_getnext(&base->active))) {
1808 			struct hrtimer *timer;
1809 
1810 			timer = container_of(node, struct hrtimer, node);
1811 
1812 			/*
1813 			 * The immediate goal for using the softexpires is
1814 			 * minimizing wakeups, not running timers at the
1815 			 * earliest interrupt after their soft expiration.
1816 			 * This allows us to avoid using a Priority Search
1817 			 * Tree, which can answer a stabbing query for
1818 			 * overlapping intervals and instead use the simple
1819 			 * BST we already have.
1820 			 * We don't add extra wakeups by delaying timers that
1821 			 * are right-of a not yet expired timer, because that
1822 			 * timer will have to trigger a wakeup anyway.
1823 			 */
1824 			if (basenow < hrtimer_get_softexpires_tv64(timer))
1825 				break;
1826 
1827 			__run_hrtimer(cpu_base, base, timer, &basenow, flags);
1828 			if (active_mask == HRTIMER_ACTIVE_SOFT)
1829 				hrtimer_sync_wait_running(cpu_base, flags);
1830 		}
1831 	}
1832 }
1833 
1834 static __latent_entropy void hrtimer_run_softirq(void)
1835 {
1836 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1837 	unsigned long flags;
1838 	ktime_t now;
1839 
1840 	hrtimer_cpu_base_lock_expiry(cpu_base);
1841 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1842 
1843 	now = hrtimer_update_base(cpu_base);
1844 	__hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_SOFT);
1845 
1846 	cpu_base->softirq_activated = 0;
1847 	hrtimer_update_softirq_timer(cpu_base, true);
1848 
1849 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1850 	hrtimer_cpu_base_unlock_expiry(cpu_base);
1851 }
1852 
1853 #ifdef CONFIG_HIGH_RES_TIMERS
1854 
1855 /*
1856  * High resolution timer interrupt
1857  * Called with interrupts disabled
1858  */
1859 void hrtimer_interrupt(struct clock_event_device *dev)
1860 {
1861 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1862 	ktime_t expires_next, now, entry_time, delta;
1863 	unsigned long flags;
1864 	int retries = 0;
1865 
1866 	BUG_ON(!cpu_base->hres_active);
1867 	cpu_base->nr_events++;
1868 	dev->next_event = KTIME_MAX;
1869 
1870 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1871 	entry_time = now = hrtimer_update_base(cpu_base);
1872 retry:
1873 	cpu_base->in_hrtirq = 1;
1874 	/*
1875 	 * We set expires_next to KTIME_MAX here with cpu_base->lock
1876 	 * held to prevent that a timer is enqueued in our queue via
1877 	 * the migration code. This does not affect enqueueing of
1878 	 * timers which run their callback and need to be requeued on
1879 	 * this CPU.
1880 	 */
1881 	cpu_base->expires_next = KTIME_MAX;
1882 
1883 	if (!ktime_before(now, cpu_base->softirq_expires_next)) {
1884 		cpu_base->softirq_expires_next = KTIME_MAX;
1885 		cpu_base->softirq_activated = 1;
1886 		raise_timer_softirq(HRTIMER_SOFTIRQ);
1887 	}
1888 
1889 	__hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
1890 
1891 	/* Reevaluate the clock bases for the [soft] next expiry */
1892 	expires_next = hrtimer_update_next_event(cpu_base);
1893 	/*
1894 	 * Store the new expiry value so the migration code can verify
1895 	 * against it.
1896 	 */
1897 	cpu_base->expires_next = expires_next;
1898 	cpu_base->in_hrtirq = 0;
1899 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1900 
1901 	/* Reprogramming necessary ? */
1902 	if (!tick_program_event(expires_next, 0)) {
1903 		cpu_base->hang_detected = 0;
1904 		return;
1905 	}
1906 
1907 	/*
1908 	 * The next timer was already expired due to:
1909 	 * - tracing
1910 	 * - long lasting callbacks
1911 	 * - being scheduled away when running in a VM
1912 	 *
1913 	 * We need to prevent that we loop forever in the hrtimer
1914 	 * interrupt routine. We give it 3 attempts to avoid
1915 	 * overreacting on some spurious event.
1916 	 *
1917 	 * Acquire base lock for updating the offsets and retrieving
1918 	 * the current time.
1919 	 */
1920 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1921 	now = hrtimer_update_base(cpu_base);
1922 	cpu_base->nr_retries++;
1923 	if (++retries < 3)
1924 		goto retry;
1925 	/*
1926 	 * Give the system a chance to do something else than looping
1927 	 * here. We stored the entry time, so we know exactly how long
1928 	 * we spent here. We schedule the next event this amount of
1929 	 * time away.
1930 	 */
1931 	cpu_base->nr_hangs++;
1932 	cpu_base->hang_detected = 1;
1933 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1934 
1935 	delta = ktime_sub(now, entry_time);
1936 	if ((unsigned int)delta > cpu_base->max_hang_time)
1937 		cpu_base->max_hang_time = (unsigned int) delta;
1938 	/*
1939 	 * Limit it to a sensible value as we enforce a longer
1940 	 * delay. Give the CPU at least 100ms to catch up.
1941 	 */
1942 	if (delta > 100 * NSEC_PER_MSEC)
1943 		expires_next = ktime_add_ns(now, 100 * NSEC_PER_MSEC);
1944 	else
1945 		expires_next = ktime_add(now, delta);
1946 	tick_program_event(expires_next, 1);
1947 	pr_warn_once("hrtimer: interrupt took %llu ns\n", ktime_to_ns(delta));
1948 }
1949 #endif /* !CONFIG_HIGH_RES_TIMERS */
1950 
1951 /*
1952  * Called from run_local_timers in hardirq context every jiffy
1953  */
1954 void hrtimer_run_queues(void)
1955 {
1956 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
1957 	unsigned long flags;
1958 	ktime_t now;
1959 
1960 	if (hrtimer_hres_active(cpu_base))
1961 		return;
1962 
1963 	/*
1964 	 * This _is_ ugly: We have to check periodically, whether we
1965 	 * can switch to highres and / or nohz mode. The clocksource
1966 	 * switch happens with xtime_lock held. Notification from
1967 	 * there only sets the check bit in the tick_oneshot code,
1968 	 * otherwise we might deadlock vs. xtime_lock.
1969 	 */
1970 	if (tick_check_oneshot_change(!hrtimer_is_hres_enabled())) {
1971 		hrtimer_switch_to_hres();
1972 		return;
1973 	}
1974 
1975 	raw_spin_lock_irqsave(&cpu_base->lock, flags);
1976 	now = hrtimer_update_base(cpu_base);
1977 
1978 	if (!ktime_before(now, cpu_base->softirq_expires_next)) {
1979 		cpu_base->softirq_expires_next = KTIME_MAX;
1980 		cpu_base->softirq_activated = 1;
1981 		raise_timer_softirq(HRTIMER_SOFTIRQ);
1982 	}
1983 
1984 	__hrtimer_run_queues(cpu_base, now, flags, HRTIMER_ACTIVE_HARD);
1985 	raw_spin_unlock_irqrestore(&cpu_base->lock, flags);
1986 }
1987 
1988 /*
1989  * Sleep related functions:
1990  */
1991 static enum hrtimer_restart hrtimer_wakeup(struct hrtimer *timer)
1992 {
1993 	struct hrtimer_sleeper *t =
1994 		container_of(timer, struct hrtimer_sleeper, timer);
1995 	struct task_struct *task = t->task;
1996 
1997 	t->task = NULL;
1998 	if (task)
1999 		wake_up_process(task);
2000 
2001 	return HRTIMER_NORESTART;
2002 }
2003 
2004 /**
2005  * hrtimer_sleeper_start_expires - Start a hrtimer sleeper timer
2006  * @sl:		sleeper to be started
2007  * @mode:	timer mode abs/rel
2008  *
2009  * Wrapper around hrtimer_start_expires() for hrtimer_sleeper based timers
2010  * to allow PREEMPT_RT to tweak the delivery mode (soft/hardirq context)
2011  */
2012 void hrtimer_sleeper_start_expires(struct hrtimer_sleeper *sl,
2013 				   enum hrtimer_mode mode)
2014 {
2015 	/*
2016 	 * Make the enqueue delivery mode check work on RT. If the sleeper
2017 	 * was initialized for hard interrupt delivery, force the mode bit.
2018 	 * This is a special case for hrtimer_sleepers because
2019 	 * __hrtimer_setup_sleeper() determines the delivery mode on RT so the
2020 	 * fiddling with this decision is avoided at the call sites.
2021 	 */
2022 	if (IS_ENABLED(CONFIG_PREEMPT_RT) && sl->timer.is_hard)
2023 		mode |= HRTIMER_MODE_HARD;
2024 
2025 	hrtimer_start_expires(&sl->timer, mode);
2026 }
2027 EXPORT_SYMBOL_GPL(hrtimer_sleeper_start_expires);
2028 
2029 static void __hrtimer_setup_sleeper(struct hrtimer_sleeper *sl,
2030 				    clockid_t clock_id, enum hrtimer_mode mode)
2031 {
2032 	/*
2033 	 * On PREEMPT_RT enabled kernels hrtimers which are not explicitly
2034 	 * marked for hard interrupt expiry mode are moved into soft
2035 	 * interrupt context either for latency reasons or because the
2036 	 * hrtimer callback takes regular spinlocks or invokes other
2037 	 * functions which are not suitable for hard interrupt context on
2038 	 * PREEMPT_RT.
2039 	 *
2040 	 * The hrtimer_sleeper callback is RT compatible in hard interrupt
2041 	 * context, but there is a latency concern: Untrusted userspace can
2042 	 * spawn many threads which arm timers for the same expiry time on
2043 	 * the same CPU. That causes a latency spike due to the wakeup of
2044 	 * a gazillion threads.
2045 	 *
2046 	 * OTOH, privileged real-time user space applications rely on the
2047 	 * low latency of hard interrupt wakeups. If the current task is in
2048 	 * a real-time scheduling class, mark the mode for hard interrupt
2049 	 * expiry.
2050 	 */
2051 	if (IS_ENABLED(CONFIG_PREEMPT_RT)) {
2052 		if (rt_or_dl_task_policy(current) && !(mode & HRTIMER_MODE_SOFT))
2053 			mode |= HRTIMER_MODE_HARD;
2054 	}
2055 
2056 	__hrtimer_setup(&sl->timer, hrtimer_wakeup, clock_id, mode);
2057 	sl->task = current;
2058 }
2059 
2060 /**
2061  * hrtimer_setup_sleeper_on_stack - initialize a sleeper in stack memory
2062  * @sl:		sleeper to be initialized
2063  * @clock_id:	the clock to be used
2064  * @mode:	timer mode abs/rel
2065  */
2066 void hrtimer_setup_sleeper_on_stack(struct hrtimer_sleeper *sl,
2067 				    clockid_t clock_id, enum hrtimer_mode mode)
2068 {
2069 	debug_init_on_stack(&sl->timer, clock_id, mode);
2070 	__hrtimer_setup_sleeper(sl, clock_id, mode);
2071 }
2072 EXPORT_SYMBOL_GPL(hrtimer_setup_sleeper_on_stack);
2073 
2074 int nanosleep_copyout(struct restart_block *restart, struct timespec64 *ts)
2075 {
2076 	switch(restart->nanosleep.type) {
2077 #ifdef CONFIG_COMPAT_32BIT_TIME
2078 	case TT_COMPAT:
2079 		if (put_old_timespec32(ts, restart->nanosleep.compat_rmtp))
2080 			return -EFAULT;
2081 		break;
2082 #endif
2083 	case TT_NATIVE:
2084 		if (put_timespec64(ts, restart->nanosleep.rmtp))
2085 			return -EFAULT;
2086 		break;
2087 	default:
2088 		BUG();
2089 	}
2090 	return -ERESTART_RESTARTBLOCK;
2091 }
2092 
2093 static int __sched do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode)
2094 {
2095 	struct restart_block *restart;
2096 
2097 	do {
2098 		set_current_state(TASK_INTERRUPTIBLE|TASK_FREEZABLE);
2099 		hrtimer_sleeper_start_expires(t, mode);
2100 
2101 		if (likely(t->task))
2102 			schedule();
2103 
2104 		hrtimer_cancel(&t->timer);
2105 		mode = HRTIMER_MODE_ABS;
2106 
2107 	} while (t->task && !signal_pending(current));
2108 
2109 	__set_current_state(TASK_RUNNING);
2110 
2111 	if (!t->task)
2112 		return 0;
2113 
2114 	restart = &current->restart_block;
2115 	if (restart->nanosleep.type != TT_NONE) {
2116 		ktime_t rem = hrtimer_expires_remaining(&t->timer);
2117 		struct timespec64 rmt;
2118 
2119 		if (rem <= 0)
2120 			return 0;
2121 		rmt = ktime_to_timespec64(rem);
2122 
2123 		return nanosleep_copyout(restart, &rmt);
2124 	}
2125 	return -ERESTART_RESTARTBLOCK;
2126 }
2127 
2128 static long __sched hrtimer_nanosleep_restart(struct restart_block *restart)
2129 {
2130 	struct hrtimer_sleeper t;
2131 	int ret;
2132 
2133 	hrtimer_setup_sleeper_on_stack(&t, restart->nanosleep.clockid, HRTIMER_MODE_ABS);
2134 	hrtimer_set_expires_tv64(&t.timer, restart->nanosleep.expires);
2135 	ret = do_nanosleep(&t, HRTIMER_MODE_ABS);
2136 	destroy_hrtimer_on_stack(&t.timer);
2137 	return ret;
2138 }
2139 
2140 long hrtimer_nanosleep(ktime_t rqtp, const enum hrtimer_mode mode,
2141 		       const clockid_t clockid)
2142 {
2143 	struct restart_block *restart;
2144 	struct hrtimer_sleeper t;
2145 	int ret = 0;
2146 
2147 	hrtimer_setup_sleeper_on_stack(&t, clockid, mode);
2148 	hrtimer_set_expires_range_ns(&t.timer, rqtp, current->timer_slack_ns);
2149 	ret = do_nanosleep(&t, mode);
2150 	if (ret != -ERESTART_RESTARTBLOCK)
2151 		goto out;
2152 
2153 	/* Absolute timers do not update the rmtp value and restart: */
2154 	if (mode == HRTIMER_MODE_ABS) {
2155 		ret = -ERESTARTNOHAND;
2156 		goto out;
2157 	}
2158 
2159 	restart = &current->restart_block;
2160 	restart->nanosleep.clockid = t.timer.base->clockid;
2161 	restart->nanosleep.expires = hrtimer_get_expires_tv64(&t.timer);
2162 	set_restart_fn(restart, hrtimer_nanosleep_restart);
2163 out:
2164 	destroy_hrtimer_on_stack(&t.timer);
2165 	return ret;
2166 }
2167 
2168 #ifdef CONFIG_64BIT
2169 
2170 SYSCALL_DEFINE2(nanosleep, struct __kernel_timespec __user *, rqtp,
2171 		struct __kernel_timespec __user *, rmtp)
2172 {
2173 	struct timespec64 tu;
2174 
2175 	if (get_timespec64(&tu, rqtp))
2176 		return -EFAULT;
2177 
2178 	if (!timespec64_valid(&tu))
2179 		return -EINVAL;
2180 
2181 	current->restart_block.fn = do_no_restart_syscall;
2182 	current->restart_block.nanosleep.type = rmtp ? TT_NATIVE : TT_NONE;
2183 	current->restart_block.nanosleep.rmtp = rmtp;
2184 	return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL,
2185 				 CLOCK_MONOTONIC);
2186 }
2187 
2188 #endif
2189 
2190 #ifdef CONFIG_COMPAT_32BIT_TIME
2191 
2192 SYSCALL_DEFINE2(nanosleep_time32, struct old_timespec32 __user *, rqtp,
2193 		       struct old_timespec32 __user *, rmtp)
2194 {
2195 	struct timespec64 tu;
2196 
2197 	if (get_old_timespec32(&tu, rqtp))
2198 		return -EFAULT;
2199 
2200 	if (!timespec64_valid(&tu))
2201 		return -EINVAL;
2202 
2203 	current->restart_block.fn = do_no_restart_syscall;
2204 	current->restart_block.nanosleep.type = rmtp ? TT_COMPAT : TT_NONE;
2205 	current->restart_block.nanosleep.compat_rmtp = rmtp;
2206 	return hrtimer_nanosleep(timespec64_to_ktime(tu), HRTIMER_MODE_REL,
2207 				 CLOCK_MONOTONIC);
2208 }
2209 #endif
2210 
2211 /*
2212  * Functions related to boot-time initialization:
2213  */
2214 int hrtimers_prepare_cpu(unsigned int cpu)
2215 {
2216 	struct hrtimer_cpu_base *cpu_base = &per_cpu(hrtimer_bases, cpu);
2217 	int i;
2218 
2219 	for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
2220 		struct hrtimer_clock_base *clock_b = &cpu_base->clock_base[i];
2221 
2222 		clock_b->cpu_base = cpu_base;
2223 		seqcount_raw_spinlock_init(&clock_b->seq, &cpu_base->lock);
2224 		timerqueue_init_head(&clock_b->active);
2225 	}
2226 
2227 	cpu_base->cpu = cpu;
2228 	hrtimer_cpu_base_init_expiry_lock(cpu_base);
2229 	return 0;
2230 }
2231 
2232 int hrtimers_cpu_starting(unsigned int cpu)
2233 {
2234 	struct hrtimer_cpu_base *cpu_base = this_cpu_ptr(&hrtimer_bases);
2235 
2236 	/* Clear out any left over state from a CPU down operation */
2237 	cpu_base->active_bases = 0;
2238 	cpu_base->hres_active = 0;
2239 	cpu_base->hang_detected = 0;
2240 	cpu_base->next_timer = NULL;
2241 	cpu_base->softirq_next_timer = NULL;
2242 	cpu_base->expires_next = KTIME_MAX;
2243 	cpu_base->softirq_expires_next = KTIME_MAX;
2244 	cpu_base->online = 1;
2245 	return 0;
2246 }
2247 
2248 #ifdef CONFIG_HOTPLUG_CPU
2249 
2250 static void migrate_hrtimer_list(struct hrtimer_clock_base *old_base,
2251 				struct hrtimer_clock_base *new_base)
2252 {
2253 	struct hrtimer *timer;
2254 	struct timerqueue_node *node;
2255 
2256 	while ((node = timerqueue_getnext(&old_base->active))) {
2257 		timer = container_of(node, struct hrtimer, node);
2258 		BUG_ON(hrtimer_callback_running(timer));
2259 		debug_deactivate(timer);
2260 
2261 		/*
2262 		 * Mark it as ENQUEUED not INACTIVE otherwise the
2263 		 * timer could be seen as !active and just vanish away
2264 		 * under us on another CPU
2265 		 */
2266 		__remove_hrtimer(timer, old_base, HRTIMER_STATE_ENQUEUED, 0);
2267 		timer->base = new_base;
2268 		/*
2269 		 * Enqueue the timers on the new cpu. This does not
2270 		 * reprogram the event device in case the timer
2271 		 * expires before the earliest on this CPU, but we run
2272 		 * hrtimer_interrupt after we migrated everything to
2273 		 * sort out already expired timers and reprogram the
2274 		 * event device.
2275 		 */
2276 		enqueue_hrtimer(timer, new_base, HRTIMER_MODE_ABS);
2277 	}
2278 }
2279 
2280 int hrtimers_cpu_dying(unsigned int dying_cpu)
2281 {
2282 	int i, ncpu = cpumask_any_and(cpu_active_mask, housekeeping_cpumask(HK_TYPE_TIMER));
2283 	struct hrtimer_cpu_base *old_base, *new_base;
2284 
2285 	old_base = this_cpu_ptr(&hrtimer_bases);
2286 	new_base = &per_cpu(hrtimer_bases, ncpu);
2287 
2288 	/*
2289 	 * The caller is globally serialized and nobody else
2290 	 * takes two locks at once, deadlock is not possible.
2291 	 */
2292 	raw_spin_lock(&old_base->lock);
2293 	raw_spin_lock_nested(&new_base->lock, SINGLE_DEPTH_NESTING);
2294 
2295 	for (i = 0; i < HRTIMER_MAX_CLOCK_BASES; i++) {
2296 		migrate_hrtimer_list(&old_base->clock_base[i],
2297 				     &new_base->clock_base[i]);
2298 	}
2299 
2300 	/*
2301 	 * The migration might have changed the first expiring softirq
2302 	 * timer on this CPU. Update it.
2303 	 */
2304 	__hrtimer_get_next_event(new_base, HRTIMER_ACTIVE_SOFT);
2305 	/* Tell the other CPU to retrigger the next event */
2306 	smp_call_function_single(ncpu, retrigger_next_event, NULL, 0);
2307 
2308 	raw_spin_unlock(&new_base->lock);
2309 	old_base->online = 0;
2310 	raw_spin_unlock(&old_base->lock);
2311 
2312 	return 0;
2313 }
2314 
2315 #endif /* CONFIG_HOTPLUG_CPU */
2316 
2317 void __init hrtimers_init(void)
2318 {
2319 	hrtimers_prepare_cpu(smp_processor_id());
2320 	hrtimers_cpu_starting(smp_processor_id());
2321 	open_softirq(HRTIMER_SOFTIRQ, hrtimer_run_softirq);
2322 }
2323