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