xref: /linux/kernel/time/alarmtimer.c (revision 492c826b9facefa84995f4dea917e301b5ee0884)
1 /*
2  * Alarmtimer interface
3  *
4  * This interface provides a timer which is similarto hrtimers,
5  * but triggers a RTC alarm if the box is suspend.
6  *
7  * This interface is influenced by the Android RTC Alarm timer
8  * interface.
9  *
10  * Copyright (C) 2010 IBM Corperation
11  *
12  * Author: John Stultz <john.stultz@linaro.org>
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License version 2 as
16  * published by the Free Software Foundation.
17  */
18 #include <linux/time.h>
19 #include <linux/hrtimer.h>
20 #include <linux/timerqueue.h>
21 #include <linux/rtc.h>
22 #include <linux/alarmtimer.h>
23 #include <linux/mutex.h>
24 #include <linux/platform_device.h>
25 #include <linux/posix-timers.h>
26 #include <linux/workqueue.h>
27 #include <linux/freezer.h>
28 
29 /**
30  * struct alarm_base - Alarm timer bases
31  * @lock:		Lock for syncrhonized access to the base
32  * @timerqueue:		Timerqueue head managing the list of events
33  * @timer: 		hrtimer used to schedule events while running
34  * @gettime:		Function to read the time correlating to the base
35  * @base_clockid:	clockid for the base
36  */
37 static struct alarm_base {
38 	spinlock_t		lock;
39 	struct timerqueue_head	timerqueue;
40 	struct hrtimer		timer;
41 	ktime_t			(*gettime)(void);
42 	clockid_t		base_clockid;
43 } alarm_bases[ALARM_NUMTYPE];
44 
45 #ifdef CONFIG_RTC_CLASS
46 /* rtc timer and device for setting alarm wakeups at suspend */
47 static struct rtc_timer		rtctimer;
48 static struct rtc_device	*rtcdev;
49 #endif
50 
51 /* freezer delta & lock used to handle clock_nanosleep triggered wakeups */
52 static ktime_t freezer_delta;
53 static DEFINE_SPINLOCK(freezer_delta_lock);
54 
55 
56 /**
57  * alarmtimer_enqueue - Adds an alarm timer to an alarm_base timerqueue
58  * @base: pointer to the base where the timer is being run
59  * @alarm: pointer to alarm being enqueued.
60  *
61  * Adds alarm to a alarm_base timerqueue and if necessary sets
62  * an hrtimer to run.
63  *
64  * Must hold base->lock when calling.
65  */
66 static void alarmtimer_enqueue(struct alarm_base *base, struct alarm *alarm)
67 {
68 	timerqueue_add(&base->timerqueue, &alarm->node);
69 	if (&alarm->node == timerqueue_getnext(&base->timerqueue)) {
70 		hrtimer_try_to_cancel(&base->timer);
71 		hrtimer_start(&base->timer, alarm->node.expires,
72 				HRTIMER_MODE_ABS);
73 	}
74 }
75 
76 /**
77  * alarmtimer_remove - Removes an alarm timer from an alarm_base timerqueue
78  * @base: pointer to the base where the timer is running
79  * @alarm: pointer to alarm being removed
80  *
81  * Removes alarm to a alarm_base timerqueue and if necessary sets
82  * a new timer to run.
83  *
84  * Must hold base->lock when calling.
85  */
86 static void alarmtimer_remove(struct alarm_base *base, struct alarm *alarm)
87 {
88 	struct timerqueue_node *next = timerqueue_getnext(&base->timerqueue);
89 
90 	timerqueue_del(&base->timerqueue, &alarm->node);
91 	if (next == &alarm->node) {
92 		hrtimer_try_to_cancel(&base->timer);
93 		next = timerqueue_getnext(&base->timerqueue);
94 		if (!next)
95 			return;
96 		hrtimer_start(&base->timer, next->expires, HRTIMER_MODE_ABS);
97 	}
98 }
99 
100 
101 /**
102  * alarmtimer_fired - Handles alarm hrtimer being fired.
103  * @timer: pointer to hrtimer being run
104  *
105  * When a alarm timer fires, this runs through the timerqueue to
106  * see which alarms expired, and runs those. If there are more alarm
107  * timers queued for the future, we set the hrtimer to fire when
108  * when the next future alarm timer expires.
109  */
110 static enum hrtimer_restart alarmtimer_fired(struct hrtimer *timer)
111 {
112 	struct alarm_base *base = container_of(timer, struct alarm_base, timer);
113 	struct timerqueue_node *next;
114 	unsigned long flags;
115 	ktime_t now;
116 	int ret = HRTIMER_NORESTART;
117 
118 	spin_lock_irqsave(&base->lock, flags);
119 	now = base->gettime();
120 	while ((next = timerqueue_getnext(&base->timerqueue))) {
121 		struct alarm *alarm;
122 		ktime_t expired = next->expires;
123 
124 		if (expired.tv64 >= now.tv64)
125 			break;
126 
127 		alarm = container_of(next, struct alarm, node);
128 
129 		timerqueue_del(&base->timerqueue, &alarm->node);
130 		alarm->enabled = 0;
131 		/* Re-add periodic timers */
132 		if (alarm->period.tv64) {
133 			alarm->node.expires = ktime_add(expired, alarm->period);
134 			timerqueue_add(&base->timerqueue, &alarm->node);
135 			alarm->enabled = 1;
136 		}
137 		spin_unlock_irqrestore(&base->lock, flags);
138 		if (alarm->function)
139 			alarm->function(alarm);
140 		spin_lock_irqsave(&base->lock, flags);
141 	}
142 
143 	if (next) {
144 		hrtimer_set_expires(&base->timer, next->expires);
145 		ret = HRTIMER_RESTART;
146 	}
147 	spin_unlock_irqrestore(&base->lock, flags);
148 
149 	return ret;
150 
151 }
152 
153 #ifdef CONFIG_RTC_CLASS
154 /**
155  * alarmtimer_suspend - Suspend time callback
156  * @dev: unused
157  * @state: unused
158  *
159  * When we are going into suspend, we look through the bases
160  * to see which is the soonest timer to expire. We then
161  * set an rtc timer to fire that far into the future, which
162  * will wake us from suspend.
163  */
164 static int alarmtimer_suspend(struct device *dev)
165 {
166 	struct rtc_time tm;
167 	ktime_t min, now;
168 	unsigned long flags;
169 	int i;
170 
171 	spin_lock_irqsave(&freezer_delta_lock, flags);
172 	min = freezer_delta;
173 	freezer_delta = ktime_set(0, 0);
174 	spin_unlock_irqrestore(&freezer_delta_lock, flags);
175 
176 	/* If we have no rtcdev, just return */
177 	if (!rtcdev)
178 		return 0;
179 
180 	/* Find the soonest timer to expire*/
181 	for (i = 0; i < ALARM_NUMTYPE; i++) {
182 		struct alarm_base *base = &alarm_bases[i];
183 		struct timerqueue_node *next;
184 		ktime_t delta;
185 
186 		spin_lock_irqsave(&base->lock, flags);
187 		next = timerqueue_getnext(&base->timerqueue);
188 		spin_unlock_irqrestore(&base->lock, flags);
189 		if (!next)
190 			continue;
191 		delta = ktime_sub(next->expires, base->gettime());
192 		if (!min.tv64 || (delta.tv64 < min.tv64))
193 			min = delta;
194 	}
195 	if (min.tv64 == 0)
196 		return 0;
197 
198 	/* XXX - Should we enforce a minimum sleep time? */
199 	WARN_ON(min.tv64 < NSEC_PER_SEC);
200 
201 	/* Setup an rtc timer to fire that far in the future */
202 	rtc_timer_cancel(rtcdev, &rtctimer);
203 	rtc_read_time(rtcdev, &tm);
204 	now = rtc_tm_to_ktime(tm);
205 	now = ktime_add(now, min);
206 
207 	rtc_timer_start(rtcdev, &rtctimer, now, ktime_set(0, 0));
208 
209 	return 0;
210 }
211 #else
212 static int alarmtimer_suspend(struct device *dev)
213 {
214 	return 0;
215 }
216 #endif
217 
218 static void alarmtimer_freezerset(ktime_t absexp, enum alarmtimer_type type)
219 {
220 	ktime_t delta;
221 	unsigned long flags;
222 	struct alarm_base *base = &alarm_bases[type];
223 
224 	delta = ktime_sub(absexp, base->gettime());
225 
226 	spin_lock_irqsave(&freezer_delta_lock, flags);
227 	if (!freezer_delta.tv64 || (delta.tv64 < freezer_delta.tv64))
228 		freezer_delta = delta;
229 	spin_unlock_irqrestore(&freezer_delta_lock, flags);
230 }
231 
232 
233 /**
234  * alarm_init - Initialize an alarm structure
235  * @alarm: ptr to alarm to be initialized
236  * @type: the type of the alarm
237  * @function: callback that is run when the alarm fires
238  */
239 void alarm_init(struct alarm *alarm, enum alarmtimer_type type,
240 		void (*function)(struct alarm *))
241 {
242 	timerqueue_init(&alarm->node);
243 	alarm->period = ktime_set(0, 0);
244 	alarm->function = function;
245 	alarm->type = type;
246 	alarm->enabled = 0;
247 }
248 
249 /**
250  * alarm_start - Sets an alarm to fire
251  * @alarm: ptr to alarm to set
252  * @start: time to run the alarm
253  * @period: period at which the alarm will recur
254  */
255 void alarm_start(struct alarm *alarm, ktime_t start, ktime_t period)
256 {
257 	struct alarm_base *base = &alarm_bases[alarm->type];
258 	unsigned long flags;
259 
260 	spin_lock_irqsave(&base->lock, flags);
261 	if (alarm->enabled)
262 		alarmtimer_remove(base, alarm);
263 	alarm->node.expires = start;
264 	alarm->period = period;
265 	alarmtimer_enqueue(base, alarm);
266 	alarm->enabled = 1;
267 	spin_unlock_irqrestore(&base->lock, flags);
268 }
269 
270 /**
271  * alarm_cancel - Tries to cancel an alarm timer
272  * @alarm: ptr to alarm to be canceled
273  */
274 void alarm_cancel(struct alarm *alarm)
275 {
276 	struct alarm_base *base = &alarm_bases[alarm->type];
277 	unsigned long flags;
278 
279 	spin_lock_irqsave(&base->lock, flags);
280 	if (alarm->enabled)
281 		alarmtimer_remove(base, alarm);
282 	alarm->enabled = 0;
283 	spin_unlock_irqrestore(&base->lock, flags);
284 }
285 
286 
287 /**
288  * clock2alarm - helper that converts from clockid to alarmtypes
289  * @clockid: clockid.
290  */
291 static enum alarmtimer_type clock2alarm(clockid_t clockid)
292 {
293 	if (clockid == CLOCK_REALTIME_ALARM)
294 		return ALARM_REALTIME;
295 	if (clockid == CLOCK_BOOTTIME_ALARM)
296 		return ALARM_BOOTTIME;
297 	return -1;
298 }
299 
300 /**
301  * alarm_handle_timer - Callback for posix timers
302  * @alarm: alarm that fired
303  *
304  * Posix timer callback for expired alarm timers.
305  */
306 static void alarm_handle_timer(struct alarm *alarm)
307 {
308 	struct k_itimer *ptr = container_of(alarm, struct k_itimer,
309 						it.alarmtimer);
310 	if (posix_timer_event(ptr, 0) != 0)
311 		ptr->it_overrun++;
312 }
313 
314 /**
315  * alarm_clock_getres - posix getres interface
316  * @which_clock: clockid
317  * @tp: timespec to fill
318  *
319  * Returns the granularity of underlying alarm base clock
320  */
321 static int alarm_clock_getres(const clockid_t which_clock, struct timespec *tp)
322 {
323 	clockid_t baseid = alarm_bases[clock2alarm(which_clock)].base_clockid;
324 
325 	return hrtimer_get_res(baseid, tp);
326 }
327 
328 /**
329  * alarm_clock_get - posix clock_get interface
330  * @which_clock: clockid
331  * @tp: timespec to fill.
332  *
333  * Provides the underlying alarm base time.
334  */
335 static int alarm_clock_get(clockid_t which_clock, struct timespec *tp)
336 {
337 	struct alarm_base *base = &alarm_bases[clock2alarm(which_clock)];
338 
339 	*tp = ktime_to_timespec(base->gettime());
340 	return 0;
341 }
342 
343 /**
344  * alarm_timer_create - posix timer_create interface
345  * @new_timer: k_itimer pointer to manage
346  *
347  * Initializes the k_itimer structure.
348  */
349 static int alarm_timer_create(struct k_itimer *new_timer)
350 {
351 	enum  alarmtimer_type type;
352 	struct alarm_base *base;
353 
354 	if (!capable(CAP_WAKE_ALARM))
355 		return -EPERM;
356 
357 	type = clock2alarm(new_timer->it_clock);
358 	base = &alarm_bases[type];
359 	alarm_init(&new_timer->it.alarmtimer, type, alarm_handle_timer);
360 	return 0;
361 }
362 
363 /**
364  * alarm_timer_get - posix timer_get interface
365  * @new_timer: k_itimer pointer
366  * @cur_setting: itimerspec data to fill
367  *
368  * Copies the itimerspec data out from the k_itimer
369  */
370 static void alarm_timer_get(struct k_itimer *timr,
371 				struct itimerspec *cur_setting)
372 {
373 	cur_setting->it_interval =
374 			ktime_to_timespec(timr->it.alarmtimer.period);
375 	cur_setting->it_value =
376 			ktime_to_timespec(timr->it.alarmtimer.node.expires);
377 	return;
378 }
379 
380 /**
381  * alarm_timer_del - posix timer_del interface
382  * @timr: k_itimer pointer to be deleted
383  *
384  * Cancels any programmed alarms for the given timer.
385  */
386 static int alarm_timer_del(struct k_itimer *timr)
387 {
388 	alarm_cancel(&timr->it.alarmtimer);
389 	return 0;
390 }
391 
392 /**
393  * alarm_timer_set - posix timer_set interface
394  * @timr: k_itimer pointer to be deleted
395  * @flags: timer flags
396  * @new_setting: itimerspec to be used
397  * @old_setting: itimerspec being replaced
398  *
399  * Sets the timer to new_setting, and starts the timer.
400  */
401 static int alarm_timer_set(struct k_itimer *timr, int flags,
402 				struct itimerspec *new_setting,
403 				struct itimerspec *old_setting)
404 {
405 	/* Save old values */
406 	old_setting->it_interval =
407 			ktime_to_timespec(timr->it.alarmtimer.period);
408 	old_setting->it_value =
409 			ktime_to_timespec(timr->it.alarmtimer.node.expires);
410 
411 	/* If the timer was already set, cancel it */
412 	alarm_cancel(&timr->it.alarmtimer);
413 
414 	/* start the timer */
415 	alarm_start(&timr->it.alarmtimer,
416 			timespec_to_ktime(new_setting->it_value),
417 			timespec_to_ktime(new_setting->it_interval));
418 	return 0;
419 }
420 
421 /**
422  * alarmtimer_nsleep_wakeup - Wakeup function for alarm_timer_nsleep
423  * @alarm: ptr to alarm that fired
424  *
425  * Wakes up the task that set the alarmtimer
426  */
427 static void alarmtimer_nsleep_wakeup(struct alarm *alarm)
428 {
429 	struct task_struct *task = (struct task_struct *)alarm->data;
430 
431 	alarm->data = NULL;
432 	if (task)
433 		wake_up_process(task);
434 }
435 
436 /**
437  * alarmtimer_do_nsleep - Internal alarmtimer nsleep implementation
438  * @alarm: ptr to alarmtimer
439  * @absexp: absolute expiration time
440  *
441  * Sets the alarm timer and sleeps until it is fired or interrupted.
442  */
443 static int alarmtimer_do_nsleep(struct alarm *alarm, ktime_t absexp)
444 {
445 	alarm->data = (void *)current;
446 	do {
447 		set_current_state(TASK_INTERRUPTIBLE);
448 		alarm_start(alarm, absexp, ktime_set(0, 0));
449 		if (likely(alarm->data))
450 			schedule();
451 
452 		alarm_cancel(alarm);
453 	} while (alarm->data && !signal_pending(current));
454 
455 	__set_current_state(TASK_RUNNING);
456 
457 	return (alarm->data == NULL);
458 }
459 
460 
461 /**
462  * update_rmtp - Update remaining timespec value
463  * @exp: expiration time
464  * @type: timer type
465  * @rmtp: user pointer to remaining timepsec value
466  *
467  * Helper function that fills in rmtp value with time between
468  * now and the exp value
469  */
470 static int update_rmtp(ktime_t exp, enum  alarmtimer_type type,
471 			struct timespec __user *rmtp)
472 {
473 	struct timespec rmt;
474 	ktime_t rem;
475 
476 	rem = ktime_sub(exp, alarm_bases[type].gettime());
477 
478 	if (rem.tv64 <= 0)
479 		return 0;
480 	rmt = ktime_to_timespec(rem);
481 
482 	if (copy_to_user(rmtp, &rmt, sizeof(*rmtp)))
483 		return -EFAULT;
484 
485 	return 1;
486 
487 }
488 
489 /**
490  * alarm_timer_nsleep_restart - restartblock alarmtimer nsleep
491  * @restart: ptr to restart block
492  *
493  * Handles restarted clock_nanosleep calls
494  */
495 static long __sched alarm_timer_nsleep_restart(struct restart_block *restart)
496 {
497 	enum  alarmtimer_type type = restart->nanosleep.clockid;
498 	ktime_t exp;
499 	struct timespec __user  *rmtp;
500 	struct alarm alarm;
501 	int ret = 0;
502 
503 	exp.tv64 = restart->nanosleep.expires;
504 	alarm_init(&alarm, type, alarmtimer_nsleep_wakeup);
505 
506 	if (alarmtimer_do_nsleep(&alarm, exp))
507 		goto out;
508 
509 	if (freezing(current))
510 		alarmtimer_freezerset(exp, type);
511 
512 	rmtp = restart->nanosleep.rmtp;
513 	if (rmtp) {
514 		ret = update_rmtp(exp, type, rmtp);
515 		if (ret <= 0)
516 			goto out;
517 	}
518 
519 
520 	/* The other values in restart are already filled in */
521 	ret = -ERESTART_RESTARTBLOCK;
522 out:
523 	return ret;
524 }
525 
526 /**
527  * alarm_timer_nsleep - alarmtimer nanosleep
528  * @which_clock: clockid
529  * @flags: determins abstime or relative
530  * @tsreq: requested sleep time (abs or rel)
531  * @rmtp: remaining sleep time saved
532  *
533  * Handles clock_nanosleep calls against _ALARM clockids
534  */
535 static int alarm_timer_nsleep(const clockid_t which_clock, int flags,
536 		     struct timespec *tsreq, struct timespec __user *rmtp)
537 {
538 	enum  alarmtimer_type type = clock2alarm(which_clock);
539 	struct alarm alarm;
540 	ktime_t exp;
541 	int ret = 0;
542 	struct restart_block *restart;
543 
544 	if (!capable(CAP_WAKE_ALARM))
545 		return -EPERM;
546 
547 	alarm_init(&alarm, type, alarmtimer_nsleep_wakeup);
548 
549 	exp = timespec_to_ktime(*tsreq);
550 	/* Convert (if necessary) to absolute time */
551 	if (flags != TIMER_ABSTIME) {
552 		ktime_t now = alarm_bases[type].gettime();
553 		exp = ktime_add(now, exp);
554 	}
555 
556 	if (alarmtimer_do_nsleep(&alarm, exp))
557 		goto out;
558 
559 	if (freezing(current))
560 		alarmtimer_freezerset(exp, type);
561 
562 	/* abs timers don't set remaining time or restart */
563 	if (flags == TIMER_ABSTIME) {
564 		ret = -ERESTARTNOHAND;
565 		goto out;
566 	}
567 
568 	if (rmtp) {
569 		ret = update_rmtp(exp, type, rmtp);
570 		if (ret <= 0)
571 			goto out;
572 	}
573 
574 	restart = &current_thread_info()->restart_block;
575 	restart->fn = alarm_timer_nsleep_restart;
576 	restart->nanosleep.clockid = type;
577 	restart->nanosleep.expires = exp.tv64;
578 	restart->nanosleep.rmtp = rmtp;
579 	ret = -ERESTART_RESTARTBLOCK;
580 
581 out:
582 	return ret;
583 }
584 
585 
586 /* Suspend hook structures */
587 static const struct dev_pm_ops alarmtimer_pm_ops = {
588 	.suspend = alarmtimer_suspend,
589 };
590 
591 static struct platform_driver alarmtimer_driver = {
592 	.driver = {
593 		.name = "alarmtimer",
594 		.pm = &alarmtimer_pm_ops,
595 	}
596 };
597 
598 /**
599  * alarmtimer_init - Initialize alarm timer code
600  *
601  * This function initializes the alarm bases and registers
602  * the posix clock ids.
603  */
604 static int __init alarmtimer_init(void)
605 {
606 	int error = 0;
607 	int i;
608 	struct k_clock alarm_clock = {
609 		.clock_getres	= alarm_clock_getres,
610 		.clock_get	= alarm_clock_get,
611 		.timer_create	= alarm_timer_create,
612 		.timer_set	= alarm_timer_set,
613 		.timer_del	= alarm_timer_del,
614 		.timer_get	= alarm_timer_get,
615 		.nsleep		= alarm_timer_nsleep,
616 	};
617 
618 	posix_timers_register_clock(CLOCK_REALTIME_ALARM, &alarm_clock);
619 	posix_timers_register_clock(CLOCK_BOOTTIME_ALARM, &alarm_clock);
620 
621 	/* Initialize alarm bases */
622 	alarm_bases[ALARM_REALTIME].base_clockid = CLOCK_REALTIME;
623 	alarm_bases[ALARM_REALTIME].gettime = &ktime_get_real;
624 	alarm_bases[ALARM_BOOTTIME].base_clockid = CLOCK_BOOTTIME;
625 	alarm_bases[ALARM_BOOTTIME].gettime = &ktime_get_boottime;
626 	for (i = 0; i < ALARM_NUMTYPE; i++) {
627 		timerqueue_init_head(&alarm_bases[i].timerqueue);
628 		spin_lock_init(&alarm_bases[i].lock);
629 		hrtimer_init(&alarm_bases[i].timer,
630 				alarm_bases[i].base_clockid,
631 				HRTIMER_MODE_ABS);
632 		alarm_bases[i].timer.function = alarmtimer_fired;
633 	}
634 	error = platform_driver_register(&alarmtimer_driver);
635 	platform_device_register_simple("alarmtimer", -1, NULL, 0);
636 
637 	return error;
638 }
639 device_initcall(alarmtimer_init);
640 
641 #ifdef CONFIG_RTC_CLASS
642 /**
643  * has_wakealarm - check rtc device has wakealarm ability
644  * @dev: current device
645  * @name_ptr: name to be returned
646  *
647  * This helper function checks to see if the rtc device can wake
648  * from suspend.
649  */
650 static int __init has_wakealarm(struct device *dev, void *name_ptr)
651 {
652 	struct rtc_device *candidate = to_rtc_device(dev);
653 
654 	if (!candidate->ops->set_alarm)
655 		return 0;
656 	if (!device_may_wakeup(candidate->dev.parent))
657 		return 0;
658 
659 	*(const char **)name_ptr = dev_name(dev);
660 	return 1;
661 }
662 
663 /**
664  * alarmtimer_init_late - Late initializing of alarmtimer code
665  *
666  * This function locates a rtc device to use for wakealarms.
667  * Run as late_initcall to make sure rtc devices have been
668  * registered.
669  */
670 static int __init alarmtimer_init_late(void)
671 {
672 	struct device *dev;
673 	char *str;
674 
675 	/* Find an rtc device and init the rtc_timer */
676 	dev = class_find_device(rtc_class, NULL, &str, has_wakealarm);
677 	/* If we have a device then str is valid. See has_wakealarm() */
678 	if (dev) {
679 		rtcdev = rtc_class_open(str);
680 		/*
681 		 * Drop the reference we got in class_find_device,
682 		 * rtc_open takes its own.
683 		 */
684 		put_device(dev);
685 	}
686 	if (!rtcdev) {
687 		printk(KERN_WARNING "No RTC device found, ALARM timers will"
688 			" not wake from suspend");
689 	}
690 	rtc_timer_init(&rtctimer, NULL, NULL);
691 
692 	return 0;
693 }
694 #else
695 static int __init alarmtimer_init_late(void)
696 {
697 	printk(KERN_WARNING "Kernel not built with RTC support, ALARM timers"
698 		" will not wake from suspend");
699 	return 0;
700 }
701 #endif
702 late_initcall(alarmtimer_init_late);
703