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