xref: /linux/kernel/time/alarmtimer.c (revision b1456f6dc167f7f101746e495bede2bac3d0e19f)
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 syncrhonized 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  */
alarmtimer_get_rtcdev(void)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 
alarmtimer_rtc_add_device(struct device * dev)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 
alarmtimer_rtc_timer_init(void)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 
alarmtimer_rtc_interface_setup(void)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 }
alarmtimer_rtc_interface_remove(void)130 static void alarmtimer_rtc_interface_remove(void)
131 {
132 	class_interface_unregister(&alarmtimer_rtc_interface);
133 }
134 #else
alarmtimer_rtc_interface_setup(void)135 static inline int alarmtimer_rtc_interface_setup(void) { return 0; }
alarmtimer_rtc_interface_remove(void)136 static inline void alarmtimer_rtc_interface_remove(void) { }
alarmtimer_rtc_timer_init(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  */
alarmtimer_enqueue(struct alarm_base * base,struct alarm * alarm)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  */
alarmtimer_dequeue(struct alarm_base * base,struct alarm * alarm)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  */
alarmtimer_fired(struct hrtimer * timer)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 
alarm_expires_remaining(const struct alarm * alarm)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  */
alarmtimer_suspend(struct device * dev)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 delta;
242 
243 		scoped_guard(spinlock_irqsave, &base->lock)
244 			next = timerqueue_getnext(&base->timerqueue);
245 		if (!next)
246 			continue;
247 		delta = ktime_sub(next->expires, base->get_ktime());
248 		if (!min || (delta < min)) {
249 			expires = next->expires;
250 			min = delta;
251 			type = i;
252 		}
253 	}
254 	if (min == 0)
255 		return 0;
256 
257 	if (ktime_to_ns(min) < 2 * NSEC_PER_SEC) {
258 		pm_wakeup_event(dev, 2 * MSEC_PER_SEC);
259 		return -EBUSY;
260 	}
261 
262 	trace_alarmtimer_suspend(expires, type);
263 
264 	/* Setup an rtc timer to fire that far in the future */
265 	rtc_timer_cancel(rtc, &rtctimer);
266 	rtc_read_time(rtc, &tm);
267 	now = rtc_tm_to_ktime(tm);
268 
269 	/*
270 	 * If the RTC alarm timer only supports a limited time offset, set the
271 	 * alarm time to the maximum supported value.
272 	 * The system may wake up earlier (possibly much earlier) than expected
273 	 * when the alarmtimer runs. This is the best the kernel can do if
274 	 * the alarmtimer exceeds the time that the rtc device can be programmed
275 	 * for.
276 	 */
277 	min = rtc_bound_alarmtime(rtc, min);
278 
279 	now = ktime_add(now, min);
280 
281 	/* Set alarm, if in the past reject suspend briefly to handle */
282 	ret = rtc_timer_start(rtc, &rtctimer, now, 0);
283 	if (ret < 0)
284 		pm_wakeup_event(dev, MSEC_PER_SEC);
285 	return ret;
286 }
287 
alarmtimer_resume(struct device * dev)288 static int alarmtimer_resume(struct device *dev)
289 {
290 	struct rtc_device *rtc;
291 
292 	rtc = alarmtimer_get_rtcdev();
293 	if (rtc)
294 		rtc_timer_cancel(rtc, &rtctimer);
295 	return 0;
296 }
297 
298 #else
alarmtimer_suspend(struct device * dev)299 static int alarmtimer_suspend(struct device *dev)
300 {
301 	return 0;
302 }
303 
alarmtimer_resume(struct device * dev)304 static int alarmtimer_resume(struct device *dev)
305 {
306 	return 0;
307 }
308 #endif
309 
310 static void
__alarm_init(struct alarm * alarm,enum alarmtimer_type type,void (* function)(struct alarm *,ktime_t))311 __alarm_init(struct alarm *alarm, enum alarmtimer_type type,
312 	     void (*function)(struct alarm *, ktime_t))
313 {
314 	timerqueue_init(&alarm->node);
315 	alarm->function = function;
316 	alarm->type = type;
317 	alarm->state = ALARMTIMER_STATE_INACTIVE;
318 }
319 
320 /**
321  * alarm_init - Initialize an alarm structure
322  * @alarm: ptr to alarm to be initialized
323  * @type: the type of the alarm
324  * @function: callback that is run when the alarm fires
325  */
alarm_init(struct alarm * alarm,enum alarmtimer_type type,void (* function)(struct alarm *,ktime_t))326 void alarm_init(struct alarm *alarm, enum alarmtimer_type type,
327 		void (*function)(struct alarm *, ktime_t))
328 {
329 	hrtimer_setup(&alarm->timer, alarmtimer_fired, alarm_bases[type].base_clockid,
330 		      HRTIMER_MODE_ABS);
331 	__alarm_init(alarm, type, function);
332 }
333 EXPORT_SYMBOL_GPL(alarm_init);
334 
335 /**
336  * alarm_start - Sets an absolute alarm to fire
337  * @alarm: ptr to alarm to set
338  * @start: time to run the alarm
339  */
alarm_start(struct alarm * alarm,ktime_t start)340 void alarm_start(struct alarm *alarm, ktime_t start)
341 {
342 	struct alarm_base *base = &alarm_bases[alarm->type];
343 
344 	scoped_guard(spinlock_irqsave, &base->lock) {
345 		alarm->node.expires = start;
346 		alarmtimer_enqueue(base, alarm);
347 		hrtimer_start(&alarm->timer, alarm->node.expires, HRTIMER_MODE_ABS);
348 	}
349 
350 	trace_alarmtimer_start(alarm, base->get_ktime());
351 }
352 EXPORT_SYMBOL_GPL(alarm_start);
353 
354 /**
355  * alarm_start_relative - Sets a relative alarm to fire
356  * @alarm: ptr to alarm to set
357  * @start: time relative to now to run the alarm
358  */
alarm_start_relative(struct alarm * alarm,ktime_t start)359 void alarm_start_relative(struct alarm *alarm, ktime_t start)
360 {
361 	struct alarm_base *base = &alarm_bases[alarm->type];
362 
363 	start = ktime_add_safe(start, base->get_ktime());
364 	alarm_start(alarm, start);
365 }
366 EXPORT_SYMBOL_GPL(alarm_start_relative);
367 
alarm_restart(struct alarm * alarm)368 void alarm_restart(struct alarm *alarm)
369 {
370 	struct alarm_base *base = &alarm_bases[alarm->type];
371 
372 	guard(spinlock_irqsave)(&base->lock);
373 	hrtimer_set_expires(&alarm->timer, alarm->node.expires);
374 	hrtimer_restart(&alarm->timer);
375 	alarmtimer_enqueue(base, alarm);
376 }
377 EXPORT_SYMBOL_GPL(alarm_restart);
378 
379 /**
380  * alarm_try_to_cancel - Tries to cancel an alarm timer
381  * @alarm: ptr to alarm to be canceled
382  *
383  * Returns 1 if the timer was canceled, 0 if it was not running,
384  * and -1 if the callback was running
385  */
alarm_try_to_cancel(struct alarm * alarm)386 int alarm_try_to_cancel(struct alarm *alarm)
387 {
388 	struct alarm_base *base = &alarm_bases[alarm->type];
389 	int ret;
390 
391 	scoped_guard(spinlock_irqsave, &base->lock) {
392 		ret = hrtimer_try_to_cancel(&alarm->timer);
393 		if (ret >= 0)
394 			alarmtimer_dequeue(base, alarm);
395 	}
396 
397 	trace_alarmtimer_cancel(alarm, base->get_ktime());
398 	return ret;
399 }
400 EXPORT_SYMBOL_GPL(alarm_try_to_cancel);
401 
402 
403 /**
404  * alarm_cancel - Spins trying to cancel an alarm timer until it is done
405  * @alarm: ptr to alarm to be canceled
406  *
407  * Returns 1 if the timer was canceled, 0 if it was not active.
408  */
alarm_cancel(struct alarm * alarm)409 int alarm_cancel(struct alarm *alarm)
410 {
411 	for (;;) {
412 		int ret = alarm_try_to_cancel(alarm);
413 		if (ret >= 0)
414 			return ret;
415 		hrtimer_cancel_wait_running(&alarm->timer);
416 	}
417 }
418 EXPORT_SYMBOL_GPL(alarm_cancel);
419 
420 
alarm_forward(struct alarm * alarm,ktime_t now,ktime_t interval)421 u64 alarm_forward(struct alarm *alarm, ktime_t now, ktime_t interval)
422 {
423 	u64 overrun = 1;
424 	ktime_t delta;
425 
426 	delta = ktime_sub(now, alarm->node.expires);
427 
428 	if (delta < 0)
429 		return 0;
430 
431 	if (unlikely(delta >= interval)) {
432 		s64 incr = ktime_to_ns(interval);
433 
434 		overrun = ktime_divns(delta, incr);
435 
436 		alarm->node.expires = ktime_add_ns(alarm->node.expires,
437 							incr*overrun);
438 
439 		if (alarm->node.expires > now)
440 			return overrun;
441 		/*
442 		 * This (and the ktime_add() below) is the
443 		 * correction for exact:
444 		 */
445 		overrun++;
446 	}
447 
448 	alarm->node.expires = ktime_add_safe(alarm->node.expires, interval);
449 	return overrun;
450 }
451 EXPORT_SYMBOL_GPL(alarm_forward);
452 
alarm_forward_now(struct alarm * alarm,ktime_t interval)453 u64 alarm_forward_now(struct alarm *alarm, ktime_t interval)
454 {
455 	struct alarm_base *base = &alarm_bases[alarm->type];
456 
457 	return alarm_forward(alarm, base->get_ktime(), interval);
458 }
459 EXPORT_SYMBOL_GPL(alarm_forward_now);
460 
461 #ifdef CONFIG_POSIX_TIMERS
462 
alarmtimer_freezerset(ktime_t absexp,enum alarmtimer_type type)463 static void alarmtimer_freezerset(ktime_t absexp, enum alarmtimer_type type)
464 {
465 	struct alarm_base *base;
466 	ktime_t delta;
467 
468 	switch(type) {
469 	case ALARM_REALTIME:
470 		base = &alarm_bases[ALARM_REALTIME];
471 		type = ALARM_REALTIME_FREEZER;
472 		break;
473 	case ALARM_BOOTTIME:
474 		base = &alarm_bases[ALARM_BOOTTIME];
475 		type = ALARM_BOOTTIME_FREEZER;
476 		break;
477 	default:
478 		WARN_ONCE(1, "Invalid alarm type: %d\n", type);
479 		return;
480 	}
481 
482 	delta = ktime_sub(absexp, base->get_ktime());
483 
484 	guard(spinlock_irqsave)(&freezer_delta_lock);
485 	if (!freezer_delta || (delta < freezer_delta)) {
486 		freezer_delta = delta;
487 		freezer_expires = absexp;
488 		freezer_alarmtype = type;
489 	}
490 }
491 
492 /**
493  * clock2alarm - helper that converts from clockid to alarmtypes
494  * @clockid: clockid.
495  */
clock2alarm(clockid_t clockid)496 static enum alarmtimer_type clock2alarm(clockid_t clockid)
497 {
498 	if (clockid == CLOCK_REALTIME_ALARM)
499 		return ALARM_REALTIME;
500 
501 	WARN_ON_ONCE(clockid != CLOCK_BOOTTIME_ALARM);
502 	return ALARM_BOOTTIME;
503 }
504 
505 /**
506  * alarm_handle_timer - Callback for posix timers
507  * @alarm: alarm that fired
508  * @now: time at the timer expiration
509  *
510  * Posix timer callback for expired alarm timers.
511  *
512  * Return: whether the timer is to be restarted
513  */
alarm_handle_timer(struct alarm * alarm,ktime_t now)514 static void alarm_handle_timer(struct alarm *alarm, ktime_t now)
515 {
516 	struct k_itimer *ptr = container_of(alarm, struct k_itimer, it.alarm.alarmtimer);
517 
518 	guard(spinlock_irqsave)(&ptr->it_lock);
519 	posix_timer_queue_signal(ptr);
520 }
521 
522 /**
523  * alarm_timer_rearm - Posix timer callback for rearming timer
524  * @timr:	Pointer to the posixtimer data struct
525  */
alarm_timer_rearm(struct k_itimer * timr)526 static void alarm_timer_rearm(struct k_itimer *timr)
527 {
528 	struct alarm *alarm = &timr->it.alarm.alarmtimer;
529 
530 	timr->it_overrun += alarm_forward_now(alarm, timr->it_interval);
531 	alarm_start(alarm, alarm->node.expires);
532 }
533 
534 /**
535  * alarm_timer_forward - Posix timer callback for forwarding timer
536  * @timr:	Pointer to the posixtimer data struct
537  * @now:	Current time to forward the timer against
538  */
alarm_timer_forward(struct k_itimer * timr,ktime_t now)539 static s64 alarm_timer_forward(struct k_itimer *timr, ktime_t now)
540 {
541 	struct alarm *alarm = &timr->it.alarm.alarmtimer;
542 
543 	return alarm_forward(alarm, timr->it_interval, now);
544 }
545 
546 /**
547  * alarm_timer_remaining - Posix timer callback to retrieve remaining time
548  * @timr:	Pointer to the posixtimer data struct
549  * @now:	Current time to calculate against
550  */
alarm_timer_remaining(struct k_itimer * timr,ktime_t now)551 static ktime_t alarm_timer_remaining(struct k_itimer *timr, ktime_t now)
552 {
553 	struct alarm *alarm = &timr->it.alarm.alarmtimer;
554 
555 	return ktime_sub(alarm->node.expires, now);
556 }
557 
558 /**
559  * alarm_timer_try_to_cancel - Posix timer callback to cancel a timer
560  * @timr:	Pointer to the posixtimer data struct
561  */
alarm_timer_try_to_cancel(struct k_itimer * timr)562 static int alarm_timer_try_to_cancel(struct k_itimer *timr)
563 {
564 	return alarm_try_to_cancel(&timr->it.alarm.alarmtimer);
565 }
566 
567 /**
568  * alarm_timer_wait_running - Posix timer callback to wait for a timer
569  * @timr:	Pointer to the posixtimer data struct
570  *
571  * Called from the core code when timer cancel detected that the callback
572  * is running. @timr is unlocked and rcu read lock is held to prevent it
573  * from being freed.
574  */
alarm_timer_wait_running(struct k_itimer * timr)575 static void alarm_timer_wait_running(struct k_itimer *timr)
576 {
577 	hrtimer_cancel_wait_running(&timr->it.alarm.alarmtimer.timer);
578 }
579 
580 /**
581  * alarm_timer_arm - Posix timer callback to arm a timer
582  * @timr:	Pointer to the posixtimer data struct
583  * @expires:	The new expiry time
584  * @absolute:	Expiry value is absolute time
585  * @sigev_none:	Posix timer does not deliver signals
586  */
alarm_timer_arm(struct k_itimer * timr,ktime_t expires,bool absolute,bool sigev_none)587 static void alarm_timer_arm(struct k_itimer *timr, ktime_t expires,
588 			    bool absolute, bool sigev_none)
589 {
590 	struct alarm *alarm = &timr->it.alarm.alarmtimer;
591 	struct alarm_base *base = &alarm_bases[alarm->type];
592 
593 	if (!absolute)
594 		expires = ktime_add_safe(expires, base->get_ktime());
595 	if (sigev_none)
596 		alarm->node.expires = expires;
597 	else
598 		alarm_start(&timr->it.alarm.alarmtimer, expires);
599 }
600 
601 /**
602  * alarm_clock_getres - posix getres interface
603  * @which_clock: clockid
604  * @tp: timespec to fill
605  *
606  * Returns the granularity of underlying alarm base clock
607  */
alarm_clock_getres(const clockid_t which_clock,struct timespec64 * tp)608 static int alarm_clock_getres(const clockid_t which_clock, struct timespec64 *tp)
609 {
610 	if (!alarmtimer_get_rtcdev())
611 		return -EINVAL;
612 
613 	tp->tv_sec = 0;
614 	tp->tv_nsec = hrtimer_resolution;
615 	return 0;
616 }
617 
618 /**
619  * alarm_clock_get_timespec - posix clock_get_timespec interface
620  * @which_clock: clockid
621  * @tp: timespec to fill.
622  *
623  * Provides the underlying alarm base time in a tasks time namespace.
624  */
alarm_clock_get_timespec(clockid_t which_clock,struct timespec64 * tp)625 static int alarm_clock_get_timespec(clockid_t which_clock, struct timespec64 *tp)
626 {
627 	struct alarm_base *base = &alarm_bases[clock2alarm(which_clock)];
628 
629 	if (!alarmtimer_get_rtcdev())
630 		return -EINVAL;
631 
632 	base->get_timespec(tp);
633 
634 	return 0;
635 }
636 
637 /**
638  * alarm_clock_get_ktime - posix clock_get_ktime interface
639  * @which_clock: clockid
640  *
641  * Provides the underlying alarm base time in the root namespace.
642  */
alarm_clock_get_ktime(clockid_t which_clock)643 static ktime_t alarm_clock_get_ktime(clockid_t which_clock)
644 {
645 	struct alarm_base *base = &alarm_bases[clock2alarm(which_clock)];
646 
647 	if (!alarmtimer_get_rtcdev())
648 		return -EINVAL;
649 
650 	return base->get_ktime();
651 }
652 
653 /**
654  * alarm_timer_create - posix timer_create interface
655  * @new_timer: k_itimer pointer to manage
656  *
657  * Initializes the k_itimer structure.
658  */
alarm_timer_create(struct k_itimer * new_timer)659 static int alarm_timer_create(struct k_itimer *new_timer)
660 {
661 	enum  alarmtimer_type type;
662 
663 	if (!alarmtimer_get_rtcdev())
664 		return -EOPNOTSUPP;
665 
666 	if (!capable(CAP_WAKE_ALARM))
667 		return -EPERM;
668 
669 	type = clock2alarm(new_timer->it_clock);
670 	alarm_init(&new_timer->it.alarm.alarmtimer, type, alarm_handle_timer);
671 	return 0;
672 }
673 
674 /**
675  * alarmtimer_nsleep_wakeup - Wakeup function for alarm_timer_nsleep
676  * @alarm: ptr to alarm that fired
677  * @now: time at the timer expiration
678  *
679  * Wakes up the task that set the alarmtimer
680  */
alarmtimer_nsleep_wakeup(struct alarm * alarm,ktime_t now)681 static void alarmtimer_nsleep_wakeup(struct alarm *alarm, ktime_t now)
682 {
683 	struct task_struct *task = alarm->data;
684 
685 	alarm->data = NULL;
686 	if (task)
687 		wake_up_process(task);
688 }
689 
690 /**
691  * alarmtimer_do_nsleep - Internal alarmtimer nsleep implementation
692  * @alarm: ptr to alarmtimer
693  * @absexp: absolute expiration time
694  * @type: alarm type (BOOTTIME/REALTIME).
695  *
696  * Sets the alarm timer and sleeps until it is fired or interrupted.
697  */
alarmtimer_do_nsleep(struct alarm * alarm,ktime_t absexp,enum alarmtimer_type type)698 static int alarmtimer_do_nsleep(struct alarm *alarm, ktime_t absexp,
699 				enum alarmtimer_type type)
700 {
701 	struct restart_block *restart;
702 	alarm->data = (void *)current;
703 	do {
704 		set_current_state(TASK_INTERRUPTIBLE);
705 		alarm_start(alarm, absexp);
706 		if (likely(alarm->data))
707 			schedule();
708 
709 		alarm_cancel(alarm);
710 	} while (alarm->data && !signal_pending(current));
711 
712 	__set_current_state(TASK_RUNNING);
713 
714 	destroy_hrtimer_on_stack(&alarm->timer);
715 
716 	if (!alarm->data)
717 		return 0;
718 
719 	if (freezing(current))
720 		alarmtimer_freezerset(absexp, type);
721 	restart = &current->restart_block;
722 	if (restart->nanosleep.type != TT_NONE) {
723 		struct timespec64 rmt;
724 		ktime_t rem;
725 
726 		rem = ktime_sub(absexp, alarm_bases[type].get_ktime());
727 
728 		if (rem <= 0)
729 			return 0;
730 		rmt = ktime_to_timespec64(rem);
731 
732 		return nanosleep_copyout(restart, &rmt);
733 	}
734 	return -ERESTART_RESTARTBLOCK;
735 }
736 
737 static void
alarm_init_on_stack(struct alarm * alarm,enum alarmtimer_type type,void (* function)(struct alarm *,ktime_t))738 alarm_init_on_stack(struct alarm *alarm, enum alarmtimer_type type,
739 		    void (*function)(struct alarm *, ktime_t))
740 {
741 	hrtimer_setup_on_stack(&alarm->timer, alarmtimer_fired, alarm_bases[type].base_clockid,
742 			       HRTIMER_MODE_ABS);
743 	__alarm_init(alarm, type, function);
744 }
745 
746 /**
747  * alarm_timer_nsleep_restart - restartblock alarmtimer nsleep
748  * @restart: ptr to restart block
749  *
750  * Handles restarted clock_nanosleep calls
751  */
alarm_timer_nsleep_restart(struct restart_block * restart)752 static long __sched alarm_timer_nsleep_restart(struct restart_block *restart)
753 {
754 	enum  alarmtimer_type type = restart->nanosleep.clockid;
755 	ktime_t exp = restart->nanosleep.expires;
756 	struct alarm alarm;
757 
758 	alarm_init_on_stack(&alarm, type, alarmtimer_nsleep_wakeup);
759 
760 	return alarmtimer_do_nsleep(&alarm, exp, type);
761 }
762 
763 /**
764  * alarm_timer_nsleep - alarmtimer nanosleep
765  * @which_clock: clockid
766  * @flags: determines abstime or relative
767  * @tsreq: requested sleep time (abs or rel)
768  *
769  * Handles clock_nanosleep calls against _ALARM clockids
770  */
alarm_timer_nsleep(const clockid_t which_clock,int flags,const struct timespec64 * tsreq)771 static int alarm_timer_nsleep(const clockid_t which_clock, int flags,
772 			      const struct timespec64 *tsreq)
773 {
774 	enum  alarmtimer_type type = clock2alarm(which_clock);
775 	struct restart_block *restart = &current->restart_block;
776 	struct alarm alarm;
777 	ktime_t exp;
778 	int ret;
779 
780 	if (!alarmtimer_get_rtcdev())
781 		return -EOPNOTSUPP;
782 
783 	if (flags & ~TIMER_ABSTIME)
784 		return -EINVAL;
785 
786 	if (!capable(CAP_WAKE_ALARM))
787 		return -EPERM;
788 
789 	alarm_init_on_stack(&alarm, type, alarmtimer_nsleep_wakeup);
790 
791 	exp = timespec64_to_ktime(*tsreq);
792 	/* Convert (if necessary) to absolute time */
793 	if (flags != TIMER_ABSTIME) {
794 		ktime_t now = alarm_bases[type].get_ktime();
795 
796 		exp = ktime_add_safe(now, exp);
797 	} else {
798 		exp = timens_ktime_to_host(which_clock, exp);
799 	}
800 
801 	ret = alarmtimer_do_nsleep(&alarm, exp, type);
802 	if (ret != -ERESTART_RESTARTBLOCK)
803 		return ret;
804 
805 	/* abs timers don't set remaining time or restart */
806 	if (flags == TIMER_ABSTIME)
807 		return -ERESTARTNOHAND;
808 
809 	restart->nanosleep.clockid = type;
810 	restart->nanosleep.expires = exp;
811 	set_restart_fn(restart, alarm_timer_nsleep_restart);
812 	return ret;
813 }
814 
815 const struct k_clock alarm_clock = {
816 	.clock_getres		= alarm_clock_getres,
817 	.clock_get_ktime	= alarm_clock_get_ktime,
818 	.clock_get_timespec	= alarm_clock_get_timespec,
819 	.timer_create		= alarm_timer_create,
820 	.timer_set		= common_timer_set,
821 	.timer_del		= common_timer_del,
822 	.timer_get		= common_timer_get,
823 	.timer_arm		= alarm_timer_arm,
824 	.timer_rearm		= alarm_timer_rearm,
825 	.timer_forward		= alarm_timer_forward,
826 	.timer_remaining	= alarm_timer_remaining,
827 	.timer_try_to_cancel	= alarm_timer_try_to_cancel,
828 	.timer_wait_running	= alarm_timer_wait_running,
829 	.nsleep			= alarm_timer_nsleep,
830 };
831 #endif /* CONFIG_POSIX_TIMERS */
832 
833 
834 /* Suspend hook structures */
835 static const struct dev_pm_ops alarmtimer_pm_ops = {
836 	.suspend = alarmtimer_suspend,
837 	.resume = alarmtimer_resume,
838 };
839 
840 static struct platform_driver alarmtimer_driver = {
841 	.driver = {
842 		.name = "alarmtimer",
843 		.pm = &alarmtimer_pm_ops,
844 	}
845 };
846 
get_boottime_timespec(struct timespec64 * tp)847 static void get_boottime_timespec(struct timespec64 *tp)
848 {
849 	ktime_get_boottime_ts64(tp);
850 	timens_add_boottime(tp);
851 }
852 
853 /**
854  * alarmtimer_init - Initialize alarm timer code
855  *
856  * This function initializes the alarm bases and registers
857  * the posix clock ids.
858  */
alarmtimer_init(void)859 static int __init alarmtimer_init(void)
860 {
861 	int error;
862 	int i;
863 
864 	alarmtimer_rtc_timer_init();
865 
866 	/* Initialize alarm bases */
867 	alarm_bases[ALARM_REALTIME].base_clockid = CLOCK_REALTIME;
868 	alarm_bases[ALARM_REALTIME].get_ktime = &ktime_get_real;
869 	alarm_bases[ALARM_REALTIME].get_timespec = ktime_get_real_ts64;
870 	alarm_bases[ALARM_BOOTTIME].base_clockid = CLOCK_BOOTTIME;
871 	alarm_bases[ALARM_BOOTTIME].get_ktime = &ktime_get_boottime;
872 	alarm_bases[ALARM_BOOTTIME].get_timespec = get_boottime_timespec;
873 	for (i = 0; i < ALARM_NUMTYPE; i++) {
874 		timerqueue_init_head(&alarm_bases[i].timerqueue);
875 		spin_lock_init(&alarm_bases[i].lock);
876 	}
877 
878 	error = alarmtimer_rtc_interface_setup();
879 	if (error)
880 		return error;
881 
882 	error = platform_driver_register(&alarmtimer_driver);
883 	if (error)
884 		goto out_if;
885 
886 	return 0;
887 out_if:
888 	alarmtimer_rtc_interface_remove();
889 	return error;
890 }
891 device_initcall(alarmtimer_init);
892