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