xref: /linux/kernel/time/alarmtimer.c (revision ed3b3c4976686b63b28e44f9805a88abc20ff18a)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Alarmtimer interface
4  *
5  * This interface provides a timer which is similar to hrtimers,
6  * but triggers a RTC alarm if the box is suspend.
7  *
8  * This interface is influenced by the Android RTC Alarm timer
9  * interface.
10  *
11  * Copyright (C) 2010 IBM Corporation
12  *
13  * Author: John Stultz <john.stultz@linaro.org>
14  */
15 #include <linux/time.h>
16 #include <linux/hrtimer.h>
17 #include <linux/timerqueue.h>
18 #include <linux/rtc.h>
19 #include <linux/sched/signal.h>
20 #include <linux/sched/debug.h>
21 #include <linux/alarmtimer.h>
22 #include <linux/mutex.h>
23 #include <linux/platform_device.h>
24 #include <linux/posix-timers.h>
25 #include <linux/workqueue.h>
26 #include <linux/freezer.h>
27 #include <linux/compat.h>
28 #include <linux/module.h>
29 #include <linux/time_namespace.h>
30 
31 #include "posix-timers.h"
32 
33 #define CREATE_TRACE_POINTS
34 #include <trace/events/alarmtimer.h>
35 
36 /**
37  * struct alarm_base - Alarm timer bases
38  * @lock:		Lock for synchronized access to the base
39  * @timerqueue:		Timerqueue head managing the list of events
40  * @get_ktime:		Function to read the time correlating to the base
41  * @get_timespec:	Function to read the namespace time correlating to the base
42  * @base_clockid:	clockid for the base
43  */
44 static struct alarm_base {
45 	spinlock_t		lock;
46 	struct timerqueue_head	timerqueue;
47 	ktime_t			(*get_ktime)(void);
48 	void			(*get_timespec)(struct timespec64 *tp);
49 	clockid_t		base_clockid;
50 } alarm_bases[ALARM_NUMTYPE];
51 
52 #if defined(CONFIG_POSIX_TIMERS) || defined(CONFIG_RTC_CLASS)
53 /* freezer information to handle clock_nanosleep triggered wakeups */
54 static enum alarmtimer_type freezer_alarmtype;
55 static ktime_t freezer_expires;
56 static ktime_t freezer_delta;
57 static DEFINE_SPINLOCK(freezer_delta_lock);
58 #endif
59 
60 #ifdef CONFIG_RTC_CLASS
61 /* rtc timer and device for setting alarm wakeups at suspend */
62 static struct rtc_timer		rtctimer;
63 static struct rtc_device	*rtcdev;
64 static DEFINE_SPINLOCK(rtcdev_lock);
65 
66 /**
67  * alarmtimer_get_rtcdev - Return selected rtcdevice
68  *
69  * This function returns the rtc device to use for wakealarms.
70  */
71 struct rtc_device *alarmtimer_get_rtcdev(void)
72 {
73 	struct rtc_device *ret;
74 
75 	guard(spinlock_irqsave)(&rtcdev_lock);
76 	ret = rtcdev;
77 
78 	return ret;
79 }
80 EXPORT_SYMBOL_GPL(alarmtimer_get_rtcdev);
81 
82 static int alarmtimer_rtc_add_device(struct device *dev)
83 {
84 	struct rtc_device *rtc = to_rtc_device(dev);
85 	struct platform_device *pdev;
86 	int ret = 0;
87 
88 	if (rtcdev)
89 		return -EBUSY;
90 
91 	if (!test_bit(RTC_FEATURE_ALARM, rtc->features))
92 		return -1;
93 	if (!device_may_wakeup(rtc->dev.parent))
94 		return -1;
95 
96 	pdev = platform_device_register_data(dev, "alarmtimer",
97 					     PLATFORM_DEVID_AUTO, NULL, 0);
98 	if (!IS_ERR(pdev))
99 		device_init_wakeup(&pdev->dev, true);
100 
101 	scoped_guard(spinlock_irqsave, &rtcdev_lock) {
102 		if (!IS_ERR(pdev) && !rtcdev && try_module_get(rtc->owner)) {
103 			rtcdev = rtc;
104 			/* hold a reference so it doesn't go away */
105 			get_device(dev);
106 			pdev = NULL;
107 		} else {
108 			ret = -1;
109 		}
110 	}
111 
112 	platform_device_unregister(pdev);
113 	return ret;
114 }
115 
116 static inline void alarmtimer_rtc_timer_init(void)
117 {
118 	rtc_timer_init(&rtctimer, NULL, NULL);
119 }
120 
121 static struct class_interface alarmtimer_rtc_interface = {
122 	.add_dev = &alarmtimer_rtc_add_device,
123 };
124 
125 static int alarmtimer_rtc_interface_setup(void)
126 {
127 	alarmtimer_rtc_interface.class = &rtc_class;
128 	return class_interface_register(&alarmtimer_rtc_interface);
129 }
130 static void alarmtimer_rtc_interface_remove(void)
131 {
132 	class_interface_unregister(&alarmtimer_rtc_interface);
133 }
134 #else
135 static inline int alarmtimer_rtc_interface_setup(void) { return 0; }
136 static inline void alarmtimer_rtc_interface_remove(void) { }
137 static inline void alarmtimer_rtc_timer_init(void) { }
138 #endif
139 
140 /**
141  * alarmtimer_enqueue - Adds an alarm timer to an alarm_base timerqueue
142  * @base: pointer to the base where the timer is being run
143  * @alarm: pointer to alarm being enqueued.
144  *
145  * Adds alarm to a alarm_base timerqueue
146  *
147  * Must hold base->lock when calling.
148  */
149 static void alarmtimer_enqueue(struct alarm_base *base, struct alarm *alarm)
150 {
151 	if (alarm->state & ALARMTIMER_STATE_ENQUEUED)
152 		timerqueue_del(&base->timerqueue, &alarm->node);
153 
154 	timerqueue_add(&base->timerqueue, &alarm->node);
155 	alarm->state |= ALARMTIMER_STATE_ENQUEUED;
156 }
157 
158 /**
159  * alarmtimer_dequeue - Removes an alarm timer from an alarm_base timerqueue
160  * @base: pointer to the base where the timer is running
161  * @alarm: pointer to alarm being removed
162  *
163  * Removes alarm to a alarm_base timerqueue
164  *
165  * Must hold base->lock when calling.
166  */
167 static void alarmtimer_dequeue(struct alarm_base *base, struct alarm *alarm)
168 {
169 	if (!(alarm->state & ALARMTIMER_STATE_ENQUEUED))
170 		return;
171 
172 	timerqueue_del(&base->timerqueue, &alarm->node);
173 	alarm->state &= ~ALARMTIMER_STATE_ENQUEUED;
174 }
175 
176 
177 /**
178  * alarmtimer_fired - Handles alarm hrtimer being fired.
179  * @timer: pointer to hrtimer being run
180  *
181  * When a alarm timer fires, this runs through the timerqueue to
182  * see which alarms expired, and runs those. If there are more alarm
183  * timers queued for the future, we set the hrtimer to fire when
184  * the next future alarm timer expires.
185  */
186 static enum hrtimer_restart alarmtimer_fired(struct hrtimer *timer)
187 {
188 	struct alarm *alarm = container_of(timer, struct alarm, timer);
189 	struct alarm_base *base = &alarm_bases[alarm->type];
190 
191 	scoped_guard(spinlock_irqsave, &base->lock)
192 		alarmtimer_dequeue(base, alarm);
193 
194 	if (alarm->function)
195 		alarm->function(alarm, base->get_ktime());
196 
197 	trace_alarmtimer_fired(alarm, base->get_ktime());
198 	return HRTIMER_NORESTART;
199 }
200 
201 ktime_t alarm_expires_remaining(const struct alarm *alarm)
202 {
203 	struct alarm_base *base = &alarm_bases[alarm->type];
204 	return ktime_sub(alarm->node.expires, base->get_ktime());
205 }
206 EXPORT_SYMBOL_GPL(alarm_expires_remaining);
207 
208 #ifdef CONFIG_RTC_CLASS
209 /**
210  * alarmtimer_suspend - Suspend time callback
211  * @dev: unused
212  *
213  * When we are going into suspend, we look through the bases
214  * to see which is the soonest timer to expire. We then
215  * set an rtc timer to fire that far into the future, which
216  * will wake us from suspend.
217  */
218 static int alarmtimer_suspend(struct device *dev)
219 {
220 	ktime_t min, now, expires;
221 	struct rtc_device *rtc;
222 	struct rtc_time tm;
223 	int i, ret, type;
224 
225 	scoped_guard(spinlock_irqsave, &freezer_delta_lock) {
226 		min = freezer_delta;
227 		expires = freezer_expires;
228 		type = freezer_alarmtype;
229 		freezer_delta = 0;
230 	}
231 
232 	rtc = alarmtimer_get_rtcdev();
233 	/* If we have no rtcdev, just return */
234 	if (!rtc)
235 		return 0;
236 
237 	/* Find the soonest timer to expire */
238 	for (i = 0; i < ALARM_NUMTYPE; i++) {
239 		struct alarm_base *base = &alarm_bases[i];
240 		struct timerqueue_node *next;
241 		ktime_t next_expires;
242 		ktime_t delta;
243 
244 		scoped_guard(spinlock_irqsave, &base->lock) {
245 			next = timerqueue_getnext(&base->timerqueue);
246 			if (next)
247 				next_expires = next->expires;
248 		}
249 		if (!next)
250 			continue;
251 		delta = ktime_sub(next_expires, base->get_ktime());
252 		if (!min || (delta < min)) {
253 			expires = next_expires;
254 			min = delta;
255 			type = i;
256 		}
257 	}
258 	if (min == 0)
259 		return 0;
260 
261 	if (ktime_to_ns(min) < 2 * NSEC_PER_SEC) {
262 		pm_wakeup_event(dev, 2 * MSEC_PER_SEC);
263 		return -EBUSY;
264 	}
265 
266 	trace_alarmtimer_suspend(expires, type);
267 
268 	/* Setup an rtc timer to fire that far in the future */
269 	rtc_timer_cancel(rtc, &rtctimer);
270 	rtc_read_time(rtc, &tm);
271 	now = rtc_tm_to_ktime(tm);
272 
273 	/*
274 	 * If the RTC alarm timer only supports a limited time offset, set the
275 	 * alarm time to the maximum supported value.
276 	 * The system may wake up earlier (possibly much earlier) than expected
277 	 * when the alarmtimer runs. This is the best the kernel can do if
278 	 * the alarmtimer exceeds the time that the rtc device can be programmed
279 	 * for.
280 	 */
281 	min = rtc_bound_alarmtime(rtc, min);
282 
283 	now = ktime_add(now, min);
284 
285 	/* Set alarm, if in the past reject suspend briefly to handle */
286 	ret = rtc_timer_start(rtc, &rtctimer, now, 0);
287 	if (ret < 0)
288 		pm_wakeup_event(dev, MSEC_PER_SEC);
289 	return ret;
290 }
291 
292 static int alarmtimer_resume(struct device *dev)
293 {
294 	struct rtc_device *rtc;
295 
296 	rtc = alarmtimer_get_rtcdev();
297 	if (rtc)
298 		rtc_timer_cancel(rtc, &rtctimer);
299 	return 0;
300 }
301 
302 #else
303 static int alarmtimer_suspend(struct device *dev)
304 {
305 	return 0;
306 }
307 
308 static int alarmtimer_resume(struct device *dev)
309 {
310 	return 0;
311 }
312 #endif
313 
314 static void
315 __alarm_init(struct alarm *alarm, enum alarmtimer_type type,
316 	     void (*function)(struct alarm *, ktime_t))
317 {
318 	timerqueue_init(&alarm->node);
319 	alarm->function = function;
320 	alarm->type = type;
321 	alarm->state = ALARMTIMER_STATE_INACTIVE;
322 }
323 
324 /**
325  * alarm_init - Initialize an alarm structure
326  * @alarm: ptr to alarm to be initialized
327  * @type: the type of the alarm
328  * @function: callback that is run when the alarm fires
329  */
330 void alarm_init(struct alarm *alarm, enum alarmtimer_type type,
331 		void (*function)(struct alarm *, ktime_t))
332 {
333 	hrtimer_setup(&alarm->timer, alarmtimer_fired, alarm_bases[type].base_clockid,
334 		      HRTIMER_MODE_ABS);
335 	__alarm_init(alarm, type, function);
336 }
337 EXPORT_SYMBOL_GPL(alarm_init);
338 
339 /**
340  * alarm_start_timer - Sets an alarm to fire
341  * @alarm:	Pointer to alarm to set
342  * @expires:	Expiry time
343  * @relative:	True if @expires is relative
344  *
345  * Returns: True if the alarm was queued. False if it already expired
346  */
347 bool alarm_start_timer(struct alarm *alarm, ktime_t expires, bool relative)
348 {
349 	struct alarm_base *base = &alarm_bases[alarm->type];
350 
351 	if (relative)
352 		expires = ktime_add_safe(expires, base->get_ktime());
353 
354 	trace_alarmtimer_start(alarm, base->get_ktime());
355 
356 	guard(spinlock_irqsave)(&base->lock);
357 	alarm->node.expires = expires;
358 	alarmtimer_enqueue(base, alarm);
359 	if (!hrtimer_start_range_ns_user(&alarm->timer, expires, 0, HRTIMER_MODE_ABS)) {
360 		alarmtimer_dequeue(base, alarm);
361 		return false;
362 	}
363 	return true;
364 }
365 EXPORT_SYMBOL_GPL(alarm_start_timer);
366 
367 /**
368  * alarm_try_to_cancel - Tries to cancel an alarm timer
369  * @alarm: ptr to alarm to be canceled
370  *
371  * Returns 1 if the timer was canceled, 0 if it was not running,
372  * and -1 if the callback was running
373  */
374 int alarm_try_to_cancel(struct alarm *alarm)
375 {
376 	struct alarm_base *base = &alarm_bases[alarm->type];
377 	int ret;
378 
379 	scoped_guard(spinlock_irqsave, &base->lock) {
380 		ret = hrtimer_try_to_cancel(&alarm->timer);
381 		if (ret >= 0)
382 			alarmtimer_dequeue(base, alarm);
383 	}
384 
385 	trace_alarmtimer_cancel(alarm, base->get_ktime());
386 	return ret;
387 }
388 EXPORT_SYMBOL_GPL(alarm_try_to_cancel);
389 
390 
391 /**
392  * alarm_cancel - Spins trying to cancel an alarm timer until it is done
393  * @alarm: ptr to alarm to be canceled
394  *
395  * Returns 1 if the timer was canceled, 0 if it was not active.
396  */
397 int alarm_cancel(struct alarm *alarm)
398 {
399 	for (;;) {
400 		int ret = alarm_try_to_cancel(alarm);
401 		if (ret >= 0)
402 			return ret;
403 		hrtimer_cancel_wait_running(&alarm->timer);
404 	}
405 }
406 EXPORT_SYMBOL_GPL(alarm_cancel);
407 
408 
409 u64 alarm_forward(struct alarm *alarm, ktime_t now, ktime_t interval)
410 {
411 	u64 overrun = 1;
412 	ktime_t delta;
413 
414 	delta = ktime_sub(now, alarm->node.expires);
415 
416 	if (delta < 0)
417 		return 0;
418 
419 	if (unlikely(delta >= interval)) {
420 		s64 incr = ktime_to_ns(interval);
421 
422 		overrun = ktime_divns(delta, incr);
423 
424 		alarm->node.expires = ktime_add_ns(alarm->node.expires,
425 							incr*overrun);
426 
427 		if (alarm->node.expires > now)
428 			return overrun;
429 		/*
430 		 * This (and the ktime_add() below) is the
431 		 * correction for exact:
432 		 */
433 		overrun++;
434 	}
435 
436 	alarm->node.expires = ktime_add_safe(alarm->node.expires, interval);
437 	return overrun;
438 }
439 EXPORT_SYMBOL_GPL(alarm_forward);
440 
441 u64 alarm_forward_now(struct alarm *alarm, ktime_t interval)
442 {
443 	struct alarm_base *base = &alarm_bases[alarm->type];
444 
445 	return alarm_forward(alarm, base->get_ktime(), interval);
446 }
447 EXPORT_SYMBOL_GPL(alarm_forward_now);
448 
449 #ifdef CONFIG_POSIX_TIMERS
450 
451 static void alarmtimer_freezerset(ktime_t absexp, enum alarmtimer_type type)
452 {
453 	struct alarm_base *base;
454 	ktime_t delta;
455 
456 	switch(type) {
457 	case ALARM_REALTIME:
458 		base = &alarm_bases[ALARM_REALTIME];
459 		type = ALARM_REALTIME_FREEZER;
460 		break;
461 	case ALARM_BOOTTIME:
462 		base = &alarm_bases[ALARM_BOOTTIME];
463 		type = ALARM_BOOTTIME_FREEZER;
464 		break;
465 	default:
466 		WARN_ONCE(1, "Invalid alarm type: %d\n", type);
467 		return;
468 	}
469 
470 	delta = ktime_sub(absexp, base->get_ktime());
471 
472 	guard(spinlock_irqsave)(&freezer_delta_lock);
473 	if (!freezer_delta || (delta < freezer_delta)) {
474 		freezer_delta = delta;
475 		freezer_expires = absexp;
476 		freezer_alarmtype = type;
477 	}
478 }
479 
480 /**
481  * clock2alarm - helper that converts from clockid to alarmtypes
482  * @clockid: clockid.
483  */
484 static enum alarmtimer_type clock2alarm(clockid_t clockid)
485 {
486 	if (clockid == CLOCK_REALTIME_ALARM)
487 		return ALARM_REALTIME;
488 
489 	WARN_ON_ONCE(clockid != CLOCK_BOOTTIME_ALARM);
490 	return ALARM_BOOTTIME;
491 }
492 
493 /**
494  * alarm_handle_timer - Callback for posix timers
495  * @alarm: alarm that fired
496  * @now: time at the timer expiration
497  *
498  * Posix timer callback for expired alarm timers.
499  */
500 static void alarm_handle_timer(struct alarm *alarm, ktime_t now)
501 {
502 	struct k_itimer *ptr = container_of(alarm, struct k_itimer, it.alarm.alarmtimer);
503 
504 	guard(spinlock_irqsave)(&ptr->it_lock);
505 	posix_timer_queue_signal(ptr);
506 }
507 
508 /**
509  * alarm_timer_rearm - Posix timer callback for rearming timer
510  * @timr:	Pointer to the posixtimer data struct
511  */
512 static bool alarm_timer_rearm(struct k_itimer *timr)
513 {
514 	struct alarm *alarm = &timr->it.alarm.alarmtimer;
515 
516 	timr->it_overrun += alarm_forward_now(alarm, timr->it_interval);
517 	return alarm_start_timer(alarm, alarm->node.expires, false);
518 }
519 
520 /**
521  * alarm_timer_forward - Posix timer callback for forwarding timer
522  * @timr:	Pointer to the posixtimer data struct
523  * @now:	Current time to forward the timer against
524  */
525 static s64 alarm_timer_forward(struct k_itimer *timr, ktime_t now)
526 {
527 	struct alarm *alarm = &timr->it.alarm.alarmtimer;
528 
529 	return alarm_forward(alarm, now, timr->it_interval);
530 }
531 
532 /**
533  * alarm_timer_remaining - Posix timer callback to retrieve remaining time
534  * @timr:	Pointer to the posixtimer data struct
535  * @now:	Current time to calculate against
536  */
537 static ktime_t alarm_timer_remaining(struct k_itimer *timr, ktime_t now)
538 {
539 	struct alarm *alarm = &timr->it.alarm.alarmtimer;
540 
541 	return ktime_sub(alarm->node.expires, now);
542 }
543 
544 /**
545  * alarm_timer_try_to_cancel - Posix timer callback to cancel a timer
546  * @timr:	Pointer to the posixtimer data struct
547  */
548 static int alarm_timer_try_to_cancel(struct k_itimer *timr)
549 {
550 	return alarm_try_to_cancel(&timr->it.alarm.alarmtimer);
551 }
552 
553 /**
554  * alarm_timer_wait_running - Posix timer callback to wait for a timer
555  * @timr:	Pointer to the posixtimer data struct
556  *
557  * Called from the core code when timer cancel detected that the callback
558  * is running. @timr is unlocked and rcu read lock is held to prevent it
559  * from being freed.
560  */
561 static void alarm_timer_wait_running(struct k_itimer *timr)
562 {
563 	hrtimer_cancel_wait_running(&timr->it.alarm.alarmtimer.timer);
564 }
565 
566 /**
567  * alarm_timer_arm - Posix timer callback to arm a timer
568  * @timr:	Pointer to the posixtimer data struct
569  * @expires:	The new expiry time
570  * @absolute:	Expiry value is absolute time
571  * @sigev_none:	Posix timer does not deliver signals
572  */
573 static bool alarm_timer_arm(struct k_itimer *timr, ktime_t expires,
574 			    bool absolute, bool sigev_none)
575 {
576 	struct alarm *alarm = &timr->it.alarm.alarmtimer;
577 	struct alarm_base *base = &alarm_bases[alarm->type];
578 
579 	if (!absolute)
580 		expires = ktime_add_safe(expires, base->get_ktime());
581 
582 	/*
583 	 * sigev_none needs to update the expires value and pretend
584 	 * that the timer is queued
585 	 */
586 	if (sigev_none) {
587 		alarm->node.expires = expires;
588 		return true;
589 	}
590 	return alarm_start_timer(&timr->it.alarm.alarmtimer, expires, false);
591 }
592 
593 /**
594  * alarm_clock_getres - posix getres interface
595  * @which_clock: clockid
596  * @tp: timespec to fill
597  *
598  * Returns the granularity of underlying alarm base clock
599  */
600 static int alarm_clock_getres(const clockid_t which_clock, struct timespec64 *tp)
601 {
602 	if (!alarmtimer_get_rtcdev())
603 		return -EINVAL;
604 
605 	tp->tv_sec = 0;
606 	tp->tv_nsec = hrtimer_resolution;
607 	return 0;
608 }
609 
610 /**
611  * alarm_clock_get_timespec - posix clock_get_timespec interface
612  * @which_clock: clockid
613  * @tp: timespec to fill.
614  *
615  * Provides the underlying alarm base time in a tasks time namespace.
616  */
617 static int alarm_clock_get_timespec(clockid_t which_clock, struct timespec64 *tp)
618 {
619 	struct alarm_base *base = &alarm_bases[clock2alarm(which_clock)];
620 
621 	if (!alarmtimer_get_rtcdev())
622 		return -EINVAL;
623 
624 	base->get_timespec(tp);
625 
626 	return 0;
627 }
628 
629 /**
630  * alarm_clock_get_ktime - posix clock_get_ktime interface
631  * @which_clock: clockid
632  *
633  * Provides the underlying alarm base time in the root namespace.
634  */
635 static ktime_t alarm_clock_get_ktime(clockid_t which_clock)
636 {
637 	struct alarm_base *base = &alarm_bases[clock2alarm(which_clock)];
638 
639 	if (!alarmtimer_get_rtcdev())
640 		return -EINVAL;
641 
642 	return base->get_ktime();
643 }
644 
645 /**
646  * alarm_timer_create - posix timer_create interface
647  * @new_timer: k_itimer pointer to manage
648  *
649  * Initializes the k_itimer structure.
650  */
651 static int alarm_timer_create(struct k_itimer *new_timer)
652 {
653 	enum  alarmtimer_type type;
654 
655 	if (!alarmtimer_get_rtcdev())
656 		return -EOPNOTSUPP;
657 
658 	if (!capable(CAP_WAKE_ALARM))
659 		return -EPERM;
660 
661 	type = clock2alarm(new_timer->it_clock);
662 	alarm_init(&new_timer->it.alarm.alarmtimer, type, alarm_handle_timer);
663 	return 0;
664 }
665 
666 /**
667  * alarmtimer_nsleep_wakeup - Wakeup function for alarm_timer_nsleep
668  * @alarm: ptr to alarm that fired
669  * @now: time at the timer expiration
670  *
671  * Wakes up the task that set the alarmtimer
672  */
673 static void alarmtimer_nsleep_wakeup(struct alarm *alarm, ktime_t now)
674 {
675 	struct task_struct *task = alarm->data;
676 
677 	alarm->data = NULL;
678 	if (task)
679 		wake_up_process(task);
680 }
681 
682 /**
683  * alarmtimer_do_nsleep - Internal alarmtimer nsleep implementation
684  * @alarm: ptr to alarmtimer
685  * @absexp: absolute expiration time
686  * @type: alarm type (BOOTTIME/REALTIME).
687  *
688  * Sets the alarm timer and sleeps until it is fired or interrupted.
689  */
690 static int alarmtimer_do_nsleep(struct alarm *alarm, ktime_t absexp,
691 				enum alarmtimer_type type)
692 {
693 	struct restart_block *restart;
694 	alarm->data = (void *)current;
695 	do {
696 		set_current_state(TASK_INTERRUPTIBLE);
697 		if (!alarm_start_timer(alarm, absexp, false))
698 			alarm->data = NULL;
699 
700 		if (likely(alarm->data))
701 			schedule();
702 
703 		alarm_cancel(alarm);
704 	} while (alarm->data && !signal_pending(current));
705 
706 	__set_current_state(TASK_RUNNING);
707 
708 	destroy_hrtimer_on_stack(&alarm->timer);
709 
710 	if (!alarm->data)
711 		return 0;
712 
713 	if (freezing(current))
714 		alarmtimer_freezerset(absexp, type);
715 	restart = &current->restart_block;
716 	if (restart->nanosleep.type != TT_NONE) {
717 		struct timespec64 rmt;
718 		ktime_t rem;
719 
720 		rem = ktime_sub(absexp, alarm_bases[type].get_ktime());
721 
722 		if (rem <= 0)
723 			return 0;
724 		rmt = ktime_to_timespec64(rem);
725 
726 		return nanosleep_copyout(restart, &rmt);
727 	}
728 	return -ERESTART_RESTARTBLOCK;
729 }
730 
731 static void
732 alarm_init_on_stack(struct alarm *alarm, enum alarmtimer_type type,
733 		    void (*function)(struct alarm *, ktime_t))
734 {
735 	hrtimer_setup_on_stack(&alarm->timer, alarmtimer_fired, alarm_bases[type].base_clockid,
736 			       HRTIMER_MODE_ABS);
737 	__alarm_init(alarm, type, function);
738 }
739 
740 /**
741  * alarm_timer_nsleep_restart - restartblock alarmtimer nsleep
742  * @restart: ptr to restart block
743  *
744  * Handles restarted clock_nanosleep calls
745  */
746 static long __sched alarm_timer_nsleep_restart(struct restart_block *restart)
747 {
748 	enum  alarmtimer_type type = restart->nanosleep.clockid;
749 	ktime_t exp = restart->nanosleep.expires;
750 	struct alarm alarm;
751 
752 	alarm_init_on_stack(&alarm, type, alarmtimer_nsleep_wakeup);
753 
754 	return alarmtimer_do_nsleep(&alarm, exp, type);
755 }
756 
757 /**
758  * alarm_timer_nsleep - alarmtimer nanosleep
759  * @which_clock: clockid
760  * @flags: determines abstime or relative
761  * @tsreq: requested sleep time (abs or rel)
762  *
763  * Handles clock_nanosleep calls against _ALARM clockids
764  */
765 static int alarm_timer_nsleep(const clockid_t which_clock, int flags,
766 			      const struct timespec64 *tsreq)
767 {
768 	enum  alarmtimer_type type = clock2alarm(which_clock);
769 	struct restart_block *restart = &current->restart_block;
770 	struct alarm alarm;
771 	ktime_t exp;
772 	int ret;
773 
774 	if (!alarmtimer_get_rtcdev())
775 		return -EOPNOTSUPP;
776 
777 	if (flags & ~TIMER_ABSTIME)
778 		return -EINVAL;
779 
780 	if (!capable(CAP_WAKE_ALARM))
781 		return -EPERM;
782 
783 	alarm_init_on_stack(&alarm, type, alarmtimer_nsleep_wakeup);
784 
785 	exp = timespec64_to_ktime(*tsreq);
786 	/* Convert (if necessary) to absolute time */
787 	if (flags != TIMER_ABSTIME) {
788 		ktime_t now = alarm_bases[type].get_ktime();
789 
790 		exp = ktime_add_safe(now, exp);
791 	} else {
792 		exp = timens_ktime_to_host(which_clock, exp);
793 	}
794 
795 	ret = alarmtimer_do_nsleep(&alarm, exp, type);
796 	if (ret != -ERESTART_RESTARTBLOCK)
797 		return ret;
798 
799 	/* abs timers don't set remaining time or restart */
800 	if (flags == TIMER_ABSTIME)
801 		return -ERESTARTNOHAND;
802 
803 	restart->nanosleep.clockid = type;
804 	restart->nanosleep.expires = exp;
805 	set_restart_fn(restart, alarm_timer_nsleep_restart);
806 	return ret;
807 }
808 
809 const struct k_clock alarm_clock = {
810 	.clock_getres		= alarm_clock_getres,
811 	.clock_get_ktime	= alarm_clock_get_ktime,
812 	.clock_get_timespec	= alarm_clock_get_timespec,
813 	.timer_create		= alarm_timer_create,
814 	.timer_set		= common_timer_set,
815 	.timer_del		= common_timer_del,
816 	.timer_get		= common_timer_get,
817 	.timer_arm		= alarm_timer_arm,
818 	.timer_rearm		= alarm_timer_rearm,
819 	.timer_forward		= alarm_timer_forward,
820 	.timer_remaining	= alarm_timer_remaining,
821 	.timer_try_to_cancel	= alarm_timer_try_to_cancel,
822 	.timer_wait_running	= alarm_timer_wait_running,
823 	.nsleep			= alarm_timer_nsleep,
824 };
825 #endif /* CONFIG_POSIX_TIMERS */
826 
827 
828 /* Suspend hook structures */
829 static const struct dev_pm_ops alarmtimer_pm_ops = {
830 	.suspend = alarmtimer_suspend,
831 	.resume = alarmtimer_resume,
832 };
833 
834 static struct platform_driver alarmtimer_driver = {
835 	.driver = {
836 		.name = "alarmtimer",
837 		.pm = &alarmtimer_pm_ops,
838 	}
839 };
840 
841 static void get_boottime_timespec(struct timespec64 *tp)
842 {
843 	ktime_get_boottime_ts64(tp);
844 	timens_add_boottime(tp);
845 }
846 
847 /**
848  * alarmtimer_init - Initialize alarm timer code
849  *
850  * This function initializes the alarm bases and registers
851  * the posix clock ids.
852  */
853 static int __init alarmtimer_init(void)
854 {
855 	int error;
856 	int i;
857 
858 	alarmtimer_rtc_timer_init();
859 
860 	/* Initialize alarm bases */
861 	alarm_bases[ALARM_REALTIME].base_clockid = CLOCK_REALTIME;
862 	alarm_bases[ALARM_REALTIME].get_ktime = &ktime_get_real;
863 	alarm_bases[ALARM_REALTIME].get_timespec = ktime_get_real_ts64;
864 	alarm_bases[ALARM_BOOTTIME].base_clockid = CLOCK_BOOTTIME;
865 	alarm_bases[ALARM_BOOTTIME].get_ktime = &ktime_get_boottime;
866 	alarm_bases[ALARM_BOOTTIME].get_timespec = get_boottime_timespec;
867 	for (i = 0; i < ALARM_NUMTYPE; i++) {
868 		timerqueue_init_head(&alarm_bases[i].timerqueue);
869 		spin_lock_init(&alarm_bases[i].lock);
870 	}
871 
872 	error = alarmtimer_rtc_interface_setup();
873 	if (error)
874 		return error;
875 
876 	error = platform_driver_register(&alarmtimer_driver);
877 	if (error)
878 		goto out_if;
879 
880 	return 0;
881 out_if:
882 	alarmtimer_rtc_interface_remove();
883 	return error;
884 }
885 device_initcall(alarmtimer_init);
886